text:
==============
Binding Events
==============

**Time Estimate:** 20 minutes

**Difficulty Level:** Advanced

.. _code_exs_events-summary:

Summary
=======

This example shows how to bind events to a mojit, configure code to run
on the client, and make AJAX calls to the YQL Web service. The application
listens for events and then makes AJAX calls to YQL to get Flickr photo
information.

The following topics will be covered:

- configuring the application to run on the client
- getting Flickr data from the model with YQL
- binding events through the ``mojitProxy`` object
- making AJAX calls to YQL from the binder

.. _events_summary-req:

Requirements
------------

You will need to `get a Flickr API key <http://www.flickr.com/services/api/keys/apply/>`_
to run this example.

.. _code_exs_events-notes:

Implementation Notes
====================

.. _events_notes-client:

Configuring the Application to Run on the Client
------------------------------------------------

Mojito lets you configure applications to run on either the server or client
side. This example uses binders that are deployed to the client, so we need
to configure Mojito to deploy the application to the client, where it will
be executed by the browser.

To configure Mojito to run on the client, you simply set the ``"deploy"``
property to ``true`` in ``application.json`` as seen below.

.. code-block:: javascript

   [
     {
       "settings": [ "master" ],
       "specs": {
         "frame": {
           "type": "HTMLFrameMojit",
           "config": {
             "deploy": true,
             "child": {
               "type": "Pager"
             }
           }
         }
       }
     }
   ]

.. _events_notes-data:

Getting Data with YQL in the Model
----------------------------------

In the mojit model, the `YUI YQL Query Utility <https://developer.yahoo.com/yui/3/yql/>`_
is used to get Flickr photo information. To access the utility in your model,
specify ``'yql'`` in the ``requires`` array as seen in the code snippet below:

.. code-block:: javascript

   YUI.add('pager-model', function(Y, NAME) {
     ...
     /* Code for pager-model */
     ...
   }, '0.0.1', {requires: ['yql']});

This code example uses the ``flickr.photos.search`` table to get information
for photos that have a title, description, or tags containing a string. For
example, the YQL statement below returns Flickr photo information for those
photos that have a title, description, or tags containing the string "Manhattan".

Copy the query below into the `YQL Console <https://developer.yahoo.com/yql/console/>`_,
replace ``{your_flickr_api_key}`` with your own Flickr API key, and then  click **TEST**
to see the returned XML response.

``select * from flickr.photos.search where text="Manhattan" and api_key="{your_flickr_api_key}"``

The returned response contains photo information in the ``photo`` element. You extract the
``farm``, ``server``, ``id``, and ``secret`` attributes from each photo element to create
the photo URI as seen here:

``http://farm + {farm} + static.flickr.com/ + {server} + / + {id} + _ + {secret} + .jpg``

In the ``model.server.js`` of ``Pager`` mojit shown below, the ``YQL`` function uses the YQL
statement above to get photo data, then parses the returned response to create the photo
URIs. The model then wraps the photo information in an object and stores those objects in
the ``images`` array that is sent to the controller through the ``callback`` function.

.. code-block:: javascript

   YUI.add('pager-model', function(Y, NAME) {
     /**
     * The pager-model module.
     * @module pager-model
     */
     /**
     * Constructor for the Model class.
     * @class Model
     * @constructor
     **/
     Y.namespace('mojito.models')[NAME] = {
       init: function(config) {
         this.config = config;
       },
       getData: function(query, start, count, callback) {
          var q = null;
         // Get Flickr API key: http://www.flickr.com/services/api/keys/apply/
         var API_KEY = "{your_flickr_api_key}";
         start = parseInt(start) || 0;
         count = parseInt(count) || 10;
         q = 'select * from flickr.photos.search(' + start + ',' + count + ')  where text="%' + query + '%" and api_key="' + API_KEY + '"';
         Y.YQL(q, function(rawData) {
           if (!rawData.query.results) {
             callback([]);
             return;
           }
           var rawImages = rawData.query.results.photo, rawImage = null,images = [], image = null, i = 0;
           for (; i<rawImages.length; i++) {
             rawImage = rawImages[i];
             image = {
               title: rawImage.title,
               location: 'http://farm' + rawImage.farm + '.static.flickr.com/' + rawImage.server + '/' + rawImage.id + '_' + rawImage.secret + '.jpg',
               farm: rawImage.farm,
               server: rawImage.server,
               image_id: rawImage.id,
               secret: rawImage.secret
             };
             if (!image.title) {
               image.title = "Generic Title: " + query;
             }
             images.push(image);
           }
           callback(images);
         });
       }
     };
   }, '0.0.1', {requires: [ 'yql']});

For a more detailed explanation about how to use YQL in your Mojito application, see
`Calling YQL from a Mojit <calling_yql.html>`_. For more information about YQL, see the
`YQL Guide <https://developer.yahoo.com/yql/guide>`_.

.. _events_notes-bind_events:

Binding Events
--------------

This section will discuss the basics of binding events in Mojito and then look at the
binder used in this code example.

.. _bind_events-basics:

Binder Basics
#############

A mojit may have zero, one, or many binders within the ``binders`` directory. Each binder
will be deployed to the browser along with the rest of the mojit code, where the
client-side Mojito runtime will call it appropriately.  On the client, the binder has a
proxy object (``mojitProxy``) for interacting with the mojit it represents as well as
with other mojits on the page. Methods can be called from the ``mojitProxy`` object
that allow binders to listen for and fire events.

The binder consists of a constructor, an initializer, and a bind function. The following
describes each component and indicates when the ``mojitProxy`` object can be used.

- **constructor** - creates the namespace for your binder that wraps the initialization
  code and binder.
- **initializer** - is passed the ``mojitProxy`` where it can be stored and used to listen
  and fire events with other binders. The ``mojitProxy`` is the only gateway back into the
  Mojito framework for your binder.
- **bind** - is a function that is passed a ``Y.Node`` instance that wraps the DOM node
  representing this mojit instance. The DOM event handlers for capturing user interactions
  should be attached in this function.

The skeleton of the ``binders/index.js`` file below illustrates the basic structure of the
binder. For more information, see `Mojito Binders <../intro/mojito_binders.html>`_.

.. code-block:: javascript

   YUI.add('awesome-binder-index', function(Y, NAME) {
     // Binder constructor
     Y.namespace('mojito.binders')[NAME] = {
       init: function(mojitProxy) {
         this.mojitProxy = mojitProxy;
       },
       // The bind function
       bind: function(node) {
         var thatNode = node;
       }
     };
   }, '0.0.1', {requires: ['mojito']});

.. _bind_events-pagemojitbinder:

Examining the Pager Binder
##########################

This code example uses the binder module ``page-binder-index`` to perform the following:

- attach ``onClick`` handlers to ``prev`` and ``next`` links
- invoke the ``index`` method of the controller through the ``mojitProxy`` object
- create an overlay with Flickr photo information received from YQL

The ``binders/index.js`` for this code example is long and fairly involved, so we will
dissect and analyze the code.  Let's begin by looking at the ``bind`` function of
``index.js``, which allows mojits to attach DOM event handlers.

In this code snippet of ``binders/index.js``, the ``bind`` function contains the nested
``updateDOM`` function that updates node content and attaches event handlers. Using the
``mojitProxy`` object, the nested ``flipper`` function calls the ``index`` function of
the controller. The callback ``updateDOM`` is passed to ``index`` to update the content.

