text:
namespace Gif89a.Extensions
{
	using System;
	using System.IO;
	using System.Linq;

	internal static class StreamExtensions
	{
		public static byte[] ReadBytes(this Stream stream, int length)
		{
			var result = new byte[length];
			stream.Read(result, 0, length);

			return result;
		}

		public static short ReadShort(this Stream stream)
		{
			var buffer = new byte[2];
			stream.Read(buffer, 0, buffer.Length);

			return BitConverter.ToInt16(buffer, 0);
		}

		public static string ReadString(this Stream stream, int length)
		{
			return new string(stream.ReadChars(length));
		}

		public static char[] ReadChars(this Stream stream, int length)
		{
			var buffer = new byte[length];
			stream.Read(buffer, 0, length);

			var charBuffer = new char[length];
			buffer.CopyTo(charBuffer, 0);

			return charBuffer;
		}

		public static void WriteString(this Stream stream, string value)
		{
			var bytes = value.ToCharArray().ToBytes().ToArray();
			stream.WriteBytes(bytes);
		}

		public static void WriteBytes(this Stream stream, byte[] bytes)
		{
			stream.Write(bytes, 0, bytes.Length);
		}
	}
}


text: * Converted from TextMate bundle

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>chessTeam4545</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="chess bet model">
    <meta name="keywords" content="chess, bet, bookmakers">
    <meta name="author" content="Alberto Santini">

    <link href="./assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="./assets/css/bootstrap-responsive.min.css" rel="stylesheet">
    <link href="shared/shiny.css" rel="stylesheet"/>

            chessTeam4545
            - Team events: beating the bookmakers?!

Team A

Team B

            Loading...

            Win Prob. for team A

            Loading...

            Draw Prob. for team A

            Loading...

            Loss Prob. for team A

            Loading...

            Win Odds for team A

            Loading...

            Draw Odds

            Loading...

            Win Odds for team B

            See also chessBet


text:
/** @file
    @brief Header

    @date 2014

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2014 Sensics, Inc.
//
// 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.

#ifndef INCLUDED_PathTree_fwd_h_GUID_EFD4ABEE_5AA0_4585_C9A7_862B457167B9
#define INCLUDED_PathTree_fwd_h_GUID_EFD4ABEE_5AA0_4585_C9A7_862B457167B9

// Internal Includes
// - none

// Library/third-party includes
// - none

// Standard includes
// - none

namespace osvr {
namespace common {
    class PathTree;
} // namespace common
} // namespace osvr

#endif // INCLUDED_PathTree_fwd_h_GUID_EFD4ABEE_5AA0_4585_C9A7_862B457167B9


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Ical.Net.CalendarComponents;
using Ical.Net.Utility;

namespace Ical.Net.Serialization
{
    public class ComponentSerializer : SerializerBase
    {
        protected virtual IComparer<ICalendarProperty> PropertySorter => new PropertyAlphabetizer();

        public ComponentSerializer() { }

        public ComponentSerializer(SerializationContext ctx) : base(ctx) { }

        public override Type TargetType => typeof(CalendarComponent);

        public override string SerializeToString(object obj)
        {
            if (!(obj is ICalendarComponent c))
            {
                return null;
            }

            var sb = new StringBuilder();
            var upperName = c.Name.ToUpperInvariant();
            sb.Append(TextUtil.FoldLines($"BEGIN:{upperName}"));

            // Get a serializer factory
            var sf = GetService<ISerializerFactory>();

            // Sort the calendar properties in alphabetical order before serializing them!
            var properties = c.Properties.OrderBy(p => p.Name).ToList();

            // Serialize properties
            foreach (var p in properties)
            {
                // Get a serializer for each property.
                var serializer = sf.Build(p.GetType(), SerializationContext) as IStringSerializer;
                sb.Append(serializer.SerializeToString(p));
            }

            // Serialize child objects
            foreach (var child in c.Children)
            {
                // Get a serializer for each child object.
                var serializer = sf.Build(child.GetType(), SerializationContext) as IStringSerializer;
                sb.Append(serializer.SerializeToString(child));
            }

            sb.Append(TextUtil.FoldLines($"END:{upperName}"));
            return sb.ToString();
        }

        public override object Deserialize(TextReader tr) => null;

        public class PropertyAlphabetizer : IComparer<ICalendarProperty>
        {
            public int Compare(ICalendarProperty x, ICalendarProperty y)
            {
                if (x == y)
                {
                    return 0;
                }
                if (x == null)
                {
                    return -1;
                }
                return y == null
                    ? 1
                    : string.Compare(x.Name, y.Name, StringComparison.OrdinalIgnoreCase);
            }
        }
    }
}


text:
from __future__ import print_function

from nltk.chat.util import Chat, reflections

pairs = (
    (r'We (.*)',
        ("What do you mean, 'we'?",
        "Don't include me in that!",
        "I wouldn't be so sure about that.")),

    (r'You should (.*)',
        ("Don't tell me what to do, buddy.",
        "Really? I should, should I?")),

    (r'You\'re(.*)',
        ("More like YOU'RE %1!",
        "Hah! Look who's talking.",
        "Come over here and tell me I'm %1.")),

    (r'You are(.*)',
        ("More like YOU'RE %1!",
        "Hah! Look who's talking.",
        "Come over here and tell me I'm %1.")),

    (r'I can\'t(.*)',
        ("You do sound like the type who can't %1.",
        "Hear that splashing sound? That's my heart bleeding for you.",
        "Tell somebody who might actually care.")),

    (r'I think (.*)',
        ("I wouldn't think too hard if I were you.",
        "You actually think? I'd never have guessed...")),

    (r'I (.*)',
        ("I'm getting a bit tired of hearing about you.",
        "How about we talk about me instead?",
        "Me, me, me... Frankly, I don't care.")),

    (r'How (.*)',
        ("How do you think?",
        "Take a wild guess.",
        "I'm not even going to dignify that with an answer.")),

    (r'What (.*)',
        ("Do I look like an encyclopedia?",
        "Figure it out yourself.")),

    (r'Why (.*)',
        ("Why not?",
        "That's so obvious I thought even you'd have already figured it out.")),

    (r'(.*)shut up(.*)',
        ("Make me.",
        "Getting angry at a feeble NLP assignment? Somebody's losing it.",
        "Say that again, I dare you.")),

    (r'Shut up(.*)',
        ("Make me.",
        "Getting angry at a feeble NLP assignment? Somebody's losing it.",
        "Say that again, I dare you.")),

    (r'Hello(.*)',
        ("Oh good, somebody else to talk to. Joy.",
        "'Hello'? How original...")),

    (r'(.*)',
        ("I'm getting bored here. Become more interesting.",
        "Either become more thrilling or get lost, buddy.",
        "Change the subject before I die of fatal boredom."))
)

rude_chatbot = Chat(pairs, reflections)

def rude_chat():
    print("Talk to the program by typing in plain English, using normal upper-")
    print('and lower-case letters and punctuation.  Enter "quit" when done.')
    print('='*72)
    print("I suppose I should say hello.")

    rude_chatbot.converse()

def demo():
    rude_chat()

if __name__ == "__main__":
    demo()


text:
from juriscraper.OpinionSite import OpinionSite
import re
import time
from datetime import date
from lxml import html

class Site(OpinionSite):
    def __init__(self):
        super(Site, self).__init__()
# This is a special backscraper to deal with problems on the 2006 page.
        self.url = 'http://www.cit.uscourts.gov/SlipOpinions/SlipOps-2006.html'
        self.court_id = self.__module__

    def _get_download_urls(self):
        return [t for t in self.html.xpath('//table[3]/tr[position() > 1]/td[1]/a/@href | //table[3]/tr[position() > 1]/td[1]/font//@href')]

    def _get_neutral_citations(self):
        neutral_citations = []
        for e in self.html.xpath('//table[3]/tr[position() > 1]/td[1]'):
            s = html.tostring(e, method='text', encoding='unicode').strip()
            neutral_citations.append(s)
        return neutral_citations

    def _get_case_names(self):
        case_names = []
        for e in self.html.xpath('//table[3]/tr[position() > 1]/td[2]/font'):
            s = html.tostring (e, method='text', encoding='unicode').strip()
# We strip "erratum: mm/dd/yyyy" from the case names of errata docs.
            if "erratum" in s:
                case_names.append(s.strip()[:-20])
            else:
                case_names.append(s.strip())
        return case_names

    def _get_precedential_statuses(self):
        return ['Published'] * len(self.case_names)

    def _get_case_dates(self):
        case_dates = []
        for e in self.html.xpath('//table[3]/tr[position() > 1]/td[3]/font'):
            s = html.tostring (e, method='text', encoding='unicode').strip()
            case_dates.append(date.fromtimestamp(time.mktime(time.strptime(s.strip(), '%m/%d/%Y'))))
        return case_dates

# Because there can be multiple docket numbers we have to replace some newlines.
    def _get_docket_numbers(self):
        docket_numbers = []
        for e in self.html.xpath('//table[3]/tr[position() > 1]/td[4]'):
            s = html.tostring (e, method='text', encoding='unicode').strip()
            docket_numbers.append(s.replace('\r\n', ' &'))
        return docket_numbers

# Comment out the following section if backscraping years 1999-2005.
# Because there are sometimes multiple judges we have to strip some whitespace.
    def _get_judges(self):
        judges = []
        for e in self.html.xpath('//table[3]/tr[position() > 1]/td[5]'):
            s = html.tostring (e, method='text', encoding='unicode')
            judges.append(s.strip())
        return judges


text:
The Code Youngstown website. The website uses GitHub Pages, so the `master` branch will always be what's located at http://codeyoungstown.com/ ! Feel free to make pull requests!

Connecting software engineers, developers, and coders in the Youngstown, OH area.

Join the ongoing chat via Slack ( http://slack.codeyoungstown.com/ ) and attend our meetups ( https://www.meetup.com/Code-Youngstown/ ).


text:
package com.icode.resources;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;

import com.icode.util.ICodeUtils;

/**
 * Identifies concrete implementations of an interface or abstract class, and loads them.
 * @author Alex
 *
 * @param <E>
 */
public abstract class ImplementationLoader<E> {
	private Logger log = ICodeUtils.getLogger(getClass());

	protected abstract Class<E> getEntityClass();
	protected abstract Comparator<? super Class<? extends E>> getSorter();

	public List<Class<? extends E>> getAll() {
		ArrayList<Class<? extends E>> entityClasses = new ArrayList<Class<? extends E>>(loadClasses());
		Collections.sort(entityClasses, getSorter());
		return entityClasses;
	}

	@SuppressWarnings("unchecked")
	protected Set<Class<? extends E>> loadClasses() {
		Set<Class<? extends E>> providers = new HashSet<Class<? extends E>>();
		for(String name : getNames()) {
			try {
				providers.add((Class<? extends E>) Class.forName(name));
			} catch(Exception ex) {
				log.warn("Could not load " + name + " for " + getEntityClass().getName(), ex);
			}
		}
		return providers;
	}

	private Set<String> getNames() {
		Enumeration<URL> resources;
		String resourceLocation = "META-INF/frontlinesms/" + getEntityClass().getSimpleName() + "s";
		try {
			ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
			resources = classLoader.getResources(resourceLocation);
		} catch (IOException e) {
			log.warn("Resource(s) not found at " + resourceLocation, e);
			return Collections.emptySet();
		}

		HashSet<String> names = new HashSet<String>();
		for(URL resourceUrl : new IterableEnumeration<URL>(resources)) {
			names.addAll(ResourceUtils.getUsefulLines(resourceUrl));
		}
		return names;
	}
}

class IterableEnumeration<E> implements Iterable<E> {
	private final Enumeration<E> e;
	public IterableEnumeration(Enumeration<E> e) {
		this.e = e;
	}
	public Iterator<E> iterator() {
		return new Iterator<E>() {
			public boolean hasNext() {
				return e.hasMoreElements();
			}
			public E next() {
				return e.nextElement();
			}
			public void remove() {
				throw new IllegalStateException();
			}
		};
	}
}


text:
package com.projecttango.experiments.nativepointcloud;

/**
 * Interfaces between C and Java.
 */
public class TangoJNINative {
  static {
    System.loadLibrary("point_cloud_jni_example");
  }

  // Initialize the Tango Service, this function starts the communication
  // between the application and Tango Service.
  // The activity object is used for checking if the API version is outdated.
  public static native int initialize(PointcloudActivity activity);

