text:
.. _aiohttp-web:

HTTP Server Usage
=================

.. highlight:: python

.. currentmodule:: aiohttp.web

.. versionchanged:: 0.12

   The module was deeply refactored in backward incompatible manner.

Run a simple web server
-----------------------

For implementing a web server, first create a :ref:`request
handler<aiohttp-web-handler>`.

Handler is a :ref:`coroutine<coroutine>` or a regular function that
accepts only *request* parameter of type :class:`Request`
and returns :class:`Response` instance::

   import asyncio
   from aiohttp import web

   @asyncio.coroutine
   def hello(request):
       return web.Response(body=b"Hello, world")

Next, you have to create a :class:`Application` instance and register
:ref:`handler<aiohttp-web-handler>` in the application's router pointing *HTTP
method*, *path* and *handler*::

   app = web.Application()
   app.router.add_route('GET', '/', hello)

After that, create a server and run the *asyncio loop* as usual::

   loop = asyncio.get_event_loop()
   f = loop.create_server(app.make_handler(), '0.0.0.0', 8080)
   srv = loop.run_until_complete(f)
   print('serving on', srv.sockets[0].getsockname())
   try:
       loop.run_forever()
   except KeyboardInterrupt:
       pass

That's it.

.. _aiohttp-web-handler:

Handler
-------

Handler is an any *callable* that accepts a single :class:`Request`
argument and returns a :class:`StreamResponse` derived
(e.g. :class:`Response`) instance.

Handler **may** be a :ref:`coroutine<coroutine>`, :mod:`aiohttp.web` will
**unyield** returned result by applying ``yield from`` to the handler.

Handlers are connected to the :class:`Application` via routes::

   handler = Handler()
   app.router.add_route('GET', '/', handler)

.. _aiohttp-web-variable-handler:

You can also use *variable routes*. If route contains string like
``'/a/{name}/c'`` that means the route matches to the path like
``'/a/b/c'`` or ``'/a/1/c'``.

Parsed *path part* will be available in the *request handler* as
``request.match_info['name']``::

   @asyncio.coroutine
   def variable_handler(request):
       return web.Response(
           text="Hello, {}".format(request.match_info['name']))

   app.router.add_route('GET', '/{name}', variable_handler)

Also you can specify regex for variable route in form ``{name:regex}``::

   app.router.add_route('GET', r'/{name:\d+}', variable_handler)

By default regex is ``[^{}/]+``.

.. versionadded:: 0.13

   Support for custom regexs in variable routes.

Handlers *may* be first-class functions, e.g.::

   @asyncio.coroutine
   def hello(request):
       return web.Response(body=b"Hello, world")

   app.router.add_route('GET', '/', hello)

But sometimes you would like to group logically coupled handlers into a
python class.

:mod:`aiohttp.web` doesn't dictate any implementation details,
so application developer can use classes if he wants::

   class Handler:

       def __init__(self):
           pass

       def handle_intro(self, request):
           return web.Response(body=b"Hello, world")

       @asyncio.coroutine
       def handle_greeting(self, request):
           name = request.match_info.get('name', "Anonymous")
           txt = "Hello, {}".format(name)
           return web.Response(text=txt)

   handler = Handler()
   app.router.add_route('GET', '/intro', handler.handle_intro)
   app.router.add_route('GET', '/greet/{name}', handler.handle_greeting)

Custom conditions for routes lookup
-----------------------------------

Sometimes you need to distinguish *web-handlers* on more complex
criteria than *HTTP method* and *path*.

While :class:`UrlDispatcher` doesn't accept extra criterias there is
easy way to do the task by implementing the second routing layer by
hands.

The example shows custom processing based on *HTTP Accept* header:

.. code-block:: python

   class AcceptChooser:

       def __init__(self):
           self._accepts = {}

       @asyncio.coroutine
       def do_route(self, request):
           for accept in request.headers.getall('ACCEPT', []):
                acceptor = self._accepts.get(accept):
                if acceptor is not None:
                    return (yield from acceptor(request))
           raise HTTPNotAcceptable()

       def reg_acceptor(self, accept, handler):
           self._accepts[accept] = handler

   @asyncio.coroutine
   def handle_json(request):
       # do json handling

   @asyncio.coroutine
   def handle_xml(request):
       # do xml handling

   chooser = AcceptChooser()
   app.router.add_route('GET', '/', chooser.do_route)

   chooser.reg_acceptor('application/json', handle_json)
   chooser.reg_acceptor('application/xml', handle_xml)

.. _aiohttp-web-file-upload:

File Uploads
------------

There are two steps necessary for handling file uploads. The first is
to make sure that you have a form that has been setup correctly to accept
files. This means adding *enctype* attribute to your form element with
the value of *multipart/form-data*. A very simple example would be a
form that accepts a mp3 file. Notice, we have set up the form as
previously explained and also added the *input* element of the *file*
type:

.. code-block:: html

   <form action="/store_mp3" method="post" accept-charset="utf-8"
         enctype="multipart/form-data">

       <label for="mp3">Mp3</label>
       <input id="mp3" name="mp3" type="file" value="" />

       <input type="submit" value="submit" />
   </form>

The second step is handling the file upload in your :ref:`request
handler<aiohttp-web-handler>` (here assumed to answer on
*/store_mp3*). The uploaded file is added to the request object as a
:class:`FileField` object accessible through the :meth:`Request.post`
coroutine. The two properties we are interested in are
:attr:`~FileField.file` and :attr:`~FileField.filename` and we will
use those to read a file's name and a content:

