text:
import os
from setuptools import setup

def read(*path):
    """Use this to read files from source directory"""
    with open(
            os.path.join(os.path.dirname(__file__), *path),
            encoding="utf8"
    ) as fp:
        return fp.read()

setup(
    name="rucola-permalinks",
    version='0.0.1',
    license="MIT",

    description="A Rucola plugin used to create custom permalinks for site pages",
    long_description=read("README.rst"),

    author="Kasper Minciel",
    author_email="kasper.minciel@gmail.com",

    url="https://github.com/lecnim/rucola-permalinks",

    py_modules=['rucola_permalinks'],
    include_package_data=True,
    zip_safe=False,
    test_suite='tests',

    classifiers=[
        "Environment :: Plugins"
    ],
    install_requires=["rucola"]
)


text:
using LiveSplit.Options;
using LiveSplit.UI.Components;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows.Forms;

namespace LiveSplit.Model
{
    public enum AutoSplitterType
    {
        Component, Script
    }
    public class AutoSplitter
    {
        public string Description { get; set; }
        public IEnumerable<string> Games { get; set; }
        public bool IsActivated { get { return Component != null; } }
        public List<string> URLs { get; set; }
        public string LocalPath { get { return Path.GetFullPath(Path.Combine(ComponentManager.BasePath ?? "", ComponentManager.PATH_COMPONENTS, FileName)); } }
        public string FileName { get { return URLs.First().Substring(URLs.First().LastIndexOf('/') + 1); } }
        public AutoSplitterType Type { get; set; }
        public bool ShowInLayoutEditor { get; set; }
        public IComponent Component { get; set; }
        public IComponentFactory Factory { get; set; }
        public bool IsDownloaded { get { return File.Exists(LocalPath); } }