.. code-block:: javascript

   ...
     bind: function(node) {
       var thatNode = node;
       // Define the action when user click on prev/next.
       var flipper = function(event) {
       var target = event.target;
       // Get the link to the page.
       var page = parsePage(target.get('href'));
       var updateDOM = function(markup) {
         thatNode.set('innerHTML', markup);
         thatNode.all('#nav a').on('click', flipper, this);
         thatNode.all('#master ul li a').on('mouseover', showOverlay, this);
         thatNode.all('#master ul li a').on('mouseout', showOverlay, this);
       };
       this.mojitProxy.invoke('index',
         {
           params: {page: page},
         }, updateDOM
       );
     };
   ...

The event handler for mouseovers and mouseouts are handled by the ``showOverlay``
function, which creates the overlay containing photo information. In the code snippet
below, ``showOverlay`` makes an AJAX call to YQL to get photo data that is placed in an
unordered list for the overlay.

.. code-block:: javascript

   ...
     bind: function(node) {
       ...
       var showOverlay = function(event) {
         var target = event.target;
         var href = target.get('href');
         var imageId = parseImageId(href);
         if (target.hasClass('overlayed')) {
           target.removeClass('overlayed');
           thatNode.one('#display').setContent('');
         } else {
           Y.log('HREF: ' + href);
           Y.log('IMAGE ID: ' + imageId);
           target.addClass('overlayed');
           // Query for the image metadata
           var query = 'select * from flickr.photos.info where photo_id="' + imageId + '" and api_key="' + {your_flickr_api_key} + '"';
           thatNode.one('#display').setContent('Loading ...');
           Y.YQL(query, function(raw) {
             if (!raw.query.results.photo) {
               Y.log('No results found for photoId: ' + imageId);
               return;
             }
             var props = raw.query.results.photo;
             var snippet = '
';
             for (var key in props) {
               if (typeof(props[key]) == 'object') {
                 continue;
               }
               snippet += '
' + key + ': ' + props[key] + '
';
             }
             snippet += '
';
             thatNode.one('#display').setContent(snippet);
           });
         }
       };
        ...
     }
   ...

Thus far, we've looked at the event handlers, but not the actual binding of the handlers
to nodes. At the end of the ``bind`` function, you'll see three important lines
(shown below) that bind the ``flipper`` and ``showOutlay`` functions to handle click and
mouseover events.

.. code-block:: javascript

   ...
     bind: function(node) {
     ...
       // Bind all the image links to showOverlay
       thatNode.all('#master ul li a').on('mouseover', showOverlay, this);
       thatNode.all('#master ul li a').on('mouseout', showOverlay, this);
       // Bind the prev + next links to flipper
       thatNode.all('#nav a').on('click', flipper, this);
     }
   ...

After a little analysis, the full ``binders/index.js`` below should be easier to
understand. The binder attaches event handlers to nodes, invokes a function in the
controller, and updates the content in the template. The binder also has a couple of
helper functions for parsing and requires the IO and YQL modules, which are specified in
the ``requires`` array.

.. code-block:: javascript

   YUI.add('pager-binder-index', function(Y, NAME) {
     var API_KEY = '{your_flickr_api_key}';
     function parseImageId(link) {
       var matches = link.match(/com\/(\d+)\/(\d+)_([0-9a-z]+)\.jpg$/);
       return matches[2];
     }
     function parsePage(link) {
       var matches = link.match(/page=(\d+)/);
       return matches[1];
     }

     /**
     * The pager-binder-index module.
     * @module pager-binder-index
     */
     /**
     * Constructor for the Binder class.
     *
     * @param mojitProxy {Object} The proxy to allow
     * the binder to interact with its owning mojit.
     * @class Binder
     * @constructor
     */
     Y.namespace('mojito.binders')[NAME] = {
       /**
       * Binder initialization method, invoked
       * after all binders on the page have
       * been constructed.
       */
       init: function(mojitProxy) {
         this.mojitProxy = mojitProxy;
       },
       /**
       * The binder method, invoked to allow the mojit
       * to attach DOM event handlers.
       * @param node {Node} The DOM node to which this
       * mojit is attached.
       */
       bind: function(node) {
         var thatNode = node;
         Y.log('NODE: ' + Y.dump(this.node));
         // define the action when user click on prev/next
         var flipper = function(event) {
           var target = event.target;
           // get the link to the page
           var page = parsePage(target.get('href'));
           Y.log('PAGE: ' + page);
           var updateDOM = function(markup) {
             thatNode.set('innerHTML', markup);
             thatNode.all('#nav a').on('click', flipper, this);
             thatNode.all('#master ul li a').on('mouseover', showOverlay, this);
             thatNode.all('#master ul li a').on('mouseout', showOverlay, this);
           };
           this.mojitProxy.invoke('index',
             {
               params: {page: page}
             }, updateDOM
           );
         };
         var showOverlay = function(event) {
           var target = event.target;
           var href = target.get('href');
           var imageId = parseImageId(href);
           if (target.hasClass('overlayed')) {
             target.removeClass('overlayed');
             thatNode.one('#display').setContent('');
           } else {
             Y.log('HREF: ' + href);
             Y.log('IMAGE ID: ' + imageId);
             target.addClass('overlayed');
             // Query for the image metadata
             var query = 'select * from flickr.photos.info where photo_id="' + imageId + '" and api_key="' + API_KEY + '"';
             thatNode.one('#display').setContent('Loading ...');
             Y.YQL(query, function(raw) {
               if (!raw.query.results.photo) {
                 Y.log('No results found for photoId: ' + imageId);
                 return;
               }
               var props = raw.query.results.photo;
               var snippet = '
';
               for (var key in props) {
                 if (typeof(props[key]) == 'object') {
                   continue;
                 }
                 snippet += '
' + key + ': ' + props[key] + '
';
               }
               snippet += '
';
               thatNode.one('#display').setContent(snippet);
             });
           }
         };
         // Bind all the image links to showOverlay
         thatNode.all('#master ul li a').on('mouseover', showOverlay, this);
         thatNode.all('#master ul li a').on('mouseout', showOverlay, this);
         // Bind the prev + next links to flipper
         thatNode.all('#nav a').on('click', flipper, this);
       }
     };
   }, '0.0.1', {requires: ['yql', 'io', 'dump']});

.. _events_notes-paging:

Using Paging
------------

The paging for this code example relies on the application configuration to set route
paths and the controller to create links to access previous and next pages.

The root path is configured in ``app.js`` with the following:

.. code-block:: javascript

   var debug = require('debug')('app'),
   express = require('express'),
   libmojito = require('mojito'),
   app;

   app = express();
   app.set('port', process.env.PORT || 8666);
   libmojito.extend(app);
   app.use(libmojito.middleware());

   app.get('/status', function (req, res) {
       res.send('200 OK');
   });

   app.get('/', libmojito.dispatch('frame.index'));

The controller for ``Pager`` performs several functions:

- uses the ``Params`` addon to get the ``page`` parameter from the query string
- calculates the index of the first photo on the page
- calls the ``getData`` function in the model to get photo data
- creates URLs for the **next** and **prev** links

The `Params addon <../../api/classes/Params.common.html>`_ allows you to access variables
from the query string parameters, the POST request bodies, or the routing systems URLs.
In this code example, you use the ``getFromMerged`` method, which merges the parameters
from the query string, POST request body, and the routing system URLs to give you access
to all of the parameters. In the code snippet taken from ``controller.server.js`` below,
the ``getFromMerged`` method is used to get the value for the ``page`` parameter and then
calculate the index of the first photo to display:

.. code-block:: javascript

   ...
      index: function(actionContext) {
         var page = actionContext.params.getFromMerged('page');
         var start;
         page = parseInt(page) || 1;
         if ((!page) || (page<1)) {
           page = 1;
         }
         // Page param is 1 based, but the model is 0 based
         start = (page - 1) * PAGE_SIZE;
      ...
      }
   ...

To get the photo data, the controller depends on the model to call YQL to query the
Flickr API. Using ``actionContext.get({model_name})`` lets you get a reference to the
model. The file naming convention for models is ``{model_name}.{affinity}.{selector}.js``.
The ``{affinity}`` can have the values ``server``, ``client``, or ``common``. The ``{selector}``
is defined by the ``selector`` property in ``application.json``, but does not need to be defined.
The ``{model_name}`` is an arbitrary string defined by the user. So, for example,
our model in this example is ``model.server.js``, so ``{model_file_name}`` is ``model``.

The example controller below calls the ``getData`` from the model
with ``actionContext.models.get('model').getData``, which
will get the returned data from YQL in the callback function. To use methods from models,
you need to require the model in the ``requires`` array of the controller.

.. code-block:: javascript

   ...
       index: function(actionContext) {
       ...
         // Data is an array of images
         actionContext.models.get('model').getData('mojito', start, PAGE_SIZE, function(data) {
           Y.log('DATA: ' + Y.dump(data));
           var theData = {
           data: data, // images
           hasLink: false,
           prev: {
             title: "prev" // opportunity to localize
           },
           next: {
             link: createLink(actionContext, {page: page+1}),
               title: "next"
             },
             query: 'mojito'
           };
           if (page > 1) {
             theData.prev.link = createLink(actionContext, {page: page-1});
             theData.hasLink = true;
           }
           actionContext.done(theData);
         });
       }
       ...
     };
   }, '0.0.1', {requires: [
     'mojito',
     'mojito-models-addon',
     'mojito-params-addon',
     'pager-model',
     'dump'
   ]});

The URLs for the **prev** and **next** links are created by passing the mojit instance,
the method, and the query string parameters.

The code snippet below creates the query string parameters with the
`YUI QueryString module <http://yuilibrary.com/yui/docs/api/modules/querystring.html>`_.
If the query string created by ``Y.QueryString.stringify`` is "page=2" ,
the ``createLink`` method would return the URL ``{domain_name}:8666/?page=2``.

.. code-block:: javascript

   ...
     function createLink(actionContext, params) {
       var mergedParams = Y.mojito.util.copy(actionContext.params.getFromMerged());
       for (var k in params) {
         mergedParams[k] = params[k];
       }
       return "/?" + Y.QueryString.stringify(mergedParams));
     }
   ...

Stitching the above code snippets together, we have the ``controller.server.js`` below.
The ``index`` function relies on the model for data and the ``createLink`` function to
create URLs for the **next** and **prev** links.