.. code-block:: python

    @asyncio.coroutine
    def store_mp3_view(request):

        data = yield from request.post()

        # filename contains the name of the file in string format.
        filename = data['mp3'].filename

        # input_file contains the actual file data which needs to be
        # stored somewhere.

        input_file = data['mp3'].file

        content = input_file.read()

        return web.Response(body=content,
                            headers=MultiDict(
                                {'CONTENT-DISPOSITION': input_file})

.. _aiohttp-web-websockets:

WebSockets
----------

.. versionadded:: 0.14

:mod:`aiohttp.web` works with websockets out-of-the-box.

You have to create :class:`WebSocketResponse` in
:ref:`web-handler<aiohttp-web-handler>` and communicate with peer
using response's methods::

    @asyncio.coroutine
    def websocket_handler(request):

        ws = web.WebSocketResponse()
        ws.start(request)

        while True:
            try:
                data = yield from ws.receive_str()
                if data == 'close':
                    ws.close()
                else:
                    ws.send_str(data + '/answer')
            except web.WSClientDisconnectedError as exc:
                print(exc.code, exc.message)
                return ws

You can have the only websocket reader task (which can call ``yield
from ws.receive_str()``) and multiple writer tasks which can only send
data asynchronously (by ``yield from ws.send_str('data')`` for example).

.. _aiohttp-web-exceptions:

Exceptions
----------

:mod:`aiohttp.web` defines exceptions for list of *HTTP status codes*.

Each class relates to a single HTTP status code.  Each class is a
subclass of the :class:`~HTTPException`.

Those exceptions are derived from :class:`Response` too, so you can
either return exception object from :ref:`aiohttp-web-handler` or raise it.

The following snippets are equal::

    @asyncio.coroutine
    def handler(request):
        return aiohttp.web.HTTPFound('/redirect')

and::

    @asyncio.coroutine
    def handler(request):
        raise aiohttp.web.HTTPFound('/redirect')

Each exception class has a status code according to :rfc:`2068`:
codes with 100-300 are not really errors; 400s are client errors,
and 500s are server errors.

Http Exception hierarchy chart::

   Exception
     HTTPException
       HTTPSuccessful
         * 200 - HTTPOk
         * 201 - HTTPCreated
         * 202 - HTTPAccepted
         * 203 - HTTPNonAuthoritativeInformation
         * 204 - HTTPNoContent
         * 205 - HTTPResetContent
         * 206 - HTTPPartialContent
       HTTPRedirection
         * 300 - HTTPMultipleChoices
         * 301 - HTTPMovedPermanently
         * 302 - HTTPFound
         * 303 - HTTPSeeOther
         * 304 - HTTPNotModified
         * 305 - HTTPUseProxy
         * 307 - HTTPTemporaryRedirect
       HTTPError
         HTTPClientError
           * 400 - HTTPBadRequest
           * 401 - HTTPUnauthorized
           * 402 - HTTPPaymentRequired
           * 403 - HTTPForbidden
           * 404 - HTTPNotFound
           * 405 - HTTPMethodNotAllowed
           * 406 - HTTPNotAcceptable
           * 407 - HTTPProxyAuthenticationRequired
           * 408 - HTTPRequestTimeout
           * 409 - HTTPConflict
           * 410 - HTTPGone
           * 411 - HTTPLengthRequired
           * 412 - HTTPPreconditionFailed
           * 413 - HTTPRequestEntityTooLarge
           * 414 - HTTPRequestURITooLong
           * 415 - HTTPUnsupportedMediaType
           * 416 - HTTPRequestRangeNotSatisfiable
           * 417 - HTTPExpectationFailed
         HTTPServerError
           * 500 - HTTPInternalServerError
           * 501 - HTTPNotImplemented
           * 502 - HTTPBadGateway
           * 503 - HTTPServiceUnavailable
           * 504 - HTTPGatewayTimeout
           * 505 - HTTPVersionNotSupported

All http exceptions have the same constructor::

    HTTPNotFound(*, headers=None, reason=None,
                 body=None, text=None, content_type=None)

if other not directly specified. *headers* will be added to *default
response headers*.

Classes :class:`HTTPMultipleChoices`, :class:`HTTPMovedPermanently`,
:class:`HTTPFound`, :class:`HTTPSeeOther`, :class:`HTTPUseProxy`,
:class:`HTTPTemporaryRedirect` has constructor signature like::

    HTTPFound(location, *, headers=None, reason=None,
              body=None, text=None, content_type=None)

where *location* is value for *Location HTTP header*.

:class:`HTTPMethodNotAllowed` constructed with pointing trial method
and list of allowed methods::

    HTTPMethodNotAllowed(method, allowed_methods, *,
                         headers=None, reason=None,
                         body=None, text=None, content_type=None)

.. _aiohttp-web-middlewares:

Middlewares
-----------

.. versionadded:: 0.13

:class:`Application` accepts optional *middlewares* keyword-only
parameter, which should be a sequence of *middleware factories*, e.g::

   app = web.Application(middlewares=[middleware_factory_1,
                                      middleware_factory_2])

The most trivial *middleware factory* example::

    @asyncio.coroutine
    def middleware_factory(app, handler):
        @asyncio.coroutine
        def middleware(request):
            return (yield from handler(request))
        return middleware

Every factory is a coroutine that accepts two parameters: *app*
(:class:`Application` instance) and *handler* (next handler in
middleware chain.

The last handler is :ref:`web-handler<aiohttp-web-handler>` selected
by routing itself (:meth:`~UrlDispatcher.resolve` call).

Middleware should return new coroutine by wrapping *handler*
parameter. Signature of returned handler should be the same as for
:ref:`web-handler<aiohttp-web-handler>`: accept single *request*
parameter, return *response* or raise exception.

The factory is a coroutine, thus it can do extra ``yield from`` calls
on making new handler, e.g. call database etc.

After constructing outermost handler by applying middleware chain to
:ref:`web-handler<aiohttp-web-handler>` in reversed order
:class:`RequestHandler` executes the outermost handler as regular
*web-handler*.

Middleware usually calls an inner handler, but may do something
other, like displaying *403 Forbidden page* or raising
:exc:`HTTPForbidden` exception if user has no permissions to access underlying
resource.  Also middleware may render errors raised by handler, do
some pre- and post- processing like handling *CORS* and so on.

.. versionchanged:: 0.14

   Middleware accepts route exceptions (:exc:`HTTPNotFound` and
   :exc:`HTTPMethodNotAllowed`).


text:
// Generated by xsd compiler for android/java
// DO NOT CHANGE!
package com.ebay.trading.api;

/**
 *
 * This type is deprecated as <b>GetProduct*</b> calls were deprecated.
 *
 *
 */
public enum ProductSortCodeType {

    /**
     *
   *
   * Sort by product popularity (as determined by eBay),
   * and return the most popular products first.
   *
     */
    POPULARITY_ASC("PopularityAsc"),

    /**
     *
   *
   * Sort by product popularity (as determined by eBay),
   * and return the least popular products first.
   *
     */
    POPULARITY_DESC("PopularityDesc"),

    /**
     *
   *
   * Sort by average rating, and return the lowest rated
   * products first.
   *
     */
    RATING_ASC("RatingAsc"),

    /**
     *
   *
   * Sort by average rating, and return the highest rated
   * products first.
   *
     */
    RATING_DESC("RatingDesc"),

    /**
     *
   *
   * Sort by the number of reviews, and return products with
   * the fewest reviews first.
   *
     */
    REVIEW_COUNT_ASC("ReviewCountAsc"),

    /**
     *
   *
   * Sort by the number of reviews, and return products with
   * the most reviews first.
   *
     */
    REVIEW_COUNT_DESC("ReviewCountDesc"),

    /**
     *
   *
   * Sort by the number of active items listed with this product,
   * and return products with the fewest items first.
   *
     */
    ITEM_COUNT_ASC("ItemCountAsc"),

    /**
     *
   *
   * Sort by the number of active items listed with this product,
   * and return products with the most items first.
   *
     */
    ITEM_COUNT_DESC("ItemCountDesc"),

    /**
     *
   *
   * Sort by the product title, and return products in ascending order.
   * For example, with Western character sets, this means alphabetical order
   * (e.g., A to Z), where titles that start with the word "A" appear
   * before titles that start with the word "The".
   *
     */
    TITLE_ASC("TitleAsc"),

    /**
     *
   *
   * Sort by the product title, and return products in reverse order
   * (e.g., Z to A).
   *
     */
    TITLE_DESC("TitleDesc"),

    /**
     *
   *
   * Reserved for values that are not available in the version of the schema
   * you are using. If eBay adds a new value to this code type as of a
   * particular version, we return CustomCode when you specify a
   * lower request version.
   *
     */
    CUSTOM_CODE("CustomCode");

    private final String value;

    ProductSortCodeType(String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    public static ProductSortCodeType fromValue(String v) {
        if (v != null) {
            for (ProductSortCodeType c: ProductSortCodeType.values()) {
                if (c.value.equals(v)) {
                    return c;
                }
            }
        }
        throw new IllegalArgumentException(v);
    }
}

redpajama_set_name: RedPajamaGithub


text:
#if AutoCAD
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
#endif

#if BricsCAD
using Teigha.Runtime;
using Teigha.DatabaseServices;
using Teigha.Geometry;
using Bricscad.ApplicationServices;
using Bricscad.EditorInput;
#endif

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

namespace Geo7.Tools
{
	public class SlopeCommand : AcCommand
    {
		protected override void ExecuteCore()
		{
			this.DisplayErrormMessageBox = false;
			this.DimStyleId = AcDwgDb.ImportMissedDimStyle("G7-Slope", Geo7App.Geo7Dwg);

			do
			{
				PromptPointResult ptRes = Ac.Editor.GetPoint("\r\n" + AppServices.Strings.EnterStartPoint);
                if (!ptRes.IsOK())
                    return;
				var startPnt = ptRes.Value;

                var epPrtOpts = Ac.Editor.GetPromptPointOptions("\r\n" + AppServices.Strings.EnterEndPoint, startPnt, true);
                ptRes = Ac.Editor.GetPoint(epPrtOpts);
                if (!ptRes.IsOK())
					return;

				var endPnt = ptRes.Value;

				AddSlope(startPnt, endPnt);

			} while (true);
		}

		ObjectId DimStyleId;

		private void AddSlope(Point3d startPnt, Point3d endPnt)
		{
			var dx = endPnt.X - startPnt.X;
			var dy = endPnt.Y - startPnt.Y;
			var dz = endPnt.Z - startPnt.Z;
			Vector2d v = new Vector2d(dx, dy);
			var slope = dz / v.Length;

			using (var trans = Ac.StartTransaction())
			{
				var dimText = (slope * 100).ToString("0.0") + @"%";
				AlignedDimension dim = new AlignedDimension(startPnt, endPnt, startPnt, dimText, this.DimStyleId);
                dim.LayerId = trans.CurrentLayer.Id;

                trans.AddEntity(dim);
				trans.Commit();
			}
		}

	}

}


text:
<?php
// Text
$_['text_title']			   = 'Cartão de crédito ou débito (Cardinity)';
$_['text_payment_success']	   = 'Pagamento confirmado! Detalhes abaixo:';
$_['text_payment_failed']	   = 'Pagamento não aprovado! Detalhes abaixo:';

// Entry
$_['entry_holder']			   = 'Titular do cartão';
$_['entry_pan']				   = 'Número do cartão';
$_['entry_expires']			   = 'Expira em';
$_['entry_exp_month']		   = 'Mês';
$_['entry_exp_year']		   = 'Ano';
$_['entry_cvc']				   = 'Código de segurança (CVV2)';

// Error
$_['error_process_order']	   = 'Houve um erro ao processar seu pedido. Entre em contato com nosso atendimento e informe este erro.';
$_['error_invalid_currency']   = 'A moeda escolhida não é aceita.';
$_['error_finalizing_payment'] = 'Erro ao confirmar o pagamento.';
$_['error_unknown_order_id']   = 'Não doi possível localiar o pagamento para este pedido.';
$_['error_invalid_hash']	   = 'Hash inválido.';
$_['error_payment_declined']   = 'O pagamento foi recusado pelo banco emissor do cartão.';

// Button
$_['button_confirm']		   = 'Pagar agora';


text:
(function (root, factory) {
    if (typeof module !== 'undefined' && module.exports) {
        //commonjs
        module.exports = factory();
    } else if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define([], factory);
    } else {

        root.elliptical.ControllerDecorators = factory();
        root.returnExports = root.elliptical.ControllerDecorators;
    }
}(this, function () {

    return{
        get:function(target, prop, descriptor){
            var fn=descriptor.value;
            descriptor.value={
                method:'get',
                value:fn
            }
        },
        post:function(target, prop, descriptor){
            var fn=descriptor.value;
            descriptor.value={
                method:'post',
                value:fn
            }
        },
        put:function(target, prop, descriptor){
            var fn=descriptor.value;
            descriptor.value={
                method:'put',
                value:fn
            }
        },
        delete:function(target, prop, descriptor){
            var fn=descriptor.value;
            descriptor.value={
                method:'delete',
                value:fn
            }
        }
    }

}));


text:
Date: Tue, 26 Nov 1996 22:51:18 GMT
Server: NCSA/1.4.2
Content-type: text/html
Last-modified: Tue, 05 Nov 1996 20:17:49 GMT
Content-length: 5051

<TITLE>COMPUTER SCIENCE DEPARTMENT at OKLAHOMA STATE UNIVERSITY</TITLE>

COMPUTER SCIENCE DEPARTMENT

OKLAHOMA STATE UNIVERSITY

Department Head: Blayne E. Mayfield

Computer Science Department

219 Mathematical Sciences

Stillwater, OK 74078-1053

Phone: (405) 744-5668

Fax: (405) 744-9097

  The Computer Science Department welcomes three new Assistant Professors to our department this fall semester.  They are:

John Hatcliff - from Kansas State University.  His interest areas are:
programming languages, program specialization and verification, logic and
type theory.

Kathleen Kaplan - from George Washington University.   Her interest areas
are: pattern recognition, string matching, biochemistry.

Nick Street - from University of Wisconsin-Madison.  His interest areas
are: machine learning, artificial intelligence in medicine, and mathematical
optimization.

The Computer Science Department   is located in the
<!WA0>College of Arts and Sciences.  The program emphasizes the software or  programming aspects of computing.  The department
offers three degrees.  These are :

<!WA1>Bachelor of Science in Computer Science

<!WA2>Masters of Science in Computer Science

<!WA3>Doctor of Philosophy in Computer Science

The number of students enrolled on the OSU campus for Fall, 1996 was:

       Undergraduates: 181
       Masters:        123
       Ph.D:            12

         Total         316

There are also students enrolled in the Telecommunications Management
Masters Degree.  There are 16 enrolled in the Computer Science area.

The number of students who graduated from the Computer Science Department
for the 1995-1996 year are:

       Undergraduates:  29
       Masters:         21
       Ph.Ds:            3

          Total         53

The department not only delivers three degree programs  on campus in Stillwater, but it  has a Master's program at University Center at Tulsa.  Some of the courses are taught by faculty in Tulsa but other  courses are offered by compressed video to Tulsa and to four other sites located at companies in Oklahoma.  With the start of <!WA4>OneNet in
the state of Oklahoma, the program will expand.

Computer Science has also been offering a course for NTU(National Technological University) for five years.  This course has students enrolled throughout the United States.

The department also plays a significant role in the Master of Science in Telecommunication Management program.  This is a program that combines courses from the Business College, Engineering College and the Arts and Sciences College.

The department has seminars of interest at various times during the semester.
These include both internal speakers and external speakers.  The seminar
series is organized and managed by the Public Relations Committee with
assistance of the local chapter of the Association for Computing Machinery.
Usually there is one seminar a month.  Check out the list of Seminars listed
in the Departmental Information area.

 More Departmental Information

<!WA5>Computer Science Faculty

<!WA6>Staff

<!WA7>
Departmental Seminars

<!WA8>Departmental Computer Resources

<!WA9>Financial Aid for Graduate Students

<!WA10>Computer Science Course Descriptions

<!WA11>Computer Science Graduate Students

<!WA12>Computer Job Related Information

<!WA13>Association of Computing Machinery

<!WA14>Internet Resources

 Other Resources about Oklahoma State University

<!WA15>OSU Home Page

<!WA16>OSU Career Services Office

<!WA17>OSU Catalog

<!WA18>OSU Catalog Information on Computer Science Department

 <!WA19>OSU Graduate College Information

<!WA20>Campus Map of Building Locations

<!WA21>Information on Stillwater

<!WA22>Information on Oklahoma

Judy Edgmand

<address>jje@cs.okstate.edu</address>


text:
#include "SKALE/Bone.hpp"
#include <math.h>
#include <algorithm>

namespace skl
{

	Bone::~Bone(void)
	{
	}

	Bone::Bone( float x, float y, float angle, float length, float minAngle,
		float maxAngle, bool relative, const std::string& name, Bone* parent /*= NULL*/ )
		: mX(x),mY(y),mAngle(angle),mLength(length),mName(name),
		mMinAngle(minAngle),mMaxAngle(maxAngle),mRelative(relative),
		mFrameX(0),mFrameY(0),mFrameAngle(0),mParent(parent),
		currentFrame(0),currentKeyFrameIndex(0),startKeyFrame(NULL),
		endKeyFrame(NULL),framesPerSecond(60),curIncreaseAngle(0.0f),
		remainingInterpolationFrames(0),mFixture(false)
	{
		mMinAngle = fmod(mMinAngle,SK_TWO_PI);
		mMaxAngle = fmod(mMaxAngle,SK_TWO_PI);
		mAngle = fmod(mAngle,SK_TWO_PI);
	}

	bool Bone::remove( Bone* child )
	{
		for(std::list<Bone>::iterator it = children.begin(); it != children.end(); ++it)
		{
			if(&(*it) == child)
			{
				children.erase(it);
				return true;
			}
		}

		return false;
	}

	void Bone::setAngle( float angle )
	{
		mAngle = angle;
	}

	const float& Bone::getAngle() const
	{
		return mAngle;
	}

	void Bone::setX( float x )
	{
		mX = x;
	}

	void Bone::setY( float y )
	{
		mY = y;
	}

	void Bone::set( float x, float y )
	{
		mX = x;
		mY = y;
	}

	void Bone::set( float x, float y, float angle )
	{
		set(x,y);
		setAngle(angle);
	}

	const float& Bone::getX() const
	{
		return mX;
	}

	const float& Bone::getY() const
	{
		return mY;
	}

	void Bone::setMinAngle( float minAngle )
	{
		mMinAngle = minAngle;
	}

	void Bone::setMaxAngle( float maxAngle )
	{
		mMaxAngle = maxAngle;
	}

	const float& Bone::getMinAngle() const
	{
		return mMinAngle;
	}

	const float& Bone::getMaxAngle() const
	{
		return mMaxAngle;
	}

	void Bone::setLength( float length )
	{
		mLength = abs(length);
	}

	void Bone::clear()
	{
		children.clear();
	}

	void Bone::setRelative( bool relative )
	{
		mRelative = relative;
	}

	bool Bone::isRelative() const
	{
		return mRelative;
	}

	Bone* Bone::add( float x, float y, float angle, float length,
					float minAngle, float maxAngle,
					const std::string& name /*= ""*/ )
	{
		children.push_back(Bone(x,y,angle,length
			,minAngle,maxAngle,true,name,this));
		return &children.back();
	}

	std::list<Bone>::iterator Bone::begin()
	{
		return children.begin();
	}

	std::list<Bone>::iterator Bone::end()
	{
		return children.end();
	}

	Bone* Bone::getParent() const
	{
		return mParent;
	}

	const std::string& Bone::getName() const
	{
		return mName;
	}

	int Bone::count() const
	{
		return children.size();
	}

	void Bone::setFrame( float frameX, float frameY, float FrameAngle )
	{
		mFrameX = frameX;
		mFrameY = frameY;
		mFrameAngle = FrameAngle;
	}

	const float& Bone::getFrameX() const
	{
		return mFrameX;
	}

	const float& Bone::getFrameY() const
	{
		return mFrameY;
	}

	const float& Bone::getLength() const
	{
		return mLength;
	}

	const float& Bone::getFrameAngle() const
	{
		return mFrameAngle;
	}

	void Bone::setName( const std::string &name )
	{
		mName = name;
		for(int i = 0; i < (int)mName.length(); ++i)
		{
			if(mName[i] == '\"')
			{
				mName[i] = '\'';
			}
		}
	}

	void Bone::addKeyFrame( const KeyFrame& keyFrame )
	{
		mKeyFrames.push_back(keyFrame);
		std::sort(mKeyFrames.begin(),mKeyFrames.end());
	}

	void Bone::addKeyFrames( const std::vector<KeyFrame>& keyFrames )
	{
		mKeyFrames = keyFrames;
		std::sort(mKeyFrames.begin(),mKeyFrames.end());
	}

	void Bone::interpolateIncreaseAngle()
	{
		if(!startKeyFrame && !endKeyFrame)
		{
			resetAnimation();
		}
		if(startKeyFrame && endKeyFrame && currentFrame >= startKeyFrame->getFrame())
		{
			bool CCW = abs(endKeyFrame->getValue() -
				startKeyFrame->getValue() ) > SK_PI;

			remainingInterpolationFrames = endKeyFrame->getFrame() - startKeyFrame->getFrame();

			//Linear interpolation
			if(CCW)
			{
				curIncreaseAngle = (SK_TWO_PI - endKeyFrame->getValue() -
					startKeyFrame->getValue()) / remainingInterpolationFrames;

				if(endKeyFrame->getValue() - startKeyFrame->getValue() > 0.0f)
				curIncreaseAngle = -curIncreaseAngle;
			}
			else
			{
				curIncreaseAngle = (endKeyFrame->getValue() -
					startKeyFrame->getValue()) / remainingInterpolationFrames;
			}
		}
		else
		{
			remainingInterpolationFrames = -1;
			curIncreaseAngle = 0.0f;
		}
	}

	void Bone::resetAnimation()
	{
		curIncreaseAngle = 0.0f;
		currentFrame = 0;
		currentKeyFrameIndex = 0;

		remainingInterpolationFrames = 0;
		if(mKeyFrames.size() >= 2)
		{
			startKeyFrame = &mKeyFrames[0];
			endKeyFrame = &mKeyFrames[1];
			currentKeyFrameIndex = 1;
			setAngle(startKeyFrame->getValue());
		}
		else
		{
			startKeyFrame = NULL;
			endKeyFrame = NULL;
		}
	}

	void Bone::processAnimation()
	{
		if(mKeyFrames.size() == 0)
		{
			return;
		}
		if (remainingInterpolationFrames > 0)
		{
			remainingInterpolationFrames--;
			setAngle(getAngle() + curIncreaseAngle);
		}

		if(remainingInterpolationFrames == 0)
		{
			interpolateIncreaseAngle();

			if(startKeyFrame && currentFrame < startKeyFrame->getFrame())
			{
				currentFrame++;
				return;
			}
			if(currentKeyFrameIndex + 1 < (int)mKeyFrames.size())
			{
				currentKeyFrameIndex++;
				startKeyFrame = endKeyFrame;

				endKeyFrame = &mKeyFrames[currentKeyFrameIndex];

			}
			else //End of animation
			{
				startKeyFrame = endKeyFrame;
				endKeyFrame = NULL;
			}
		}
		currentFrame++;
	}

	void Bone::setAsFixture( bool fixture )
	{
		mFixture = fixture;
	}

	bool Bone::isFixture() const
	{
		return mFixture;
	}

}


text:
Plugin.define "activeWeb-Content-Server" do
author "Brendan Coles <bcoles@gmail.com>" # 2011-03-25
version "0.2"
description "Content Server is a comprehensive, scalable content management platform for professional demands. It combines editorial system, website management and development environment for Web applications in one package."
website "http://www.active-web.de/"

# ShodanHQ results as at 2011-03-25 #
# 19 for X-AwCache

# Matches #
matches [

# Version Detection # HTML Comment
{ :version=>/<!--[\s]+page generated with activeWeb contentserver R([\d\.]+)/ },
{ :version=>/<!--[\s]+activeWeb cache extension R([\d\.]+)/ },

# HTML Comment
{ :text=>'<!-- AWNOCACHEBEGIN__AWNOCACHEBEGIN__AWNOCACHEBEGIN__AWNOCACHEBEGIN__AWNOCACHEBEGIN -->' },

# X-AwCache-* HTTP Server Header
{ :name=>"X-AwCache-FollowUp Header", :text=>"", :search=>"headers[x-awcache-followup]" },
{ :name=>"X-AwCache-Command Header", :text=>"", :search=>"headers[x-awcache-command]" },

# Technology Detection
{ :name=>"X-AwCache-ScriptTechnology Header", :string=>/^.*$/ ,:search=>"headers[x-awcache-scripttechnology]" },

]

end


text:
/* ###
 * IP: GHIDRA
 * REVIEWED: YES
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.program.util;

import ghidra.program.model.mem.MemoryBlock;
import ghidra.util.SystemUtilities;

/**
 * MemoryBlockDiff determines the types of differences between two memory blocks.
 */
public class MemoryBlockDiff {

	public static final int NAME          = 0x001;
	public static final int START_ADDRESS = 0x002;
	public static final int END_ADDRESS   = 0x004;
	public static final int SIZE          = 0x008;
	public static final int READ          = 0x010;
	public static final int WRITE         = 0x020;
	public static final int EXECUTE       = 0x040;
	public static final int VOLATILE      = 0x080;
	public static final int TYPE          = 0x100;
	public static final int INIT          = 0x200;
	public static final int SOURCE        = 0x400;
	public static final int COMMENT       = 0x800;
	public static final int ALL           = 0xFFF;

	private MemoryBlock block1;
	private MemoryBlock block2;
	private int diffFlags;

	/**
	 * Constructor. MemoryBlockDiff determines the types of differences
	 * between two memory blocks.
	 * @param block1 the first program's memory block
	 * @param block2 the second program's memory block
	 */
	public MemoryBlockDiff(MemoryBlock block1, MemoryBlock block2) {
		this.block1 = block1;
		this.block2 = block2;
		diffFlags = getDiffFlags();
	}

	MemoryBlock getBlock1() {
		return block1;
	}

	MemoryBlock getBlock2() {
		return block2;
	}

	/**
	 * Returns true if the memory block names differ.
	 */
	public boolean isNameDifferent() {
		return (diffFlags & NAME) != 0;
	}

	/**
	 * Returns true if the start addresses of the memory blocks differ.
	 */
	public boolean isStartAddressDifferent() {
		return (diffFlags & START_ADDRESS) != 0;
	}

	/**
	 * Returns true if the end addresses of the memory blocks differ.
	 */
	public boolean isEndAddressDifferent() {
		return (diffFlags & END_ADDRESS) != 0;
	}

	/**
	 * Returns true if the sizes of the memory blocks differ.
	 */
	public boolean isSizeDifferent() {
		return (diffFlags & SIZE) != 0;
	}

	/**
	 * Returns true if the memory blocks Read flags differ.
	 */
	public boolean isReadDifferent() {
		return (diffFlags & READ) != 0;
	}

	/**
	 * Returns true if the memory blocks Write flags differ.
	 */
	public boolean isWriteDifferent() {
		return (diffFlags & WRITE) != 0;
	}

	/**
	 * Returns true if the memory blocks Execute flags differ.
	 */
	public boolean isExecDifferent() {
		return (diffFlags & EXECUTE) != 0;
	}

	/**
	 * Returns true if the memory blocks Volatile flags differ.
	 */
	public boolean isVolatileDifferent() {
		return (diffFlags & VOLATILE) != 0;
	}

	/**
	 * Returns true if the type for the memory blocks differ.
	 */
	public boolean isTypeDifferent() {
		return (diffFlags & TYPE) != 0;
	}

	/**
	 * Returns true if the initialization of the memory blocks isn't the same.
	 */
	public boolean isInitDifferent() {
		return (diffFlags & INIT) != 0;
	}

	/**
	 * Returns true if the source for the memory blocks differ.
	 */
	public boolean isSourceDifferent() {
		return (diffFlags & SOURCE) != 0;
	}

	/**
	 * Returns true if the comments on the memory blocks differ.
	 */
	public boolean isCommentDifferent() {
		return (diffFlags & COMMENT) != 0;
	}

	/**
	 * Gets a string representation of the types of memory differences for this MemoryBlockDiff.
	 */
	public String getDifferencesAsString() {
		StringBuffer buf = new StringBuffer();
		if((diffFlags & NAME) != 0) {
			buf.append("Name ");
		}
		if((diffFlags & START_ADDRESS) != 0) {
			buf.append("StartAddress ");
		}
		if((diffFlags & END_ADDRESS) != 0) {
			buf.append("EndAddress ");
		}
		if((diffFlags & SIZE) != 0) {
			buf.append("Size ");
		}
		if((diffFlags & READ) != 0) {
			buf.append("R ");
		}
		if((diffFlags & WRITE) != 0) {
			buf.append("W ");
		}
		if((diffFlags & EXECUTE) != 0) {
			buf.append("X ");
		}
		if((diffFlags & VOLATILE) != 0) {
			buf.append("Volatile ");
		}
		if((diffFlags & TYPE) != 0) {
			buf.append("Type ");
		}
		if((diffFlags & INIT) != 0) {
			buf.append("Initialized ");
		}
		if((diffFlags & SOURCE) != 0) {
			buf.append("Source ");
		}
		if((diffFlags & COMMENT) != 0) {
			buf.append("Comment ");
		}
		return buf.toString();
	}

	/**
	 * Gets an integer value that has bits set as flags indicating the types of differences
	 * that exist between the two memory blocks.
	 * @param block1 the first program's memory block
	 * @param block2 the second program's memory block
	 * @return the memory difference flags
	 */
	private int getDiffFlags() {
		if (block1 == null) {
			if (block2 == null) {
				return 0;
			}
			return ALL;
		}
		if (block2 == null) {
			return ALL;
		}

		int flags = 0;
		if(!block1.getName().equals(block2.getName())) {
			flags |= NAME;
		}
		if (!block1.getStart().equals(block2.getStart())) {
			flags |= START_ADDRESS;
		}
		if (!block1.getEnd().equals(block2.getEnd())) {
			flags |= END_ADDRESS;
		}
		if (block1.getSize() != block2.getSize()) {
			flags |= SIZE;
		}
		if (block1.isRead() != block2.isRead()) {
			flags |= READ;
		}
		if (block1.isWrite() != block2.isWrite()) {
			flags |= WRITE;
		}
		if (block1.isExecute() != block2.isExecute()) {
			flags |= EXECUTE;
		}
		if (block1.isVolatile() != block2.isVolatile()) {
			flags |= VOLATILE;
		}
		if (!block1.getType().equals(block2.getType())) {
			flags |= TYPE;
		}
		if (block1.isInitialized() != block2.isInitialized()) {
			flags |= INIT;
		}
		if (!SystemUtilities.isEqual(block1.getSourceName(), block2.getSourceName())) {
			flags |= SOURCE;
		}
		if (!SystemUtilities.isEqual(block1.getComment(), block2.getComment())) {
			flags |= COMMENT;
		}
		return flags;
	}
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jdbi.v3.freemarker;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import org.jdbi.v3.core.Handle;
import org.jdbi.v3.core.Jdbi;
import org.jdbi.v3.core.Something;
import org.jdbi.v3.core.mapper.SomethingMapper;
import org.jdbi.v3.sqlobject.SqlObjectPlugin;
import org.jdbi.v3.sqlobject.customizer.BindBeanList;
import org.jdbi.v3.sqlobject.statement.SqlQuery;
import org.jdbi.v3.testing.junit5.JdbiExtension;
import org.jdbi.v3.testing.junit5.internal.TestingInitializers;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

public class BindBeanListTest {

    private Handle handle;

    private List<Something> expectedSomethings;

    @RegisterExtension
    public JdbiExtension h2Extension = JdbiExtension.h2().withInitializer(TestingInitializers.something());

    @BeforeEach
    public void before() {
        final Jdbi db = h2Extension.getJdbi();
        db.installPlugin(new SqlObjectPlugin());
        db.registerRowMapper(new SomethingMapper());
        handle = db.open();

        handle.execute("insert into something(id, name) values(1, '1')");
        handle.execute("insert into something(id, name) values(2, '2')");

        // "control group" element that should *not* be returned by the queries
        handle.execute("insert into something(id, name) values(3, '3')");

        expectedSomethings = Arrays.asList(new Something(1, "1"), new Something(2, "2"));
    }

    @AfterEach
    public void after() {
        handle.close();
    }

    //

    @Test
    public void testSomethingWithExplicitAttributeName() {
        final SomethingWithExplicitAttributeName s = handle.attach(SomethingWithExplicitAttributeName.class);

        final List<Something> out = s.get(
                new SomethingKey(1, "1"),
                new SomethingKey(2, "2"));

        assertThat(out).hasSameElementsAs(expectedSomethings);
    }

    @UseFreemarkerEngine
    public interface SomethingWithExplicitAttributeName {
        @SqlQuery("select id, name from something where (id, name) in (${keys})")
        List<Something> get(@BindBeanList(value = "keys", propertyNames = {"id", "name"})
                                    SomethingKey... blarg);
    }

    //

    @Test
    public void testSomethingByVarargsWithVarargs() {
        final SomethingByVarargs s = handle.attach(SomethingByVarargs.class);

        final List<Something> out = s.get(
                new SomethingKey(1, "1"),
                new SomethingKey(2, "2"));

        assertThat(out).hasSameElementsAs(expectedSomethings);
    }

    @Test
    public void testSomethingByVarargsWithEmptyVarargs() {
        final SomethingByVarargs s = handle.attach(SomethingByVarargs.class);

        assertThatThrownBy(s::get).isInstanceOf(IllegalArgumentException.class);
    }

    @UseFreemarkerEngine
    public interface SomethingByVarargs {
        @SqlQuery("select id, name from something where (id, name) in (${keys})")
        List<Something> get(@BindBeanList(propertyNames = {"id", "name"}) SomethingKey... keys);
    }

    //

    @Test
    public void testSomethingByArrayWithNull() {
        final SomethingByArray s = handle.attach(SomethingByArray.class);

        assertThatThrownBy(() -> s.get(null)).isInstanceOf(IllegalArgumentException.class);
    }

    @Test
    public void testSomethingByArrayWithEmptyArray() {
        final SomethingByArray s = handle.attach(SomethingByArray.class);

        assertThatThrownBy(() -> s.get(new SomethingKey[]{})).isInstanceOf(IllegalArgumentException.class);
    }

    @Test
    public void testSomethingByArrayWithNonEmptyArray() {
        final SomethingByVarargs s = handle.attach(SomethingByVarargs.class);

        final List<Something> out = s.get(
                new SomethingKey(1, "1"),
                new SomethingKey(2, "2"));

        assertThat(out).hasSameElementsAs(expectedSomethings);
    }

    @UseFreemarkerEngine
    private interface SomethingByArray {
        @SqlQuery("select id, name from something where (id, name) in (<keys>)")
        List<Something> get(@BindBeanList(propertyNames = {"id", "name"}) SomethingKey[] keys);
    }

    //

    @Test
    public void testSomethingByIterableWithIterable() {
        final SomethingByIterable s = handle.attach(SomethingByIterable.class);

        final List<Something> out = s.get(() -> Arrays.asList(new SomethingKey(1, "1"),
                new SomethingKey(2, "2"))
                .iterator());

        assertThat(out).hasSameElementsAs(expectedSomethings);
    }

    @Test
    public void testSomethingByIterableWithEmptyIterable() {
        final SomethingByIterable s = handle.attach(SomethingByIterable.class);

        assertThatThrownBy(() -> s.get(new ArrayList<>())).isInstanceOf(IllegalArgumentException.class);
    }

    @UseFreemarkerEngine
    public interface SomethingByIterable {
        @SqlQuery("select id, name from something where (id, name) in (${keys})")
        List<Something> get(@BindBeanList(propertyNames = {"id", "name"}) Iterable<SomethingKey> keys);
    }

    //

    public void testSomethingByIterator() {
        final SomethingByIterator s = handle.attach(SomethingByIterator.class);

        List<Something> results = s.get(Arrays.asList(
                new SomethingKey(1, "1"),
                new SomethingKey(2, "2"))
            .iterator());
        assertThat(results).hasSameElementsAs(expectedSomethings);
    }

    @UseFreemarkerEngine
    public interface SomethingByIterator {
        @SqlQuery("select id, name from something where (id, name) in (<keys>)")
        List<Something> get(@BindBeanList(propertyNames = {"id", "name"}) Iterator<SomethingKey> keys);
    }

    public static class SomethingKey {
        private final int id;
        private final String name;

        SomethingKey(int id, String name) {
            this.id = id;
            this.name = name;
        }

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }
    }
}


text: """ Test anthemav module """


text:
based on a template, this react app is a learning app

poker stats app


text:
package org.apache.guacamole.auth.totp.form;

import com.google.common.io.BaseEncoding;
import com.google.inject.Inject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import javax.ws.rs.core.UriBuilder;
import org.apache.guacamole.GuacamoleException;
import org.apache.guacamole.auth.totp.user.UserTOTPKey;
import org.apache.guacamole.auth.totp.conf.ConfigurationService;
import org.apache.guacamole.form.Field;
import org.apache.guacamole.totp.TOTPGenerator;
import org.codehaus.jackson.annotate.JsonProperty;

/**
 * Field which prompts the user for an authentication code generated via TOTP.
 */
public class AuthenticationCodeField extends Field {

    /**
     * The name of the HTTP parameter which will contain the TOTP code provided
     * by the user to verify their identity.
     */
    public static final String PARAMETER_NAME = "guac-totp";

    /**
     * The unique name associated with this field type.
     */
    private static final String FIELD_TYPE_NAME = "GUAC_TOTP_CODE";

    /**
     * The width of QR codes to generate, in pixels.
     */
    private static final int QR_CODE_WIDTH = 256;

    /**
     * The height of QR codes to generate, in pixels.
     */
    private static final int QR_CODE_HEIGHT = 256;

    /**
     * BaseEncoding which encodes/decodes base32.
     */
    private static final BaseEncoding BASE32 = BaseEncoding.base32();

    /**
     * Service for retrieving configuration information.
     */
    @Inject
    private ConfigurationService confService;

    /**
     * The TOTP key to expose to the user for the sake of enrollment, if any.
     * If no such key should be exposed to the user, this will be null.
     */
    private UserTOTPKey key;

    /**
     * Creates a new field which prompts the user for an authentication code
     * generated via TOTP. The user's TOTP key is not exposed for enrollment.
     */
    public AuthenticationCodeField() {
        super(PARAMETER_NAME, FIELD_TYPE_NAME);
    }

    /**
     * Exposes the given key to facilitate enrollment.
     *
     * @param key
     *     The TOTP key to expose to the user for the sake of enrollment.
     */
    public void exposeKey(UserTOTPKey key) {
        this.key = key;
    }

    /**
     * Returns the username of the user associated with the key being used to
     * generate TOTP codes. If the user's key is not being exposed to facilitate
     * enrollment, this value will not be exposed either.
     *
     * @return
     *     The username of the user associated with the key being used to
     *     generate TOTP codes, or null if the user's key is not being exposed
     *     to facilitate enrollment.
     */
    public String getUsername() {

        // Do not reveal TOTP mode unless enrollment is in progress
        if (key == null)
            return null;

        return key.getUsername();

    }

    /**
     * Returns the base32-encoded secret key that is being used to generate TOTP
     * codes for the authenticating user. If the user's key is not being exposed
     * to facilitate enrollment, this value will not be exposed either.
     *
     * @return
     *     The base32-encoded secret key that is being used to generate TOTP
     *     codes for the authenticating user, or null if the user's key is not
     *     being exposed to facilitate enrollment.
     */
    public String getSecret() {

        // Do not reveal TOTP mode unless enrollment is in progress
        if (key == null)
            return null;

        return BASE32.encode(key.getSecret());

    }

    /**
     * Returns the number of digits used for each TOTP code. If the user's key
     * is not being exposed to facilitate enrollment, this value will not be
     * exposed either.
     *
     * @return
     *     The number of digits used for each TOTP code, or null if the user's
     *     key is not being exposed to facilitate enrollment.
     *
     * @throws GuacamoleException
     *     If the number of digits cannot be read from guacamole.properties.
     */
    public Integer getDigits() throws GuacamoleException {

        // Do not reveal code size unless enrollment is in progress
        if (key == null)
            return null;

        return confService.getDigits();

    }

    /**
     * Returns the human-readable name of the entity issuing user accounts. If
     * the user's key is not being exposed to facilitate enrollment, this value
     * will not be exposed either.
     *
     * @return
     *     The human-readable name of the entity issuing user accounts, or null
     *     if the user's key is not being exposed to facilitate enrollment.
     *
     * @throws GuacamoleException
     *     If the issuer cannot be read from guacamole.properties.
     */
    public String getIssuer() throws GuacamoleException {

        // Do not reveal code issuer unless enrollment is in progress
        if (key == null)
            return null;

        return confService.getIssuer();

    }

    /**
     * Returns the mode that TOTP code generation is operating in. This value
     * will be one of "SHA1", "SHA256", or "SHA512". If the user's key is not
     * being exposed to facilitate enrollment, this value will not be exposed
     * either.
     *
     * @return
     *     The mode that TOTP code generation is operating in, such as "SHA1",
     *     "SHA256", or "SHA512", or null if the user's key is not being
     *     exposed to facilitate enrollment.
     *
     * @throws GuacamoleException
     *     If the TOTP mode cannot be read from guacamole.properties.
     */
    public TOTPGenerator.Mode getMode() throws GuacamoleException {

        // Do not reveal TOTP mode unless enrollment is in progress
        if (key == null)
            return null;

        return confService.getMode();

    }

    /**
     * Returns the number of seconds that each TOTP code remains valid. If the
     * user's key is not being exposed to facilitate enrollment, this value will
     * not be exposed either.
     *
     * @return
     *     The number of seconds that each TOTP code remains valid, or null if
     *     the user's key is not being exposed to facilitate enrollment.
     *
     * @throws GuacamoleException
     *     If the period cannot be read from guacamole.properties.
     */
    public Integer getPeriod() throws GuacamoleException {

        // Do not reveal code period unless enrollment is in progress
        if (key == null)
            return null;

        return confService.getPeriod();

    }

    /**
     * Returns the "otpauth" URI for the secret key used to generate TOTP codes
     * for the current user. If the secret key is not being exposed to
     * facilitate enrollment, null is returned.
     *
     * @return
     *     The "otpauth" URI for the secret key used to generate TOTP codes
     *     for the current user, or null is the secret ket is not being exposed
     *     to facilitate enrollment.
     *
     * @throws GuacamoleException
     *     If the configuration information required for generating the key URI
     *     cannot be read from guacamole.properties.
     */
    @JsonProperty("keyUri")
    public URI getKeyURI() throws GuacamoleException {

        // Do not generate a key URI if no key is being exposed
        if (key == null)
            return null;

        // Format "otpauth" URL (see https://github.com/google/google-authenticator/wiki/Key-Uri-Format)
        String issuer = confService.getIssuer();
        return UriBuilder.fromUri("otpauth://totp/")
                .path(issuer + ":" + key.getUsername())
                .queryParam("secret", BASE32.encode(key.getSecret()))
                .queryParam("issuer", issuer)
                .queryParam("algorithm", confService.getMode())
                .queryParam("digits", confService.getDigits())
                .queryParam("period", confService.getPeriod())
                .build();

    }

    /**
     * Returns the URL of a QR code describing the user's TOTP key and
     * configuration. If the key is not being exposed for enrollment, null is
     * returned.
     *
     * @return
     *     The URL of a QR code describing the user's TOTP key and
     *     configuration, or null if the key is not being exposed for
     *     enrollment.
     *
     * @throws GuacamoleException
     *     If the configuration information required for generating the QR code
     *     cannot be read from guacamole.properties.
     */
    @JsonProperty("qrCode")
    public String getQRCode() throws GuacamoleException {

        // Do not generate a QR code if no key is being exposed
        URI keyURI = getKeyURI();
        if (keyURI == null)
            return null;

        ByteArrayOutputStream stream = new ByteArrayOutputStream();

        try {

            // Create QR code writer
            QRCodeWriter writer = new QRCodeWriter();
            BitMatrix matrix = writer.encode(keyURI.toString(),
                    BarcodeFormat.QR_CODE, QR_CODE_WIDTH, QR_CODE_HEIGHT);

            // Produce PNG image of TOTP key text
            MatrixToImageWriter.writeToStream(matrix, "PNG", stream);

        }
        catch (WriterException e) {
            throw new IllegalArgumentException("QR code could not be "
                    + "generated for TOTP key.", e);
        }
        catch (IOException e) {
            throw new IllegalStateException("Image stream of QR code could "
                    + "not be written.", e);
        }

        // Return data URI for generated image
        return "data:image/png;base64,"
                + BaseEncoding.base64().encode(stream.toByteArray());

    }

}


text:
class EventsController < ApplicationController
  before_filter :authenticate_user!
  # GET /events
  # GET /events.json
  def index
    @events = Event.page(params[:page]).per(3)

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @events }
    end
  end

  # GET /events/1
  # GET /events/1.json
  def show
    #TODO what I have done for Location do it for Event
    @event = Event.find(params[:id])
    #after this line
    ###don't add this line // @location = @event.location.id
    @location = Location.find(@event.location.id)
    #then
    @hash = Gmaps4rails.build_markers(@location) do |location, marker|
      marker.lat location.latitude
      marker.lng location.longitude
      marker.infowindow location.address
    end

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @event }
    end
  end

  # GET /events/new
  # GET /events/new.json
  def new
    @event = Event.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @event }
    end
  end

  # GET /events/1/edit
  def edit
    @event = Event.find(params[:id])
  end

  # POST /events
  # POST /events.json
  def create
    @event = Event.new(params[:event])
    @event.user_id = current_user.id

    respond_to do |format|
      if @event.save
        format.html { redirect_to @event, notice: 'Event was successfully created.' }
        format.json { render json: @event, status: :created, location: @event }
      else
        format.html { render action: "new" }
        format.json { render json: @event.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /events/1
  # PUT /events/1.json
  def update
    @event = Event.find(params[:id])

    respond_to do |format|
      if @event.update_attributes(params[:event])
        format.html { redirect_to @event, notice: 'Event was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @event.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /events/1
  # DELETE /events/1.json
  def destroy
    @event = Event.find(params[:id])
    @event.destroy

    respond_to do |format|
      format.html { redirect_to events_url }
      format.json { head :no_content }
    end
  end
end


text:
const {describe, it} = global;
import {expect} from 'chai';
import {mount} from 'enzyme';
import Textcomponent from '../todotextcomponent.jsx';

describe('Todo text component', function () {

  const testClass = '.todoname';

  var wrapper = mount(<Textcomponent />);

  it('should render content', function () {
    expect(wrapper.find(testClass).length).to.equal(1);
  });
});


text:
/*
    This file is part of the WebKit open source project.
    This file has been generated by generate-bindings.pl. DO NOT MODIFY!

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "config.h"
#include "WebKitDOMTestMediaQueryListListener.h"

#include "DOMObjectCache.h"
#include "ExceptionCode.h"
#include "JSMainThreadExecState.h"
#include "WebKitDOMBinding.h"
#include "WebKitDOMTestMediaQueryListListenerPrivate.h"
#include "gobject/ConvertToUTF8String.h"
#include "webkitglobalsprivate.h"
#include <wtf/GetPtr.h>
#include <wtf/RefPtr.h>

namespace WebKit {

WebKitDOMTestMediaQueryListListener* kit(WebCore::TestMediaQueryListListener* obj)
{
    g_return_val_if_fail(obj, 0);

    if (gpointer ret = DOMObjectCache::get(obj))
        return static_cast<WebKitDOMTestMediaQueryListListener*>(ret);

    return static_cast<WebKitDOMTestMediaQueryListListener*>(DOMObjectCache::put(obj, WebKit::wrapTestMediaQueryListListener(obj)));
}

WebCore::TestMediaQueryListListener* core(WebKitDOMTestMediaQueryListListener* request)
{
    g_return_val_if_fail(request, 0);

    WebCore::TestMediaQueryListListener* coreObject = static_cast<WebCore::TestMediaQueryListListener*>(WEBKIT_DOM_OBJECT(request)->coreObject);
    g_return_val_if_fail(coreObject, 0);

    return coreObject;
}

WebKitDOMTestMediaQueryListListener* wrapTestMediaQueryListListener(WebCore::TestMediaQueryListListener* coreObject)
{
    g_return_val_if_fail(coreObject, 0);

    // We call ref() rather than using a C++ smart pointer because we can't store a C++ object
    // in a C-allocated GObject structure. See the finalize() code for the matching deref().
    coreObject->ref();

    return WEBKIT_DOM_TEST_MEDIA_QUERY_LIST_LISTENER(g_object_new(WEBKIT_TYPE_DOM_TEST_MEDIA_QUERY_LIST_LISTENER, "core-object", coreObject, NULL));
}

} // namespace WebKit

G_DEFINE_TYPE(WebKitDOMTestMediaQueryListListener, webkit_dom_test_media_query_list_listener, WEBKIT_TYPE_DOM_OBJECT)

enum {
    PROP_0,
};

static void webkit_dom_test_media_query_list_listener_finalize(GObject* object)
{

    WebKitDOMObject* domObject = WEBKIT_DOM_OBJECT(object);

    if (domObject->coreObject) {
        WebCore::TestMediaQueryListListener* coreObject = static_cast<WebCore::TestMediaQueryListListener*>(domObject->coreObject);

        WebKit::DOMObjectCache::forget(coreObject);
        coreObject->deref();

        domObject->coreObject = 0;
    }

    G_OBJECT_CLASS(webkit_dom_test_media_query_list_listener_parent_class)->finalize(object);
}

static void webkit_dom_test_media_query_list_listener_set_property(GObject* object, guint propertyId, const GValue* value, GParamSpec* pspec)
{
    WebCore::JSMainThreadNullState state;
    switch (propertyId) {
    default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propertyId, pspec);
        break;
    }
}

static void webkit_dom_test_media_query_list_listener_get_property(GObject* object, guint propertyId, GValue* value, GParamSpec* pspec)
{
    WebCore::JSMainThreadNullState state;
    switch (propertyId) {
    default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propertyId, pspec);
        break;
    }
}

static void webkit_dom_test_media_query_list_listener_constructed(GObject* object)
{

    if (G_OBJECT_CLASS(webkit_dom_test_media_query_list_listener_parent_class)->constructed)
        G_OBJECT_CLASS(webkit_dom_test_media_query_list_listener_parent_class)->constructed(object);
}

static void webkit_dom_test_media_query_list_listener_class_init(WebKitDOMTestMediaQueryListListenerClass* requestClass)
{
    GObjectClass* gobjectClass = G_OBJECT_CLASS(requestClass);
    gobjectClass->finalize = webkit_dom_test_media_query_list_listener_finalize;
    gobjectClass->set_property = webkit_dom_test_media_query_list_listener_set_property;
    gobjectClass->get_property = webkit_dom_test_media_query_list_listener_get_property;
    gobjectClass->constructed = webkit_dom_test_media_query_list_listener_constructed;

}

static void webkit_dom_test_media_query_list_listener_init(WebKitDOMTestMediaQueryListListener* request)
{
}


text:
// Copyright 2017 Victor Smirnov
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <dumbo/v1/reactor/linux/io_poller.hpp>
#include <dumbo/v1/tools/ptr_cast.hpp>
#include <dumbo/v1/tools/perror.hpp>

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif

#include <stdio.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <fcntl.h>
#include <string.h>
#include <stdint.h>

namespace dumbo {
namespace v1 {
namespace reactor {

int io_setup(unsigned nr, aio_context_t *ctxp)
{
    return syscall(__NR_io_setup, nr, ctxp);
}

int io_destroy(aio_context_t ctx)
{
    return syscall(__NR_io_destroy, ctx);
}

int io_submit(aio_context_t ctx, long nr,  struct iocb **iocbpp)
{
    return syscall(__NR_io_submit, ctx, nr, iocbpp);
}

int io_getevents(aio_context_t ctx, long min_nr, long max_nr, struct io_event *events, struct timespec *timeout)
{
    return syscall(__NR_io_getevents, ctx, min_nr, max_nr, events, timeout);
}

void assert_ok(int result, const char* msg)
{
    if (result < 0)
    {
        std::cout << msg << " -- " << strerror(errno) << std::endl;
        std::terminate();
    }
}

IOPoller::IOPoller(IOBuffer& buffer):buffer_(buffer)
{
    int result = io_setup(BATCH_SIZE, &aio_context_);
    if (result < 0)
    {
        std::cout << "Can't initialize file AIO subsystem: " << result << std::endl;
        std::terminate();
    }

    epoll_fd_ = epoll_create(BATCH_SIZE);

    assert_ok(epoll_fd_, "Can't initialize file EPOLL subsystem");

    event_fd_ = eventfd(0, EFD_NONBLOCK); //

    assert_ok(event_fd_, "Can't initialize file EVENTFD subsystem");

    epoll_event ev0;
    ev0.events = EPOLLIN | EPOLLOUT ; //| EPOLLET
    ev0.data.ptr = &event_fd_;

    assert_ok(
        epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, event_fd_, &ev0),
        "Can't configure EPOLLFD"
    );

    //eventfd_read();

}

IOPoller::~IOPoller()
{
    if (epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, event_fd_, nullptr) == -1)
    {
        tools::report_perror(tools::SBuf() << "Can't stop watching eventfd events");
    }

    ::close(event_fd_);

    if (io_destroy(aio_context_) < 0) {
        tools::report_perror(tools::SBuf() << "Can't stop watching file AIO events");
    }

    //FIXME: How to close/destroy epoll_fd_?
}

void IOPoller::poll()
{
    int buffer_capacity = buffer_.capacity_i();
    if (buffer_capacity > 0)
    {
        epoll_event eevents[BATCH_SIZE];

        sigset_t sigmask;

        int max_events = std::min(buffer_capacity, (int)BATCH_SIZE);

        int epoll_result = epoll_pwait(epoll_fd_, eevents, max_events, 0, &sigmask);

        if (epoll_result >= 0)
        {
            for (int c = 0; c < epoll_result; c++)
            {
                if (eevents[c].data.ptr == &event_fd_)
                {
                    if (read_eventfd()) {
                        poll_file_events(buffer_capacity, epoll_result - 1); // FIXME take timerfd into account too!!!
                    }
                }
                else if (eevents[c].data.ptr)
                {
                    Message* msg = tools::ptr_cast<Message>(eevents[c].data.ptr);
                    buffer_.push_front(msg);
                }
            }
        }
        else {
            std::cout << "epoll_pwait failed: " << epoll_result << std::endl;
            std::terminate();
        }
    }
}

void IOPoller::poll_file_events(int buffer_capacity, int other_events)
{
    struct io_event events[BATCH_SIZE];

    int max_events = std::min(buffer_capacity - other_events, (int)BATCH_SIZE);

    timespec timeout{0, 0};
    int e_num = io_getevents(aio_context_, 1, max_events, events, &timeout);

    if (e_num >= 0)
    {
        for (int c = 0; c < e_num; c++)
        {
            FileIOMessage* msg = tools::ptr_cast<FileIOMessage>((void*)events[c].data);
            msg->process();
            msg->report(&events[c]);
            buffer_.push_front(msg);
        }
    }
    else {
        std::cout << "io_getevents failed: " << e_num << std::endl;
        std::terminate();
    }
}

ssize_t IOPoller::read_eventfd()
{
    return true;//for now

    /*char data[8];
    ssize_t res = ::read(event_fd_, data, sizeof(data));

    if (res == 8) {
        return true;
    }
    else if (errno == EAGAIN) {
        return false;
    }
    else {
        tools::report_perror(tools::SBuf() << "Can't read counters form eventfd. Aborting. ");
        std::terminate();
    }*/
}

}}}