        public void Activate(LiveSplitState state)
        {
            if (!IsActivated)
            {
                try
                {
                    if (!IsDownloaded || Type == AutoSplitterType.Script)
                        DownloadFiles();
                    if (Type == AutoSplitterType.Component)
                    {
                        Factory = ComponentManager.ComponentFactories[FileName];
                        Component = Factory.Create(state);
                    }
                    else
                    {
                        Factory = ComponentManager.ComponentFactories["LiveSplit.ScriptableAutoSplit.dll"];
                        Component = ((dynamic)Factory).Create(state, LocalPath);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    MessageBox.Show(state.Form, "The Auto Splitter could not be activated. (" + ex.Message + ")", "Activation Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void DownloadFiles()
        {
            var client = new WebClient();

            foreach (var url in URLs)
            {
                var fileName = url.Substring(url.LastIndexOf('/') + 1);
                var localPath = Path.GetFullPath(Path.Combine(ComponentManager.BasePath ?? "", ComponentManager.PATH_COMPONENTS, fileName));

                try
                {
                    client.DownloadFile(new Uri(url), localPath);
                }
                catch (WebException)
                {
                    Log.Error("Error downloading file from " + url);
                }
            }

            if (Type == AutoSplitterType.Component)
            {
                var factory = ComponentManager.LoadFactory(LocalPath);
                ComponentManager.ComponentFactories.Add(Path.GetFileName(LocalPath), factory);
            }
        }

        public void Deactivate()
        {
            if (IsActivated)
            {
                Component.Dispose();
                Component = null;
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
		<input name="{{ property.name }}"type="radio" name="{{property.name}}" ng-value="true" ng-model="value.text" id="{{ fieldId }}-true" ng-disabled="disableField(mode, property)">
		{{ true | activeInactive:property:mode | translate }}

		<input type="radio" name="{{property.name}}" ng-value="false" ng-model="value.text" id="{{ fieldId }}-false" ng-disabled="disableField(mode, property)">
		{{ false | activeInactive:property:mode | translate }}


text:
<link   type="text/css" href="<?php echo base_url(); ?>assets/css/dark-hive/jquery-ui-1.8.10.custom.css" rel="stylesheet" />

<?php mensaje_resultado($mensaje); ?>

Informacion del grupo

				    Nombre
				    <input type="email" class="form-control" id="email" value="<?=$grupo_informacion['nombre']?>" readonly="readonly">

				    Cantidad default
            <input type="email" class="form-control" id="email" value="<?=$grupo_informacion['cantidad_default']?>" readonly="readonly">

			    	Cantidad máxima
			    	<input type="email" class="form-control" id="email" value="<?=$grupo_informacion['cantidad_minima']?>" readonly="readonly">

            Cantidad minima
            <input type="email" class="form-control" id="email" value="<?=$grupo_informacion['cantidad_maxima']?>" readonly="readonly">

            Precio adicional ($)
            <input type="email" class="form-control" id="email" value="<?=$grupo_informacion['precio_adicional']?>" readonly="readonly">

            <a class="btn btn-primary btn-block" class="form-control" href="<?=base_url()?>/index.php/administrador/grupo_ingregientes/edit/<?=$grupo_informacion['id_grupo']?>"> Editar

Ingredientes del grupo

          <?php if(count($grupo_ingredientes) > 0 ): ?>

              <?php foreach ($grupo_ingredientes as $row): ?>

                  <img style="width:100px"  class="img img-responsive" src="<?=base_url()?>/assets/images/productos/<?=$row['path_imagen']?>">
                  <?=$row['nombre']?>

                    <a class="btn btn-danger btn-xs" onclick="eliminar_ingrediente_grupo(<?=$row['id_ingrediente']?>,<?=$row['id_grupo']?>)">
                      Eliminar

              <?php endforeach ?>

        <?php  else: ?>

                No hay ingredientes. Aún no se ha cargado ningún ingrediente al grupo.

        <?php  endif;  ?>

Agregar ingrediente

    		<form  name="form_agregar_ingrediente2" id="form_agregar_ingrediente"  method="POST"  action="<?=base_url()?>index.php/administrador/agregar_ingrediente_grupo/" >

          <input type="hidden" class="form-control" name="id_grupo" id="id_grupo" value="<?=$grupo_informacion['id_grupo']?>" readonly="readonly">

  				    Buscar Ingrediente
  				    <input type="text" class="form-control" id="ingrediente"  name="ingrediente" >

                No se ha encontrado ningún ingrediente.

              <input readonly="readonly" type="text" class="form-control" id="ingrediente_seleccionado"  name="ingrediente_seleccionado" >

              <input readonly="readonly" type="hidden" class="form-control" id="id_ingrediente" name="id_ingrediente" >

                <input class="btn btn-primary" type="submit" value="Agregar Ingrediente" >

  			</form>


text:
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>{{meta.title}}</title>
    <meta name="description" content="{{meta.description}}">
    <meta name="keywords" content="{{meta.keywords}}">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    {% include "../includes/socialmeta.html" %}

    <link rel="stylesheet" href="/css/app.css">
    <link rel="stylesheet" href="/css/fonts.css">

    <script src="/js/modernizr.js"></script>

</head>

<body>

{% include "../includes/header.html" %}

{% block content %}{% endblock %}

{% include "../includes/footer.html" %}

<script src="/js/app.js"></script>
{% block extrajs %}{% endblock %}

</body>

</html>


text:
package cn.net.normcore.iorder.service.promotion.impl;

import cn.net.normcore.iorder.entity.promotion.Promotion;
import cn.net.normcore.iorder.repository.promotion.PromotionRepository;
import cn.net.normcore.iorder.service.BaseServiceImpl;
import cn.net.normcore.iorder.service.promotion.PromotionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by 81062 on 2017/3/19.
 */
@Service
@Transactional(readOnly = true)
public class PromotionServiceImpl extends BaseServiceImpl<Promotion, Long, PromotionRepository> implements PromotionService {
}


text:
package com.azakordonets.utils

import com.azakordonets.entities.{DatesRange, NextDay, RelativeDate}
import com.azakordonets.enums.Day
import org.joda.time.{DateTime, DateTimeZone, LocalDate}

object DateTimeUtils {
  def apply(): DateTimeUtils = {
    new DateTimeUtils
  }
}

class DateTimeUtils {

  def datesRange: DatesRange = new DatesRange

  def relativeDate: RelativeDate = new RelativeDate

  def relativeDate(initialDate: DateTime): RelativeDate = new RelativeDate(initialDate)

  def relativeDate(timeZone: DateTimeZone): RelativeDate = new RelativeDate(timeZone)

  def getNext(dayOfWeek: Day): NextDay = NextDay(dayOfWeek)

  def getNext(dayOfWeek: Day, startPoint: LocalDate): NextDay = NextDay(dayOfWeek, startPoint)

}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

  <solid
      android:color="@color/translucent_white"/>

  <corners
      android:radius="@dimen/images_count_bg_corners"/>

  <padding
      android:top="@dimen/images_count_bg_padding_vertical"
      android:bottom="@dimen/images_count_bg_padding_vertical"
      android:left="@dimen/images_count_bg_padding_horizontal"
      android:right="@dimen/images_count_bg_padding_horizontal"/>

</shape>


text:
*Projeto da cadeira de testes 2016.2*

Nesse tutorial vamos demonstrar diversos casos de uso de uma das ferramentas de testes de performance e carga mais conhecidos, o Jmeter!

###O que é o Jmeter?

é uma aplicação Java projetado para testar e medir a Performance de aplicações web. Pode ser utilizado como um servidor de benchmarck bem como gerador de carga multiclient.

Algumas features são:

Capacidade de testes de carregar e de performance em diferentes tipode de servidores / protocolos:

* Web - HTTP, HTTPS
* SOAP / REST
* FTP
* Banco de dados via JDBC
* LDAP
* Middleware orientado a mensagem (MOM) via JMS
* Mail - SMTP (S), POP3 (S) e IMAP (S)
* Native commands ou scripts shell
* TCP

### Pre requisitos

A seguir os pré requisitos para rodar os testes do tutorial com o JMeter:

* Java 7 (mínimo) Runtime Environment.
* JDBC

## Instalando

###Para Windows

* Faça o Download da versão mais atual do Jmeter [aqui](http://jmeter.apache.org/download_jmeter.cgi]).
* Descompactar arquivo numa pasta.
Para rodar o Jmeter
```
jmeter.bat
```

###Para Mac
Caso você tenha o Homebrew vá para o Terminal:

```
brew update
```

```
brew install jmeter --with-plugins
```
e para rodar o Jmeter

```
open /usr/local/bin/jmeter
```

##Testes Realizados

Para ter acesso a cada case, vá para nossa wiki.

* Caso base
* JDBC
* REST API
*
*

##Links importantes
* [Site oficial - Apache Jmeter](jmeter.apache.org)
* [Destilando Jmeter](http://www.bugbang.com.br/destilando-jmeter-i-introducao-e-conceitos/)
* [Tutorials on Point - Jmeter](https://www.tutorialspoint.com/jmeter/jmeter_tutorial.pdf)
* [Jmeter tutorial Series](http://www.softwaretestingclass.com/learn-jmeter-performance-testing-jmeter-tutorial-series/)
* [Ultimate Resoures List](https://www.blazemeter.com/blog/ultimate-jmeter-resource-list)


text:
// Thanks: https://core.trac.wordpress.org/attachment/ticket/25809/color-picker-widget.php
(function($) {

	'use strict';

	function initColorPicker(widget) {
		widget.find('.nm-widget-color-picker').wpColorPicker(/*{
			change: _.throttle(function() { // For Customizer
				$(this).trigger('change');
			}, 3000)
		}*/);
	};

	function onFormUpdate(event, widget) {
		initColorPicker(widget);
	};

	var $document = $(document);

	$document.on('widget-added widget-updated', onFormUpdate);

	$document.ready(function() {
		$('#widgets-right .widget:has(.nm-widget-color-picker)').each(function() {
			initColorPicker($(this));
		});
	});
} (jQuery));


text:
function newChart(data, id) {
  $("#"+id+"-placeholder").append('<svg id="'+id+'" style="display:block;margin:auto;width:90%;height:90%"></svg>')
  var xScale = new Plottable.Scales.Time();
  var xAxis = new Plottable.Axes.Numeric(xScale, "bottom");
  xAxis.formatter(Plottable.Formatters.multiTime());
  var yScale = new Plottable.Scales.Linear();
  var yAxis = new Plottable.Axes.Numeric(yScale, "left");
  var colorScale = new Plottable.Scales.Color();
  var series = new Plottable.Dataset(data, { name: "series" });
  var plot = new Plottable.Plots.Line();
  plot.x(function(d) { return d.x; }, xScale).y(function(d) { return d.y; }, yScale);
  plot.attr("stroke", function(d, i, dataset) { return dataset.metadata().name; }, colorScale);
  plot.addDataset(series)
  plot.autorangeMode("y");
  var sparklineXScale = new Plottable.Scales.Time();
  var sparklineXAxis = new Plottable.Axes.Time(sparklineXScale, "bottom");
  var sparklineYScale = new Plottable.Scales.Linear();
  var sparkline = new Plottable.Plots.Line();
  sparkline.x(function(d) { return d.x; }, sparklineXScale).y(function(d) { return d.y; }, sparklineYScale);
  sparkline.attr("stroke", function(d, i, dataset) { return dataset.metadata().name; }, colorScale);
  sparkline.addDataset(series);
  var dragBox = new Plottable.Components.XDragBoxLayer();
  dragBox.resizable(true);
  dragBox.onDrag(function(bounds) {
    var min = sparklineXScale.invert(bounds.topLeft.x);
    var max = sparklineXScale.invert(bounds.bottomRight.x);
    xScale.domain([min, max]);
  });
  dragBox.onDragEnd(function(bounds) {
    if (bounds.topLeft.x === bounds.bottomRight.x) {
      xScale.domain(sparklineXScale.domain());
    }
  });
  xScale.onUpdate(function() {
    dragBox.boxVisible(true);
    var xDomain = xScale.domain();
    dragBox.bounds({
      topLeft: { x: sparklineXScale.scale(xDomain[0]), y: null },
      bottomRight: { x: sparklineXScale.scale(xDomain[1]), y: null }
    });
  });
  var miniChart = new Plottable.Components.Group([sparkline, dragBox]);
  var pzi = new Plottable.Interactions.PanZoom(xScale, null);
  pzi.attachTo(plot);
  var output = d3.select("#hoverFeedback");
  var outputDefaultText = "Closest:"
  output.text(outputDefaultText);
  var chart = new Plottable.Components.Table([
    [yAxis, plot          ],
    [null , xAxis         ],
    [null , miniChart     ],
    [null , sparklineXAxis]
    ]);
  chart.rowWeight(2, 0.2);
  chart.renderTo('#'+id);
  var crosshair = createCrosshair(plot);
  var pointer = new Plottable.Interactions.Pointer();
  pointer.onPointerMove(function(p) {
    var nearestEntity = plot.entityNearest(p);
    if (nearestEntity.datum == null) {
      return;
    }
    crosshair.drawAt(nearestEntity.position);
    var datum = nearestEntity.datum;
    output.text("Closest: (" + datum.x.toLocaleString() + ", " + datum.y.toFixed(2) + ")");
  });
  pointer.onPointerExit(function() {
    crosshair.hide();
    output.text(outputDefaultText);
  });
  pointer.attachTo(plot);
  function createCrosshair(plot) {
    var crosshair = {};
    var crosshairContainer = plot.foreground().append("g").style("visibility", "hidden");
    crosshair.vLine = crosshairContainer.append("line")
    .attr("stroke", "black")
    .attr("y1", 0)
    .attr("y2", plot.height());
    crosshair.circle = crosshairContainer.append("circle")
    .attr("stroke", "black")
    .attr("fill", "white")
    .attr("r", 3);
    crosshair.drawAt = function(p) {
      crosshair.vLine.attr({
        x1: p.x,
        x2: p.x
      });
      crosshair.circle.attr({
        cx: p.x,
        cy: p.y
      });
      crosshairContainer.style("visibility", "visible");
    }
    crosshair.hide = function() {
      crosshairContainer.style("visibility", "hidden");
    }
    return crosshair;
  }
}


text:
Links on an edition are checked using the [LinkChecker API](https://github.com/alphagov/link-checker-api/blob/master/docs/api.md). Links are checked when the `Check Links` button is clicked on the edition show page. This fires off a request to the Link Checker API using the [`/create_batch`](https://github.com/alphagov/link-checker-api/blob/master/docs/api.md#post-batch) endpoint. Once this has checked all the links present in the edition it makes a callback with a [`batch_report`](https://github.com/alphagov/link-checker-api/blob/master/docs/api.md#batchreport-entity) that gets saved as a `LinkCheckerApiReport`.

## Models

### LinkCheckerApiReports

The `LinkCheckerApiReports` are returned by the API contain a [report](https://github.com/alphagov/link-checker-api/blob/master/docs/api.md#linkreport-entity) of all the links present in an edition.

### LinkCheckerApiReportLinks

These are saved as `LinkCheckerApiReportLinks`. These contain [information](https://github.com/alphagov/link-checker-api/blob/master/docs/api.md#linkreport-entity) on the warnings or errors on the links, including a `suggested_fix`.

The `LinkCheckerApiReport` is displayed on the admin page with a list of the broken links found on the edition.

## Workers

The `CheckAllOrganisationsLinksWorker` is a scheduled worker that runs nightly at 2 a.m. it queues up individual link checking tasks for each organisation using `CheckOrganisationLinksWorker`

`CheckOrganisationLinksWorker` uses the [LinkCheckerApiService#check_links](https://github.com/alphagov/whitehall/blob/master/app/services/link_checker_api_service.rb#L10) calls the [`create batch endpoint`](https://github.com/alphagov/link-checker-api/blob/master/docs/api.md#post-batch) in the LinkCheckerApi. The callback and the subsequent link check report creation happen as per the on-demand check.


text:
namespace Http.Query.Filter.Infrastructure.Extensions
{
    using System.Text.RegularExpressions;

    internal static class MatchExtension
    {
        internal static string GetValue(this Match @this, string group) => @this.Groups[group].Value;
    }
}


text:
<?php
include('common.inc.php');

try {
	$provider = new OAuthProvider($params);

	/* the endpoint which issues a request token is special, it doesn't take an oauth_token and hence there's no call to the tokenHandler() */
	$provider->isRequestTokenEndpoint(true);

	/* OAuthProvider will call this callback with the $provider object as an argument, you can throw errors from that handler and set the $provider->consumer_key if all is good */
	$provider->consumerHandler('lookupConsumer');

	/* similar to consumerHandler, throw errors related to the timestamp/nonce in this callback */
	$provider->timestampNonceHandler('timestampNonceChecker');

	/* this is the meat of request authorization, the first argument is the URL of this endpoint as the outside world sees it
	 * the optional second argument is the HTTP method, GET, POST, etc ... the provider will try to detect this via $_SERVER["REQUEST_METHOD"] (usually reliable) when it's not set */
	$provider->checkOAuthRequest("http://localhost/request_token.php", PHP_SAPI=="cli" ? OAUTH_HTTP_METHOD_GET : NULL);

} catch (OAuthException $E) {

	/* when you catch OAuthException and echo OAuthProvider::reportProblem with it, you'll get the problem reporting extension described here:
	 * http://wiki.oauth.net/ProblemReporting for free, it also sets the most appropriate HTTP response code */
	echo OAuthProvider::reportProblem($E);
}

?>


text:
```shell
> docker pull arobasmusic/cdash
```

### Configuration

To customize your CDash service, mount your **CDash** config file to

`/srv/cdash/cdash/config.local.php`.

Example:

```shell
> cat > $PWD/config.local.php << EOF
'<?php'
\$CDASH_DB_HOST = 'db';
\$CDASH_DB_TYPE = 'mysql';
\$CDASH_DB_NAME = 'cdash';
\$CDASH_DB_PASS = 'password-for-cdash-table';
\$CDASH_DB_LOGIN = 'cdash'
EOF
> docker run --link mysql:db -v "$PWD/config.local.php":"/srv/cdash/cdash/config.local.php" -P -d arobasmusic/cdash:2.2.2
```

See [CDash setup documentation](http://public.kitware.com/Wiki/CDash:Installation#Configuration) for more details.

### Other available volumes

- `/srv/cdash/backup`
- `/srv/cdash/upload`
- `/srv/cdash/rss`
- `/var/log/apache2`


text:
"""Exposes a set of layout and utility functions to be invoked from 164. These
These functions have access to the global browser instance.
"""
import json
from urllib import urlencode, urlopen
from urlparse import urlparse, urlunparse, parse_qsl
from warnings import warn
import sys

from PyQt4.QtNetwork import QNetworkReply
from browser import Browser, Renderer

import grammar_parser
import parser_generator
import interpreter

tmlGrm = './tml.grm'
cs164Grm = 'cs164c.grm'
cs164Lib = 'library.164'

def initialize():
    global _browser
    # Initialize reusable parts of the browser infrastructure.
    tmlParser = parser_generator.makeParser(grammar_parser.parseFile(tmlGrm))
    print >> sys.stderr, 'TML parser loaded.'
    cs164Parser = parser_generator.makeParser(grammar_parser.parseFile(cs164Grm))
    print >> sys.stderr, 'CS164 parser loaded.'
    # TODO: Currently, the interpreter "object" is the module itself. Later,
    # expose an API for constructing interpreters.
    renderer = Renderer(interpreter)
    print >> sys.stderr, 'Renderer initialized.'
    _browser = Browser(tmlParser, cs164Parser, interpreter, renderer)
    interpreter.ExecGlobal(cs164Parser.parse(open(cs164Lib).read()))
    print >> sys.stderr, 'Browser initialized.'
    print >> sys.stderr, 'Loading the layout engine modules...'
    # Load the layout engine, which is implemented in 164.
    dependencies = ['object', 'node', 'window', 'box',
                    'hbox', 'vbox', 'link', 'word', 'img',
                    'script', 'bquery', 'rx', 'textbox',
                    #TODO: Uncomment for PA8 'pbar', 'ibox', 'script',
                    #TODO: Uncomment for PA9 'rx',
                    #TODO: Uncomment for PA8 'bquery',
                    'layout', 'browser']
    for dependency in dependencies:
        print >> sys.stderr, '\tloading ' + dependency
        ast = cs164Parser.parse(open('./browser/{0}.164'.format(dependency)).read())
        interpreter.ExecGlobal(ast)
    print >> sys.stderr, 'Done.'

def clear():
    _browser.clear(_browser.window)

def drawBox(x, y, width, height, properties, widget=None):
    return _browser.renderer.drawBox(x, y, width, height, properties,
                                     _browser.window.canvas, widget)

def drawWord(word, x, y, properties, widget=None):
    return _browser.renderer.drawWord(word, x, y, properties,
                                      _browser.window.canvas, widget)

def drawInput(x, y, width, height, text, widget=None):
  inp = _browser.renderer.drawInput(x, y, width, height, '',
                                     _browser.window.canvas, widget)
  inp.setPlaceholderText(text)
  return inp
def drawPBar(x, y, width, height, value, widget=None):
  return _browser.renderer.drawPBar(x, y, width, height, value,
                                     _browser.window.canvas, widget)
def drawImg(x, y, width, height, rawdata, widget=None):
  return _browser.renderer.drawImg(x, y, width, height, rawdata,
                                     _browser.window.canvas, widget)
def getWordDimensions(word, properties):
    return _browser.renderer.getWordDimensions(word, properties)

def setDOMWindowSize(width, height):
    """Sets the size of the window in the DOM. This is not the application
    window.
    """
    _browser.window.canvas.setMinimumSize(width, height)
    _browser.window.canvas.resize(width, height)

def parseTML(tml):
    """Returns the raw DOM object constructed by the TML parser."""
    parsed = _browser.tmlParser.parse(tml)
    return parsed

def evaluateScript(url):
    """Evaluates the script at the given URL."""
    connection = urlopen(url)
    code = connection.read()
    connection.close()
    _browser.execScript(code)

def load(url):
    print >> sys.stderr, 'Loading', url
    _browser.load(url)

def create164Callback(node, code):
    """Run the specified string of 164 code when an event is fired on the
    target node. The 'code' argument may be a 164 function instead of a string
    of code to allow the 164 programmer to pass in lambdas as callbacks.
    """
    assert (isinstance(code, basestring) or
            isinstance(code, interpreter.FunVal)), \
            'callback must be a string or closure'

    def callback(ev = None, relayout = False):
        if isinstance(code, basestring):
            _browser.execScript(code, {'self': node, 'event': ev})
        else:
            _browser.interpreter.ExecFun(code, [ev])
        if (relayout):
            _browser.relayout()
    return callback

def removeHandlers(node):
    node['__qt'].clicked.disconnect()

def addEventListener(node, event, code, context=None):
    """Subscribes to an event on the given node, executing the specified code
    when such an event is triggered. A "context" node may be specified to
    indicate the node that is the "self" object for the callback.
    """
    callback = create164Callback(node if context is None else context, code)

    # For each event type, we need to define custom handlers (Qt slots) that
    # convert Qt events into 164 event objects.
    if event == 'click':
        def clickHandler(ev):
            event = {'x': ev.x(), 'y': ev.y(),
                     'screenX': ev.globalX(), 'screenY': ev.globalY()}
            callback(event, True)
        node['__qt'].clicked.connect(clickHandler)
    elif event == 'textChanged':
        def changeHandler(text):
            event = {'text': text}
            callback(event, False)
        node['__qt'].textChanged.connect(changeHandler)
    elif event == 'returnPressed':
        def returnHandler():
            event = {'text': str(node['__qt'].text())}
            node['__qt'].setText("")
            callback(event, False)
        node['__qt'].returnPressed.connect(returnHandler)
    elif event == 'focusChanged':
        def focusHandler(ev):
            event = {'gotFocus': ev.gotFocus(), 'lostFocus': ev.lostFocus()}
            callback(event, False)
        node['__qt'].focused.connect(focusHandler)
    elif event == 'editingFinished':
        def editHandler():
            callback({}, False)
        node['__qt'].editingFinished.connect(editHandler)
    else:
        raise TypeError("Unknown event " + str(event))

def addAnchorTarget(node, url):
    node['__qt'].clicked.connect(lambda _: load(url))

def addTimerCallback(window, ms, code, repeat=False):
    callback = create164Callback(window, code)
    timer = _browser.createTimer()
    timer.setInterval(ms)
    timer.setSingleShot(not repeat)
    timer.timeout.connect(callback)
    return timer.timerId()

def sendHttp(window, uri, code):
    reply = _browser.createNetworkReply(uri)
    callback = create164Callback(window, code)

    def responseHandler():
        if reply.error() == QNetworkReply.NoError:
            data = reply.readAll().data()
            try:
                data = json.loads(data)
            except ValueError:
                # The data is not JSON.
                pass
            else:
                data = jsonTo164Object(data)
            response = {'status': 'ok', 'response': data}
        else:
            response = {'status': 'error', 'response': reply.errorString()}
        callback(response, False)

    reply.finished.connect(responseHandler)

    # Create an object that 164 can handle.
    return {'__qt': reply}

def keys(obj):
    ks = obj.keys()
    result = {}
    for i,v in enumerate(ks):
        result[i] = ks[i]
    return result

def objToJson(obj):
    if isinstance(obj, dict):
        keys = obj.keys()
        if len(keys) > 0 and isinstance(keys[0], int):
            res = []
            keys.sort()
            for v in keys:
                res.append(objToJson(obj[v]))
            obj = res
        else:
            obj = {k: objToJson(v) for k, v in obj.items()}
    return obj

def jsondumps(obj):
    obj = objToJson(obj)
    return json.dumps(obj, sort_keys=True)

def setFocus(node):
    """Set the focus onto the Qt widget underneath "node"."""
    _browser.setFocus(node)

# Basically, convert all lists seen.
def jsonTo164Object(json):
    """Convert the JSON string "json" into a 164 object."""
    if isinstance(json, dict):
        json = dict((key, jsonTo164Object(json[key])) for key in json)
    elif isinstance(json, list):
        json = dict(enumerate(map(jsonTo164Object, json)))
    return json

def doQuote(str):
    """Add quotes around "str"."""
    return "\"" + str + "\""


text:
using namespace std;

typedef pair<vector<kmer_int_type_t>,int> Path_n_count_pair;

struct my_sorter {

    bool operator() (Path_n_count_pair& a, Path_n_count_pair& b) {

        if (a.second < b.second) {
            return(true);
        }
        else {
            return(false);
        }
    }
};

class IRKE {

public:

    IRKE();
    IRKE(unsigned int kmer_length,
         unsigned int max_recursion = 25,
         float min_seed_entropy = 1.5,
         unsigned int min_seed_coverage = 2,
         float min_any_entropy = 0.0,
         bool pacman = false,
         bool crawl = false,
         unsigned int crawl_length = 1,
         bool double_stranded = false
         );

    bool TWO_PHASE; // draft inchworm contig built, new seed selected from it, and then proper inchworm contig built.

    void build_graph(const string& reads_fasta_filename, bool reassembleIworm = false, bool useKmers = false);

    unsigned long get_graph_size();

    void set_prune_singleton_read_interval (unsigned long interval);

    void prune_kmers_min_count(unsigned int min_count);

    void prune_kmers_min_entropy(float min_entropy);

    bool prune_kmer_extensions(float min_ratio_non_error);

    bool prune_some_kmers(unsigned int min_count, float min_entropy, bool prune_error_kmers, float min_ratio_non_error);

    //void report_connected_components (float min_connectivity, unsigned int min_component_size, bool summarize_size_only_flag = false);

    string reconstruct_path_sequence(vector<kmer_int_type_t>& path, vector<unsigned int>& cov_counter);

    bool sequence_path_exists(string& sequence, unsigned int min_coverage, float min_entropy, float min_connectivity, vector<unsigned int>& cov_counter);

    void monitor_progress(unsigned int monitor_setting);

    void compute_sequence_assemblies(float min_connectivity = 0.2,
                                     unsigned int min_assembly_length = 100,
                                     unsigned int min_assembly_coverage = 2,
                                     bool PARALLEL_IWORM = false,
                                     bool write_coverage = false,
                                     string coverage_output_filename = "assembly_coverage.out");

    void describe_kmers(); // just describe each kmer in the graph, print to stdout.

    string thread_sequence_through_graph(string& sequence); // describe kmers in this sequence.

    // utilities for setting and unsetting the sorted kmer list targeted as seeds for inchworm assembly
    void populate_sorted_kmers_list();
    void clear_sorted_kmers_list();

private:

    KmerCounter kcounter;

    unsigned int MONITOR;
    unsigned int INCHWORM_ASSEMBLY_COUNTER;
    float MIN_SEED_ENTROPY;
    unsigned int MIN_SEED_COVERAGE;
    float MIN_ANY_ENTROPY;
    bool PACMAN;
    bool CRAWL;
    unsigned int CRAWL_LENGTH;
    unsigned int MAX_RECURSION;
    bool DOUBLE_STRANDED_MODE;
    unsigned long PRUNE_SINGLETON_READ_INTERVAL;

    bool got_sorted_kmers_flag;
    //vector<Kmer_counter_map_iterator> sorted_kmers;
    vector<Kmer_Occurence_Pair> sorted_kmers;

    void populate_Kmers_from_kmers(const string& kmers_filename);
    void populate_Kmers_from_fasta(const string& fasta_filename, bool reassembleIworm = false);

    string reconstruct_path_sequence(KmerCounter& kcounter, vector<kmer_int_type_t>& path, vector<unsigned int>& cov_counter);

    Path_n_count_pair inchworm(KmerCounter& kcounter, char direction, kmer_int_type_t kmer,
                               Kmer_visitor& visitor, float min_connectivity);  // direction = [FR]

    Path_n_count_pair inchworm_step(KmerCounter& kcounter, char direction, Kmer_Occurence_Pair kmer, Kmer_visitor& visitor,
                                    Kmer_visitor& eliminator, unsigned int inchworm_round, unsigned int depth,
                                    float min_connectivity, unsigned int max_recurse);  // direction = [FR]

    void compute_sequence_assemblies(KmerCounter& kcounter, float min_connectivity,
                                     unsigned int min_assembly_length, unsigned int min_assembly_coverage,
                                     bool PARALLEL_IWORM, bool write_coverage, string coverage_output_filename);

    void traverse_path(KmerCounter& kcounter, Kmer_Occurence_Pair seed_kmer, Kmer_visitor& visitor, Kmer_visitor& place_holder,
                       float min_connectivity_ratio, unsigned int depth);

    // helper function prototypes
    vector<kmer_int_type_t> _join_forward_n_reverse_paths(vector<kmer_int_type_t>& reverse_path,
                                                          kmer_int_type_t seed_kmer_val, vector<kmer_int_type_t>& forward_path);

    bool exceeds_min_connectivity (KmerCounter& kcounter, Kmer_Occurence_Pair kmerA, Kmer_Occurence_Pair kmerB, float min_connectivity);
    bool exceeds_min_connectivity (KmerCounter& kcounter, string kmerA, string kmerB, float min_connectivity);

    void describe_kmers(KmerCounter& kcounter);

    vector<kmer_int_type_t> build_inchworm_contig_from_seed(kmer_int_type_t kmer, KmerCounter& kcounter,
                                                            float min_connectivity, unsigned int& total_counts,
                                                            bool PARALLEL_IWORM);

    bool is_good_seed_kmer(kmer_int_type_t kmer, unsigned int kmer_count, unsigned int kmer_length,
                           float min_connectivity);

    kmer_int_type_t extract_best_seed(vector<kmer_int_type_t>& kmer_vec, KmerCounter& kcounter, float min_connectivity);

};


text:
package scalismo.mesh

/**
 * express correspondence of a triangulated surface to another triangulation, maps points on this surface to target surface
 */
trait MeshSurfaceCorrespondence extends MeshSurfaceProperty[(TriangleId, BarycentricCoordinates)] {

  /**
   * get corresponding point on target surface
   * @param triangleId triangle on this surface
   * @param bcc barycentric coordinates on this surface
   * @return corresponding triangle and barycentric coordinates on target surface
   */
  def correspondingPoint(triangleId: TriangleId, bcc: BarycentricCoordinates): (TriangleId, BarycentricCoordinates)

  /**
   * triangulation of this surface
   * @return
   */
  override def triangulation: TriangleList

  /**
   * triangulation of target surface
   * @return
   */
  def targetTriangulation: TriangleList

  override def onSurface(triangleId: TriangleId, bcc: BarycentricCoordinates): (TriangleId, BarycentricCoordinates) =
    correspondingPoint(triangleId: TriangleId, bcc: BarycentricCoordinates)
}


text:
import {regionByPrefixedCode} from './regionUtil'
import {dimensionLabelTitle} from './labels'
import humanizeList from 'humanize-list'
//import util from 'util'
//import _debug from './debug'

function listify(arr, options = {}) {
  const defaults = {oxfordComma: false, conjunction: 'og'}
  return humanizeList(arr, Object.assign({}, defaults, options))
}

function downcaseFirstLetter(string) {
  return string.charAt(0).toLowerCase() + string.slice(1)
}

// hvilke andre fordleinger har vi?
// Hvertfall:
// vreg3 --> http://localhost:3000/steder/K0301/arbeid/vedvarende-lavinntekt
// botid3 --> http://localhost:3000/steder/K0301/befolkning/flyktning_botid_flytting
const dict = {
  kjonn0: 'kvinner',
  kjonn1: 'menn',
  kjonn: 'kjønnsfordeling',
  bhgalder: 'aldersfordeling'
}

function languagify(dimension) {
  const vars = dimension.variables
  if (vars.length == 1 && vars[0] == 'alle') {
    return null
  }
  // Temporary hack until vars[0] is renamed 'all', at which point the preceding logic will handle this case
  if (dimension.name == 'bhgalder' && vars[0] == '1_5') {
    return null
  }
  let distribution = dimensionLabelTitle(dimension.name)
  let subject = dimensionLabelTitle(dimension.name, vars[0])
  if (dimension.name == 'kjonn') {
    distribution = dict.kjonn
    subject = dict[`kjonn${vars[0]}`]
  }
  if (dimension.name == 'bhgalder') {
    distribution = dict.bhgalder
  }
  // Temporary fix to avoid uppercased first letters in the middel of the sentence when figures are delimited
  // This can not be done with all dimensions since some are countrynames and the like.
  if (
    dimension.name == 'avslstat4'
    || dimension.name == 'forsteBosettingskommune'
    || dimension.name == 'utd6'
    || dimension.name == 'undervisningGrskole'
    || dimension.name == 'innvkat3'
    ) {
    subject = downcaseFirstLetter(subject)
  }

  return `${downcaseFirstLetter(distribution)} avgrenset til ${subject}`
}

function chartLabel(card, unit) {
  let unitKey = unit
  if (Array.isArray(unit)) {
    unitKey = unit[0]
  }
  if (!card.hasOwnProperty('metadata')) {
    console.log('Missing metadata for card %s', card.name) // eslint-disable-line no-console
    return unitKey
  }

  if (!card.metadata.hasOwnProperty('unitDescriptions')) {
    console.log('Missing unit descriptions for card %s', card.name) // eslint-disable-line no-console
    return unitKey
  }

  if (!card.metadata.unitDescriptions.hasOwnProperty(unitKey)) {
    console.log('Missing unit descriptions for key %s of card %s', unitKey, card.name) // eslint-disable-line no-console
    return unitKey
  }

  return card.metadata.unitDescriptions[unitKey]

}

export function queryToOptions(query, card, headerGroup, allRegions) {
  const opts = {}

  // showing
  opts.showing = chartLabel(card, query.unit)

  // regions
  const prefixedRegionCodes = (query.comparisonRegions || []).slice()
  prefixedRegionCodes.unshift(query.region)
  opts.regions = prefixedRegionCodes.map(code => regionByPrefixedCode(code, allRegions).name)

  // timePeriod
  opts.timePeriod = query.year
  if (opts.timePeriod == 'all') {
    opts.timePeriod = headerGroup.aar.slice()
  }
  opts.timePeriod.sort((num1, num2) => {
    return num1 - num2
  })

  // bounds
  opts.bounds = query.dimensions.map(dimension => {
    if (dimension.variables == 'all') {
      return null
    }
    if (Array.isArray(dimension.variables) && dimension.variables.length == 1) {
      const readableDimension = languagify(dimension)
      if (readableDimension) {
        return readableDimension
      }
    }
    return null
  }).filter(Boolean)

  // groupedBy
  opts.groupedBy = []
  query.dimensions.forEach(dimension => {
    if (!dimension.variables || dimension.variables == 'all') {
      return
    }
    if (dimension.variables.length > 1) {
      opts.groupedBy.push(downcaseFirstLetter(dimensionLabelTitle(dimension.name)))
    }
  })
  return opts
}

// This function returns something along these lines. Beware of various edge cases :)
//
// Figuren viser
//   flyktninger
// med
//   aldersfordeling avgrenset til	0-3 år,	kjønnsfordeling	avgrenset til	kvinner	og bakgrunn	avgrenset til	innvandrere,
// fordelt på
//   kjønnsfordeling og befolkningsgrupper
// i (perioden)
//   2014
// fra
//   Sandefjord kommune (Drøbak, Larvik og Bø i Telemark)
export function describeChart(options) {
  let result = 'Figuren viser'
  if (options.showing) {
    result = `${result} ${options.showing}`
  }
  if (options.bounds && options.bounds.length > 0) {
    result = `${result} med ${listify(options.bounds)}`
  }
  if (options.groupedBy && options.groupedBy.length > 0) {
    result = `${result} fordelt etter ${listify(options.groupedBy)}`
  }
  if (options.timePeriod) {
    const period = options.timePeriod.length == 1 ? options.timePeriod[0] : `perioden ${options.timePeriod[0]} til ${options.timePeriod.slice(-1)}`
    result = `${result} i ${period}`
  }
  if (options.regions) {
    result = `${result} i ${listify(options.regions)}`
  }
  return `${result}.`
}


text:
package com.fincatto.nfe310.classes;

public enum NFFinalidade {

    NORMAL("1", "Normal"),
    COMPLEMENTAR("2", "Complementar"),
    AJUSTE("3", "Ajuste"),
    DEVOLUCAO_OU_RETORNO("4", "Devolucao ou retorno");

    private final String codigo;
    private final String descricao;

    private NFFinalidade(final String codigo, final String descricao) {
        this.codigo = codigo;
        this.descricao = descricao;
    }

    public String getCodigo() {
        return this.codigo;
    }

    public String getDescricao() {
        return this.descricao;
    }

    public static NFFinalidade valueOfCodigo(final String codigo) {
        for (final NFFinalidade tipo : NFFinalidade.values()) {
            if (tipo.getCodigo().equals(codigo)) {
                return tipo;
            }
        }
        return null;
    }
}


text:
import React from 'react'
import { langs } from 'i18n/lang'
import FileMenu from './fileMenu'
import StyleMenu from './styleMenu'
import './index.less'
import _ from 'lodash'
import BespokeThemeMenu from './bespokeThemeMenu'

module.exports = class Header extends React.Component {
  createWidget = type => {
    let deck = this.props.deck
    let activeSlide = deck.getActiveSlide()
    activeSlide.components.forEach(e => {
      delete e.selected
    })
    this.props.onNewWidget(
      activeSlide,
      null,
      {
        type: type,
        x: 0,
        y: 0,
        text:
          '
(' +
          langs[this.props.language]['triClickEdt'] +
          ')
',
        selected: true
      },
      langs[this.props.language]['new'] + ' ' + langs[this.props.language][type]
    )
  }

  render() {
    let bespokeThemeMenu, styleMenu
    if (
      this.props.currentView === 'overview' &&
      this.props.presentationFormat === 'bespoke'
    ) {
      bespokeThemeMenu = <BespokeThemeMenu {...this.props} />
    }
    if (
      this.props.currentView === 'slides' ||
      this.props.presentationFormat !== 'handouts'
    ) {
      styleMenu =


text:
/*
 * Modifications de Yannick :
 * https://fluidlog.cloud.xwiki.com/xwiki/bin/view/Main/NettoyageTaskboard10k
 * ====================================================================
 */

(function (document, $, storage) {

var version = "0.7" ;
var COLORS = ['white', 'green', 'blue', 'red', 'orange', 'yellow'];
var R_MOUSEIN = /^mouse(enter|over)/i;

var    ACTIONS = {

		r: function ()
		{
            if (confirm("Are you sure you want to clear all saved data?"))
            {
                storage.removeItem("board"); // .clear() would be fine too, but I don't want to remove
                                                 // data of other demos on 10k apart domain :)
                location.reload();
            }
        },

        e: function ($card) { $card["dblclick"](); },

        c: function ($card) {
            var color = $card.color();
            if (color) {
                $card.removeClass(color);
                color = COLORS.indexOf(color);
                color = COLORS[++color < 6 ? color : 0]; // 6 is COLORS.length
                $card.addClass(color); // .addClass
                save();
            }
        },

        // delete
        d: function ($card) {
                $card.fadeOut(function ()
                	{
                    	$card.remove();
                    	save();
                	}
                );
        },

        b: function () { document.execCommand("bold", false, ""); },
        i: function () { document.execCommand("italic", false, ""); },
        h: function () { block("p", "h2"); },
        p: function () { block("h2", "p"); }

    };

    // list of some more or less useful tips
/*
    TIPS = [
        "Need a new card2? Just grab it from a deck on the left",
        "Move cards around to arrange them in any way you want: todo list? kanban board?",
        "Double-click card to edit",
        "You can use hotkeys when editing text, just check Ctrl+I or Ctrl+B",
        //"Just guess what ESC and Ctrl+S do", -- let them discover it... cause Ctrl+S is not working in IE9
        "Every change is immediately saved in your browser",
        "You've already noticed #tags, didn't you?",
        "Ctrl+H makes a

Heading

and Ctrl+G turns text into a paragraph",
        0, // pause
        "It's not a tip... I just had some spare bytes below 10k limit ;)"
    ],
*/

// Now, these down there can be finally called variables
// even though some of them don't change much

    // VARIABLES
    // ===========

    // jQuery objects with application elements
    //var $document = $(document);
	//var $body = $(document.body);

    var $board;   //
 -- contains all the cards added by user
	var $deck;    //     -- contains set of new cards to take
	var $actions; // <menu>             -- toolbar with card actions
	var $editbar; // <menu class=edit>  -- toolbar with text formatting actions

	var data; // here is were board data is loaded

    //lastTip = -1, // index of last used tip

// http://en.wikipedia.org/wiki/Truecolor ;)
//TIPS[24] = "Oh, I forgot to tell you about HEX color tags #F5A";

// little easter egg ;)
//TIPS[42] = "Answer to life, the universe and everything is 42";

// FUNCTIONS
// ===========

// returns tips, one by one
/*
function tip() {
    return TIPS[++lastTip] ? "
" + TIPS[lastTip] + " #tip
" : "";
}
*/

// Firefox for some reason didn't work well with execCommand("formatblock",...)
// so here is some workaround for that
//   find     - is name of the tag we want to replace
//   replace  - is name of the tag we want to have
// In the case of card text only "p" and "h2" are possible
function block(find, replace) {
    if ($.browser.mozilla) {
        var $node = $(getSelection().anchorNode);
        if ($node.is(".text")) {
            $node = $node.$(find).eq(0);
        } else {
            $node = $node.closest(".text" + " " + find);
        }
        $node.replaceWith(function (i, html) {
            return "<" + replace + ">" + html + "</" + replace + ">";
        });
    } else {
        document.execCommand("formatblock", false, "<" + replace + ">");
    }
}

// returns all the tags with given text
/*
function tags(text) {
    return $board.$(".tag").filter(function () {
        return $(this).text().toLowerCase() == text.toLowerCase();
    });
}
*/

// saves current board state to local storage
function save() {
    var cards = [],
        $card; // used in .each loop, but it saves one 'var' statement

    $board.$(".card").each(function () {
        $card = $(this);
        cards.push($.extend($card.offset(), {
            type: $card.color(),
            text: $card.data("value") || ""
        }));
    });
    storage.setItem("board", JSON.stringify(cards));
}

// builds an actions toolbar for given list of actions
//   actions -- is an array of action definitions, where first element of each
//              action definition is a class name (action alias) and the second
//              one is a title to display in tooltip
//              ... just look at line 403 and you will know what I mean ;)
function buildActions(actions) {
    var menu = $("<menu>");
    $.each(actions, function (i, action) {
        menu.append("");
    });
    return menu
            // on click on action icon
            .delegate("menu a", "click", function (e)
            		{
            			// launch action based on class name
                		ACTIONS[this.className]($(this).closest(".card"));
                		return false;
            		}
            );
}

// closes edit mode and stores or discards changes
// by default changes are saved
//   cancel - if true, discards the changes
function closeEdit(cancel) {
    var $card = $board.$(".card" + ".edit").eq(0);
    var value;

    $editbar.detach();

    $(document.body).add($card.drop()).removeClass("edit"); // .removeClass
    value = cancel ? $card.data("value") : $card.$(".text").html();
    $card.saveText(value)
        .$(".text")
            .attr("contentEditable", false) // cannot remove the attr because Firefox is complaining
            .blur();
    $(document).unbind("keydown");
    save();
}

// key code based action aliases (for hot-keys)
/*
$.extend(ACTIONS, {
    66: ACTIONS.b, // Ctrl + B
    73: ACTIONS.i, // Ctrl + I
    72: ACTIONS.h, // Ctrl + H
    // 80: ACTIONS.p -- using 'G' as a hotkey for paraGraph, as printing on Ctrl+P cannot be canceled in IE9
    71: ACTIONS.p, // Ctrl + G
    83: closeEdit  // Ctrl + S -- not working in IE9 (cannot prevent save dialog)
});
*/

// JQUERY EXTENSIONS
// ===================

// override default easing with easeOutBack
// this is a shortened version of easeOutBack from jQuery UI

//$.easing.swing = function (x, t, b, c, d, s) {
//    return c * ((t = t / d - 1) * t * (((s = 1.70158) + 1) * t + s) + 1) + b;
//};

// jQuery.fn.pick -- visually picks the card(s) (by adding 'pick' class and moving
//                   it a little to top / left
//
// jQuery.fn.drop -- drops the card(s) back
$.each(["pick", "drop"], function (i, name) {
    var pick = name == "pick";
    function offset(i, value) {
        return parseInt(value, 10) + (pick ? -5 : 5);
    }

    $.fn[name] = function () {
        return this.each(function ($this) {
            $this = $(this);
            if ($this.hasClass("pick") != pick) { // .hasClass
                $this.toggleClass("pick", pick).css("top", offset).css("left", offset); // .toggleClass
            }
        });
    };
});

$.fn.extend({

    // jQuery.fn.color -- returns a color class of the card
    color: function (color) { // var as param
        r_colorclass = new RegExp('\\b(' + COLORS.join(')|(') + ')\\b');
        color = this[0].className.match(r_colorclass);
        return color ? color[0] : "";
    },

    // jQuery.fn.saveText -- saves and formats card text... and something more ;)
    saveText: function (text) {

        // if HEX color tag found in text, use this color as card background :)
        var colorTag = text.match(/(\s|^|>)(#[a-f0-9]{3}([a-f0-9]{3})?)\b/i);
        colorTag = colorTag ? colorTag[2] : "";

        this.closest(".card")
            .css({ backgroundColor: colorTag, borderColor: colorTag }) // change color to HEX tag found (if any)
            .data("value", text)                                         // store raw text
            .$(".text").html(                                             // format and put card text
                text.replace(/(\s|^|>)(#\w*)(\b)/gi, "$1$2$3")   // #tags

                    // parsing and making links clickable is done with *VERY* basic regexp
                    // 'cause something more sophisticated would not fit into 10k...
                    // so fingers crossed that it will not cause problems ;)
                    //
                    // one of the problems --   may break link parsing
                    .replace(/ /g, " ")
                    .replace(/(\s|^|>)(https?\:\/\/[^\s<>]+)/g, "$1$2")
            );
        return this;
    },

    // jQuery.fn.move -- a shortcut to the only animation used

    move: function (left) {
        return this.animate({ left: left });
    },

    $: $.fn.find,
});

// And after all these definitions finally something will begin to happen

$(function ()
	{ // $(document).ready()

/*
*/
	// loading data from storage (or using some dummy cards)
    data = storage.getItem("board");
    data = data ? JSON.parse(data) : [
        { type: COLORS[0], text: "
Welcome to
Semantic Taskboard !", top: 40, left: 70 },
        { type: COLORS[5], text: "Soyez vaillants !", top: 120, left: 80 },
        { type: COLORS[1], text: "
Soyez heureux!
", top: 180, left: 90 }
    ];

    // building the board
    $board = $("
").appendTo($(document.body));
/*
*/
    $.each(data, function (i, card) {
        $("

")
            .addClass(card.type || COLORS[5]) // .addClass
            .css(card) // we are interested in top and left values only, rest will be hopefully ignored ;)
            .saveText(card.text)
            .appendTo($board);
    });
    // preparing toolbars
    $actions = buildActions([ ["e", "Edit"], ["c", "Change color"], ["d", "Delete"]]);

    $editbar = buildActions([["b", "Bold (Ctrl+B)"],
                             ["i", "Italic (Ctrl+I)"],
                             ["h", "Heading (Ctrl+H)"],
                             ["p", "Paragraph (Ctrl+R)"]]).addClass("edit"); // .addClass

    buildActions([["r", "Clear board"]]).appendTo($(document.body));

    // preparing deck with new cards
    $deck = $("").appendTo($(document.body))
        // on hover cards in deck are animated to encourage users to take them :)
        .delegate(".card", "hover", function (event) {
        	if (!$(document.body).hasClass("edit") && !$(document.body).hasClass("mark")) { // .hasClass
                $(this).stop().move(R_MOUSEIN.test(event.type) ? 50 : 0);
            }
        })
        // on mousedown new card is added to the board and can be dragged
        .delegate(".card", "mousedown", function (event) {
            // adding new cards from deck
            if (!$(document.body).hasClass("edit") && !$(document.body).hasClass("mark")) { // .hasClass
                var $card = $(this);
                $card.clone()          // clone deck card and add it to the board
                    .pick().addClass("drag")
                    .css($card.offset())
//                    .saveText(tip())
                    .appendTo($board)
                    .trigger(event);   // start dragging new card

                $card.hide();             // hide deck card
                setTimeout(function () {  // and show it again after a while
                    $card.css("left", -40).show().move(0);
                }, 1000);
            }
        });

    // add a card to the deck for each color
    $.each(COLORS, function (i, color) {
        i = 6 - i; // 6 is COLORS.length
        $("

")
            .appendTo($deck)
            .addClass(color) // .addClass
            .css("top", i * 30).css("left", -40)
            .delay(i * 100) // animate cards into view one by one
            .move(0);
    });

// And finally the most interesting part - here it what is going on on the board

    $board
        // CARD EVENTS
        // on mousedown init card dragging
        .delegate(".card", "mousedown", function (mouseDownEvent) {
            // don't drag in edit mode or if a tag or action is clicked on a card
            if (!$(document.body).hasClass("edit") && !$(mouseDownEvent.target).is(".tag" + "," + "menu a")) { // .hasClass
                var $card = $(this).appendTo($board),
                    offset = $card.offset();

                $(document)
                    .bind("mousemove", function (moveEvent) {
                        // pick a card and move it around
                        $card.pick().addClass("drag") // .addClass
                            .css("left", offset["left"] + moveEvent.pageX - mouseDownEvent.pageX)
                            .css("top",  offset["top"]  + moveEvent.pageY - mouseDownEvent.pageY);
                    });

                return false; // and don't select text, please
            }
        })
        // on mouseup finish dragging
        .delegate(".card", "mouseup", function ($card) { // var as param
            $card = $(this);
            $(document).unbind("mousemove");
            if ($card.hasClass("drag")) { // .hasClass
                $card.removeClass("drag");   // .removeClass
                if (!$card.hasClass("mark")) {
                    $card.drop(); // drop a card, but only if it is not selected
                }
                save();
            }
        })
        // on dblclick start editing card text
        .delegate(".card", "dblclick", function (event) {
            // don't start editing if a tag or action was clicked
            if (!$(event.target).is(".tag" + "," + "menu a")) {
                var $card = $(this),
                    $text = $card.$(".text"),
                    value = $card.data("value");

                if ($text[0]["contentEditable"] != "true") {
                    $(document)["click"](); // trigger document click to unselect cards
                                        // check line 549 to see what it does
                    $(document.body).add($card.pick().removeClass("mark")).addClass("edit"); // .addClass
                    $editbar.appendTo($card);

                    $text
                        .html(value)
                        .attr("contentEditable", "true")
                        .focus();

                    $(document).bind("keydown", function (keyEvent)
                    	{ // bind hot-keys listener
                            if (keyEvent.which == 27)
                            { // ESC pressed - cancel edit
                                closeEdit("true");
                            }
                            if (keyEvent.ctrlKey && ACTIONS[keyEvent.which])
                            {
                                ACTIONS[keyEvent.which]();
                                return false;
                            }
                    	}
                    );
                }
            }
        })
        // on hover show action toolbar
        .delegate(".card", "hover", function (event) {
            if (R_MOUSEIN.test(event.type)) {
                $actions.appendTo($(this));
            } else {
                $actions.detach();
            }
        })
/*
        // TAG EVENTS
        // on hover highlight all tags with same text
        .delegate(".tag", "hover", function (event) {
            // toggle hover class on all tags with same text
            tags($(this).text()).toggleClass("hover", R_MOUSEIN.test(event.type)); // .toggleClass
        })
        // on click select all cards with same tags
        .delegate(".tag", "click", function ($cards) { // var as param
            $cards = tags($(this).text()).toggleClass("mark").closest(".card"); // .toggleClass

            if ($(this).hasClass("mark")) { // .hasClass
                // tags were selected, so highlight tagged cards
                $cards.pick()
                    .add($(document.body)).addClass("mark"); // .addClass
            } else {
                // tags were unselected, so drop tagged cards
                $cards.not(':has(.mark)').removeClass("mark").drop();
                $(document.body).not(':has(.mark)').removeClass("mark"); // .removeClass
            }
        });
*/
// We are almost at the end of out journey.
// Last but not least, the event binded to the document itself.

    $(document)
        // when clicked somewhere on the page close edit mode and unselect all cards
        .bind("click", function ($target)
        		{
            		$target = $($target.target);
            		if ($(document.body).hasClass("edit") && !$target.closest(".card" + ".edit")[0])
            		{ // .hasClass
            			// if in edit mode and clicked outside edited card, close edit mode and save
            			closeEdit();
            		} else if ($target.has($(document.body))[0])
            		{ // .has($(document.body)) is a short way of checking if element is document root
            			// if clicked somewhere on the page background, unselect all cards
            			$(".mark").removeClass("mark").drop(); // .removeClass
            		}
        });

});

// And that's all folks!

})(document, jQuery, localStorage);

/*
 * I really cannot believe you've done it, all the way down here.
 * You are very brave!
 *
 * But that's really it. There is nothing more.
 *
 * I hope you enjoyed it at least a little bit.
 * Probably you did, if you are still here :)
 *
 * I need to go now, because my wife is going to hate me
 * for all these evenings and nights I did spend here ;)
 */


text:
@startDocuBlock general_graph_create_http_examples
@brief Create a new graph in the graph module.

@RESTHEADER{POST /_api/gharial, Create a graph}

@RESTDESCRIPTION
The creation of a graph requires the name of the graph and a
definition of its edges.
[See also edge definitions](../../Manual/Graphs/GeneralGraphs/Management.html#edge-definitions).

@RESTQUERYPARAMETERS

@RESTQUERYPARAM{waitForSync,boolean,optional}
define if the request should wait until everything is synced to disc.
Will change the success response code.

@RESTBODYPARAM{name,string,required,string}
Name of the graph.

@RESTBODYPARAM{edgeDefinitions,array,optional,graph_edge_definition}
An array of definitions for the relations of the graph.
Each has the following type:

@RESTBODYPARAM{isSmart,boolean,optional,boolean}
Define if the created graph should be smart.
This only has effect in Enterprise Edition.

@RESTBODYPARAM{options,object,optional,post_api_gharial_create_opts}
a JSON object to define options for creating collections within this graph.
It can contain the following attributes:

@RESTSTRUCT{smartGraphAttribute,post_api_gharial_create_opts,string,optional,}
Only has effect in Enterprise Edition and it is required if isSmart is true.
The attribute name that is used to smartly shard the vertices of a graph.
Every vertex in this SmartGraph has to have this attribute.
Cannot be modified later.

@RESTSTRUCT{numberOfShards,post_api_gharial_create_opts,integer,required,}
The number of shards that is used for every collection within this graph.
Cannot be modified later.

@RESTSTRUCT{replicationFactor,post_api_gharial_create_opts,integer,required,}
The replication factor used when initially creating collections for this graph.

@RESTSTRUCT{minReplicationFactor,post_api_gharial_create_opts,integer,optional,}
The minimal replication factor used for every new collection in the graph.
If one shard has less than minReplicationFactor copies, we cannot write
to this shard, but to all others.

@RESTRETURNCODES

@RESTRETURNCODE{201}
Is returned if the graph could be created and waitForSync is enabled
for the `_graphs` collection, or given in the request.
The response body contains the graph configuration that has been stored.

@RESTREPLYBODY{error,boolean,required,}
Flag if there was an error (true) or not (false).
It is false in this response.

@RESTREPLYBODY{code,integer,required,}
The response code.

@RESTREPLYBODY{graph,object,required,graph_representation}
The information about the newly created graph.

@RESTRETURNCODE{202}
Is returned if the graph could be created and waitForSync is disabled
for the `_graphs` collection and not given in the request.
The response body contains the graph configuration that has been stored.

@RESTREPLYBODY{error,boolean,required,}
Flag if there was an error (true) or not (false).
It is false in this response.

@RESTREPLYBODY{code,integer,required,}
The response code.

@RESTREPLYBODY{graph,object,required,graph_representation}
The information about the newly created graph.

@RESTRETURNCODE{400}
Returned if the request is in a wrong format.

@RESTREPLYBODY{error,boolean,required,}
Flag if there was an error (true) or not (false).
It is true in this response.

@RESTREPLYBODY{code,integer,required,}
The response code.

@RESTREPLYBODY{errorNum,integer,required,}
ArangoDB error number for the error that occured.

@RESTREPLYBODY{errorMessage,string,required,}
A message created for this error.

@RESTRETURNCODE{403}
Returned if your user has insufficient rights.
In order to create a graph you at least need to have the following privileges:

  1. `Administrate` access on the Database.
  2. `Read Only` access on every collection used within this graph.

@RESTREPLYBODY{error,boolean,required,}
Flag if there was an error (true) or not (false).
It is true in this response.

@RESTREPLYBODY{code,integer,required,}
The response code.

@RESTREPLYBODY{errorNum,integer,required,}
ArangoDB error number for the error that occured.

@RESTREPLYBODY{errorMessage,string,required,}
A message created for this error.

@RESTRETURNCODE{409}
Returned if there is a conflict storing the graph.  This can occur
either if a graph with this name is already stored, or if there is one
edge definition with a the same
[edge collection](../../Manual/Appendix/Glossary.html#edge-collection) but a
different signature used in any other graph.

@RESTREPLYBODY{error,boolean,required,}
Flag if there was an error (true) or not (false).
It is true in this response.

@RESTREPLYBODY{code,integer,required,}
The response code.

@RESTREPLYBODY{errorNum,integer,required,}
ArangoDB error number for the error that occured.

@RESTREPLYBODY{errorMessage,string,required,}
A message created for this error.

@EXAMPLES

@EXAMPLE_ARANGOSH_RUN{HttpGharialCreate}
  var graph = require("@arangodb/general-graph");
| if (graph._exists("myGraph")) {
|    graph._drop("myGraph", true);
  }
  var url = "/_api/gharial";
  body = {
    name: "myGraph",
    edgeDefinitions: [{
      collection: "edges",
      from: [ "startVertices" ],
      to: [ "endVertices" ]
    }]
  };

  var response = logCurlRequest('POST', url, body);

  assert(response.code === 202);

  logJsonResponse(response);

  graph._drop("myGraph", true);
@END_EXAMPLE_ARANGOSH_RUN

@EXAMPLE_ARANGOSH_RUN{HttpGharialCreate2}
  var graph = require("@arangodb/general-graph");
| if (graph._exists("myGraph")) {
|    graph._drop("myGraph", true);
  }
  var url = "/_api/gharial";
  body = {
    name: "myGraph",
    edgeDefinitions: [{
      collection: "edges",
      from: [ "startVertices" ],
      to: [ "endVertices" ]
    }],
    isSmart: true,
    options: {
      replicationFactor: 2,
      numberOfShards: 9,
      smartGraphAttribute: "region"
    }
  };

  var response = logCurlRequest('POST', url, body);

  assert(response.code === 202);

  logJsonResponse(response);

  graph._drop("myGraph", true);
@END_EXAMPLE_ARANGOSH_RUN

@endDocuBlock


text:
package org.apache.helix.task.assigner;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.apache.helix.common.caches.TaskDataCache;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.model.LiveInstance;
import org.apache.helix.task.AssignableInstanceManager;
import org.apache.helix.task.TaskConfig;
import org.testng.Assert;
import org.testng.annotations.Test;

public class TestThreadCountBasedTaskAssigner extends AssignerTestBase {

  @Test
  public void testSuccessfulAssignment() {
    TaskAssigner assigner = new ThreadCountBasedTaskAssigner();
    int taskCountPerType = 150;
    int instanceCount = 20;
    int threadCount = 50;
    AssignableInstanceManager assignableInstanceManager =
        createAssignableInstanceManager(instanceCount, threadCount);

    for (String quotaType : testQuotaTypes) {
      // Create tasks
      List<TaskConfig> tasks = createTaskConfigs(taskCountPerType);

      // Assign
      Map<String, TaskAssignResult> results = assigner.assignTasks(assignableInstanceManager,
          assignableInstanceManager.getAssignableInstanceNames(), tasks, quotaType);

      // Check success
      assertAssignmentResults(results.values(), true);

      // Check evenness
      for (AssignableInstance instance : assignableInstanceManager.getAssignableInstanceMap()
          .values()) {
        int assignedCount = instance.getUsedCapacity()
            .get(LiveInstance.InstanceResourceType.TASK_EXEC_THREAD.name()).get(quotaType);
        Assert.assertTrue(assignedCount <= taskCountPerType / instanceCount + 1
            && assignedCount >= taskCountPerType / instanceCount);
      }
    }
  }

  @Test
  public void testAssignmentFailureNoInstance() {
    TaskAssigner assigner = new ThreadCountBasedTaskAssigner();
    int taskCount = 10;
    List<TaskConfig> tasks = createTaskConfigs(taskCount);
    AssignableInstanceManager assignableInstanceManager = new AssignableInstanceManager();
    Map<String, TaskAssignResult> results = assigner.assignTasks(assignableInstanceManager,
        assignableInstanceManager.getAssignableInstanceNames(), tasks, "Dummy");
    Assert.assertEquals(results.size(), taskCount);
    for (TaskAssignResult result : results.values()) {
      Assert.assertFalse(result.isSuccessful());
      Assert.assertNull(result.getAssignableInstance());
      Assert.assertEquals(result.getFailureReason(),
          TaskAssignResult.FailureReason.INSUFFICIENT_QUOTA);
    }
  }

  @Test
  public void testAssignmentFailureNoTask() {
    TaskAssigner assigner = new ThreadCountBasedTaskAssigner();
    AssignableInstanceManager assignableInstanceManager = createAssignableInstanceManager(1, 10);
    Map<String, TaskAssignResult> results = assigner.assignTasks(assignableInstanceManager,
        assignableInstanceManager.getAssignableInstanceNames(),
        Collections.<TaskConfig> emptyList(), AssignableInstance.DEFAULT_QUOTA_TYPE);
    Assert.assertTrue(results.isEmpty());
  }

  @Test
  public void testAssignmentFailureInsufficientQuota() {
    TaskAssigner assigner = new ThreadCountBasedTaskAssigner();

    // 10 * Type1 quota
    AssignableInstanceManager assignableInstanceManager = createAssignableInstanceManager(2, 10);
    List<TaskConfig> tasks = createTaskConfigs(20);

    Map<String, TaskAssignResult> results = assigner.assignTasks(assignableInstanceManager,
        assignableInstanceManager.getAssignableInstanceNames(), tasks, testQuotaTypes[0]);
    int successCnt = 0;
    int failCnt = 0;
    for (TaskAssignResult rst : results.values()) {
      if (rst.isSuccessful()) {
        successCnt += 1;
      } else {
        failCnt += 1;
        Assert.assertEquals(rst.getFailureReason(),
            TaskAssignResult.FailureReason.INSUFFICIENT_QUOTA);
      }
    }
    Assert.assertEquals(successCnt, 10);
    Assert.assertEquals(failCnt, 10);
  }

  @Test
  public void testAssignmentFailureDuplicatedTask() {
    TaskAssigner assigner = new ThreadCountBasedTaskAssigner();
    AssignableInstanceManager assignableInstanceManager = createAssignableInstanceManager(1, 20);
    List<TaskConfig> tasks = createTaskConfigs(10, false);

    // Duplicate all tasks
    tasks.addAll(createTaskConfigs(10, false));
    Collections.shuffle(tasks);

    Map<String, TaskAssignResult> results = assigner.assignTasks(assignableInstanceManager,
        assignableInstanceManager.getAssignableInstanceNames(), tasks, testQuotaTypes[0]);
    Assert.assertEquals(results.size(), 10);
    assertAssignmentResults(results.values(), true);
  }

  @Test(enabled = false, description = "Not enabling profiling tests")
  public void testAssignerProfiling() {
    int instanceCount = 1000;
    int taskCount = 50000;
    for (int batchSize : new int[] {10000, 5000, 2000, 1000, 500, 100}) {
      System.out.println("testing batch size: " + batchSize);
      profileAssigner(batchSize, instanceCount, taskCount);
    }
  }

  @Test
  public void testAssignmentToGivenInstances() {
    int totalNumberOfInstances = 10;
    int eligibleNumberOfInstances = 5;
    String instanceNameFormat = "instance-%s";

    TaskAssigner assigner = new ThreadCountBasedTaskAssigner();
    AssignableInstanceManager assignableInstanceManager = createAssignableInstanceManager(10, 20);
    List<TaskConfig> tasks = createTaskConfigs(100, false);
    Set<String> eligibleInstances = new HashSet<>();

    // Add only eligible number of instances
    for (int i = 0; i < eligibleNumberOfInstances; i++) {
      eligibleInstances.add(String.format(instanceNameFormat, i));
    }

    Map<String, TaskAssignResult> result = assigner.assignTasks(assignableInstanceManager,
        eligibleInstances, tasks, testQuotaTypes[0]);

    for (int i = 0; i < totalNumberOfInstances; i++) {
      String instance = String.format(instanceNameFormat, i);
      Set<String> test = assignableInstanceManager.getAssignableInstance(instance)
          .getCurrentAssignments();
      boolean isAssignmentEmpty = assignableInstanceManager.getAssignableInstance(instance)
          .getCurrentAssignments().isEmpty();
      // Check that assignment only took place to eligible number of instances and that assignment
      // did not happen to non-eligible AssignableInstances
      if (i < eligibleNumberOfInstances) {
        // Must have tasks assigned to these instances
        Assert.assertFalse(isAssignmentEmpty);
      } else {
        // These instances should have no tasks assigned to them
        Assert.assertTrue(isAssignmentEmpty);
      }
    }
  }

  private void profileAssigner(int assignBatchSize, int instanceCount, int taskCount) {
    int trail = 100;
    long totalTime = 0;
    for (int i = 0; i < trail; i++) {
      TaskAssigner assigner = new ThreadCountBasedTaskAssigner();

      // 50 * instanceCount number of tasks
      AssignableInstanceManager assignableInstanceManager =
          createAssignableInstanceManager(instanceCount, 100);
      List<TaskConfig> tasks = createTaskConfigs(taskCount);
      List<Map<String, TaskAssignResult>> allResults = new ArrayList<>();

      // Assign
      long start = System.currentTimeMillis();
      for (int j = 0; j < taskCount / assignBatchSize; j++) {
        allResults.add(assigner.assignTasks(assignableInstanceManager,
            assignableInstanceManager.getAssignableInstanceNames(),
            tasks.subList(j * assignBatchSize, (j + 1) * assignBatchSize), testQuotaTypes[0]));
      }
      long duration = System.currentTimeMillis() - start;
      totalTime += duration;

      // Validate
      for (Map<String, TaskAssignResult> results : allResults) {
        for (TaskAssignResult rst : results.values()) {
          Assert.assertTrue(rst.isSuccessful());
        }
      }
    }
    System.out.println("Average time: " + totalTime / trail + "ms");
  }

  private void assertAssignmentResults(Iterable<TaskAssignResult> results, boolean expected) {
    for (TaskAssignResult rst : results) {
      Assert.assertEquals(rst.isSuccessful(), expected);
    }
  }

  private List<TaskConfig> createTaskConfigs(int count) {
    return createTaskConfigs(count, true);
  }

  private List<TaskConfig> createTaskConfigs(int count, boolean randomID) {
    List<TaskConfig> tasks = new ArrayList<>();
    for (int i = 0; i < count; i++) {
      TaskConfig task =
          new TaskConfig(null, null, randomID ? UUID.randomUUID().toString() : "task-" + i, null);
      tasks.add(task);
    }
    return tasks;
  }

  private AssignableInstanceManager createAssignableInstanceManager(int count, int threadCount) {
    AssignableInstanceManager assignableInstanceManager = new AssignableInstanceManager();
    ClusterConfig clusterConfig = createClusterConfig(testQuotaTypes, testQuotaRatio, false);
    String instanceNameFormat = "instance-%s";
    Map<String, LiveInstance> liveInstanceMap = new HashMap<>();
    Map<String, InstanceConfig> instanceConfigMap = new HashMap<>();
    for (int i = 0; i < count; i++) {
      String instanceName = String.format(instanceNameFormat, i);
      liveInstanceMap.put(instanceName, createLiveInstance(
          new String[] { LiveInstance.InstanceResourceType.TASK_EXEC_THREAD.name() },
          new String[] { Integer.toString(threadCount) }, instanceName));
      instanceConfigMap.put(instanceName, new InstanceConfig(instanceName));
    }

    assignableInstanceManager
        .buildAssignableInstances(clusterConfig, new TaskDataCache(testClusterName),
            liveInstanceMap, instanceConfigMap);
    return assignableInstanceManager;
  }
}


text:
package header

import (
	"net/http"
	"testing"

	"github.com/google/martian"
	"github.com/google/martian/proxyutil"
	"github.com/google/martian/session"
)

func TestViaModifier(t *testing.T) {
	m := NewViaModifier("martian")
	req, err := http.NewRequest("GET", "/", nil)
	if err != nil {
		t.Fatalf("http.NewRequest(): got %v, want no error", err)
	}
	res := proxyutil.NewResponse(200, nil, req)

	ctx, err := session.FromContext(nil)
	if err != nil {
		t.Fatalf("session.FromContext(): got %v, want no error", err)
	}

	martian.SetContext(req, ctx)
	defer martian.RemoveContext(req)

	if err := m.ModifyRequest(req); err != nil {
		t.Fatalf("ModifyRequest(): got %v, want no error", err)
	}
	if got, want := req.Header.Get("Via"), "1.1 martian"; got != want {
		t.Errorf("req.Header.Get(%q): got %q, want %q", "Via", got, want)
	}

	if err := m.ModifyResponse(res); err != nil {
		t.Fatalf("ModifyResponse(): got %v, want no error", err)
	}

	req.Header.Set("Via", "1.0 alpha")
	if err := m.ModifyRequest(req); err != nil {
		t.Fatalf("ModifyRequest(): got %v, want no error", err)
	}
	if got, want := req.Header.Get("Via"), "1.0 alpha, 1.1 martian"; got != want {
		t.Errorf("req.Header.Get(%q): got %q, want %q", "Via", got, want)
	}

	req.Header.Set("Via", "1.0 alpha, 1.1 martian, 1.1 beta")
	if err := m.ModifyRequest(req); err == nil {
		t.Fatal("ModifyRequest(): got nil, want request loop error")
	}
	if !ctx.SkippingRoundTrip() {
		t.Errorf("ctx.SkippingRoundTrip(): got false, want true")
	}

	if err := m.ModifyResponse(res); err == nil {
		t.Fatal("ModifyResponse(): got nil, want request loop error")
	}
	if got, want := res.StatusCode, 400; got != want {
		t.Errorf("res.StatusCode: got %d, want %d", got, want)
	}
	if got, want := res.Status, http.StatusText(400); got != want {
		t.Errorf("res.Status: got %q, want %q", got, want)
	}
}


text:
package io.github.nasso.nhengine.ui.control;

import java.util.function.Consumer;

import io.github.nasso.nhengine.graphics.Texture2D;

public class UIMenuItem {
	private CharSequence text;
	protected UIMenu parent = null;
	private Texture2D icon = null;

	private Consumer<UIMenuItem> onAction = null;

	public UIMenuItem() {
		this(null);
	}

	public UIMenuItem(CharSequence text) {
		this(null, text);
	}

	public UIMenuItem(CharSequence text, Consumer<UIMenuItem> onAction) {
		this(null, text, onAction);
	}

	public UIMenuItem(Texture2D icon, CharSequence text) {
		this(icon, text, null);
	}

	public UIMenuItem(Texture2D icon, CharSequence text, Consumer<UIMenuItem> onAction) {
		this.text = text;
		this.icon = icon;
		this.onAction = onAction;
	}

	public void doClick() {
		if(this.onAction != null) this.onAction.accept(this);
	}

	public UIMenu getRootMenu() {
		return this.parent == null ? null : this.parent.getRootMenu();
	}

	public CharSequence getText() {
		return this.text;
	}

	public void setText(CharSequence text) {
		this.text = text;
	}

	public Texture2D getIcon() {
		return this.icon;
	}

	public void setIcon(Texture2D icon) {
		this.icon = icon;
	}

	public Consumer<UIMenuItem> getOnAction() {
		return this.onAction;
	}

	public void setOnAction(Consumer<UIMenuItem> onAction) {
		this.onAction = onAction;
	}
}


text:
{% import "_includes/forms" as forms %}

{{ forms.textField({
    label: "Start year"|t,
    instructions: "What year should we start counting? Use a full year notation or a PHP [```strtotime()```](http://php.net/manual/en/function.strtotime.php) value based on the current date/time."|t,
    id: 'yearRangeStart',
    name: 'yearRangeStart',
    value: settings.yearRangeStart,
    errors: settings.getErrors('yearRangeStart')
}) }}

{{ forms.textField({
    label: "End year"|t,
    instructions: "What year should we end counting? Use a full year notation or a PHP [```strtotime()```](http://php.net/manual/en/function.strtotime.php) value based on the current date/time."|t,
    id: 'yearRangeEnd',
    name: 'yearRangeEnd',
    value: settings.yearRangeEnd,
    errors: settings.getErrors('yearRangeEnd')
}) }}


text:
require 'stringio'
require 'rubocop'
require 'haml_lint'

class CommitMonitorHandlers::CommitRange::RubocopChecker::MessageBuilder
  include BranchWorkerMixin

  def initialize(results, branch)
    @results = results
    @branch  = branch
  end

  def comments
    build_comments
    message_builder.comments
  end

  private

  attr_reader :results, :message_builder

  SUCCESS_EMOJI = %w{:+1: :cookie: :star: :cake: :trophy:}

  SEVERITY = {
    "fatal"      => ":red_circle: **Fatal**",
    "error"      => ":red_circle: **Error**",
    "warning"    => ":red_circle: **Warn**",
    "convention" => ":large_orange_diamond:",
    "refactor"   => ":small_blue_diamond:",
  }.freeze

  COP_DOCUMENTATION_URI = File.join("http://rubydoc.info/gems/rubocop", RuboCop::Version.version)
  COP_URIS =
    RuboCop::Cop::Cop.subclasses.each_with_object({}) do |cop, h|
      cop_name_parts = cop.name.split("::")
      cop_name = cop_name_parts[2..-1].join("/")
      cop_uri  = File.join(COP_DOCUMENTATION_URI, cop_name_parts)
      h[cop_name] = "[#{cop_name}](#{cop_uri})"
    end.freeze

  def tag
    "<rubocop />"
  end

  def header
    header1 = "Checked #{"commit".pluralize(commits.length)} #{commit_range_text} with ruby #{RUBY_VERSION}, rubocop #{rubocop_version}, and haml-lint #{hamllint_version}"

    file_count    = results.fetch_path("summary", "target_file_count").to_i
    offense_count = results.fetch_path("summary", "offense_count").to_i
    header2 = "#{file_count} #{"file".pluralize(file_count)} checked, #{offense_count} #{"offense".pluralize(offense_count)} detected"

    "#{tag}#{header1}\n#{header2}"
  end

  def continuation_header
    "#{tag}**...continued**\n"
  end

  def build_comments
    @message_builder = MiqToolsServices::Github::MessageBuilder.new(header, continuation_header)
    files.empty? ? write_success : write_offenses
  end

  def write_success
    message_builder.write("Everything looks good. #{SUCCESS_EMOJI.sample}")
  end

  def write_offenses
    files.each do |f|
      message_builder.write("\n**#{f["path"]}**")
      message_builder.write_lines(offense_lines(f))
    end
  end

  def files
    results["files"].select { |f| f["offenses"].any? }.sort_by { |f| f["path"] }
  end

  def offense_lines(file)
    sorted_offense_records(file).collect do |o|
      "- [ ] %s - %s, %s - %s - %s" % [
        format_severity(o["severity"]),
        format_line(o["location"]["line"], file["path"]),
        format_column(o["location"]["column"]),
        format_cop_name(o["cop_name"]),
        o["message"]
      ]
    end
  end

  def sorted_offense_records(file)
    file["offenses"].sort_by do |o|
      [
        order_severity(o["severity"]),
        o["location"]["line"],
        o["location"]["column"],
        o["cop_name"]
      ]
    end
  end

  def order_severity(sev)
    SEVERITY.keys.index(sev) || Float::INFINITY
  end

  def format_severity(sev)
    SEVERITY[sev] || sev.capitalize[0, 5]
  end

  # TODO: Don't reuse the commit_uri.  This should probably be its own URI.
  def line_uri
    branch.commit_uri.chomp("commit/$commit")
  end

  def format_line(line, path)
    uri = File.join(line_uri, "blob", commits.last, path)
    "[Line #{line}](#{uri}#L#{line})"
  end

  def format_column(column)
    "Col #{column}"
  end

  def format_cop_name(cop_name)
    COP_URIS[cop_name] || cop_name
  end

  def rubocop_version
    RuboCop::Version.version
  end

  def hamllint_version
    HamlLint::VERSION
  end
end


text:
SYNONYM

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

#### Published in
in von Arx, Guarro & van der Aa, Persoonia 13(3): 268 (1987)

#### Original name
Sordaria prolifica Cailleux, 1972

### Remarks
null


text:
<?php
/**
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 */

namespace Piwik\Plugins\Actions\Actions;

use Piwik\Common;
use Piwik\Tracker\Action;
use Piwik\Tracker\PageUrl;
use Piwik\Tracker\Request;
use Piwik\Tracker\Cache;
use Piwik\UrlHelper;

/**
 * This class represents a search on the site.
 * - Its name is the search keyword
 * - by default the URL is not recorded (since it's not used)
 * - tracks site search result count and site search category as custom variables
 *
 */
class ActionSiteSearch extends Action
{
    private $searchCategory = false;
    private $searchCount = false;

    const CVAR_KEY_SEARCH_CATEGORY = '_pk_scat';
    const CVAR_KEY_SEARCH_COUNT = '_pk_scount';
    const CVAR_INDEX_SEARCH_CATEGORY = '4';
    const CVAR_INDEX_SEARCH_COUNT = '5';

    public function __construct(Request $request, $detect = true)
    {
        parent::__construct(Action::TYPE_SITE_SEARCH, $request);
        $this->originalUrl = $request->getParam('url');

        if ($detect) {
            $this->isSearchDetected();
        }
    }

    public static function shouldHandle(Request $request)
    {
        $search = new self($request, false);

        return $search->detectSiteSearch($request->getParam('url'));
    }

    protected function getActionsToLookup()
    {
        return array(
            'idaction_name' => array($this->getActionName(), Action::TYPE_SITE_SEARCH),
        );
    }

    public function getIdActionUrl()
    {
        // Site Search, by default, will not track URL. We do not want URL to appear as "Page URL not defined"
        // so we specifically set it to NULL in the table (the archiving query does IS NOT NULL)
        return null;
    }

    public function getCustomFloatValue()
    {
        return $this->request->getPageGenerationTime();
    }

    protected function isSearchDetected()
    {
        $siteSearch = $this->detectSiteSearch($this->originalUrl);

        if (empty($siteSearch)) {
            return false;
        }

        list($actionName, $url, $category, $count) = $siteSearch;

        if (!empty($category)) {
            $this->searchCategory = trim($category);
        }
        if ($count !== false) {
            $this->searchCount = $count;
        }
        $this->setActionName($actionName);
        $this->setActionUrl($url);

        return true;
    }

    public function getCustomVariables()
    {
        $customVariables = parent::getCustomVariables();

        // Enrich Site Search actions with Custom Variables, overwriting existing values
        if (!empty($this->searchCategory)) {
            if (!empty($customVariables['custom_var_k' . self::CVAR_INDEX_SEARCH_CATEGORY])) {
                Common::printDebug("WARNING: Overwriting existing Custom Variable  in slot " . self::CVAR_INDEX_SEARCH_CATEGORY . " for this page view");
            }
            $customVariables['custom_var_k' . self::CVAR_INDEX_SEARCH_CATEGORY] = self::CVAR_KEY_SEARCH_CATEGORY;
            $customVariables['custom_var_v' . self::CVAR_INDEX_SEARCH_CATEGORY] = Request::truncateCustomVariable($this->searchCategory);
        }
        if ($this->searchCount !== false) {
            if (!empty($customVariables['custom_var_k' . self::CVAR_INDEX_SEARCH_COUNT])) {
                Common::printDebug("WARNING: Overwriting existing Custom Variable  in slot " . self::CVAR_INDEX_SEARCH_COUNT . " for this page view");
            }
            $customVariables['custom_var_k' . self::CVAR_INDEX_SEARCH_COUNT] = self::CVAR_KEY_SEARCH_COUNT;
            $customVariables['custom_var_v' . self::CVAR_INDEX_SEARCH_COUNT] = (int)$this->searchCount;
        }
        return $customVariables;
    }

    protected function detectSiteSearchFromUrl($website, $parsedUrl)
    {
        $doRemoveSearchParametersFromUrl = true;
        $separator = '&';
        $count = $actionName = $categoryName = false;

        $keywordParameters = isset($website['sitesearch_keyword_parameters'])
            ? $website['sitesearch_keyword_parameters']
            : array();
        $queryString = (!empty($parsedUrl['query']) ? $parsedUrl['query'] : '') . (!empty($parsedUrl['fragment']) ? $separator . $parsedUrl['fragment'] : '');
        $parametersRaw = UrlHelper::getArrayFromQueryString($queryString);

        // strtolower the parameter names for smooth site search detection
        $parameters = array();
        foreach ($parametersRaw as $k => $v) {
            $parameters[Common::mb_strtolower($k)] = $v;
        }
        // decode values if they were sent from a client using another charset
        $pageEncoding = $this->request->getParam('cs');
        PageUrl::reencodeParameters($parameters, $pageEncoding);

        // Detect Site Search keyword
        foreach ($keywordParameters as $keywordParameterRaw) {
            $keywordParameter = Common::mb_strtolower($keywordParameterRaw);
            if (!empty($parameters[$keywordParameter])) {
                $actionName = $parameters[$keywordParameter];
                break;
            }
        }

        if (empty($actionName)) {
            return false;
        }

        $categoryParameters = isset($website['sitesearch_category_parameters'])
            ? $website['sitesearch_category_parameters']
            : array();

        foreach ($categoryParameters as $categoryParameterRaw) {
            $categoryParameter = Common::mb_strtolower($categoryParameterRaw);
            if (!empty($parameters[$categoryParameter])) {
                $categoryName = $parameters[$categoryParameter];
                break;
            }
        }

        if (isset($parameters['search_count'])
            && $this->isValidSearchCount($parameters['search_count'])
        ) {
            $count = $parameters['search_count'];
        }
        // Remove search kwd from URL
        if ($doRemoveSearchParametersFromUrl) {
            // @see excludeQueryParametersFromUrl()
            // Excluded the detected parameters from the URL
            $parametersToExclude = array($categoryParameterRaw, $keywordParameterRaw);
            if (isset($parsedUrl['query'])) {
                $parsedUrl['query'] = UrlHelper::getQueryStringWithExcludedParameters(UrlHelper::getArrayFromQueryString($parsedUrl['query']), $parametersToExclude);
            }
            if (isset($parsedUrl['fragment'])) {
                $parsedUrl['fragment'] = UrlHelper::getQueryStringWithExcludedParameters(UrlHelper::getArrayFromQueryString($parsedUrl['fragment']), $parametersToExclude);
            }
        }
        $url = UrlHelper::getParseUrlReverse($parsedUrl);
        if (is_array($actionName)) {
            $actionName = reset($actionName);
        }

        $actionName = PageUrl::urldecodeValidUtf8($actionName);
        $actionName = trim($actionName);
        if (empty($actionName)) {
            return false;
        }

        if (is_array($categoryName)) {
            $categoryName = reset($categoryName);
        }
        $categoryName = PageUrl::urldecodeValidUtf8($categoryName);
        $categoryName = trim($categoryName);

        return array($url, $actionName, $categoryName, $count);
    }

    protected function isValidSearchCount($count)
    {
        return is_numeric($count) && $count >= 0;
    }

    public function detectSiteSearch($originalUrl)
    {
        $website = Cache::getCacheWebsiteAttributes($this->request->getIdSite());
        if (empty($website['sitesearch'])) {
            Common::printDebug("Internal 'Site Search' tracking is not enabled for this site. ");
            return false;
        }

        $actionName = $url = $categoryName = $count = false;

        $originalUrl = PageUrl::cleanupUrl($originalUrl);

        // Detect Site search from Tracking API parameters rather than URL
        $searchKwd = $this->request->getParam('search');
        if (!empty($searchKwd)) {
            $actionName = $searchKwd;
            $isCategoryName = $this->request->getParam('search_cat');
            if (!empty($isCategoryName)) {
                $categoryName = $isCategoryName;
            }
            $isCount = $this->request->getParam('search_count');
            if ($this->isValidSearchCount($isCount)) {
                $count = $isCount;
            }
        }

        if (empty($actionName)) {
            $parsedUrl = @parse_url($originalUrl);

            // Detect Site Search from URL query parameters
            if (!empty($parsedUrl['query']) || !empty($parsedUrl['fragment'])) {
                // array($url, $actionName, $categoryName, $count);
                $searchInfo = $this->detectSiteSearchFromUrl($website, $parsedUrl);
                if (!empty($searchInfo)) {
                    list ($url, $actionName, $categoryName, $count) = $searchInfo;
                }
            }
        }

        $actionName = trim($actionName);
        $categoryName = trim($categoryName);

        if (empty($actionName)) {
            Common::printDebug("(this is not a Site Search request)");
            return false;
        }

        Common::printDebug("Detected Site Search keyword '$actionName'. ");
        if (!empty($categoryName)) {
            Common::printDebug("- Detected Site Search Category '$categoryName'. ");
        }
        if ($count !== false) {
            Common::printDebug("- Search Results Count was '$count'. ");
        }
        if ($url != $originalUrl) {
            Common::printDebug("NOTE: The Page URL was changed / removed, during the Site Search detection, was '$originalUrl', now is '$url'");
        }

        return array(
            $actionName,
            $url,
            $categoryName,
            $count
        );
    }

}


text:
package java.nio

import scala.scalajs.js.typedarray._

private[nio] final class DataViewFloatBuffer private (
    override private[nio] val _dataView: DataView,
    _initialPosition: Int, _initialLimit: Int, _readOnly: Boolean,
    override private[nio] val isBigEndian: Boolean)
    extends FloatBuffer(_dataView.byteLength / 4, null, -1) {

  position(_initialPosition)
  limit(_initialLimit)

  private[this] implicit def newDataViewFloatBuffer =
    DataViewFloatBuffer.NewDataViewFloatBuffer

  def isReadOnly(): Boolean = _readOnly

  def isDirect(): Boolean = true

  @noinline
  def slice(): FloatBuffer =
    GenDataViewBuffer(this).generic_slice()

  @noinline
  def duplicate(): FloatBuffer =
    GenDataViewBuffer(this).generic_duplicate()

  @noinline
  def asReadOnlyBuffer(): FloatBuffer =
    GenDataViewBuffer(this).generic_asReadOnlyBuffer()

  @noinline
  def get(): Float =
    GenBuffer(this).generic_get()

  @noinline
  def put(f: Float): FloatBuffer =
    GenBuffer(this).generic_put(f)

  @noinline
  def get(index: Int): Float =
    GenBuffer(this).generic_get(index)

  @noinline
  def put(index: Int, f: Float): FloatBuffer =
    GenBuffer(this).generic_put(index, f)

  @noinline
  override def get(dst: Array[Float], offset: Int, length: Int): FloatBuffer =
    GenBuffer(this).generic_get(dst, offset, length)

  @noinline
  override def put(src: Array[Float], offset: Int, length: Int): FloatBuffer =
    GenBuffer(this).generic_put(src, offset, length)

  @noinline
  def compact(): FloatBuffer =
    GenDataViewBuffer(this).generic_compact()

  def order(): ByteOrder =
    GenDataViewBuffer(this).generic_order()

  // Internal API

  @inline
  override private[nio] def _arrayBuffer: ArrayBuffer =
    GenDataViewBuffer(this).generic_arrayBuffer

  @inline
  override private[nio] def _arrayBufferOffset: Int =
    GenDataViewBuffer(this).generic_arrayBufferOffset

  @inline
  private[nio] def load(index: Int): Float =
    _dataView.getFloat32(4 * index, !isBigEndian)

  @inline
  private[nio] def store(index: Int, elem: Float): Unit =
    _dataView.setFloat32(4 * index, elem, !isBigEndian)

  @inline
  override private[nio] def load(startIndex: Int,
      dst: Array[Float], offset: Int, length: Int): Unit =
    GenBuffer(this).generic_load(startIndex, dst, offset, length)

  @inline
  override private[nio] def store(startIndex: Int,
      src: Array[Float], offset: Int, length: Int): Unit =
    GenBuffer(this).generic_store(startIndex, src, offset, length)
}

private[nio] object DataViewFloatBuffer {
  private[nio] implicit object NewDataViewFloatBuffer
      extends GenDataViewBuffer.NewDataViewBuffer[FloatBuffer] {
    def bytesPerElem: Int = 4

    def apply(dataView: DataView,
        initialPosition: Int, initialLimit: Int,
        readOnly: Boolean, isBigEndian: Boolean): FloatBuffer = {
      new DataViewFloatBuffer(dataView,
          initialPosition, initialLimit, readOnly, isBigEndian)
    }
  }

  @inline
  def fromTypedArrayByteBuffer(byteBuffer: TypedArrayByteBuffer): FloatBuffer =
    GenDataViewBuffer.generic_fromTypedArrayByteBuffer(byteBuffer)
}


text:
package org.ansj.solr;

import java.io.IOException;
import java.io.StringReader;
import java.util.List;

import org.ansj.domain.Term;
import org.ansj.splitWord.analysis.IndexAnalysis;
import org.ansj.splitWord.analysis.ToAnalysis;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;

public class TestAnsj {

	public static void main(String[] args) throws IOException {
		List<Term> parse = ToAnalysis.parse("天天向上,媒体打打。《回家真好》");
		System.out.println(parse);
		Tokenizer tokenizer = new AnsjTokenizer(new StringReader("天天向上,媒体打打。《回家真好》"), 0, true);
		CharTermAttribute termAtt = tokenizer.addAttribute(CharTermAttribute.class);
		OffsetAttribute offsetAtt =
				tokenizer.addAttribute(OffsetAttribute.class);
			PositionIncrementAttribute positionIncrementAtt =
				tokenizer.addAttribute(PositionIncrementAttribute.class);

		while (tokenizer.incrementToken()){

			System.out.print(new String(termAtt.toString()) );
			System.out.print( offsetAtt.startOffset() + "-" + offsetAtt.endOffset() + "-" );
			System.out.print( positionIncrementAtt.getPositionIncrement() +"/");

		}
		tokenizer.close();
	}
}


text:
$packageName = 'aria2'
$unzipLoc = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
# hack to overcome limitations of Ketarin/chocopkgup when using repos like sf.net
$urlArray = @('http://sourceforge.net/projects/aria2/files/stable/aria2-1.18.9/aria2-1.18.9-win-32bit-build1.zip/download', 'http://sourceforge.net/projects/aria2/files/stable/aria2-1.18.9/aria2-1.18.9-win-64bit-build1.zip/download')
$url = $urlArray[0]
$url64 = $urlArray[1]
Install-ChocolateyZipPackage "$packageName" "$url" "$unzipLoc" "$url64"


text:
#include <common.h>
#include <SA-1100.h>

ulong get_timer (ulong base)
{
	return get_timer_masked ();
}

void __udelay (unsigned long usec)
{
	udelay_masked (usec);
}

ulong get_timer_masked (void)
{
	return OSCR;
}

void udelay_masked (unsigned long usec)
{
	ulong tmo;
	ulong endtime;
	signed long diff;

	if (usec >= 1000) {
		tmo = usec / 1000;
		tmo *= CONFIG_SYS_HZ;
		tmo /= 1000;
	} else {
		tmo = usec * CONFIG_SYS_HZ;
		tmo /= (1000*1000);
	}

	endtime = get_timer_masked () + tmo;

	do {
		ulong now = get_timer_masked ();
		diff = endtime - now;
	} while (diff >= 0);
}

/*
 * This function is derived from PowerPC code (read timebase as long long).
 * On ARM it just returns the timer value.
 */
unsigned long long get_ticks(void)
{
	return get_timer(0);
}

/*
 * This function is derived from PowerPC code (timebase clock frequency).
 * On ARM it returns the number of timer ticks per second.
 */
ulong get_tbclk (void)
{
	return CONFIG_SYS_HZ;
}