.. code-block:: javascript

   YUI.add('pager', function(Y, NAME) {
     /**
     * The pager module.
     * @module pager */
     var PAGE_SIZE = 10;
     /**
     * Constructor for the Controller class.
     * @class Controller
     * @constructor
     */
     Y.namespace('mojito.controllers')[NAME] = {

       index: function(actionContext) {
         var page = actionContext.params.getFromMerged('page');
         var start;
         page = parseInt(page) || 1;
         if ((!page) || (page<1)) {
           page = 1;
         }
         // Page param is 1 based, but the model is 0 based
         start = (page - 1) * PAGE_SIZE;
         // Data is an array of images
         actionContext.models.get('model').getData('mojito', start, PAGE_SIZE, function(data) {
           Y.log('DATA: ' + Y.dump(data));
           var theData = {
             data: data, // images
             hasLink: false,
             prev: {
               title: "prev" // opportunity to localize
             },
             next: {
               link: createLink(actionContext, {page: page+1}),
               title: "next"
             },
             query: 'mojito'
           };
           if (page > 1) {
             theData.prev.link = createLink(actionContext, {page: page-1});
             theData.hasLink = true;
           }
           actionContext.done(theData);
         });
       }
     };
     // generate the link to the next page based on:
     // - mojit id
     // - action
     // - params
     function createLink(actionContext, params) {
       var mergedParams = Y.mojito.util.copy(actionContext.params.getFromMerged());
       for (var k in params) {
         mergedParams[k] = params[k];
       }
       return actionContext.url.make('frame', 'index', Y.QueryString.stringify(mergedParams));
     }
   }, '0.0.1', {requires: [
     'mojito',
     'mojito-models-addon',
     'mojito-params-addon',
     'pager-model',
     'dump'
   ]});

.. _code_exs_events-setup:

Setting Up this Example
=======================

To set up and run ``binding_events``:

#. Create your application.

   ``$ mojito create app binding_events``
#. Change to the application directory.
#. Create your mojit.

   ``$ mojito create mojit Pager``
#. To configure you application to run on the client and use ``HTMLFrameMojit``, replace
   the code in ``application.json`` with the following:

   .. code-block:: javascript

      [
        {
          "settings": [ "master" ],
          "specs": {
            "frame": {
              "type": "HTMLFrameMojit",
              "config": {
                "deploy": true,
                "child": {
                  "type": "Pager"
                }
              }
            }
          }
        }
      ]

#. Confirm that your ``app.js`` has the following content:

   .. code-block:: javascript

      'use strict';

      var debug = require('debug')('app'),
          express = require('express'),
          libmojito = require('mojito'),
          app;

          app = express();
          app.set('port', process.env.PORT || 8666);
          libmojito.extend(app);

          app.use(libmojito.middleware());

          app.get('/status', function (req, res) {
              res.send('200 OK');
          });
          app.get('/', libmojito.dispatch('frame.index'));

          app.listen(app.get('port'), function () {
              debug('Server listening on port ' + app.get('port') + ' ' +
              'in ' + app.get('env') + ' mode');
          });
          module.exports = app;

#. Also, confirm that your ``package.json`` has the correct dependencies as show below. If not,
   update ``package.json``.

   .. code-block:: javascript

      "dependencies": {
          "debug": "*",
           "mojito": "~0.9.0"
      },
      "devDependencies": {
          "mojito-cli": ">= 0.2.0"
      },
#. From the application directory, install the application dependencies:

   ``$ npm install``
#. Change to ``mojits/Pager``.
#. To have the controller get data from the model and create links for paging, replace the
   code in ``controller.server.js`` with the following:

   .. code-block:: javascript

      YUI.add('pager', function(Y, NAME) {
        var PAGE_SIZE = 10;
        /**
        * Constructor for the Controller class.
        * @class Controller
        * @constructor
        */
          Y.namespace('mojito.controllers')[NAME] = {

            index: function(actionContext) {
              var page = actionContext.params.getFromMerged('page');
              var start;
              page = parseInt(page) || 1;
              if ((!page) || (page<1)) {
                page = 1;
              }
              // Page param is 1 based, but the model is 0 based
              start = (page - 1) * PAGE_SIZE;
              // Data is an array of images
              actionContext.models.get('model').getData('mojito', start, PAGE_SIZE, function(data) {
                Y.log('DATA: ' + Y.dump(data));
                var theData = {
                  data: data, // images
                  hasLink: false,
                  prev: {
                    title: "prev" // opportunity to localize
                  },
                  next: {
                    link: createLink(actionContext, {page: page+1}),
                    title: "next"
                  },
                  query: 'mojito'
                };
                if (page > 1) {
                  theData.prev.link = createLink(actionContext, {page: page-1});
                  theData.hasLink = true;
                }
                actionContext.done(theData);
              });
            }
          };
          // Generate the link to the next page based on:
          // - mojit id
          // - action
          // - params
          function createLink(actionContext, params) {
            var mergedParams = Y.mojito.util.copy(actionContext.params.getFromMerged());
            for (var k in params) {
              mergedParams[k] = params[k];
            }
            return "/?" + Y.QueryString.stringify(mergedParams);
          }
      }, '0.0.1', {requires: [
        'mojito',
        'mojito-models-addon',
        'mojito-params-addon',
        'pager-model',
        'dump'
      ]});

#. To get Flickr photo information using YQL, create the file ``models/model.server.js``
   with the code below. Be sure to replace the ``'{your_flickr_api_key}'`` with your own
   Flickr API key.

   .. code-block:: javascript

      YUI.add('pager-model', function(Y, NAME) {
        var API_KEY = '{your_flickr_api_key}';
        /**
        * The pager-model module.
        * @module pager-model
        */
        /**
        * Constructor for the Model class.
        * @class Model
        * @constructor
        */
        Y.namespace('mojito.models')[NAME] = {

          getData: function(query, start, count, callback) {
             var q = null;
            // Get Flickr API key: http://www.flickr.com/services/api/keys/apply/
            var API_KEY = "{your_api_key}";
            start = parseInt(start) || 0;
            count = parseInt(count) || 10;
            q = 'select * from flickr.photos.search(' + start + ',' + count + ')  where text="%' + query + '%" and api_key="' + API_KEY+ '"';
            Y.YQL(q, function(rawData) {
              if (!rawData.query.results) {
                callback([]);
                return;
              }
              var rawImages = rawData.query.results.photo, rawImage = null,images = [], image = null, i = 0;
              for (; i<rawImages.length; i++) {
                rawImage = rawImages[i];
                image = {
                  title: rawImage.title,
                  location: 'http://farm' + rawImage.farm + '.static.flickr.com/' + rawImage.server + '/' + rawImage.id + '_' + rawImage.secret + '.jpg',
                  farm: rawImage.farm,
                  server: rawImage.server,
                  image_id: rawImage.id,
                  secret: rawImage.secret
                };
                if (!image.title) {
                  image.title = "Generic Title: " + query;
                }
                images.push(image);
              }
              callback(images);
            });
          }
        };
      }, '0.0.1', {requires: ['yql']});

#. To create the binder for click events and invoke the ``index`` function of the
   controller, replace the code in ``binders/index.js`` with the code below. Again,
   Be sure to replace the ``'{your_flickr_api_key}'`` with your own Flickr API key.

   .. code-block:: javascript

      YUI.add('pager-binder-index', function(Y, NAME) {
        var API_KEY = '{your_flickr_api_key}';
        function parseImageId(link) {
          var matches = link.match(/com\/(\d+)\/(\d+)_([0-9a-z]+)\.jpg$/);
          return matches[2];
        }
        function parsePage(link) {
          var matches = link.match(/page=(\d+)/);
          return matches[1];
        }

        /**
        * The pager-binder-index module.
        * @module pager-binder-index
        */
        /**
        * Constructor for the Binder class.
        *
        * @param mojitProxy {Object} The proxy to allow
        * the binder to interact with its owning mojit.
        * @class Binder
        * @constructor
        */
        Y.namespace('mojito.binders')[NAME] = {
          /**
          * Binder initialization method, invoked
          * after all binders on the page have
          * been constructed.
          */
          init: function(mojitProxy) {
            this.mojitProxy = mojitProxy;
          },
          /**
          * The binder method, invoked to allow the mojit
          * to attach DOM event handlers.
          * @param node {Node} The DOM node to which this
          * mojit is attached.
          */
          bind: function(node) {
            var thatNode = node;
            Y.log('NODE: ' + Y.dump(this.node));
            // define the action when user click on prev/next
            var flipper = function(event) {
              var target = event.target;
              // get the link to the page
              var page = parsePage(target.get('href'));
              Y.log('PAGE: ' + page);
              var updateDOM = function(markup) {
                thatNode.set('innerHTML', markup);
                thatNode.all('#nav a').on('click', flipper, this);
                thatNode.all('#master ul li a').on('mouseover', showOverlay, this);
                thatNode.all('#master ul li a').on('mouseout', showOverlay, this);
              };
              this.mojitProxy.invoke('index',
                {
                  params: {
                    url: {
                      page: page
                    }
                  }
                }, updateDOM
              );
            };
            var showOverlay = function(event) {
              var target = event.target;
              var href = target.get('href');
              var imageId = parseImageId(href);
              if (target.hasClass('overlayed')) {
                target.removeClass('overlayed');
                thatNode.one('#display').setContent('');
              } else {
                Y.log('HREF: ' + href);
                Y.log('IMAGE ID: ' + imageId);
                target.addClass('overlayed');
                // Query for the image metadata
                var query = 'select * from flickr.photos.info where photo_id="' + imageId + '" and api_key="' + API_KEY + '"';
                thatNode.one('#display').setContent('Loading ...');
                Y.YQL(query, function(raw) {
                  if (!raw.query.results.photo) {
                    Y.log('No results found for photoId: ' + imageId);
                    return;
                  }
                  var props = raw.query.results.photo;
                  var snippet = '
';
                  for (var key in props) {
                    if (typeof(props[key]) == 'object') {
                      continue;
                    }
                    snippet += '
' + key + ': ' + props[key] + '
';
                  }
                  snippet += '
';
                  thatNode.one('#display').setContent(snippet);
                });
              }
            };
            // Bind all the image links to showOverlay
            thatNode.all('#master ul li a').on('mouseover', showOverlay, this);
            thatNode.all('#master ul li a').on('mouseout', showOverlay, this);
            // Bind the prev + next links to flipper
            thatNode.all('#nav a').on('click', flipper, this);
          }
        };
      }, '0.0.1', {requires: ['yql', 'io', 'dump']});