text:
function test_exists() {
  type $1 >/dev/null 2>&1
}

function install_neovim_dependencies {
  echo " -- Updating apt-get package info from sources --"
  sudo apt-get update

  # Install NeoVim dependencies_solarized
  echo ""
  echo " -- Updating and installing nvim dependencies --"
  sudo apt-get install \
    autoconf \
    automake \
    cmake \
    g++ \
    gettext \
    libtool \
    libtool-bin \
    ninja-build \
    pkg-config \
    unzip \
    --assume-yes
}
install_neovim_dependencies

# Clone and Build
function build_neovim {
  echo ""
  echo " --- Building Neovim --"
  local nvim_code_dir="$HOME/dev/github/neovim/neovim"
  if [[ ! -d "$nvim_code_dir" ]]; then
    echo ""
    echo " --- Pulling down code to $nvim_code_dir --"
    mkdir -p "$nvim_code_dir"
    git clone https://github.com/neovim/neovim.git "$nvim_code_dir"
  else
    echo ""
    echo " --- Neovim code exists at $nvim_code_dir, building there --"
  fi

  echo ""
  echo " --- Pulling latest --"
  cd "$nvim_code_dir"
  git pull

  if [[ -n "$REBUILD" ]]; then
    if [[ -d build ]]; then
      echo ""
      echo " --- Removing existing build folder --"
      rm -r build
    fi
    echo ""
    echo " --- Starting Neovim Build --"
    make clean
    make CMAKE_BUILD_TYPE=Release
    echo ""
    echo " --- Installing Neovim --"
    sudo make install
  fi
}
build_neovim

function uninstall_neovim {
  echo ""
  echo " -- Uninstalling Neovim --"
  sudo rm /usr/local/bin/nvim
  sudo rm -r /usr/local/share/nvim/
}

# Link config
function link_neovim_config {
  echo ""
  echo " -- Linking Neovim config --"
  mkdir -p "$HOME/.config/nvim"
  ln -sf "$HOME/.dotfiles/.config/nvim/init.vim" "$HOME/.config/nvim/init.vim"
}
link_neovim_config

echo ""
echo " -- NOTE: --"
echo "To get the neovim clipboard working, download a https://github.com/equalsraf/win32yank release and link it with the following:"
echo "  sudo ln -s /mnt/d/Neovim/bin/win32yank.exe /usr/bin/win32yank"