  // Setup the configuration file of the Tango Service. We are also setting up
  // the auto-recovery option from here.
  public static native int setupConfig(boolean isAutoRecovery);

  // Connect the onPoseAvailable callback.
  public static native int connectCallbacks();

  // Connect to the Tango Service.
  // This function will start the Tango Service pipeline, in this case, it will
  // start Motion Tracking and Depth sensing.
  public static native int connect();

  // Disconnect from the Tango Service, release all the resources that the app is
  // holding from the Tango Service.
  public static native void disconnect();

  // Release all non OpenGl resources that are allocated from the program.
  public static native void deleteResources();

  // Allocate OpenGL resources for rendering.
  public static native void initGlContent();

  // Setup the view port width and height.
  public static native void setupGraphic(int width, int height);

  // Main render loop.
  public static native void render();

  // Set the render camera's viewing angle:
  //   first person, third person, or top down.
  public static native void setCamera(int cameraIndex);

  // Get the latest pose string from our application for display in our debug UI.
  public static native String getPoseString();

  // Get the latest event string from our application for display in our debug UI.
  public static native String getEventString();

  // Get the TangoCore version from our application for display in our debug UI.
  public static native String getVersionNumber();

  // Get total point count in current depth frame.
  public static native int getVerticesCount();

  // Get average depth (in meters) in current depth frame.
  public static native float getAverageZ();

  // Get depth frame delta time between current frame and previous frame.
  public static native float getFrameDeltaTime();

  // Pass touch events to the native layer.
  public static native void onTouchEvent(int touchCount, int event0,
                                         float x0, float y0, float x1, float y1);
}


text:
'''
    plugin.video.mrknow XBMC Addon
    Copyright (C) 2017 mrknow

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

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

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import sys, urlparse, os
import re
from __generic_host__ import GenericHost
import HTMLParser
import xbmcgui
import urllib

from __generic_host__ import GenericHost
from search import Search

mainUrl = 'https://cdax.tv/'
seriesUrl = 'https://cdax.tv/seriale-online/'
catUrl = 'https://cdax.tv/filmy-online/category:%s/?page=1'
lastUrl = 'https://cdax.tv/filmy-online/?page=1'
szukajUrl = 'http://alltube.tv/szukaj'

class cdaxseriale(GenericHost):

    scriptname = 'cdaxseriale'
    host = 'cdaxseriale'
    MENU_TAB = [
        {'id': 1, 'title': 'Ostatnio dodane', 'mod': 'Ostatniododane'},
        {'id': 10, 'title': 'Alfabetycznie', 'mod': 'Alfabetycznie'},
         #{'id': 4, 'title': 'Szukaj', 'mod': 'find', },
        #{'id': 5, 'title': 'Historia wyszukiwania', 'mod': 'history'},
        # {'id': 3, 'title': 'Bajki', 'mod': 'ListBajki', },
        # {'id': 3, 'title': 'Bajki', 'mod': 'ListBajki', },

    ]

    #search = Search(url='%(quoted)s', service='alltubefilmy', listItemsFun=self.listsItemsOther)

    def ListSeries(self):
        result = self.client.request(seriesUrl)
        r = self.client.parseDOM(result, 'ul', {"id": "series-list"})[0]
        r = self.client.parseDOM(r, 'li')
        r = [(self.client.parseDOM(i, 'a'), self.client.parseDOM(i,'a', ret='href')) for i in r]

        #r = [(r[0][0][i],r[0][1][i]) for i,j in enumerate(r[0])]
        for i in r:
            self.control.log('%s' % str(i))
            self.control.log('%s' % str(i[1][0]))

            #    myurl = catUrl  % i[1]
            self.add(self.host, 'categories-menu', i[0][0],i[0][0],  'None', i[1][0], True, False)
        #xbmcplugin.endOfDirectory(int(sys.argv[1]))
        self.control.directory(int(sys.argv[1]))

    def listsSearchResults(self, key):
        self.control.log(key)
        post_data = {'search': key}
        result = self.s.post(szukajUrl, data=post_data).text
        #self.control.log('ALA %s' % result.encode('utf-8'))
        try:
            result = re.findall('
Filmy
(.*)
Seriale
', result, re.DOTALL)[0]
            r = self.client.parseDOM(result, 'div', attrs={'class':'item-block clearfix'})
            r = [(self.client.parseDOM(i, 'a', ret='href'),
                  self.client.parseDOM(i, 'img', ret='src'),
                  self.client.parseDOM(i, 'h3'),
                  self.client.parseDOM(i, 'p')) for i in r]
            for i in r:
                self.control.log('ALA %s' % str(i))
                 # self.control.log('%s' % str(i) )
                try:
                    # self.control.log('AAA %s' % str(i))
                    meta = {'title': i[2][0], 'poster': i[1][0], 'year': '','plot': i[3][0]}
                    meta['originaltitle'] = i[2][0].encode('utf-8')
                    params = {'service': self.host, 'name': 'playselectedmovie', 'category': '', 'isplayable': 'true',
                              'url': i[0][0]}
                    params.update(meta)
                    self.add2(params)
                except Exception as e:
                    self.control.log('EEEEEEEEERRRTOO %s' % e)
                    pass
        except:
            pass
        self.dirend(int(sys.argv[1]))

    def listsEpisodes(self, url):
        self.control.log('[]1 %s' % url)
        result = self.request(url, utf=False)
        img = self.client.parseDOM(result, 'div', {"id": "single-poster"})[0]
        img = self.client.parseDOM(img, 'img', {"id": "item-image"}, ret='src')[0]
        plot = self.client.parseDOM(result, 'p', {"id": "item-description"})[0]
        year = self.client.parseDOM(result, 'sup')[0]
        title = self.client.parseDOM(result, 'h2')[0]
        title = title.split('')[0].strip()
        r = self.client.parseDOM(result, 'div', {"id": "accordion"})[0]
        r = self.client.parseDOM(r, 'li')

        r = [(self.client.parseDOM(i, 'a', ret='href'),self.client.parseDOM(i, 'a')) for i in r]

        for i in r:
            #self.control.log('AAA %s' % str(i))
            mytitle = '%s - %s' %(title,i[1][0])
            mytitle = " ".join(mytitle.splitlines()).strip().replace(' ','')

            try:
                meta = {'title': mytitle, 'poster': img,'plot': plot, 'year':year}
                params = {'service': self.host, 'name': 'playselectedmovie', 'category': 'None',
                          'isplayable': 'true','url': i[0][0]}
                params.update(meta)
                self.add2(params)
            except Exception as e:
                self.control.log('cdaxf-1 ITEM ADD ERROR %s' % e)
                pass
        self.dirend(int(sys.argv[1]))

    def listsItems(self, url):
        try:
            mypagenumber = re.findall('=(\d+)',url)[0]
            page = int(mypagenumber)
        except:
            page = 1
        self.control.log('[]1 %s' % url)
        self.control.log('[]1 %s' % page)
        mynext = url.replace('='+str(page), '='+str(page+1))
        self.control.log('[]2 %s' % mynext)

        #link = self.client.request(url)
        result = self.request(url, utf=False)
        r = self.client.parseDOM(result,'div', {"class": "col-xs-6 col-sm-3"})
        r = [(self.client.parseDOM(i, 'a', ret='href'),self.client.parseDOM(i, 'img', ret='src'),
              self.client.parseDOM(i, 'a', ret='data-content'),self.client.parseDOM(i, 'div', attrs={'class': 'year'}),
              self.client.parseDOM(i, 'div', attrs={'class': 'title'})) for i in r]

        for i in r:
            #self.control.log('%s' % str(i))
            try:
                tite = i[4][0].split('/')[1]
                titp = i[4][0].split('/')[0]
            except:
                tite = i[4][0]
                titp = i[4][0]
            try:
                meta = {'title': titp, 'poster': i[1][0],'plot': i[2][0], 'orginaltitle':tite}
                params = {'service': self.host, 'name': 'categories-menu', 'category': 'None','isplayable': 'false','url': i[0][0]}
                params.update(meta)
                self.add2(params)
            except Exception as e:
                self.control.log('cdaxf-1 ITEM ADD ERROR %s' % e)
                pass

        #self.add(self.host, 'categories-menu', u'Następna strona',u'Następna strona',  'None', mynext, True, False)
        self.dirend(int(sys.argv[1]))

    def getMovieLinkFromXML(self, url):
        link = self.client.request(url)
        r = self.client.parseDOM(link, 'tr')

        r = [(self.client.parseDOM(i, 'a', ret='href'),
              self.client.parseDOM(i, 'img', ret='alt'),
              self.client.parseDOM(i, 'td')
              ) for i in r]

        r = [(i[0][0], i[1][0], i[2][0], i[2][1]) for i in r if len(i[0]) > 0]

        for i in r:
            self.control.log('%s' % str(i))

        tab = []
        tab2 = []
        for i in r:
            self.control.log("Link ALL %s" % str(i))
            tab.append(i[1] + ' - ' + i[2]+ ' - ' + i[3])
            tab2.append(i[0])
        d = xbmcgui.Dialog()
        video_menu = d.select("Wybór strony video", tab)
        self.control.log('Altube wybrales [%s]' % video_menu)

        if video_menu != -1:
            linkVideo = tab2[video_menu]
            if 'cdax.tv/link/redirect' in linkVideo:
                link = self.request(linkVideo)
                match = re.search('Link do strony z video', link)
                if match:
                    linkVideo = match.group(1).split('http')[-1]
                    linkVideo = 'http' + linkVideo
                    self.control.log('GRR  [%s]' % str(linkVideo))
            self.control.log('2 All pageparser   YXYXYYX   PLAYYYYYYERRRRRRRRRRRR [%s]' % linkVideo)
            #linkVideo = self.up.getVideoLink(tab2[video_menu], url)
            return self.urlresolve(linkVideo)
        else:
            return None

    def sub_handleService(self, params):
        name = params["name"]
        category = params["category"]
        url = params["url"]

        if name == 'main-menu' and category == 'Ostatniododane':
            self.control.log('Jest Ostatnio dodane: ')
            self.listsItems(seriesUrl)
        elif name == 'main-menu' and category == 'Alfabetycznie':
            self.control.log('Jest Kategorie: ')
            self.ListSeries()
        elif name == 'categories-menu':
            self.control.log('Jest categories-menu: ')
            self.listsEpisodes(url)


text:
''' Common enumerations to be used together with |Enum| property.

This module provides many pre-defined enumerations, as well as functions
for creating new enumerations.

New enumerations can be created using the |enumeration| function:

.. code-block:: python

    #: Specify a nautically named side, port or starboard
    MyEnum = enumeration("port", "starboard")

Typically, enumerations are used to define |Enum| properties:

.. code-block:: python

    from bokeh.model import Model
    from bokeh.core.properties import Enum

    class MyModel(Model):

        location = Enum(MyEnum, help="""
        Whether the thing should be a port or starboard.
        """)

Enumerations have a defined order and support iteration:

.. code-block:: python

    >>> for loc in MyEnum:
    ...     print(loc)
    ...
    port
    starboard

as well as containment tests:

.. code-block:: python

    >>> "port" in MyEnum
    True

Enumerations can be easily documented in Sphinx documentation with the
:ref:`bokeh.sphinxext.bokeh_enum` Sphinx extension.

----

.. autofunction:: bokeh.core.enums.enumeration

----

.. |Enum| replace:: :class:`~bokeh.core.properties.Enum`
.. |enumeration| replace:: :func:`~bokeh.core.enums.enumeration`