#. To display links to photos and associated photo data in the rendered template, replace
   the code in ``views/index.hb.html`` with the following:

   .. code-block:: html

Query Term: {{query}}

        {{#hasLink}}
          {{#prev}}
          {{title}}
          {{/prev}}
        {{/hasLink}}
        {{^hasLink}}
          {{#prev}}{{title}}{{/prev}}
        {{/hasLink}}
        {{#next}}
          {{title}}
        {{/next}}

          {{#data}}

{{title}}

          {{/data}}

#. From the application directory, run the server.

   ``$ node app.js``
#. To view your application, go to the URL:

   http://localhost:8666

.. _code_exs_events-src:

Source Code
===========

- `Application Configuration <http://github.com/yahoo/mojito/tree/master/examples/developer-guide/binding_events/application.json>`_
- `Mojit Binder <http://github.com/yahoo/mojito/tree/master/examples/developer-guide/binding_events/mojits/Pager/binders/index.js>`_
- `Binding Events Application <http://github.com/yahoo/mojito/tree/master/examples/developer-guide/binding_events/>`_


text:
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.provider;

import org.eclipse.emf.common.ui.celleditor.ExtendedDialogCellEditor;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.ui.provider.PropertyDescriptor;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.wso2.developerstudio.eclipse.gmf.esb.ValidateMediator;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.configure.ui.ValidateFeatureDialog;

public class ValidateFeaturePropertyDescriptor extends PropertyDescriptor {

	public ValidateFeaturePropertyDescriptor(Object object,
			IItemPropertyDescriptor itemPropertyDescriptor) {
		super(object, itemPropertyDescriptor);

	}

	public CellEditor createPropertyEditor(Composite parent) {
		return new ExtendedDialogCellEditor(parent, getLabelProvider()) {

			protected Object openDialogBox(Control cellEditorWindow) {
				Display display = Display.getDefault();
				Shell shell = new Shell(display);

				ValidateMediator  validateMediator = (ValidateMediator)object;

				ValidateFeatureDialog featureDialog = new ValidateFeatureDialog(shell,validateMediator);
				featureDialog.setBlockOnOpen(true);
				featureDialog.open();
				return null;
			}
		};
	}

}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

require('./email_in_use');
require('./compare_to');
require('./loading_progress');
require('./file_reader');
require('./profile_picture');

require('./overlay');

require('./media_picker');
require('./picture_media_picker');
require('./video_media_picker');
require('./youtube_media_picker');

require('./media_renderer');
require('./picture_renderer');
require('./video_renderer');
require('./youtube_renderer');

require('./workout_builder/workout_renderer');
require('./workout_builder/speed_time_renderer');
require('./workout_builder/set_renderer');
require('./workout_builder/set_element_renderer');
require('./workout_builder/set_element_modification_renderer');

require('./font_awesome_centered_icon');
require('./font_awesome_icon_text');

require('./confirm_click');

require('./workout_widget');
require('./workout_icons');

require('./question_widget');

require('./collapsible_content');

require('./clipboard_copy_link');
require('./clipboard_paste');

require('./hover_options_overlay');

require('./comment');

require('./user_link');

require('./notifications_button');
require('./notification');


text:
package geojson

import (
	"fmt"
)

// SetProperty provides the inverse of all the property functions
// and is here for consistency.
func (f *Feature) SetProperty(key string, value interface{}) {
	if f.Properties == nil {
		f.Properties = make(map[string]interface{})
	}
	f.Properties[key] = value
}

// PropertyBool type asserts a property to `bool`.
func (f *Feature) PropertyBool(key string) (bool, error) {
	if b, ok := (f.Properties[key]).(bool); ok {
		return b, nil
	}
	return false, fmt.Errorf("type assertion of `%s` to bool failed", key)
}

// PropertyInt type asserts a property to `int`.
func (f *Feature) PropertyInt(key string) (int, error) {
	if i, ok := (f.Properties[key]).(int); ok {
		return i, nil
	}

	if i, ok := (f.Properties[key]).(float64); ok {
		return int(i), nil
	}

	return 0, fmt.Errorf("type assertion of `%s` to int failed", key)
}

// PropertyFloat64 type asserts a property to `float64`.
func (f *Feature) PropertyFloat64(key string) (float64, error) {
	if i, ok := (f.Properties[key]).(float64); ok {
		return i, nil
	}
	return 0, fmt.Errorf("type assertion of `%s` to float64 failed", key)
}

// PropertyString type asserts a property to `string`.
func (f *Feature) PropertyString(key string) (string, error) {
	if s, ok := (f.Properties[key]).(string); ok {
		return s, nil
	}
	return "", fmt.Errorf("type assertion of `%s` to string failed", key)
}

// PropertyMustBool guarantees the return of a `bool` (with optional default)
//
// useful when you explicitly want a `bool` in a single value return context:
//     myFunc(f.PropertyMustBool("param1"), f.PropertyMustBool("optional_param", true))
func (f *Feature) PropertyMustBool(key string, def ...bool) bool {
	var defaul bool

	b, err := f.PropertyBool(key)
	if err == nil {
		return b
	}

	if len(def) > 0 {
		defaul = def[0]
	}

	return defaul
}

// PropertyMustInt guarantees the return of a `int` (with optional default)
//
// useful when you explicitly want a `int` in a single value return context:
//     myFunc(f.PropertyMustInt("param1"), f.PropertyMustInt("optional_param", 123))
func (f *Feature) PropertyMustInt(key string, def ...int) int {
	var defaul int

	b, err := f.PropertyInt(key)
	if err == nil {
		return b
	}

	if len(def) > 0 {
		defaul = def[0]
	}

	return defaul
}

// PropertyMustFloat64 guarantees the return of a `float64` (with optional default)
//
// useful when you explicitly want a `float64` in a single value return context:
//     myFunc(f.PropertyMustFloat64("param1"), f.PropertyMustFloat64("optional_param", 10.1))
func (f *Feature) PropertyMustFloat64(key string, def ...float64) float64 {
	var defaul float64

	b, err := f.PropertyFloat64(key)
	if err == nil {
		return b
	}

	if len(def) > 0 {
		defaul = def[0]
	}

	return defaul
}

// PropertyMustString guarantees the return of a `string` (with optional default)
//
// useful when you explicitly want a `string` in a single value return context:
//     myFunc(f.PropertyMustString("param1"), f.PropertyMustString("optional_param", "default"))
func (f *Feature) PropertyMustString(key string, def ...string) string {
	var defaul string

	b, err := f.PropertyString(key)
	if err == nil {
		return b
	}

	if len(def) > 0 {
		defaul = def[0]
	}

	return defaul
}


text:
package com.github.yannicklamprecht.worldborder.plugin;

import com.github.yannicklamprecht.worldborder.api.*;
import org.bukkit.Location;
import org.bukkit.NamespacedKey;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.persistence.PersistentDataContainer;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.Vector;

import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

public class PersistenceWrapper implements PersistentWorldBorderApi {

    private final WorldBorderApi worldBorderApi;
    private final NamespacedKey worldBorderDataKey;
    private final WorldBorderDataTagType worldBorderDataTagType;

    public PersistenceWrapper(JavaPlugin javaPlugin, WorldBorderApi worldBorderApi) {
        this.worldBorderApi = worldBorderApi;
        this.worldBorderDataKey = new NamespacedKey(javaPlugin, "world_border_data");
        this.worldBorderDataTagType = new WorldBorderDataTagType(javaPlugin);
    }

    @Override
    public IWorldBorder getWorldBorder(Player p) {
        IWorldBorder worldBorder = worldBorderApi.getWorldBorder(p);
        PersistentDataContainer persistentDataContainer = p.getPersistentDataContainer();
        if (persistentDataContainer.has(worldBorderDataKey, worldBorderDataTagType)) {
            applyWorldDataToWorldBorder(worldBorder, persistentDataContainer.get(worldBorderDataKey, worldBorderDataTagType));
        }
        return worldBorder;
    }

    @Override
    public IWorldBorder getWorldBorder(World world) {
        return worldBorderApi.getWorldBorder(world);
    }

    @Override
    public void resetWorldBorderToGlobal(Player player) {
        worldBorderApi.resetWorldBorderToGlobal(player);
        PersistentDataContainer persistentDataContainer = player.getPersistentDataContainer();
        if (persistentDataContainer.has(worldBorderDataKey, worldBorderDataTagType)) {
            persistentDataContainer.remove(worldBorderDataKey);
        }
    }

    @Override
    public void setBorder(Player player, double size) {
        worldBorderApi.setBorder(player, size);
        modifyAndUpdateWorldData(player, worldBorderData -> worldBorderData.setSize(size));
    }

    @Override
    public void setBorder(Player player, double size, Vector vector) {
        setBorder(player, size, Position.of(vector));
    }

    @Override
    public void setBorder(Player player, double size, Location location) {
        setBorder(player, size, Position.of(location));
    }

    @Override
    public void setBorder(Player player, double size, Position position) {
        worldBorderApi.setBorder(player, size, position);
        modifyAndUpdateWorldData(player, worldBorderData -> {
            worldBorderData.setSize(size);
            worldBorderData.setCenter(position.x(), position.z());
        });
    }

    @Override
    public void sendRedScreenForSeconds(Player player, long timeSeconds, JavaPlugin javaPlugin) {
        worldBorderApi.sendRedScreenForSeconds(player, timeSeconds, javaPlugin);
    }

    @Override
    public void setBorder(Player player, double size, long milliSeconds) {
        worldBorderApi.setBorder(player, size, milliSeconds);
        modifyAndUpdateWorldData(player, worldBorderData -> worldBorderData.setSize(size));
    }

    @Override
    public void setBorder(Player player, double size, long time, TimeUnit timeUnit) {
        worldBorderApi.setBorder(player, size, time, timeUnit);
        modifyAndUpdateWorldData(player, worldBorderData -> worldBorderData.setSize(size));
    }

    @Override
    public WorldBorderData getWorldBorderData(Player p) {
        PersistentDataContainer persistentDataContainer = p.getPersistentDataContainer();
        if (persistentDataContainer.has(worldBorderDataKey, worldBorderDataTagType)) {
            return persistentDataContainer.get(worldBorderDataKey, worldBorderDataTagType);
        }
        return null;
    }

    private void applyWorldDataToWorldBorder(IWorldBorder iWorldBorder, WorldBorderData worldBorderData) {
        worldBorderData.applyCenter((x, z) -> iWorldBorder.setCenter(new Position(x, z)));
        iWorldBorder.setSize(worldBorderData.getSize());
        iWorldBorder.setDamageBufferInBlocks(worldBorderData.getDamageBuffer());
        iWorldBorder.setDamagePerSecondPerBlock(worldBorderData.getDamageAmount());
        iWorldBorder.setWarningDistanceInBlocks(worldBorderData.getWarningDistance());
        iWorldBorder.setWarningTimeInSeconds(worldBorderData.getWarningTimeSeconds());
    }

    private void modifyAndUpdateWorldData(Player player, Consumer<WorldBorderData> worldBorderDataConsumer) {
        PersistentDataContainer persistentDataContainer = player.getPersistentDataContainer();
        WorldBorderData worldBorderData = new WorldBorderData();
        if (persistentDataContainer.has(worldBorderDataKey, worldBorderDataTagType)) {
            worldBorderData = persistentDataContainer.get(worldBorderDataKey, worldBorderDataTagType);
        }
        worldBorderDataConsumer.accept(worldBorderData);
        persistentDataContainer.set(worldBorderDataKey, worldBorderDataTagType, worldBorderData);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<QCARConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="qcar_config.xsd">
  <Tracking>
    <ImageTarget name="zombie" size="17.000000 11.555992" />
    <CylinderTarget name="SodaOrigin" sideLength="9.150000"/>
    <CylinderTarget name="SodaDiet" sideLength="9.030000"/>
  </Tracking>
</QCARConfig>


text:
@media screen and (min-width: 0px) and (max-width: 991px) {
  /* do not show it on small screens */
  #updateDiv { display: none; }
  #deleteDiv { display: none; }
  #addDiv { display: none; }
  #displayCollection { display: none; }
  #fakediv { display: none; }

}

@media screen and (min-width: 992px) {
  /* do not show it on big screens */
  #instaDiv { display: none; }
}

#instagramMessage {
	text-align: center;
}

#emailform {
	float:left;
}

.form-group {
	margin-left: 20px;
}

#heading {
	text-align: center;
}

#wrapper {
	margin-left: 20px;
	margin-right: 20px;
}

.nav-wrapper {
	padding-left: 10px;
	padding-right: 10px;
}

#images {
	text-align: center;
}

#home {
	text-align: center;
}

.form-signin-heading {
	text-align: center;
}


text:
module WorkhorseHelpers
  extend self

  def workhorse_send_data
    @_workhorse_send_data ||= begin
      header = response.headers[Gitlab::Workhorse::SEND_DATA_HEADER]
      split_header = header.split(':')
      type = split_header.shift
      header = split_header.join(':')
      [
        type,
        JSON.parse(Base64.urlsafe_decode64(header)),
      ]
    end
  end
end


text:
using System.Data.Common;
using System.Data.SqlClient;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Z.Data.Test
{
    [TestClass]
    public class System_Data_Common_DbCommand_ExecuteExpandoObject
    {
        [TestMethod]
        public void ExecuteExpandoObject()
        {
            string sql = "SELECT 1 AS IntColumn, 'FizzBuzz' AS StringColumn";

            // Examples
            using (var conn = new SqlConnection(My.Config.ConnectionString.UnitTest.ConnectionString))
            {
                conn.Open();
                using (DbCommand command = conn.CreateCommand())
                {
                    command.CommandText = sql;
                    dynamic entity = command.ExecuteExpandoObject();

                    // Unit Test
                    Assert.AreEqual(1, entity.IntColumn);
                    Assert.AreEqual("FizzBuzz", entity.StringColumn);
                }
            }
        }
    }
}


text:
using AspNet.Security.OpenIdConnect.Extensions;
using AspNet.Security.OpenIdConnect.Server;
using AspNetApiMonolithSample.Api.Models;
using AspNetApiMonolithSample.Api.Mvc;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Authentication;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using OpenIddict;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Threading.Tasks;

namespace AspNetApiMonolithSample.Api.Controllers
{
    /// <summary>
    /// OpenId specific actions, not to be used in API calls
    /// </summary>
    [Route("[controller]")]
    [ApiExplorerSettings(IgnoreApi = true)]
    public class OpenIdController : ControllerBase
    {
        private readonly ILogger _logger;
        private readonly OpenIddictApplicationManager<OpenIddictApplication> _applicationManager;
        private readonly SignInManager<User> _signInManager;
        private readonly UserManager<User> _userManager;
        private readonly UiBrandingHtmlConfiguration _brandingHtml;
        private readonly IOptions<Dictionary<string, OpenIddictApplication>> _officialApplications;
        private readonly MvcJsonOptions _mvcJsonOptions;
        private readonly JwtConfiguration _jwtConfiguration;

        public OpenIdController(
            ILoggerFactory loggerFactory,
            IOptions<UiBrandingHtmlConfiguration> brandingHtml,
            IOptions<Dictionary<string, OpenIddictApplication>> officialApplications,
            IOptions<MvcJsonOptions> mvcJsonOptions,
            IOptions<JwtConfiguration> jwtConfiguration,
            OpenIddictApplicationManager<OpenIddictApplication> applicationManager,
            SignInManager<User> signInManager,
            UserManager<User> userManager)
        {
            _logger = loggerFactory.CreateLogger<OpenIdController>();
            _applicationManager = applicationManager;
            _signInManager = signInManager;
            _userManager = userManager;
            _brandingHtml = brandingHtml.Value;
            _officialApplications = officialApplications;
            _mvcJsonOptions = mvcJsonOptions.Value;
            _jwtConfiguration = jwtConfiguration.Value;
        }

        /// <summary>
        /// Logs out from all applications by removing the Identity cookies
        /// </summary>
        /// <returns></returns>
        [HttpGet("[action]")]
        public async Task<IActionResult> Logout()
        {
            await _signInManager.SignOutAsync();
            return SignOut(OpenIdConnectServerDefaults.AuthenticationScheme);
        }

        // Fatal errors are such that are not recoverable, error must be shown, it's not possible to login
        public enum FatalErrors
        {
            UserNotFound,
            InvalidClient,
            RedirectMissing,
        }

        // Login errors are recoverable, new login attempt may work
        public enum LoginErrors
        {
            Ok,
            LockedOut,
            NotAllowed,
            UsernameOrPassword,
            EmailIsNotConfirmed,
        }

        [HttpGet("[action]")]
        public IActionResult Login(
            [FromQuery] LoginErrors error = LoginErrors.Ok,
            [FromQuery] string returnUrl = "",
            [FromQuery] string display = "")
        {
            // TODO: Anti forgery token for login
            var data = JsonConvert.SerializeObject(new
            {
                Display = display,
                Error = error.ToString(),
                FormMethod = "POST",
                FormAction = Url.Action(nameof(LoginPost), new
                {
                    returnUrl = returnUrl,
                    display = display
                }),
                FormData = new
                {
                    Email = "",
                    Password = "",
                    RememberMe = "",
                }
            }, _mvcJsonOptions.SerializerSettings);

            return new ContentResult()
            {
                Content = $@"<!DOCTYPE html>
                    <html>
                    <head>
                    <script>var OPENID_LOGIN_PAGE = {data};</script>
                    {_brandingHtml?.Login}
                    </head>
                    <body>
                    <form action=""{Url.Action(nameof(LoginPost), new { returnUrl = returnUrl, display = display })}"" method=""POST"">
                    <input type=""email"" name=""Email"" placeholder=""EMAIL"" required />
                    <input type=""password"" name=""Password"" placeholder=""PASSWORD"" required />
                    <input type=""checkbox"" name=""RememberMe"" value=""1"" title=""REMEMBER_ME"" />
                    <button type=""submit"">LOGIN</button>
                    ",
                ContentType = "text/html; charset=utf8"
            };
        }

        public class LoginViewModel
        {
            [Required]
            [EmailAddress]
            public string Email { get; set; }

            [Required]
            [DataType(DataType.Password)]
            public string Password { get; set; }

            [Display(Name = "Remember me?")]
            public string RememberMe { get; set; }
        }

        /// <summary>
        /// Handle login
        /// </summary>
        [HttpPost("Login")] // TODO: Anti forgery token
        public async Task<IActionResult> LoginPost(
            [FromForm] LoginViewModel model,
            [FromQuery] string returnUrl = "",
            [FromQuery] string display = "")
        {
            if (returnUrl.Length == 0)
            {
                return RedirectToAction(nameof(ErrorController.Error), nameof(ErrorController), new { message = FatalErrors.RedirectMissing });
            }

            var user = await _userManager.FindByEmailAsync(model.Email);
            if (user != null)
            {
                if (!await _userManager.IsEmailConfirmedAsync(user))
                {
                    return RedirectToLogin(LoginErrors.EmailIsNotConfirmed, returnUrl, display);
                }
            }

            var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe != "", lockoutOnFailure: false);
            if (result.Succeeded)
            {
                return Redirect(returnUrl);
            }
            else if (result.RequiresTwoFactor)
            {
                //return RedirectToAction(nameof(SendCode),
                //    new { returnUrl = returnUrl, RememberMe = model.RememberMe });
                // TODO: TWO FACTOR INPUT
                // _brandingHtml?.TwoFactor
                return new OkObjectResult("TODO: TWO FACTOR");
            }
            else if (result.IsLockedOut)
            {
                return RedirectToLogin(LoginErrors.LockedOut, returnUrl, display);
            }
            else if (result.IsNotAllowed)
            {
                return RedirectToLogin(LoginErrors.NotAllowed, returnUrl, display);
            }
            return RedirectToLogin(LoginErrors.UsernameOrPassword, returnUrl, display);
        }

        /// <summary>
        /// Authorize OpenId request, shows the accept or deny dialog if applicable
        /// </summary>
        [Authorize(Policy="COOKIES"), HttpGet("[action]"), HttpPost("[action]")]
        public virtual async Task<IActionResult> Authorize([RequestUser] User requestUser,
            [FromQuery] string returnUrl = "")
        {
            if (requestUser == null)
            {
                return Redirect("/OpenId/Login?ReturnUrl=" + returnUrl);
            }
            // Identity cookie that is not valid anymore (e.g. deleted user), still gets through
            // the [Authorize] attribute by design. Check that user actually exists.
            var user = await _userManager.GetUserAsync(HttpContext.User);
            if (user == null)
            {
                await _signInManager.SignOutAsync();
                return Redirect(HttpContext.Request.GetEncodedUrl());
            }

            // Extract the authorization request from the ASP.NET environment.
            var request = HttpContext.GetOpenIdConnectRequest();

            // Retrieve the application details from the database.
            var application = await _applicationManager.FindByClientIdAsync(request.ClientId);
            if (application == null)
            {
                return RedirectToAction(nameof(ErrorController.Error), nameof(ErrorController), new { message = FatalErrors.InvalidClient });
            }

            // Check if the application is official (registered in settings) and
            // accept any request by default
            if (_officialApplications.Value.Any(x => x.Value.ClientId == request.ClientId))
            {
                return await Accept();
            }

            var appName = await _applicationManager.GetDisplayNameAsync(application);
            var inputs = "";
            var hiddenParams = new Dictionary<string, string> { { "request_id", request.RequestId } };
            foreach (var item in hiddenParams)
            {
                var key = WebUtility.HtmlEncode(item.Key);
                var value = WebUtility.HtmlEncode(item.Value);
                inputs = inputs + $@"<input type=""hidden"" name=""{key}"" value=""{value}"" />";
            }

            // TODO: Anti forgery token for Accept and Deny
            var data = JsonConvert.SerializeObject(new
            {
                Display = request.GetParameter("display"),
                Scopes = request.GetScopes().ToList(),
                FormMethod = "POST",
                FormActionAccept = Url.Action(nameof(Accept)),
                FormActionDeny = Url.Action(nameof(Deny)),
                ApplicationName = appName,
                FormData = hiddenParams
            }, _mvcJsonOptions.SerializerSettings);

            return new ContentResult()
            {
                Content = $@"<!DOCTYPE html>
                    <html>
                    <head>
                    <script>var OPENID_AUTHORIZE_PAGE = {data};</script>
                    {_brandingHtml?.Authorize}
                    </head>
                    <body>
                    <form enctype=""application/x-www-form-urlencoded"" method=""POST"">
                    {inputs}
                    <div>{WebUtility.HtmlEncode(appName)}</div>
                    <button formaction=""{Url.Action(nameof(Accept))}"" type=""submit"" />ACCEPT</button>
                    <button formaction=""{Url.Action(nameof(Deny))}"" type=""submit"">DENY</button>
                ",
                ContentType = "text/html; charset=utf8"
            };
        }

        /// <summary>
        /// Accept the application request
        /// </summary>
        [Authorize(Policy = "COOKIES"), HttpPost("Authorize/[action]")] // TODO: Anti forgery token
        public virtual async Task<IActionResult> Accept()
        {
            // Extract the authorization request from the ASP.NET environment.
            var request = HttpContext.GetOpenIdConnectRequest();

            // Retrieve the profile of the logged in user.
            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                await _signInManager.SignOutAsync();
                return RedirectToAction(nameof(ErrorController.Error), nameof(ErrorController), new { message = FatalErrors.UserNotFound });
            }

            // Create a new authentication ticket.
            var ticket = await CreateTicketAsync(request, user);

            // Returning a SignInResult will ask OpenIddict to issue the appropriate access/identity tokens.
            return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
        }

        /// <summary>
        /// Deny the application request
        /// </summary>
        [Authorize(Policy = "COOKIES"), HttpPost("Authorize/[action]")] // TODO: Anti forgery token
        public IActionResult Deny()
        {
            // Notify OpenIddict that the authorization grant has been denied by the resource owner
            // to redirect the user agent to the client application using the appropriate response_mode.
            return Forbid(OpenIdConnectServerDefaults.AuthenticationScheme);
        }

        private async Task<AuthenticationTicket> CreateTicketAsync(OpenIdConnectRequest request, User user)
        {
            // Create a new ClaimsPrincipal containing the claims that
            // will be used to create an id_token, a token or a code.
            var principal = await _signInManager.CreateUserPrincipalAsync(user);

            // Add your application specific claims, e.g. if user owns a Thingie, this is a good way to
            // cache user's ownership of the Thingie
            if (principal.Identity.IsAuthenticated && principal.Identity is ClaimsIdentity)
            {
                (principal.Identity as ClaimsIdentity).AddClaim(new Claim(AspNetApiMonolithSampleConstants.Claims.OwnsThingie, "12345"));
            }

            // Note: by default, claims are NOT automatically included in the access and identity tokens.
            // To allow OpenIddict to serialize them, you must attach them a destination, that specifies
            // whether they should be included in access tokens, in identity tokens or in both.

            foreach (var claim in principal.Claims)
            {
                // In this sample, every claim is serialized in both the access and the identity tokens.
                // In a real world application, you'd probably want to exclude confidential claims
                // or apply a claims policy based on the scopes requested by the client application.
                claim.SetDestinations(OpenIdConnectConstants.Destinations.AccessToken,
                                      OpenIdConnectConstants.Destinations.IdentityToken);
            }

            // Create a new authentication ticket holding the user identity.
            var ticket = new AuthenticationTicket(
                principal, new AuthenticationProperties(),
                OpenIdConnectServerDefaults.AuthenticationScheme);

            // Set the list of scopes granted to the client application.
            // Note: the offline_access scope must be granted
            // to allow OpenIddict to return a refresh token.
            ticket.SetScopes(new[] {
                OpenIdConnectConstants.Scopes.OpenId,
                OpenIdConnectConstants.Scopes.Email,
                OpenIdConnectConstants.Scopes.Profile,
                OpenIdConnectConstants.Scopes.OfflineAccess,
                OpenIddictConstants.Scopes.Roles,
                AspNetApiMonolithSampleConstants.Scopes.ApiUser,
            }.Intersect(request.GetScopes()));

            ticket.SetResources(new string[]
            {
                _jwtConfiguration.Audience
            });

            return ticket;
        }

        private IActionResult RedirectToLogin(LoginErrors error, String returnUrl, String display = "")
        {
            return RedirectToAction(nameof(Login), new { error = error, returnUrl = returnUrl, display = display });
        }
    }
}


text:
namespace Zmey
{

EntityId EntityManager::SpawnOne()
{
	if (m_FreeIndices.size() == 0)
	{
		m_Generation.push_back(0);
		return EntityId(static_cast<uint32_t>(m_Generation.size() - 1u), 0u);
	}
	else
	{
		uint32_t freeIndex = m_FreeIndices.front();
		m_FreeIndices.pop();
		return EntityId(freeIndex, m_Generation[freeIndex]);
	}
}

tmp::vector<EntityId> EntityManager::SpawnRange(EntityId::IndexType count)
{
	tmp::vector<EntityId> entities;
	entities.reserve(count);
	for (EntityId::IndexType i = 0; i < count; i++)
	{
		entities.push_back(SpawnOne());
	}
	return entities;
}

void EntityManager::Destroy(EntityId id)
{
	if (m_Generation[id.Index] != id.Generation)
	{
		return;
	}
	++m_Generation[id.Index];
	m_FreeIndices.push(id.Index);
}
bool EntityManager::IsAlive(EntityId id)
{
	return m_Generation[id.Index] == id.Generation;
}

}


text:
import argparse
from nose.tools import assert_equal

from IPython.core.magic_arguments import (argument, argument_group, kwds,
    magic_arguments, parse_argstring, real_name)

@magic_arguments()
@argument('-f', '--foo', help="an argument")
def magic_foo1(self, args):
    """ A docstring.
    """
    return parse_argstring(magic_foo1, args)

@magic_arguments()
def magic_foo2(self, args):
    """ A docstring.
    """
    return parse_argstring(magic_foo2, args)

@magic_arguments()
@argument('-f', '--foo', help="an argument")
@argument_group('Group')
@argument('-b', '--bar', help="a grouped argument")
@argument_group('Second Group')
@argument('-z', '--baz', help="another grouped argument")
def magic_foo3(self, args):
    """ A docstring.
    """
    return parse_argstring(magic_foo3, args)

@magic_arguments()
@kwds(argument_default=argparse.SUPPRESS)
@argument('-f', '--foo', help="an argument")
def magic_foo4(self, args):
    """ A docstring.
    """
    return parse_argstring(magic_foo4, args)

@magic_arguments('frobnicate')
@argument('-f', '--foo', help="an argument")
def magic_foo5(self, args):
    """ A docstring.
    """
    return parse_argstring(magic_foo5, args)

@magic_arguments()
@argument('-f', '--foo', help="an argument")
def magic_magic_foo(self, args):
    """ A docstring.
    """
    return parse_argstring(magic_magic_foo, args)

@magic_arguments()
@argument('-f', '--foo', help="an argument")
def foo(self, args):
    """ A docstring.
    """
    return parse_argstring(foo, args)

def test_magic_arguments():
    assert_equal(magic_foo1.__doc__, '::\n\n  %foo1 [-f FOO]\n\n A docstring.\n\noptional arguments:\n  -f FOO, --foo FOO  an argument\n')
    assert_equal(getattr(magic_foo1, 'argcmd_name', None), None)
    assert_equal(real_name(magic_foo1), 'foo1')
    assert_equal(magic_foo1(None, ''), argparse.Namespace(foo=None))
    assert hasattr(magic_foo1, 'has_arguments')

    assert_equal(magic_foo2.__doc__, '::\n\n  %foo2\n\n A docstring.\n')
    assert_equal(getattr(magic_foo2, 'argcmd_name', None), None)
    assert_equal(real_name(magic_foo2), 'foo2')
    assert_equal(magic_foo2(None, ''), argparse.Namespace())
    assert hasattr(magic_foo2, 'has_arguments')

    assert_equal(magic_foo3.__doc__, '::\n\n  %foo3 [-f FOO] [-b BAR] [-z BAZ]\n\n A docstring.\n\noptional arguments:\n  -f FOO, --foo FOO  an argument\n\nGroup:\n  -b BAR, --bar BAR  a grouped argument\n\nSecond Group:\n  -z BAZ, --baz BAZ  another grouped argument\n')
    assert_equal(getattr(magic_foo3, 'argcmd_name', None), None)
    assert_equal(real_name(magic_foo3), 'foo3')
    assert_equal(magic_foo3(None, ''),
                       argparse.Namespace(bar=None, baz=None, foo=None))
    assert hasattr(magic_foo3, 'has_arguments')

    assert_equal(magic_foo4.__doc__, '::\n\n  %foo4 [-f FOO]\n\n A docstring.\n\noptional arguments:\n  -f FOO, --foo FOO  an argument\n')
    assert_equal(getattr(magic_foo4, 'argcmd_name', None), None)
    assert_equal(real_name(magic_foo4), 'foo4')
    assert_equal(magic_foo4(None, ''), argparse.Namespace())
    assert hasattr(magic_foo4, 'has_arguments')

    assert_equal(magic_foo5.__doc__, '::\n\n  %frobnicate [-f FOO]\n\n A docstring.\n\noptional arguments:\n  -f FOO, --foo FOO  an argument\n')
    assert_equal(getattr(magic_foo5, 'argcmd_name', None), 'frobnicate')
    assert_equal(real_name(magic_foo5), 'frobnicate')
    assert_equal(magic_foo5(None, ''), argparse.Namespace(foo=None))
    assert hasattr(magic_foo5, 'has_arguments')

    assert_equal(magic_magic_foo.__doc__, '::\n\n  %magic_foo [-f FOO]\n\n A docstring.\n\noptional arguments:\n  -f FOO, --foo FOO  an argument\n')
    assert_equal(getattr(magic_magic_foo, 'argcmd_name', None), None)
    assert_equal(real_name(magic_magic_foo), 'magic_foo')
    assert_equal(magic_magic_foo(None, ''), argparse.Namespace(foo=None))
    assert hasattr(magic_magic_foo, 'has_arguments')

    assert_equal(foo.__doc__, '::\n\n  %foo [-f FOO]\n\n A docstring.\n\noptional arguments:\n  -f FOO, --foo FOO  an argument\n')
    assert_equal(getattr(foo, 'argcmd_name', None), None)
    assert_equal(real_name(foo), 'foo')
    assert_equal(foo(None, ''), argparse.Namespace(foo=None))
    assert hasattr(foo, 'has_arguments')


text:
namespace ApplicationInsights
{
	namespace core
	{
		class TELEMETRYCLIENT_API TelemetryContext : public BaseTelemetryContext
		{
		public:
			/// <summary>
			/// Stores the context.
			/// </summary>
			/// <param name="iKey">The iKey.</param>
			/// <returns></returns>
			TelemetryContext(const std::wstring& iKey);

			/// <summary>
			/// Finalizes an instance of the <see cref=""/> class.
			/// </summary>
			/// <returns></returns>
			virtual ~TelemetryContext();

			/// <summary>
			/// Initializes the user.
			/// </summary>
			virtual void InitUser();

			/// <summary>
			/// Initializes the device.
			/// </summary>
			virtual void InitDevice();

			/// <summary>
			/// Initializes the application.
			/// </summary>
			virtual void InitApplication();

			/// <summary>
			/// Initializes the session.
			/// </summary>
			virtual void InitSession();
		};
	}
}
#endif


text:
import * as enzyme from 'enzyme';
import adapter from 'enzyme-adapter-react-16';

enzyme.configure({
  adapter: new adapter(),
});


text:
			<img src="<?php echo base_url(); ?>assets/admin/img/logo.png" id="logoimg" alt=" Logo" />

				<?php
				$attlogin = array("id"=>"loginform", "name"=>"loginform", "class"=>"form-signin");
				echo form_open("panel/login", $attlogin);?>

						Enter your username and password

					<input type="text" name="username" id="username" placeholder="Username" class="form-control" />
					<input type="password" name="password" id="password" placeholder="Password" class="form-control" />
					<input class="btn text-center btn-success large" type="submit" id="btn_login" name="btn_login" value="Sign into your account">
				<?php echo form_close(); ?>
				<?php echo $this->session->flashdata('msg'); ?>

				<?php
				$attforgot = array("id"=>"forgotform", "name"=>"forgotform", "class"=>"form-signin");
				echo form_open("panel/forgot", $attforgot);?>

Enter your valid e-mail

					<input type="email"  required="required" placeholder="Your E-mail"  class="form-control" />

					<button class="btn text-muted text-center btn-success" type="submit">Recover Password</button>
				<?php echo form_close(); ?>
				<?php echo $this->session->flashdata('msg'); ?>

Login

Forgot Password


text:
""" Standalone webinterface for Openstack Swift. """

import re
import string
import random
import logging

from urllib.parse import urlparse

from django.conf import settings
from django.contrib import messages
from django.utils.translation import gettext

from swiftclient import client
from identity.keystone import KeystoneNoRequest

log = logging.getLogger(__name__)

def get_storage_endpoint(request, endpoint_type):
    """
    service_catalog na sessao eh referente a conexao com o project "admin"
    para retornar o endpoint do "project_id" da sessao, usa-se o service_catalog
    do project "admin", substituindo o project_id

    Isto eh necessario pois a conexao com o Keystone eh sempre com o mesmo
    project, nao estando disponivel de forma direta o service_catalog de um
    project qualquer

    :param request: http resquest
    :param endpoint_type: adminURL, publicURL, internalURL
    :return: endpoint url or None

    """
    service_catalog = request.session.get('service_catalog')
    project_id = request.session.get('project_id')

    if service_catalog is None or project_id is None:
        msg = gettext('No project selected')
        log.error(msg)
        messages.add_message(request, messages.ERROR, msg)
        return None

    service = service_catalog.get('object_store')
    endpoint_on_session = service.get(endpoint_type)

    if endpoint_on_session is None:
        return None

    _, project_admin_id = endpoint_on_session.split('AUTH_')

    final_url = endpoint_on_session.replace(project_admin_id, project_id)

    return final_url

def get_token_id(request):
    return request.session.get('auth_token')

def replace_hyphens(olddict):
    """ Replaces all hyphens in dict keys with an underscore.

    Needed in Django templates to get a value from a dict by key name. """
    newdict = {}
    for key, value in olddict.items():
        key = key.replace('-', '_')
        newdict[key] = value
    return newdict

def prefix_list(prefix):
    prefixes = []

    if prefix:
        elements = prefix.split('/')
        elements = filter(None, elements)
        prefix = ""
        for element in elements:
            prefix += element + '/'
            prefixes.append({'display_name': element, 'full_name': prefix})

    return prefixes

def pseudofolder_object_list(objects, prefix, public_url):
    pseudofolders = []
    objs = []
    duplist = []

    for obj in objects:
        # Rackspace Cloudfiles uses application/directory
        # Cyberduck uses application/x-directory
        if obj.get('content_type', None) in ('application/directory',
                                             'application/x-directory'):
            obj['subdir'] = obj['name']

        if 'subdir' in obj:
            # make sure that there is a single slash at the end
            # Cyberduck appends a slash to the name of a pseudofolder
            entry = obj['subdir'].strip('/') + '/'
            if entry != prefix and entry not in duplist:
                duplist.append(entry)
                # pseudofolders.append((entry, obj['subdir']))
                pseudofolders.append({'prefix': entry, 'name': obj['subdir']})
        else:
            # verifico se e um internal folder
            # se for, preciso redirecionar pra i.s3
            pattern = re.compile('^internal_.+')
            if pattern.match(public_url.split('/')[-1]):
                public_url = public_url.replace('://s3.', '://i.s3.')
            obj['public_url'] = public_url + '/' + obj['name']
            objs.append(obj)

    # return (pseudofolders, objs)
    return pseudofolders + objs

def get_temp_key(storage_url, auth_token, http_conn):
    """ Tries to get meta-temp-url key from account.
    If not set, generate tempurl and save it to account.
    This requires at least account owner rights. """

    try:
        account = client.get_account(storage_url, auth_token,
                                     http_conn=http_conn)
    except client.ClientException:
        return None

    key = account[0].get('x-account-meta-temp-url-key')

    if not key:
        chars = string.ascii_lowercase + string.digits
        key = ''.join(random.choice(chars) for x in range(32))
        headers = {'x-account-meta-temp-url-key': key}

        try:
            client.post_account(storage_url, token=auth_token, headers=headers,
                                http_conn=http_conn)
        except client.ClientException:
            return None
    return key

def get_acls(storage_url, auth_token, container, http_conn):
    """ Returns ACLs of given container. """
    acls = client.head_container(storage_url,
                                 auth_token,
                                 container,
                                 http_conn=http_conn)

    readers = acls.get('x-container-read', '')
    writers = acls.get('x-container-write', '')
    return (readers, writers)

def get_cors(storage_url, auth_token, container, http_conn):
    """ Returns CORS header of given container. """
    headers = client.head_container(storage_url,
                                    auth_token,
                                    container,
                                    http_conn=http_conn)

    cors = headers.get('x-container-meta-access-control-allow-origin', '')

    return cors

def remove_duplicates(text, separator):
    """ Removes possible duplicates from a separator-separated list. """
    entries = text.split(separator)
    cleaned_entries = list(set(entries))
    text = separator.join(cleaned_entries)
    return text

def remove_duplicates_from_acl(acls):
    """ Removes possible duplicates from a comma-separated list. """
    return remove_duplicates(acls, ',')

def remove_duplicates_from_cors(cors):
    """ Removes possible duplicates from a space-separated list. """
    return remove_duplicates(cors, ' ')

def get_account_containers(storage_url, auth_token):
    """ List all containers in an account"""
    container_list = []
    http_conn = client.http_connection(storage_url,
                                       insecure=settings.SWIFT_INSECURE)

    _, containers = client.get_account(storage_url, auth_token,
                                       http_conn=http_conn)

    for container in containers:
        container_list.append(container['name'])

    return container_list

def get_container_objects(container, storage_url, auth_token):
    object_list = []
    http_conn = client.http_connection(storage_url, insecure=settings.SWIFT_INSECURE)

    _, objects = client.get_container(storage_url, auth_token, container,
                                      http_conn=http_conn)

    for object in objects:
        object_list.append(object['name'])

    return object_list

def update_swift_account(user, password, project_name, headers):
    keystone = KeystoneNoRequest(user, password, project_name)
    endpoints = keystone.get_endpoints()
    storage_url = endpoints.get("object_store").get("adminURL")
    http_conn = client.http_connection(
        storage_url, insecure=settings.SWIFT_INSECURE)

    try:
        client.post_account(storage_url,
            keystone.conn.auth_token, headers, http_conn=http_conn)
    except client.ClientException as err:
        log.exception('Exception: {}'.format(err))
        return False

    return True

def delete_swift_account(storage_url, auth_token):
    insecure = settings.SWIFT_INSECURE

    try:
        # Criar container vazio para garantir que o account existe no swift
        http_conn = client.http_connection(storage_url, insecure=insecure)

        client.put_container(storage_url, auth_token, 'dummy_container',
            http_conn=http_conn)
        client.delete_container(storage_url, auth_token, 'dummy_container',
            http_conn=http_conn)
    except client.ClientException as err:
        log.exception('Fail to create container "dummy_container": {0}'.format(err))
        return False

    try:
        # Deletar o account
        url = urlparse(storage_url)
        domain = '{}://{}'.format(url.scheme, url.netloc)
        path = url.path

        http_conn = client.HTTPConnection(domain, insecure=insecure)
        headers = {'X-Auth-Token': auth_token}

        resp = http_conn.request('DELETE', path, headers=headers)

        if resp.status_code != 204:
            error_msg = resp.json().get('error')
            log.exception('Fail to delete account {}: {}, status code {}'.format(
                storage_url, error_msg, resp.status_code))
            return False, error_msg

    except client.ClientException as err:
        log.exception(f'Exception: {err}')
        return False, str(err)

    return True, 'success'

def get_name_from_document(data):
    return data.get('_source').get('object')

def get_uri_object_from_document(data):
    return data.get('hits').get('hits')[0].get('_id')


text:
Player::Player(float x, float y, int speed) : DamnCute::APlayer("resources/player_dark.png", x, y, 0, speed), _life(2), _whichWorld(__dark)
{
    _tex1.loadFromFile("resources/player_dark.png");
    _tex2.loadFromFile("resources/player_light.png");
    _tex = _tex2;

    setHitboxPosition(23, 32);

    addAction(new ActMoveX(this, sf::Keyboard::Key::Left,
                sf::Keyboard::Key::Right, sf::Joystick::X));
    addAction(new ActMoveY(this, sf::Keyboard::Key::Up,
                sf::Keyboard::Key::Down, sf::Joystick::Y));
    addAction(new ActFocus(this, sf::Keyboard::Key::LShift, 2));
    addAction(new ActWeapon(this, sf::Keyboard::Key::Space, 0));
}

void Player::toggle() {

    if (_whichWorld == __dark) {
        _whichWorld = __light;
        _tex = _tex1;
    }
    else {
        _whichWorld = __dark;
        _tex = _tex2;
    }

}