'''

from __future__ import absolute_import

from six import string_types

from .. import colors, palettes

class Enumeration(object):
    ''' Represent an enumerated collection of values.

    .. note::
        Instances of ``Enumeration`` typically should not be constructed
        directly. Instead, use the |enumeration| function.

    '''
    __slots__ = ()

    def __iter__(self):
        return iter(self._values)

    def __contains__(self, value):
        if not self._case_sensitive:
            value = value.lower()
        return value in self._values

    def __str__(self):
        return "Enumeration(%s)" % ", ".join(self._values)

    __repr__ = __str__

def enumeration(*values, **kwargs):
    ''' Create an |Enumeration| object from a sequence of values.

    Call ``enumeration`` with a sequence of (unique) strings to create an
    Enumeration object:

    .. code-block:: python

        #: Specify the horizontal alignment for rendering text
        TextAlign = enumeration("left", "right", "center")

    Args:
        values (str) : string enumeration values, passed as positional arguments

            The order of arguments is the order of the enumeration, and the
            first element will be considered the default value when used
            to create |Enum| properties.

    Keyword Args:
        case_sensitive (bool, optional) :
            Whether validation should consider case or not (default: True)

    Raises:
        ValueError if values empty, if any value is not a string or not unique

    Returns:
        Enumeration

    '''
    if not (values and all(isinstance(value, string_types) and value for value in values)):
        raise ValueError("expected a non-empty sequence of strings, got %s" % values)

    if len(values) != len(set(values)):
        raise ValueError("enumeration items must be unique, got %s" % values)

    attrs = dict([ (value, value) for value in values ])
    attrs.update({
        "_values": list(values),
        "_default": values[0],
        "_case_sensitive": kwargs.get("case_sensitive", True),
    })

    return type("Enumeration", (Enumeration,), attrs)()

#: Specify whether events should be combined or collected as-is when a Document hold is in effect
HoldPolicy = enumeration( "combine", "collect")

#: Specify whether a dimension or coordinate is latitude or longitude
LatLon = enumeration("lat", "lon")

#: Specify how stroked lines should be joined together
LineJoin = enumeration("miter", "round", "bevel")

#: Specify a named dash pattern for stroking lines
LineDash = enumeration("solid", "dashed", "dotted", "dotdash", "dashdot")

#: Specify how stroked lines should be terminated
LineCap = enumeration("butt", "round", "square")

#: Specify the font style for rendering text
FontStyle = enumeration("normal", "italic", "bold")

#: Specify the vertical alignment for rendering text
VerticalAlign = enumeration("top", "middle", "bottom")

#: Specify the horizontal alignment for rendering text
TextAlign = enumeration("left", "right", "center")

#: Specify the baseline location for rendering text
TextBaseline = enumeration("top", "middle", "bottom", "alphabetic", "hanging", "ideographic")

#: Specify a stroke direction for circles, wedges, etc.
Direction = enumeration("clock", "anticlock")

#: Specify units for mapping values
SpatialUnits = enumeration("screen", "data")

#: Specify the units for an angle value
AngleUnits = enumeration("deg", "rad")

#: Specify a date/time scale
DatetimeUnits = enumeration("microseconds", "milliseconds", "seconds", "minsec",
                            "minutes", "hourmin", "hours", "days", "months", "years")

#: Specify a vertical/horizontal dimension
Dimension = enumeration("width", "height")

#: Specify a vertical/horizontal dimensions
Dimensions = enumeration("width", "height", "both")

#: Specify a vertical/horizontal orientation for something
Orientation = enumeration("horizontal", "vertical")

#: Specify a fixed location for a Bokeh legend
LegendLocation = Anchor = enumeration(
    "top_left",    "top_center",    "top_right",
    "center_left", "center",        "center_right",
    "bottom_left", "bottom_center", "bottom_right")

#: Specify a location in plot layouts
Location = enumeration("above", "below", "left", "right")

#: Specify a vertical location in plot layouts
VerticalLocation = enumeration("above", "below")

#: Specify a horizontal location in plot layouts
HorizontalLocation = enumeration("left", "right")

#: Specify a named dashing patter for stroking lines
DashPattern = enumeration("solid", "dashed", "dotted", "dotdash", "dashdot")

#: Specify a style for button widgets
ButtonType = enumeration("default", "primary", "success", "warning", "danger", "link")

#: Specify one of the 137 named CSS colors
NamedColor = enumeration(*colors.named.__all__, case_sensitive=False)

#: Specify the name of a palette from :ref:`bokeh.palettes`
Palette = enumeration(*palettes.__palettes__)

#: Specify a style for a Google map
MapType = enumeration("satellite", "roadmap", "terrain", "hybrid")

#: Specify a format for printing dates
DateFormat = enumeration("ATOM", "W3C", "RFC-3339", "ISO-8601", "COOKIE", "RFC-822",
                         "RFC-850", "RFC-1036", "RFC-1123", "RFC-2822", "RSS", "TIMESTAMP")

#: Specify a policy for  how numbers should be rounded
RoundingFunction = enumeration("round", "nearest", "floor", "rounddown", "ceil", "roundup")

#: Specify a locale for printing numeric values
NumeralLanguage = enumeration("be-nl", "chs", "cs", "da-dk", "de-ch", "de", "en",
                              "en-gb", "es-ES", "es", "et", "fi", "fr-CA", "fr-ch",
                              "fr", "hu", "it", "ja", "nl-nl", "pl", "pt-br",
                              "pt-pt", "ru", "ru-UA", "sk", "th", "tr", "uk-UA")

#: Specify an output backend to render a plot area onto
OutputBackend = enumeration("canvas", "svg", "webgl")

#: Specify a position in the render order for a Bokeh renderer
RenderLevel = enumeration("image", "underlay", "glyph", "annotation", "overlay")

#: Specify a render mode for renderers that support both Canvas or CSS rendering
RenderMode = enumeration("canvas", "css")

#: Specify a start/end value
StartEnd = enumeration("start", "end")

#: Specify a mode for stepwise interpolation
StepMode = enumeration("before", "after", "center")

#: Specify different callback policies for the slider widget
SliderCallbackPolicy = enumeration("continuous", "throttle", "mouseup")

#: Specify a distribution to use for the Jitter class
JitterRandomDistribution = enumeration("uniform", "normal")

#: Specify sorting directions
SortDirection = enumeration("ascending", "descending")

#: Sizing mode policies
SizingMode = enumeration("stretch_both", "scale_width", "scale_height", "scale_both", "fixed")

#: Specify how a legend should respond to click events
LegendClickPolicy = enumeration("none", "hide", "mute")

#: Whether range padding should be interpreted a percentage or and absolute quantity
PaddingUnits = enumeration("percent", "absolute")

#: Specify how a format string for a tooltip field should be interpreted
TooltipFieldFormatter = enumeration("numeral", "datetime", "printf")


text:
if(Util.isDefined('main')){
    main();
} else{
    alert('Main Function is not Defined!');
}


text:
'use strict';

var events2 = require('eventemitter2'),
    util = require('util');

module.exports = function(manager, data) {
    events2.EventEmitter2.call(this);
    var timeout = 10000 * Math.random(),
        end;

    manager.on('start', function() {
        manager.log('timing out in ' + timeout);

        // This task echos timeout! after an interval & stops, to be cleaned up
        end = setTimeout(function() {
            manager.log('timeout!');

            // Arbitrary pubsub emit
            this.emit('testing', 'an argument');

            // Notify task finished
            this.emit('_end');
        }.bind(this), timeout);

        // Arbitrary pubsub emit
        this.emit('start');
    }.bind(this));

    // Stop when requested
    manager.on('stop', function() {
        // Stop task
        clearTimeout(end);

        // Notify stopped
        this.emit('_stop');
    }.bind(this));
};

util.inherits(module.exports, events2.EventEmitter2);


text:
"""Utils"""

def prompt_choice(list):
    """prompts user for a numerical choice"""

    options = u"\n[0]\tNone of these\n"
    for i in range(0, len(list)):
        options += u"\n[{0}]{1}\n".format(i + 1, list[i])
    print options

    prompt = u": "
    while True:
        answer = raw_input(prompt)
        try:
            if int(answer) in range(0, len(list) + 1):
                return int(answer)
            else:
                raise ValueError
        except:
            print u"Please enter a number from 0 to {}".format(len(list))
            continue

def confirm(prompt, yes):
    """prompts user for a yes/no choice"""

    if yes:
        print prompt
        return True

    prompt += u"\n[y|n]:\t"
    while True:
        answer = raw_input(prompt.encode("utf-8"))
        if answer in ["y", "Y", "yes"]:
            return True
        elif answer in ["n", "N", "no"]:
            return False
        else:
            print u"Please answer with \"y|yes\" or \"n|no\""
            continue


text:
/**
 * Created by chenqiu on 15/8/27.
 */
var calcTofDistance = require('../../../lib/algorithm/tof/calcTofDistance');
var math            = require('mathjs');

var chanPrf = 33;
var pollTXTime = math.bignumber('308049538');
var pollRXTime = math.bignumber('1064863147617');
var rspTXTime  = math.bignumber('1065118754434');
var rspRXTime  = math.bignumber('563661116');
var finalTXTime= math.bignumber('883165314');
var finalRXTime= math.bignumber('1065438260866');

var result = calcTofDistance(chanPrf, pollTXTime, pollRXTime, rspTXTime, rspRXTime, finalTXTime, finalRXTime, 0, 0);

// 8.26226157267644
console.log(result);

chanPrf = 33;
pollTXTime = math.bignumber('2868018818');
pollRXTime = math.bignumber('673089648806');
rspTXTime  = math.bignumber('673345255538');
rspRXTime  = math.bignumber('3123627474');
finalTXTime= math.bignumber('3443131522');
finalRXTime= math.bignumber('673664761344');

result = calcTofDistance(chanPrf, pollTXTime, pollRXTime, rspTXTime, rspRXTime, finalTXTime, finalRXTime, 0, 0);

// 4.43747349686843
console.log(result);


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <winpr/assert.h>

#include "shadow.h"

#include "shadow_encoder.h"

#define TAG CLIENT_TAG("shadow")

UINT32 shadow_encoder_preferred_fps(rdpShadowEncoder* encoder)
{
	/* Return preferred fps calculated according to the last
	 * sent frame id and last client-acknowledged frame id.
	 */
	return encoder->fps;
}

UINT32 shadow_encoder_inflight_frames(rdpShadowEncoder* encoder)
{
	/* Return inflight frame count.
	 * If queueDepth is SUSPEND_FRAME_ACKNOWLEDGEMENT, count = 0
	 * Otherwise, calculate count =
	 * <last sent frame id> - <last client-acknowledged frame id>
	 * Note: This function is exported so that subsystem could
	 * implement its own strategy to tune fps.
	 */
	return (encoder->queueDepth == SUSPEND_FRAME_ACKNOWLEDGEMENT)
	           ? 0
	           : encoder->frameId - encoder->lastAckframeId;
}

UINT32 shadow_encoder_create_frame_id(rdpShadowEncoder* encoder)
{
	UINT32 frameId;
	UINT32 inFlightFrames = shadow_encoder_inflight_frames(encoder);

	/*
	 * Calculate preferred fps according to how much frames are
	 * in-progress. Note that it only works when subsytem implementation
	 * calls shadow_encoder_preferred_fps and takes the suggestion.
	 */
	if (inFlightFrames > 1)
	{
		encoder->fps = (100 / (inFlightFrames + 1) * encoder->maxFps) / 100;
	}
	else
	{
		encoder->fps += 2;

		if (encoder->fps > encoder->maxFps)
			encoder->fps = encoder->maxFps;
	}

	if (encoder->fps < 1)
		encoder->fps = 1;

	frameId = ++encoder->frameId;
	return frameId;
}

static int shadow_encoder_init_grid(rdpShadowEncoder* encoder)
{
	UINT32 i, j, k;
	UINT32 tileSize;
	UINT32 tileCount;
	encoder->gridWidth = ((encoder->width + (encoder->maxTileWidth - 1)) / encoder->maxTileWidth);
	encoder->gridHeight =
	    ((encoder->height + (encoder->maxTileHeight - 1)) / encoder->maxTileHeight);
	tileSize = encoder->maxTileWidth * encoder->maxTileHeight * 4;
	tileCount = encoder->gridWidth * encoder->gridHeight;
	encoder->gridBuffer = (BYTE*)calloc(tileSize, tileCount);

	if (!encoder->gridBuffer)
		return -1;

	encoder->grid = (BYTE**)calloc(tileCount, sizeof(BYTE*));

	if (!encoder->grid)
		return -1;

	for (i = 0; i < encoder->gridHeight; i++)
	{
		for (j = 0; j < encoder->gridWidth; j++)
		{
			k = (i * encoder->gridWidth) + j;
			encoder->grid[k] = &(encoder->gridBuffer[k * tileSize]);
		}
	}

	return 0;
}

static int shadow_encoder_uninit_grid(rdpShadowEncoder* encoder)
{
	if (encoder->gridBuffer)
	{
		free(encoder->gridBuffer);
		encoder->gridBuffer = NULL;
	}

	if (encoder->grid)
	{
		free(encoder->grid);
		encoder->grid = NULL;
	}

	encoder->gridWidth = 0;
	encoder->gridHeight = 0;
	return 0;
}

static int shadow_encoder_init_rfx(rdpShadowEncoder* encoder)
{
	if (!encoder->rfx)
		encoder->rfx = rfx_context_new_ex(TRUE, encoder->server->settings->ThreadingFlags);

	if (!encoder->rfx)
		goto fail;

	if (!rfx_context_reset(encoder->rfx, encoder->width, encoder->height))
		goto fail;

	encoder->rfx->mode = encoder->server->rfxMode;
	rfx_context_set_pixel_format(encoder->rfx, PIXEL_FORMAT_BGRX32);
	encoder->codecs |= FREERDP_CODEC_REMOTEFX;
	return 1;
fail:
	rfx_context_free(encoder->rfx);
	return -1;
}

static int shadow_encoder_init_nsc(rdpShadowEncoder* encoder)
{
	rdpContext* context = (rdpContext*)encoder->client;
	rdpSettings* settings = context->settings;

	if (!encoder->nsc)
		encoder->nsc = nsc_context_new();

	if (!encoder->nsc)
		goto fail;

	if (!nsc_context_reset(encoder->nsc, encoder->width, encoder->height))
		goto fail;

	if (!nsc_context_set_parameters(encoder->nsc, NSC_COLOR_LOSS_LEVEL,
	                                settings->NSCodecColorLossLevel))
		goto fail;
	if (!nsc_context_set_parameters(encoder->nsc, NSC_ALLOW_SUBSAMPLING,
	                                (UINT32)settings->NSCodecAllowSubsampling))
		goto fail;
	if (!nsc_context_set_parameters(encoder->nsc, NSC_DYNAMIC_COLOR_FIDELITY,
	                                (UINT32)settings->NSCodecAllowDynamicColorFidelity))
		goto fail;
	if (!nsc_context_set_parameters(encoder->nsc, NSC_COLOR_FORMAT, PIXEL_FORMAT_BGRX32))
		goto fail;
	encoder->codecs |= FREERDP_CODEC_NSCODEC;
	return 1;
fail:
	nsc_context_free(encoder->nsc);
	return -1;
}

static int shadow_encoder_init_planar(rdpShadowEncoder* encoder)
{
	DWORD planarFlags = 0;
	rdpContext* context = (rdpContext*)encoder->client;
	rdpSettings* settings = context->settings;

	if (settings->DrawAllowSkipAlpha)
		planarFlags |= PLANAR_FORMAT_HEADER_NA;

	planarFlags |= PLANAR_FORMAT_HEADER_RLE;

	if (!encoder->planar)
	{
		encoder->planar = freerdp_bitmap_planar_context_new(planarFlags, encoder->maxTileWidth,
		                                                    encoder->maxTileHeight);
	}

	if (!encoder->planar)
		goto fail;

	if (!freerdp_bitmap_planar_context_reset(encoder->planar, encoder->maxTileWidth,
	                                         encoder->maxTileHeight))
		goto fail;

	encoder->codecs |= FREERDP_CODEC_PLANAR;
	return 1;
fail:
	freerdp_bitmap_planar_context_free(encoder->planar);
	return -1;
}

static int shadow_encoder_init_interleaved(rdpShadowEncoder* encoder)
{
	if (!encoder->interleaved)
		encoder->interleaved = bitmap_interleaved_context_new(TRUE);

	if (!encoder->interleaved)
		goto fail;

	if (!bitmap_interleaved_context_reset(encoder->interleaved))
		goto fail;

	encoder->codecs |= FREERDP_CODEC_INTERLEAVED;
	return 1;
fail:
	bitmap_interleaved_context_free(encoder->interleaved);
	return -1;
}

static int shadow_encoder_init_h264(rdpShadowEncoder* encoder)
{
	if (!encoder->h264)
		encoder->h264 = h264_context_new(TRUE);

	if (!encoder->h264)
		goto fail;

	if (!h264_context_reset(encoder->h264, encoder->width, encoder->height))
		goto fail;

	encoder->h264->RateControlMode = encoder->server->h264RateControlMode;
	encoder->h264->BitRate = encoder->server->h264BitRate;
	encoder->h264->FrameRate = encoder->server->h264FrameRate;
	encoder->h264->QP = encoder->server->h264QP;

	encoder->codecs |= FREERDP_CODEC_AVC420 | FREERDP_CODEC_AVC444;
	return 1;
fail:
	h264_context_free(encoder->h264);
	return -1;
}

static int shadow_encoder_init_progressive(rdpShadowEncoder* encoder)
{
	WINPR_ASSERT(encoder);
	if (!encoder->progressive)
		encoder->progressive = progressive_context_new(TRUE);

	if (!encoder->progressive)
		goto fail;

	if (!progressive_context_reset(encoder->progressive))
		goto fail;

	encoder->codecs |= FREERDP_CODEC_PROGRESSIVE;
	return 1;
fail:
	progressive_context_free(encoder->progressive);
	return -1;
}

static int shadow_encoder_init(rdpShadowEncoder* encoder)
{
	encoder->width = encoder->server->screen->width;
	encoder->height = encoder->server->screen->height;
	encoder->maxTileWidth = 64;
	encoder->maxTileHeight = 64;
	shadow_encoder_init_grid(encoder);

	if (!encoder->bs)
		encoder->bs = Stream_New(NULL, encoder->maxTileWidth * encoder->maxTileHeight * 4ULL);

	if (!encoder->bs)
		return -1;

	return 1;
}

static int shadow_encoder_uninit_rfx(rdpShadowEncoder* encoder)
{
	if (encoder->rfx)
	{
		rfx_context_free(encoder->rfx);
		encoder->rfx = NULL;
	}

	encoder->codecs &= (UINT32)~FREERDP_CODEC_REMOTEFX;
	return 1;
}

static int shadow_encoder_uninit_nsc(rdpShadowEncoder* encoder)
{
	if (encoder->nsc)
	{
		nsc_context_free(encoder->nsc);
		encoder->nsc = NULL;
	}

	encoder->codecs &= (UINT32)~FREERDP_CODEC_NSCODEC;
	return 1;
}

static int shadow_encoder_uninit_planar(rdpShadowEncoder* encoder)
{
	if (encoder->planar)
	{
		freerdp_bitmap_planar_context_free(encoder->planar);
		encoder->planar = NULL;
	}

	encoder->codecs &= (UINT32)~FREERDP_CODEC_PLANAR;
	return 1;
}

static int shadow_encoder_uninit_interleaved(rdpShadowEncoder* encoder)
{
	if (encoder->interleaved)
	{
		bitmap_interleaved_context_free(encoder->interleaved);
		encoder->interleaved = NULL;
	}

	encoder->codecs &= (UINT32)~FREERDP_CODEC_INTERLEAVED;
	return 1;
}

static int shadow_encoder_uninit_h264(rdpShadowEncoder* encoder)
{
	if (encoder->h264)
	{
		h264_context_free(encoder->h264);
		encoder->h264 = NULL;
	}

	encoder->codecs &= (UINT32) ~(FREERDP_CODEC_AVC420 | FREERDP_CODEC_AVC444);
	return 1;
}

static int shadow_encoder_uninit_progressive(rdpShadowEncoder* encoder)
{
	WINPR_ASSERT(encoder);
	if (encoder->progressive)
	{
		progressive_context_free(encoder->progressive);
		encoder->progressive = NULL;
	}

	encoder->codecs &= (UINT32)~FREERDP_CODEC_PROGRESSIVE;
	return 1;
}

static int shadow_encoder_uninit(rdpShadowEncoder* encoder)
{
	shadow_encoder_uninit_grid(encoder);

	if (encoder->bs)
	{
		Stream_Free(encoder->bs, TRUE);
		encoder->bs = NULL;
	}

		shadow_encoder_uninit_rfx(encoder);

		shadow_encoder_uninit_nsc(encoder);

		shadow_encoder_uninit_planar(encoder);

		shadow_encoder_uninit_interleaved(encoder);
		shadow_encoder_uninit_h264(encoder);

	    shadow_encoder_uninit_progressive(encoder);

	    return 1;
}

int shadow_encoder_reset(rdpShadowEncoder* encoder)
{
	int status;
	UINT32 codecs = encoder->codecs;
	rdpContext* context = (rdpContext*)encoder->client;
	rdpSettings* settings = context->settings;
	status = shadow_encoder_uninit(encoder);

	if (status < 0)
		return -1;

	status = shadow_encoder_init(encoder);

	if (status < 0)
		return -1;

	status = shadow_encoder_prepare(encoder, codecs);

	if (status < 0)
		return -1;

	encoder->fps = 16;
	encoder->maxFps = 32;
	encoder->frameId = 0;
	encoder->lastAckframeId = 0;
	encoder->frameAck = settings->SurfaceFrameMarkerEnabled;
	return 1;
}

int shadow_encoder_prepare(rdpShadowEncoder* encoder, UINT32 codecs)
{
	int status;

	if ((codecs & FREERDP_CODEC_REMOTEFX) && !(encoder->codecs & FREERDP_CODEC_REMOTEFX))
	{
		WLog_DBG(TAG, "initializing RemoteFX encoder");
		status = shadow_encoder_init_rfx(encoder);

		if (status < 0)
			return -1;
	}

	if ((codecs & FREERDP_CODEC_NSCODEC) && !(encoder->codecs & FREERDP_CODEC_NSCODEC))
	{
		WLog_DBG(TAG, "initializing NSCodec encoder");
		status = shadow_encoder_init_nsc(encoder);

		if (status < 0)
			return -1;
	}

	if ((codecs & FREERDP_CODEC_PLANAR) && !(encoder->codecs & FREERDP_CODEC_PLANAR))
	{
		WLog_DBG(TAG, "initializing planar bitmap encoder");
		status = shadow_encoder_init_planar(encoder);

		if (status < 0)
			return -1;
	}

	if ((codecs & FREERDP_CODEC_INTERLEAVED) && !(encoder->codecs & FREERDP_CODEC_INTERLEAVED))
	{
		WLog_DBG(TAG, "initializing interleaved bitmap encoder");
		status = shadow_encoder_init_interleaved(encoder);

		if (status < 0)
			return -1;
	}

	if ((codecs & (FREERDP_CODEC_AVC420 | FREERDP_CODEC_AVC444)) &&
	    !(encoder->codecs & (FREERDP_CODEC_AVC420 | FREERDP_CODEC_AVC444)))
	{
		WLog_DBG(TAG, "initializing H.264 encoder");
		status = shadow_encoder_init_h264(encoder);

		if (status < 0)
			return -1;
	}

	if ((codecs & FREERDP_CODEC_PROGRESSIVE) && !(encoder->codecs & FREERDP_CODEC_PROGRESSIVE))
	{
		WLog_DBG(TAG, "initializing progressive encoder");
		status = shadow_encoder_init_progressive(encoder);

		if (status < 0)
			return -1;
	}

	return 1;
}

rdpShadowEncoder* shadow_encoder_new(rdpShadowClient* client)
{
	rdpShadowEncoder* encoder;
	rdpShadowServer* server = client->server;
	encoder = (rdpShadowEncoder*)calloc(1, sizeof(rdpShadowEncoder));

	if (!encoder)
		return NULL;

	encoder->client = client;
	encoder->server = server;
	encoder->fps = 16;
	encoder->maxFps = 32;

	if (shadow_encoder_init(encoder) < 0)
	{
		free(encoder);
		return NULL;
	}

	return encoder;
}

void shadow_encoder_free(rdpShadowEncoder* encoder)
{
	if (!encoder)
		return;

	shadow_encoder_uninit(encoder);
	free(encoder);
}


text:
{-# LANGUAGE OverloadedStrings #-}

module Queries.AQuery
    ( module Queries.AQuery.Trades
    , module Queries.AQuery.Packets
    ) where

import           Queries.AQuery.Packets
import           Queries.AQuery.Trades


text:
from distutils.core import setup

packages = [
    "pyrem_torq",
    "pyrem_torq.utility",
    "pyrem_torq.treeseq",
    "pyrem_torq.expression",
    "pyrem_torq.script",
    "pyrem_torq.extra"
]

setup(
    name = 'pyrem_torq',
    version = '0.5',
    packages = packages,
    package_dir = dict((p, "src/" + p.replace(".", "/")) for p in packages),
    package_data={'pyrem_torq':
        [
            './LICENSE',
            './README.rst',
        ],
    },

    license="MIT license",
    classifiers=[
        "Development Status :: 3 - Alpha",
        "Environment :: Console",
        "Intended Audience :: Developers",
        "Intended Audience :: Science/Research",
        "License :: OSI Approved :: MIT License",
        "Natural Language :: English",
        "Operating System :: POSIX :: Linux",
        "Programming Language :: Python :: 2 :: Only",
        "Programming Language :: Python :: Implementation :: CPython",
        "Topic :: Scientific/Engineering :: Information Analysis",
        "Topic :: Software Development :: Libraries :: Python Modules",
        "Topic :: Utilities",
    ],
)


text:
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0">
    <persistence-unit name="minijax" transaction-type="RESOURCE_LOCAL">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <class>com.techempower.minijax.Fortune</class>
        <class>com.techempower.minijax.World</class>
        <shared-cache-mode>NONE</shared-cache-mode>
        <properties>
            <property name="eclipselink.jdbc.batch-writing" value="JDBC" />
            <property name="eclipselink.jdbc.cache-statements" value="true" />
            <property name="eclipselink.weaving" value="static" />
        </properties>
    </persistence-unit>
</persistence>


text:
Go HTTP Router Benchmark
========================

This benchmark suite aims to compare the performance of HTTP request routers for [Go](https://golang.org) by implementing the routing structure of some real world APIs.
Some of the APIs are slightly adapted, since they can not be implemented 1:1 in some of the routers.

Of course the tested routers can be used for any kind of HTTP request → handler function routing, not only (REST) APIs.

#### Tested routers & frameworks:

 * [Beego](http://beego.me/)
 * [go-json-rest](https://github.com/ant0ine/go-json-rest)
 * [Denco](https://github.com/naoina/denco)
 * [Gocraft Web](https://github.com/gocraft/web)
 * [Goji](https://github.com/zenazn/goji/)
 * [Gorilla Mux](http://www.gorillatoolkit.org/pkg/mux)
 * [http.ServeMux](http://golang.org/pkg/net/http/#ServeMux)
 * [HttpRouter](https://github.com/julienschmidt/httprouter)
 * [HttpTreeMux](https://github.com/dimfeld/httptreemux)
 * [Kocha-urlrouter](https://github.com/naoina/kocha-urlrouter)
 * [Martini](https://github.com/go-martini/martini)
 * [Pat](https://github.com/bmizerany/pat)
 * [TigerTonic](https://github.com/rcrowley/go-tigertonic)
 * [Traffic](https://github.com/pilu/traffic)

## Motivation

Go is a great language for web applications. Since the [default *request multiplexer*](http://golang.org/pkg/net/http/#ServeMux) of Go's net/http package is very simple and limited, an accordingly high number of HTTP request routers exist.

Unfortunately, most of the (early) routers use pretty bad routing algorithms. Moreover, many of them are very wasteful with memory allocations, which can become a problem in a language with Garbage Collection like Go, since every (heap) allocation results in more work for the Garbage Collector.

Lately more and more bloated frameworks pop up, outdoing one another in the number of features. This benchmark tries to measure their overhead.

Beware that we are comparing apples to oranges here, we compare feature-rich frameworks to packages with simple routing functionality only. But since we are only interested in decent request routing, I think this is not entirely unfair. The frameworks are configured to do as little additional work as possible.

If you care about performance, this benchmark can maybe help you find the right router, which scales with your application.

Personally, I prefer slim and optimized software, which is why I implemented [HttpRouter](https://github.com/julienschmidt/httprouter), which is also tested here. In fact, this benchmark suite started as part of the packages tests, but was then extended to a generic benchmark suite.
So keep in mind, that I am not completely unbiased :relieved:

## Results

Benchmark System:
 * Intel Core i5-2500K (4x 3,30GHz + Turbo Boost), CPU-governor: performance
 * 2x 4 GiB DDR3-1333 RAM, dual-channel
 * go version go1.3rc1 linux/amd64
 * Ubuntu 14.04 amd64 (Linux Kernel 3.13.0-29), fresh installation

### Memory Consumption

Besides the micro-benchmarks, there are 3 sets of benchmarks where we play around with clones of some real-world APIs, and one benchmark with static routes only, to allow a comparison with [http.ServeMux](http://golang.org/pkg/net/http/#ServeMux).
The following table shows the memory required only for loading the routing structure for the respective API.
The best 3 values for each test are bold. I'm pretty sure you can detect a pattern :wink:

| Router       | Static    | GitHub     | Google+   | Parse     |
|:-------------|----------:|-----------:|----------:|----------:|
| HttpServeMux |__18064 B__|         -  |        -  |        -  |
| Beego        |  79472 B  |  497248 B  |  26480 B  |  38768 B  |
| Denco        |  44752 B  |  107632 B  |  54896 B  |  36368 B  |
| Gocraft Web  |  57976 B  |   95736 B  |   8024 B  |  13120 B  |
| Goji         |  32400 B  | __58424 B__| __3392 B__| __6704 B__|
| Go-Json-Rest | 152608 B  |  148352 B  |  11696 B  |  13712 B  |
| Gorilla Mux  | 685152 B  | 1557216 B  |  80240 B  | 125480 B  |
| HttpRouter   |__26232 B__| __44344 B__| __3144 B__| __5792 B__|
| HttpTreeMux  |  75624 B  |   81408 B  |   7712 B  |   7616 B  |
| Kocha        | 130336 B  |  811744 B  | 139968 B  | 191632 B  |
| Martini      | 312592 B  |  579472 B  |  27520 B  |  50608 B  |
| Pat          |__21272 B__| __18968 B__| __1448 B__| __2360 B__|
| TigerTonic   |  85264 B  |   99392 B  |  10576 B  |  11008 B  |
| Traffic      | 649568 B  | 1124704 B  |  57984 B  |  98168 B  |

The first place goes to [Pat](https://github.com/bmizerany/pat), followed by [HttpRouter](https://github.com/julienschmidt/httprouter) and [Goji](https://github.com/zenazn/goji/). Now, before everyone starts reading the documentation of Pat, `[SPOILER]` this low memory consumption comes at the price of relatively bad routing performance. The routing structure of Pat is simple - probably too simple. `[/SPOILER]`.

Moreover main memory is cheap and usually not a scarce resource. As long as the router doesn't require Megabytes of memory, it should be no deal breaker. But it gives us a first hint how efficient or wasteful a router works.

### Static Routes

The `Static` benchmark is not really a clone of a real-world API. It is just a collection of random static paths inspired by the structure of the Go directory. It might not be a realistic URL-structure.

The only intention of this benchmark is to allow a comparison with the default router of Go's net/http package, [http.ServeMux](http://golang.org/pkg/net/http/#ServeMux), which is limited to static routes and does not support parameters in the route pattern.

In the `StaticAll` benchmark each of 157 URLs is called once per repetition (op, *operation*). If you are unfamiliar with the `go test -bench` tool, the first number is the number of repetitions the `go test` tool made, to get a test running long enough for measurements. The second column shows the time in nanoseconds that a single repetition takes. The third number is the amount of heap memory allocated in bytes, the last one the average number of allocations made per repetition.

The logs below show, that http.ServeMux has only medium performance, compared to more feature-rich routers. The fastest router only needs 1.8% of the time http.ServeMux needs.

[HttpRouter](https://github.com/julienschmidt/httprouter) was the first router (I know of) that managed to serve all the static URLs without a single heap allocation. Since [the first run of this benchmark](https://github.com/julienschmidt/go-http-routing-benchmark/blob/0eb78904be13aee7a1e9f8943386f7c26b9d9d79/README.md) more routers followed this trend and were optimized in the same way.

```
BenchmarkHttpServeMux_StaticAll         5000     706222 ns/op          96 B/op        6 allocs/op

BenchmarkBeego_StaticAll                2000    1408954 ns/op      482433 B/op    14088 allocs/op
BenchmarkDenco_StaticAll              200000      12679 ns/op           0 B/op        0 allocs/op
BenchmarkGocraftWeb_StaticAll          10000     154142 ns/op       51468 B/op      947 allocs/op
BenchmarkGoji_StaticAll                20000      80518 ns/op           0 B/op        0 allocs/op
BenchmarkGoJsonRest_StaticAll           2000     978164 ns/op      180973 B/op     3945 allocs/op
BenchmarkGorillaMux_StaticAll           1000    1763690 ns/op       71804 B/op      956 allocs/op
BenchmarkHttpRouter_StaticAll         100000      15010 ns/op           0 B/op        0 allocs/op
BenchmarkHttpTreeMux_StaticAll        100000      15123 ns/op           0 B/op        0 allocs/op
BenchmarkKocha_StaticAll              100000      23093 ns/op           0 B/op        0 allocs/op
BenchmarkMartini_StaticAll               500    3444278 ns/op      156015 B/op     2351 allocs/op
BenchmarkPat_StaticAll                  1000    1640745 ns/op      549187 B/op    11186 allocs/op
BenchmarkTigerTonic_StaticAll          50000      58264 ns/op        7714 B/op      157 allocs/op
BenchmarkTraffic_StaticAll               500    7230129 ns/op     3763731 B/op    27453 allocs/op
```

### Micro Benchmarks

The following benchmarks measure the cost of some very basic operations.

In the first benchmark, only a single route, containing a parameter, is loaded into the routers. Then a request for a URL matching this pattern is made and the router has to call the respective registered handler function. End.
```
BenchmarkBeego_Param                  500000       5495 ns/op        1165 B/op       14 allocs/op
BenchmarkDenco_Param                 5000000        312 ns/op          50 B/op        2 allocs/op
BenchmarkGocraftWeb_Param            1000000       1440 ns/op         684 B/op        9 allocs/op
BenchmarkGoji_Param                  5000000        748 ns/op         340 B/op        2 allocs/op
BenchmarkGoJsonRest_Param             500000       6980 ns/op        1787 B/op       29 allocs/op
BenchmarkGorillaMux_Param            1000000       2665 ns/op         780 B/op        7 allocs/op
BenchmarkHttpRouter_Param           20000000        139 ns/op          33 B/op        1 allocs/op
BenchmarkHttpTreeMux_Param           5000000        558 ns/op         340 B/op        2 allocs/op
BenchmarkKocha_Param                 5000000        377 ns/op          58 B/op        2 allocs/op
BenchmarkMartini_Param                500000       6265 ns/op        1251 B/op       12 allocs/op
BenchmarkPat_Param                   1000000       1620 ns/op         670 B/op       11 allocs/op
BenchmarkTigerTonic_Param            1000000       2766 ns/op        1015 B/op       18 allocs/op
BenchmarkTraffic_Param                500000       4440 ns/op        2013 B/op       22 allocs/op
```

Same as before, but now with multiple parameters, all in the same single route. The intention is to see how the routers scale with the number of parameters. The values of the parameters must be passed to the handler function somehow, which requires allocations. Let's see how clever the routers solve this task with a route containing 5 and 20 parameters:
```
BenchmarkBeego_Param5                 100000      18473 ns/op        1291 B/op       14 allocs/op
BenchmarkDenco_Param5                2000000        982 ns/op         405 B/op        5 allocs/op
BenchmarkGocraftWeb_Param5           1000000       2218 ns/op         957 B/op       12 allocs/op
BenchmarkGoji_Param5                 1000000       1093 ns/op         340 B/op        2 allocs/op
BenchmarkGoJsonRest_Param5            200000      10462 ns/op        3264 B/op       40 allocs/op
BenchmarkGorillaMux_Param5            500000       4680 ns/op         906 B/op        7 allocs/op
BenchmarkHttpRouter_Param5           5000000        319 ns/op         162 B/op        1 allocs/op
BenchmarkHttpTreeMux_Param5          2000000        898 ns/op         340 B/op        2 allocs/op
BenchmarkKocha_Param5                1000000       1326 ns/op         448 B/op        7 allocs/op
BenchmarkMartini_Param5               200000      13027 ns/op        1376 B/op       12 allocs/op
BenchmarkPat_Param5                   500000       3416 ns/op        1435 B/op       18 allocs/op
BenchmarkTigerTonic_Param5            200000       9247 ns/op        2568 B/op       41 allocs/op
BenchmarkTraffic_Param5               500000       7206 ns/op        2312 B/op       26 allocs/op

BenchmarkBeego_Param20                 10000     106746 ns/op        3681 B/op       17 allocs/op
BenchmarkDenco_Param20               1000000       2882 ns/op        1666 B/op        7 allocs/op
BenchmarkGocraftWeb_Param20           500000       7156 ns/op        3857 B/op       16 allocs/op
BenchmarkGoji_Param20                1000000       3197 ns/op        1260 B/op        2 allocs/op
BenchmarkGoJsonRest_Param20           100000      25809 ns/op       10605 B/op       75 allocs/op
BenchmarkGorillaMux_Param20           200000       9885 ns/op        3295 B/op        9 allocs/op
BenchmarkHttpRouter_Param20          2000000        954 ns/op         646 B/op        1 allocs/op
BenchmarkHttpTreeMux_Param20          500000       5016 ns/op        2216 B/op        4 allocs/op
BenchmarkKocha_Param20                500000       4268 ns/op        1836 B/op       17 allocs/op
BenchmarkMartini_Param20               50000      55039 ns/op        3765 B/op       14 allocs/op
BenchmarkPat_Param20                  500000       3412 ns/op        1435 B/op       18 allocs/op
BenchmarkTigerTonic_Param20            50000      36825 ns/op       10710 B/op      131 allocs/op
BenchmarkTraffic_Param20              100000      22605 ns/op        8077 B/op       49 allocs/op
```

Now let's see how expensive it is to access a parameter. The handler function reads the value (by the name of the parameter, e.g. with a map lookup; depends on the router) and writes it to our [web scale storage](https://www.youtube.com/watch?v=b2F-DItXtZs) (`/dev/null`).
```
BenchmarkBeego_ParamWrite             500000       6604 ns/op        1602 B/op       18 allocs/op
BenchmarkDenco_ParamWrite            5000000        377 ns/op          50 B/op        2 allocs/op
BenchmarkGocraftWeb_ParamWrite       1000000       1590 ns/op         693 B/op        9 allocs/op
BenchmarkGoji_ParamWrite             2000000        818 ns/op         340 B/op        2 allocs/op
BenchmarkGoJsonRest_ParamWrite        200000       8388 ns/op        2265 B/op       33 allocs/op
BenchmarkGorillaMux_ParamWrite       1000000       2913 ns/op         780 B/op        7 allocs/op
BenchmarkHttpRouter_ParamWrite      10000000        193 ns/op          33 B/op        1 allocs/op
BenchmarkHttpTreeMux_ParamWrite      5000000        649 ns/op         340 B/op        2 allocs/op
BenchmarkKocha_ParamWrite            5000000        435 ns/op          58 B/op        2 allocs/op
BenchmarkMartini_ParamWrite           500000       7538 ns/op        1359 B/op       15 allocs/op
BenchmarkPat_ParamWrite              1000000       2940 ns/op        1109 B/op       15 allocs/op
BenchmarkTigerTonic_ParamWrite        500000       4639 ns/op        1471 B/op       23 allocs/op
BenchmarkTraffic_ParamWrite           500000       5855 ns/op        2435 B/op       25 allocs/op
```

### [Parse.com](https://parse.com/docs/rest#summary)

Enough of the micro benchmark stuff. Let's play a bit with real APIs. In the first set of benchmarks, we use a clone of the structure of [Parse](https://parse.com)'s decent medium-sized REST API, consisting of 26 routes.

The tasks are 1.) routing a static URL (no parameters), 2.) routing a URL containing 1 parameter, 3.) same with 2 parameters, 4.) route all of the routes once (like the StaticAll benchmark, but the routes now contain parameters).

Worth noting is, that the requested route might be a good case for some routing algorithms, while it is a bad case for another algorithm. The values might vary slightly depending on the selected route.

```
BenchmarkBeego_ParseStatic            500000       3461 ns/op        1247 B/op       15 allocs/op
BenchmarkDenco_ParseStatic          50000000         42.6 ns/op         0 B/op        0 allocs/op
BenchmarkGocraftWeb_ParseStatic      2000000        889 ns/op         328 B/op        6 allocs/op
BenchmarkGoji_ParseStatic            5000000        341 ns/op           0 B/op        0 allocs/op
BenchmarkGoJsonRest_ParseStatic       500000       5860 ns/op        1136 B/op       25 allocs/op
BenchmarkGorillaMux_ParseStatic      1000000       2760 ns/op         456 B/op        6 allocs/op
BenchmarkHttpRouter_ParseStatic     50000000         36.7 ns/op         0 B/op        0 allocs/op
BenchmarkHttpTreeMux_ParseStatic    50000000         62.6 ns/op         0 B/op        0 allocs/op
BenchmarkKocha_ParseStatic          50000000         72.2 ns/op         0 B/op        0 allocs/op
BenchmarkMartini_ParseStatic          500000       5528 ns/op         927 B/op       11 allocs/op
BenchmarkPat_ParseStatic             2000000        809 ns/op         246 B/op        5 allocs/op
BenchmarkTigerTonic_ParseStatic     10000000        264 ns/op          49 B/op        1 allocs/op
BenchmarkTraffic_ParseStatic          500000       5008 ns/op        2377 B/op       24 allocs/op

BenchmarkBeego_ParseParam             500000       7983 ns/op        1775 B/op       28 allocs/op
BenchmarkDenco_ParseParam            5000000        347 ns/op          50 B/op        2 allocs/op
BenchmarkGocraftWeb_ParseParam       1000000       1535 ns/op         700 B/op        9 allocs/op
BenchmarkGoji_ParseParam             2000000        983 ns/op         340 B/op        2 allocs/op
BenchmarkGoJsonRest_ParseParam        500000       7208 ns/op        1789 B/op       29 allocs/op
BenchmarkGorillaMux_ParseParam       1000000       3186 ns/op         780 B/op        7 allocs/op
BenchmarkHttpRouter_ParseParam      10000000        178 ns/op          65 B/op        1 allocs/op
BenchmarkHttpTreeMux_ParseParam      5000000        617 ns/op         340 B/op        2 allocs/op
BenchmarkKocha_ParseParam            5000000        413 ns/op          58 B/op        2 allocs/op
BenchmarkMartini_ParseParam           500000       7524 ns/op        1251 B/op       12 allocs/op
BenchmarkPat_ParseParam              1000000       2707 ns/op        1160 B/op       18 allocs/op
BenchmarkTigerTonic_ParseParam       1000000       3010 ns/op        1048 B/op       19 allocs/op
BenchmarkTraffic_ParseParam           500000       5228 ns/op        2314 B/op       24 allocs/op

BenchmarkBeego_Parse2Params           200000       9217 ns/op        1935 B/op       28 allocs/op
BenchmarkDenco_Parse2Params          5000000        542 ns/op         115 B/op        3 allocs/op
BenchmarkGocraftWeb_Parse2Params     1000000       1756 ns/op         750 B/op       10 allocs/op
BenchmarkGoji_Parse2Params           2000000        954 ns/op         340 B/op        2 allocs/op
BenchmarkGoJsonRest_Parse2Params      500000       8131 ns/op        2145 B/op       32 allocs/op
BenchmarkGorillaMux_Parse2Params      500000       3623 ns/op         812 B/op        7 allocs/op
BenchmarkHttpRouter_Parse2Params    10000000        202 ns/op          65 B/op        1 allocs/op
BenchmarkHttpTreeMux_Parse2Params    5000000        708 ns/op         340 B/op        2 allocs/op
BenchmarkKocha_Parse2Params          5000000        666 ns/op         132 B/op        4 allocs/op
BenchmarkMartini_Parse2Params         200000       7723 ns/op        1283 B/op       12 allocs/op
BenchmarkPat_Parse2Params            1000000       2687 ns/op         887 B/op       19 allocs/op
BenchmarkTigerTonic_Parse2Params      500000       4720 ns/op        1473 B/op       28 allocs/op
BenchmarkTraffic_Parse2Params         500000       5467 ns/op        2120 B/op       24 allocs/op

BenchmarkBeego_ParseAll                10000     197920 ns/op       38877 B/op      616 allocs/op
BenchmarkDenco_ParseAll               500000       7692 ns/op        1000 B/op       35 allocs/op
BenchmarkGocraftWeb_ParseAll           50000      36226 ns/op       14639 B/op      208 allocs/op
BenchmarkGoji_ParseAll                100000      19721 ns/op        5448 B/op       32 allocs/op
BenchmarkGoJsonRest_ParseAll           10000     180128 ns/op       41202 B/op      727 allocs/op
BenchmarkGorillaMux_ParseAll           10000     120929 ns/op       17138 B/op      173 allocs/op
BenchmarkHttpRouter_ParseAll          500000       3592 ns/op         660 B/op       16 allocs/op
BenchmarkHttpTreeMux_ParseAll         200000      11650 ns/op        5452 B/op       32 allocs/op
BenchmarkKocha_ParseAll               200000       9371 ns/op        1163 B/op       44 allocs/op
BenchmarkMartini_ParseAll              10000     200307 ns/op       29375 B/op      305 allocs/op
BenchmarkPat_ParseAll                  50000      53113 ns/op       18017 B/op      363 allocs/op
BenchmarkTigerTonic_ParseAll           50000      67208 ns/op       20547 B/op      419 allocs/op
BenchmarkTraffic_ParseAll              10000     164938 ns/op       70161 B/op      743 allocs/op
```

### [GitHub](http://developer.github.com/v3/)

The GitHub API is rather large, consisting of 203 routes. The tasks are basically the same as in the benchmarks before.

```
BenchmarkBeego_GithubStatic           500000       3880 ns/op        1148 B/op       31 allocs/op
BenchmarkDenco_GithubStatic         50000000         60.5 ns/op         0 B/op        0 allocs/op
BenchmarkGocraftWeb_GithubStatic     2000000        933 ns/op         328 B/op        6 allocs/op
BenchmarkGoji_GithubStatic           5000000        401 ns/op           0 B/op        0 allocs/op
BenchmarkGoJsonRest_GithubStatic      500000       6006 ns/op        1150 B/op       25 allocs/op
BenchmarkGorillaMux_GithubStatic      100000      18227 ns/op         456 B/op        6 allocs/op
BenchmarkHttpRouter_GithubStatic    50000000         63.2 ns/op         0 B/op        0 allocs/op
BenchmarkHttpTreeMux_GithubStatic   50000000         65.1 ns/op         0 B/op        0 allocs/op
BenchmarkKocha_GithubStatic         20000000         99.5 ns/op         0 B/op        0 allocs/op
BenchmarkMartini_GithubStatic         100000      18546 ns/op         927 B/op       11 allocs/op
BenchmarkPat_GithubStatic             200000      11503 ns/op        3754 B/op       76 allocs/op
BenchmarkTigerTonic_GithubStatic     5000000        308 ns/op          49 B/op        1 allocs/op
BenchmarkTraffic_GithubStatic          50000      44923 ns/op       23105 B/op      168 allocs/op

BenchmarkBeego_GithubParam             50000      44645 ns/op        2973 B/op       50 allocs/op
BenchmarkDenco_GithubParam           5000000        643 ns/op         115 B/op        3 allocs/op
BenchmarkGocraftWeb_GithubParam      1000000       1855 ns/op         750 B/op       10 allocs/op
BenchmarkGoji_GithubParam            1000000       1314 ns/op         340 B/op        2 allocs/op
BenchmarkGoJsonRest_GithubParam       200000       8427 ns/op        2159 B/op       32 allocs/op
BenchmarkGorillaMux_GithubParam       200000      11485 ns/op         813 B/op        7 allocs/op
BenchmarkHttpRouter_GithubParam      5000000        304 ns/op          97 B/op        1 allocs/op
BenchmarkHttpTreeMux_GithubParam     2000000        770 ns/op         340 B/op        2 allocs/op
BenchmarkKocha_GithubParam           5000000        754 ns/op         132 B/op        4 allocs/op
BenchmarkMartini_GithubParam          100000      22637 ns/op        1284 B/op       12 allocs/op
BenchmarkPat_GithubParam              500000       7319 ns/op        2538 B/op       44 allocs/op
BenchmarkTigerTonic_GithubParam       500000       4722 ns/op        1467 B/op       26 allocs/op
BenchmarkTraffic_GithubParam          100000      18700 ns/op        7076 B/op       58 allocs/op

BenchmarkBeego_GithubAll                 100   23430165 ns/op      502614 B/op     9871 allocs/op
BenchmarkDenco_GithubAll               10000     120365 ns/op       21219 B/op      506 allocs/op
BenchmarkGocraftWeb_GithubAll           5000     358982 ns/op      139091 B/op     1903 allocs/op
BenchmarkGoji_GithubAll                 5000     604522 ns/op       56896 B/op      340 allocs/op
BenchmarkGoJsonRest_GithubAll           1000    1645794 ns/op      404222 B/op     6303 allocs/op
BenchmarkGorillaMux_GithubAll            500    6634737 ns/op      152277 B/op     1402 allocs/op
BenchmarkHttpRouter_GithubAll          50000      51138 ns/op       14039 B/op      168 allocs/op
BenchmarkHttpTreeMux_GithubAll         10000     132507 ns/op       56907 B/op      340 allocs/op
BenchmarkKocha_GithubAll               10000     143398 ns/op       24117 B/op      676 allocs/op
BenchmarkMartini_GithubAll               200    9802351 ns/op      258349 B/op     2713 allocs/op
BenchmarkPat_GithubAll                   500    4154815 ns/op     1539081 B/op    24970 allocs/op
BenchmarkTigerTonic_GithubAll           2000     920839 ns/op      247085 B/op     5171 allocs/op
BenchmarkTraffic_GithubAll               200    8087393 ns/op     3143039 B/op    23958 allocs/op
```

### [Google+](https://developers.google.com/+/api/latest/)

Last but not least the Google+ API, consisting of 13 routes. In reality this is just a subset of a much larger API.

```
BenchmarkBeego_GPlusStatic           1000000       2321 ns/op         808 B/op       11 allocs/op
BenchmarkDenco_GPlusStatic          50000000         37.2 ns/op         0 B/op        0 allocs/op
BenchmarkGocraftWeb_GPlusStatic      2000000        862 ns/op         312 B/op        6 allocs/op
BenchmarkGoji_GPlusStatic           10000000        270 ns/op           0 B/op        0 allocs/op
BenchmarkGoJsonRest_GPlusStatic       500000       5827 ns/op        1136 B/op       25 allocs/op
BenchmarkGorillaMux_GPlusStatic      1000000       1793 ns/op         456 B/op        6 allocs/op
BenchmarkHttpRouter_GPlusStatic     50000000         34.6 ns/op         0 B/op        0 allocs/op
BenchmarkHttpTreeMux_GPlusStatic    50000000         35.4 ns/op         0 B/op        0 allocs/op
BenchmarkKocha_GPlusStatic          50000000         63.8 ns/op         0 B/op        0 allocs/op
BenchmarkMartini_GPlusStatic          500000       4887 ns/op         927 B/op       11 allocs/op
BenchmarkPat_GPlusStatic             5000000        336 ns/op          98 B/op        2 allocs/op
BenchmarkTigerTonic_GPlusStatic     10000000        186 ns/op          33 B/op        1 allocs/op
BenchmarkTraffic_GPlusStatic          500000       3350 ns/op        1503 B/op       18 allocs/op

BenchmarkBeego_GPlusParam             200000       7657 ns/op        1231 B/op       16 allocs/op
BenchmarkDenco_GPlusParam            5000000        365 ns/op          50 B/op        2 allocs/op
BenchmarkGocraftWeb_GPlusParam       1000000       1519 ns/op         684 B/op        9 allocs/op
BenchmarkGoji_GPlusParam             2000000        889 ns/op         340 B/op        2 allocs/op
BenchmarkGoJsonRest_GPlusParam        500000       7388 ns/op        1806 B/op       29 allocs/op
BenchmarkGorillaMux_GPlusParam        500000       4040 ns/op         780 B/op        7 allocs/op
BenchmarkHttpRouter_GPlusParam      10000000        203 ns/op          65 B/op        1 allocs/op
BenchmarkHttpTreeMux_GPlusParam      5000000        638 ns/op         340 B/op        2 allocs/op
BenchmarkKocha_GPlusParam            5000000        444 ns/op          58 B/op        2 allocs/op
BenchmarkMartini_GPlusParam           200000       8672 ns/op        1251 B/op       12 allocs/op
BenchmarkPat_GPlusParam              1000000       1895 ns/op         719 B/op       12 allocs/op
BenchmarkTigerTonic_GPlusParam       1000000       3166 ns/op        1085 B/op       18 allocs/op
BenchmarkTraffic_GPlusParam           500000       5369 ns/op        2030 B/op       22 allocs/op

BenchmarkBeego_GPlus2Params           200000       9999 ns/op        1293 B/op       16 allocs/op
BenchmarkDenco_GPlus2Params          5000000        618 ns/op         115 B/op        3 allocs/op
BenchmarkGocraftWeb_GPlus2Params     1000000       1860 ns/op         750 B/op       10 allocs/op
BenchmarkGoji_GPlus2Params           1000000       1296 ns/op         340 B/op        2 allocs/op
BenchmarkGoJsonRest_GPlus2Params      200000       8516 ns/op        2178 B/op       32 allocs/op
BenchmarkGorillaMux_GPlus2Params      200000       9007 ns/op         812 B/op        7 allocs/op
BenchmarkHttpRouter_GPlus2Params    10000000        246 ns/op          65 B/op        1 allocs/op
BenchmarkHttpTreeMux_GPlus2Params    2000000        751 ns/op         340 B/op        2 allocs/op
BenchmarkKocha_GPlus2Params          5000000        744 ns/op         132 B/op        4 allocs/op
BenchmarkMartini_GPlus2Params         100000      27700 ns/op        1382 B/op       16 allocs/op
BenchmarkPat_GPlus2Params             500000       5981 ns/op        2347 B/op       34 allocs/op
BenchmarkTigerTonic_GPlus2Params      500000       5076 ns/op        1561 B/op       27 allocs/op
BenchmarkTraffic_GPlus2Params         200000      12711 ns/op        3599 B/op       34 allocs/op

BenchmarkBeego_GPlusAll                10000     113601 ns/op       15897 B/op      217 allocs/op
BenchmarkDenco_GPlusAll               500000       5761 ns/op         880 B/op       27 allocs/op
BenchmarkGocraftWeb_GPlusAll          100000      20527 ns/op        8513 B/op      116 allocs/op
BenchmarkGoji_GPlusAll                200000      12312 ns/op        3746 B/op       22 allocs/op
BenchmarkGoJsonRest_GPlusAll           20000      99250 ns/op       23871 B/op      386 allocs/op
BenchmarkGorillaMux_GPlusAll           50000      63046 ns/op        9655 B/op       90 allocs/op
BenchmarkHttpRouter_GPlusAll         1000000       2513 ns/op         655 B/op       11 allocs/op
BenchmarkHttpTreeMux_GPlusAll         500000       7706 ns/op        3748 B/op       22 allocs/op
BenchmarkKocha_GPlusAll               500000       6858 ns/op        1017 B/op       35 allocs/op
BenchmarkMartini_GPlusAll              10000     155402 ns/op       16368 B/op      179 allocs/op
BenchmarkPat_GPlusAll                  50000      47397 ns/op       17270 B/op      302 allocs/op
BenchmarkTigerTonic_GPlusAll           50000      49864 ns/op       15160 B/op      311 allocs/op
BenchmarkTraffic_GPlusAll              10000     108007 ns/op       41779 B/op      430 allocs/op
```

## Conclusions
First of all, there is no reason to use net/http's default [ServeMux](http://golang.org/pkg/net/http/#ServeMux), which is very limited and does not have especially good performance. There are enough alternatives coming in every flavor, choose the one you like best.

Secondly, the broad range of functions of some of the frameworks comes at a high price in terms of performance. For example Martini has great flexibility, but very bad performance. Martini has the worst performance of all tested routers in a lot of the benchmarks. Beego seems to have some scalability problems and easily defeats Martini with even worse performance, when the number of parameters or routes is high. I really hope, that the routing of these packages can be optimized. I think the Go-ecosystem needs great feature-rich frameworks like these.

Last but not least, we have to determine the performance champion.

Denco and its predecessor Kocha-urlrouter seem to have great performance, but are not convenient to use as a router for the net/http package. A lot of extra work is necessary to use it as a http.Handler. [The README of Denco claims](https://github.com/naoina/denco/blob/b03dbb499269a597afd0db715d408ebba1329d04/README.md), that the package is not intended as a replacement for [http.ServeMux](http://golang.org/pkg/net/http/#ServeMux).

[Goji](https://github.com/zenazn/goji/) looks very decent. It has great performance while also having a great range of features, more than any other router / framework in the top group.

Currently no router can beat the performance of the [HttpRouter](https://github.com/julienschmidt/httprouter) package, which currently dominates nearly all benchmarks.

In the end, performance can not be the (only) criterion for choosing a router. Play around a bit with some of the routers, and choose the one you like best.


text:
package com.luqili.utils.maven_utils;

/**
 * Created by cyh on 2015/5/2.
 */

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HtmlCompressorTool {
  private static String tempPreBlock = "%%%HTMLCOMPRESS~PRE&&&";
  private static String tempTextAreaBlock = "%%%HTMLCOMPRESS~TEXTAREA&&&";
  private static String tempScriptBlock = "%%%HTMLCOMPRESS~SCRIPT&&&";
  private static String tempStyleBlock = "%%%HTMLCOMPRESS~STYLE&&&";
  private static String tempJspBlock = "%%%HTMLCOMPRESS~JSP&&&";

  //HTML注释语法 <!-- -->
  private static Pattern commentPattern = Pattern.compile("<!--\\s*[^\\[].*?-->", Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
  //HTML中的空白字符
  private static Pattern itsPattern = Pattern.compile(">\\s+?<", Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

  private static Pattern prePattern = Pattern.compile("<pre[^>]*?>.*?</pre>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
  //HTML中的文本域不做处理
  private static Pattern taPattern = Pattern.compile("<textarea[^>]*?>.*?</textarea>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
  //HTML中的Java代码
  private static Pattern jspPattern = Pattern.compile("<%([^-@][\\w\\W]*?)%>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
  // <script></script>
  private static Pattern scriptPattern = Pattern.compile("(?:<script\\s*>|<script type=['\"]text/javascript['\"]\\s*>)(.*?)</script>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
  // <style></style>
  private static Pattern stylePattern = Pattern.compile("<style[^>()]*?>(.+)</style>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

  // 单行注释,
  private static Pattern signleCommentPattern = Pattern.compile("//.*");
  // 字符串匹配
  private static Pattern stringPattern = Pattern.compile("(\"[^\"\\n]*?\"|'[^'\\n]*?')");
  // trim去空格和换行符
  private static Pattern trimPattern = Pattern.compile("\\n\\s*", Pattern.MULTILINE);
  private static Pattern trimPattern2 = Pattern.compile("\\s*\\r", Pattern.MULTILINE);
  // Js中的多行注释
  private static Pattern multiCommentPattern = Pattern.compile("/\\*.*?\\*/", Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

  private static String tempSingleCommentBlock = "%%%HTMLCOMPRESS~SINGLECOMMENT&&&"; // //占位符
  private static String tempMulitCommentBlock1 = "%%%HTMLCOMPRESS~MULITCOMMENT1&&&"; // /*占位符
  private static String tempMulitCommentBlock2 = "%%%HTMLCOMPRESS~MULITCOMMENT2&&&"; // */占位符

  public static void main(String[] args) {

    try {
      System.out.println(args[0]);
      System.out.println(args[1]);
      System.out.println(args[2]);
      String path = args[0];
      String order = args[1];
      String outPath = args[2];
      if (order.equalsIgnoreCase("-o")) {
        String str = Read(path);
        str = compress(str);
        Write(outPath, str);
      } else {
        System.out.println("use -o to set output path.");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private static String Read(String path) throws IOException {
    File file = new File(path);
    // BufferedReader:从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。
    BufferedReader bufReader = null;
    StringBuilder sb = new StringBuilder();
    try {
      // FileReader:用来读取字符文件的便捷类。
      InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
      bufReader = new BufferedReader(isr);
      // buf = new BufferedReader(new InputStreamReader(new
      // FileInputStream(file)));
      String temp = null;
      while ((temp = bufReader.readLine()) != null) {
        sb.append(temp).append("\n");
      }
    } catch (Exception e) {
      e.getStackTrace();
    } finally {
      if (bufReader != null) {
        try {
          bufReader.close();
        } catch (IOException e) {
          e.getStackTrace();
        }
      }
    }
    return sb.toString();
  }

  private static void Write(String path, String text) throws IOException {
    try {
      File f = new File(path);
      if (!f.exists()) {
        f.createNewFile();
      }
      OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
      BufferedWriter writer = new BufferedWriter(write);
      writer.write(text);
      writer.close();
    } catch (Exception e) {
      e.getStackTrace();
    }
  }

  public static String compress(String html) throws Exception {
    if (html == null || html.length() == 0) {
      return html;
    }

    List<String> preBlocks = new ArrayList<String>();
    List<String> taBlocks = new ArrayList<String>();
    List<String> scriptBlocks = new ArrayList<String>();
    List<String> styleBlocks = new ArrayList<String>();
    List<String> jspBlocks = new ArrayList<String>();

    String result = html;

    // preserve inline java code
    Matcher jspMatcher = jspPattern.matcher(result);
    while (jspMatcher.find()) {
      jspBlocks.add(jspMatcher.group(0));
    }
    result = jspMatcher.replaceAll(tempJspBlock);

    // preserve PRE tags
    Matcher preMatcher = prePattern.matcher(result);
    while (preMatcher.find()) {
      preBlocks.add(preMatcher.group(0));
    }
    result = preMatcher.replaceAll(tempPreBlock);

    // preserve TEXTAREA tags
    Matcher taMatcher = taPattern.matcher(result);
    while (taMatcher.find()) {
      taBlocks.add(taMatcher.group(0));
    }
    result = taMatcher.replaceAll(tempTextAreaBlock);

    // preserve SCRIPT tags
    Matcher scriptMatcher = scriptPattern.matcher(result);
    while (scriptMatcher.find()) {
      scriptBlocks.add(scriptMatcher.group(0));
    }
    result = scriptMatcher.replaceAll(tempScriptBlock);

    // don't process inline css
    Matcher styleMatcher = stylePattern.matcher(result);
    while (styleMatcher.find()) {
      styleBlocks.add(styleMatcher.group(0));
    }
    result = styleMatcher.replaceAll(tempStyleBlock);

    // process pure html
    result = processHtml(result);

    // process preserved blocks
    result = processPreBlocks(result, preBlocks);
    result = processTextareaBlocks(result, taBlocks);
    result = processScriptBlocks(result, scriptBlocks);
    result = processStyleBlocks(result, styleBlocks);
    result = processJspBlocks(result, jspBlocks);

    preBlocks = taBlocks = scriptBlocks = styleBlocks = jspBlocks = null;

    return result.trim();
  }

  private static String processHtml(String html) {
    String result = html;

    // remove comments
    // if(removeComments) {
    result = commentPattern.matcher(result).replaceAll("");
    // }

    // remove inter-tag spaces
    // if(removeIntertagSpaces) {
    result = itsPattern.matcher(result).replaceAll("><");
    // }

    // remove multi whitespace characters
    // if(removeMultiSpaces) {
    result = result.replaceAll("\\s{2,}", " ");
    // }

    return result;
  }

  private static String processJspBlocks(String html, List<String> blocks) {
    String result = html;
    for (int i = 0; i < blocks.size(); i++) {
      blocks.set(i, compressJsp(blocks.get(i)));
    }
    // put preserved blocks back
    while (result.contains(tempJspBlock)) {
      result = result.replaceFirst(tempJspBlock, Matcher.quoteReplacement(blocks.remove(0)));
    }

    return result;
  }

  private static String processPreBlocks(String html, List<String> blocks) throws Exception {
    String result = html;

    // put preserved blocks back
    while (result.contains(tempPreBlock)) {
      result = result.replaceFirst(tempPreBlock, Matcher.quoteReplacement(blocks.remove(0)));
    }

    return result;
  }

  private static String processTextareaBlocks(String html, List<String> blocks) throws Exception {
    String result = html;

    // put preserved blocks back
    while (result.contains(tempTextAreaBlock)) {
      result = result.replaceFirst(tempTextAreaBlock, Matcher.quoteReplacement(blocks.remove(0)));
    }

    return result;
  }

  private static String processScriptBlocks(String html, List<String> blocks) throws Exception {
    String result = html;

    // if(compressJavaScript) {
    for (int i = 0; i < blocks.size(); i++) {
      blocks.set(i, compressJavaScript(blocks.get(i)));
    }
    // }

    // put preserved blocks back
    while (result.contains(tempScriptBlock)) {
      result = result.replaceFirst(tempScriptBlock, Matcher.quoteReplacement(blocks.remove(0)));
    }

    return result;
  }

  private static String processStyleBlocks(String html, List<String> blocks) throws Exception {
    String result = html;

    // if(compressCss) {
    for (int i = 0; i < blocks.size(); i++) {
      blocks.set(i, compressCssStyles(blocks.get(i)));
    }
    // }

    // put preserved blocks back
    while (result.contains(tempStyleBlock)) {
      result = result.replaceFirst(tempStyleBlock, Matcher.quoteReplacement(blocks.remove(0)));
    }

    return result;
  }

  private static String compressJsp(String source) {
    // check if block is not empty
    Matcher jspMatcher = jspPattern.matcher(source);
    if (jspMatcher.find()) {
      String result = compressJspJs(jspMatcher.group(1));
      return (new StringBuilder(source.substring(0, jspMatcher.start(1))).append(result).append(source.substring(jspMatcher.end(1)))).toString();
    } else {
      return source;
    }
  }

  private static String compressJavaScript(String source) {
    // check if block is not empty
    Matcher scriptMatcher = scriptPattern.matcher(source);
    if (scriptMatcher.find()) {
      String result = compressJspJs(scriptMatcher.group(1));
      return (new StringBuilder(source.substring(0, scriptMatcher.start(1))).append(result).append(source.substring(scriptMatcher.end(1)))).toString();
    } else {
      return source;
    }
  }

  private static String compressCssStyles(String source) {
    // check if block is not empty
    Matcher styleMatcher = stylePattern.matcher(source);
    if (styleMatcher.find()) {
      // 去掉注释,换行
      String result = multiCommentPattern.matcher(styleMatcher.group(1)).replaceAll("");
      result = trimPattern.matcher(result).replaceAll("");
      result = trimPattern2.matcher(result).replaceAll("");
      return (new StringBuilder(source.substring(0, styleMatcher.start(1))).append(result).append(source.substring(styleMatcher.end(1)))).toString();
    } else {
      return source;
    }
  }

  private static String compressJspJs(String source) {
    String result = source;
    // 因注释符合有可能出现在字符串中,所以要先把字符串中的特殊符好去掉
    Matcher stringMatcher = stringPattern.matcher(result);
    while (stringMatcher.find()) {
      String tmpStr = stringMatcher.group(0);

      if (tmpStr.indexOf("//") != -1 || tmpStr.indexOf("/*") != -1 || tmpStr.indexOf("*/") != -1) {
        String blockStr = tmpStr.replaceAll("//", tempSingleCommentBlock).replaceAll("/\\*", tempMulitCommentBlock1).replaceAll("\\*/", tempMulitCommentBlock2);
        result = result.replace(tmpStr, blockStr);
      }
    }
    // 去掉注释
    result = signleCommentPattern.matcher(result).replaceAll("");
    result = multiCommentPattern.matcher(result).replaceAll("");
    result = trimPattern2.matcher(result).replaceAll("");
    result = trimPattern.matcher(result).replaceAll(" ");
    // 恢复替换掉的字符串
    result = result.replaceAll(tempSingleCommentBlock, "//").replaceAll(tempMulitCommentBlock1, "/*").replaceAll(tempMulitCommentBlock2, "*/");

    return result;
  }
}


text:
package org.apache.juddi.v3.client.subscription;

import org.uddi.sub_v3.SubscriptionResultsList;

/**
 * This is an interface for creating asynchronous callback clients for the
 * UDDI Subscription API.
 *
 * Change notice, since 3.3.5, methods were renamed for the most standard convention (lowercase)
 * @since 3.2
 * @author Alex O'Ree
 * @see SubscriptionCallbackListener
 */
public interface ISubscriptionCallback {

    /**
     * Called when a UDDI server notifies us that something has changed.
     * Implementations should never block.
     * @param body
     */
    public void handleCallback(SubscriptionResultsList body);

    /**
     * Called when the callback endpoint is stopped
     */
    public void notifyEndpointStopped();
}


text:
import { RowNode } from "./entities/rowNode";
import { exists, defaultComparator } from "./utils/generic";

export function defaultGroupComparator(valueA: any, valueB: any, nodeA: RowNode, nodeB: RowNode, accentedCompare: boolean = false): number {
    console.warn('AG Grid: Since ag-grid 11.0.0 defaultGroupComparator is not necessary. You can remove this from your colDef');
    const nodeAIsGroup = exists(nodeA) && nodeA.group;
    const nodeBIsGroup = exists(nodeB) && nodeB.group;

    const bothAreGroups = nodeAIsGroup && nodeBIsGroup;
    const bothAreNormal = !nodeAIsGroup && !nodeBIsGroup;

    if (bothAreGroups) {
        return defaultComparator(nodeA.key, nodeB.key, accentedCompare);
    }

    if (bothAreNormal) {
        return defaultComparator(valueA, valueB, accentedCompare);
    }

    if (nodeAIsGroup) {
        return 1;
    }

    return -1;
}


text:
var marked = require('marked'),
    fm = require('front-matter'),
    url = require('url'),

    // private vars
    rebaseLinksPath = "",
    ghUser = "",
    ghRepo = "",
    ghBranch = "",
    ghDir = "";

// initialize marked renderer
var renderer = new marked.Renderer();
renderer.link = function (href, title, text) {

    var localUrl = rebaseLink(rebaseLinksPath, href);

    var out = '' + text + '';
    return out;

};
renderer.image = function(href, title, text){

    var localUrl = rebaseLink(rebaseLinksPath, href);

    var out = '';
    return out;

};
marked.setOptions({
    renderer: renderer,
    gfm: true,
    tables: true,
    breaks: false,
    pedantic: false,
    sanitize: true,
    smartLists: true,
    smartypants: false
});

function rebaseLink(rebaseRoot, href){

    var pUrl = url.parse(href);
    var localUrl = pUrl.path;

    // rebase absolute URLs if the host is github.com
    if(pUrl.host){

        if(ghUser && ghRepo && ((pUrl.host == "github.com") || (pUrl.host == "raw.githubusercontent.com"))) {

            // ONLY rebase matching absolute GitHub links
            var ghTreeLink = "/" + [ghUser, ghRepo, "tree", ghBranch, ghDir].join("/");
            var ghBlobLink = "/" + [ghUser, ghRepo, "blob", ghBranch, ghDir].join("/");
            var ghRawLink = "/" + [ghUser, ghRepo, ghBranch, ghDir].join("/");

            if (pUrl.path.indexOf(ghTreeLink) == 0) {
                localUrl = rebaseRoot + pUrl.path.substring(ghTreeLink.length);
            } else if (pUrl.path.indexOf(ghBlobLink) == 0) {
                localUrl = rebaseRoot + pUrl.path.substring(ghBlobLink.length);
            } else if(pUrl.path.indexOf(ghRawLink) == 0) {
                localUrl = rebaseRoot + pUrl.path.substring(ghRawLink.length);
            } else {

                // cannot rebase anything
                return href;

            }

        } else {

            // cannot rebase anything
            return href;

        }

        // rebase any other absolute URLs
    } else if(localUrl && (localUrl.length > 0) && (localUrl[0] == "/")){

        localUrl = rebaseRoot + localUrl;

    }

    // remove readme.md && .md
    if(localUrl && (localUrl.length > 3) && (localUrl.substr(-3) == ".md")){

        // remove .md
        localUrl = localUrl.substr(0, localUrl.length-3);

        // remove readme
        if((localUrl.length > 6) && (localUrl.substr(-6).toLowerCase() == "readme")){
            localUrl = localUrl.substr(0, localUrl.length-6);
        }
    }

    // remove trailing slash
    if(localUrl && (localUrl.length > 1) && (localUrl.substr(-1) == "/")){
        localUrl = localUrl.substr(0, localUrl.length-1);
    }

    // add hash
    if(pUrl.hash){
        if(!localUrl) localUrl = '';
        localUrl += pUrl.hash;
    }

    return localUrl;
}

function mdParser(rawFile, opts){

    // expose private vars
    rebaseLinksPath = opts.rebasePath || "";
    ghUser = opts.ghUser || "";
    ghRepo = opts.ghRepo || "";
    ghBranch = opts.ghBranch || "master";
    ghDir = opts.ghDir || "docs";

    // parse front matter
    var data = fm(rawFile);

    // parse content
    if(data && data.body){
        data.content = marked(data.body);
    } else {
        data.content = "";
    }

    return data;
}

module.exports = mdParser;