text:
<?php

namespace Doctrine\ODM\CouchDB\Mapping;

use Doctrine\ODM\CouchDB\Mapping\ClassMetadata;
use Doctrine\ODM\CouchDB\Types\Type;
use Doctrine\Common\Util\ClassUtils;

/**
 * Helper class serializing/unserializing embedded documents.
 *
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link        www.doctrine-project.com
 * @since       1.0
 * @author      Bartfai Tamas <bartfaitamas@gmail.com>
 */
class EmbeddedDocumentSerializer
{
    private $metadataFactory;

    private $metadataResolver;

    public function __construct($metadataFactory, $metadataResolver)
    {
        $this->metadataFactory = $metadataFactory;
        $this->metadataResolver = $metadataResolver;
    }

    /**
     * Serializes an embedded document value into array given the mapping
     * metadata for the class.
     *
     * @param object $embeddedValue
     * @param array $embeddedFieldMapping
     * @return array
     *
     */
    public function serializeEmbeddedDocument($embeddedValue, $embeddedFieldMapping, $embedMany = false)
    {
        if ($embeddedValue === null) {
            return null;
        }

        if (!$embedMany && 'many' == $embeddedFieldMapping['embedded'] && (is_array($embeddedValue) || $embeddedValue instanceof \Traversable)) {
            $data = array();
            foreach ($embeddedValue as $key => $val) {
                $data[$key] = $this->serializeEmbeddedDocument($val, $embeddedFieldMapping, true);
            }
        } else {
            $embeddedClass = null;
            if (isset($embeddedFieldMapping['targetDocument'])) {
                $embeddedClass = $this->metadataFactory->getMetadataFor(ClassUtils::getClass($embeddedValue));

                if ($embeddedClass->name !== $embeddedFieldMapping['targetDocument'] &&
                    !is_subclass_of($embeddedClass->name, $embeddedFieldMapping['targetDocument']) ) {

                    throw new \InvalidArgumentException(
                        'Mismatching metadata description in the EmbeddedDocument, expected class ' .
                        $embeddedFieldMapping['targetDocument'] . ' but got ' . get_class($embeddedValue)
                    );
                }
            } else {
                $embeddedClass = $this->metadataFactory->getMetadataFor(get_class($embeddedValue));
            }

            $data = $this->metadataResolver->createDefaultDocumentStruct($embeddedClass);
            foreach($embeddedClass->reflFields AS $fieldName => $reflProperty) {
                $value = $reflProperty->getValue($embeddedValue);
                $fieldMapping = $embeddedClass->fieldMappings[$fieldName];

                if ($value === null) {
                    continue;
                } else if (isset($fieldMapping['embedded'])) {
                    $data[$fieldMapping['jsonName']] = $this->serializeEmbeddedDocument($value, $fieldMapping);
                } else {
                    $data[$fieldMapping['jsonName']] = Type::getType($fieldMapping['type'])
                        ->convertToCouchDBValue($value);
                }
            }
        }
        return $data;
    }

    /**
     * Create a document for an embedded document field mapping from json data.
     *
     * @param array $data
     * @param object $embeddedFieldMapping
     * @return object
     */
    public function createEmbeddedDocument($data, $embeddedFieldMapping)
    {
        if ($data === null) {
            return null;
        } else if (!is_array($data)) {
            throw new \InvalidArgumentException("Cannot hydrate embedded if the data given is not an array");
        }

        if ('many' == $embeddedFieldMapping['embedded']) {

            $result = array();
            foreach ($data as $jsonName => $jsonValue) {
                if (!is_array($jsonValue)) {
                    throw new \InvalidArgumentException("Cannot hydrate many embedded if the data given is not an array");
                }

                $result[$jsonName] = $this->doCreateEmbeddedDocument($jsonValue, $embeddedFieldMapping);
            }
            ksort($result);
            return $result;
        } else {
            return $this->doCreateEmbeddedDocument($data, $embeddedFieldMapping);
        }
    }

    public function doCreateEmbeddedDocument($data, $embeddedFieldMapping)
    {
        if (!$this->metadataResolver->canMapDocument($data)) {
            if (!isset($embeddedFieldMapping['targetDocument'])) {
                throw new \InvalidArgumentException("Missing or missmatching metadata description in the EmbeddedDocument, cannot hydrate!");
            }
            $type = $embeddedFieldMapping['targetDocument'];
        } else {
            $type = $this->metadataResolver->getDocumentType($data);
        }

        $class = $this->metadataFactory->getMetadataFor($type);
        $instance = $class->newInstance();

        $documentState = array();
        foreach ($data as $jsonName => $jsonValue) {
            if ($this->metadataResolver->canResolveJsonField($jsonName)) {
                continue;
            }
            if (isset($class->jsonNames[$jsonName])) {
                $fieldName = $class->jsonNames[$jsonName];
                if (isset($class->fieldMappings[$fieldName])) {
                    if ($jsonValue === null) {
                        $fieldValue = null;
                    } else if (isset($class->fieldMappings[$fieldName]['embedded'])) {
                        $fieldValue = $this->createEmbeddedDocument($jsonValue, $class->fieldMappings[$fieldName]);
                    } else {
                        $fieldValue =
                            Type::getType($class->fieldMappings[$fieldName]['type'])
                            ->convertToPHPValue($jsonValue);
                    }

                    $class->setFieldValue($instance,
                                          $class->fieldMappings[$fieldName]['fieldName'],
                                          $fieldValue);

                }
            } else {
                //$nonMappedData[$jsonName] = $jsonValue;
            }
        }
        return $instance;
    }

    /**
     * Compares the two representation of an embedded document.
     *
     * If the original misses doctrine_metadata, but the values are the same, we assume there is no change
     * If the original has doctrine_metadata, and the new value has different class, that's a change,
     * even if the values are the same.
     *
     * @param array $value
     * @param object $originalData
     * @param array $fieldMapping Mapping of the field that contains the embedded document in the
     *                            embedder document.
     * @return boolean
     */
    public function isChanged($value, $originalData, $valueFieldMapping)
    {
        // EmbedMany case
        if ('many' == $valueFieldMapping['embedded'] && is_array($value)) {
            if (count($originalData) != count($value)) {
                return true;
            }
            foreach ($value as $key => $valueElement) {
                if (!isset($originalData[$key])
                    || $this->isChanged($valueElement, $originalData[$key], $valueFieldMapping)) {
                    return true;
                }
            }
            return false;
        }

        // EmbedOne case, or one instance of and EmbedMany
        if ($this->metadataResolver->canMapDocument($originalData)
            && get_class($value) !== $this->metadataResolver->getDocumentType($originalData)) {
            return true;
        }

        $class = $this->metadataFactory->getMetadataFor(get_class($value));
        foreach ($class->reflFields as $fieldName => $fieldValue) {
            $fieldMapping = $class->fieldMappings[$fieldName];
            $originalDataValue = isset($originalData[$fieldMapping['jsonName']])
                ? $originalData[$fieldMapping['jsonName']]
                : null;

            $currentValue = $class->getFieldValue($value, $fieldMapping['fieldName']);

            if ($originalDataValue === null && $currentValue === null) {
                continue;
            } else if ($originalDataValue === null || $currentValue === null) {
                return true;
            }

            if (!isset($fieldMapping['embedded'])) {
                // simple property comparison
                // TODO this conversion could be avoided if we store the php value in the original data
                //      as with the simple property mapping in UOW.
                $originalValue = Type::getType($fieldMapping['type'])
                    ->convertToPHPValue($originalDataValue);
                if ($originalValue != $currentValue) {
                    return true;
                }
            } else {

                if ('many' == $fieldMapping['embedded']) {
                    if (count($originalDataValue) != count($currentValue)) {
                        return true;
                    }
                    foreach ($currentValue as $currentKey => $currentElem) {
                        if (!isset($originalDataValue[$currentKey])) {
                            return true;
                        }
                        if ($this->isChanged($currentElem, $originalDataValue[$currentKey], $fieldMapping)) {
                            return true;
                        }
                    }
                } else { // embedOne
                    if ($this->isChanged($currentValue, $originalDataValue, $fieldMapping)) {
                        return true;
                    }
                }

            }
        }
        return false;
    }
}


text:
/*
 * Zed Attack Proxy (ZAP) and its related class files.
 *
 * ZAP is an HTTP/HTTPS proxy for assessing web application security.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.zaproxy.zap.extension.websocket.brk;

import org.zaproxy.zap.extension.brk.BreakPanel;
import org.zaproxy.zap.extension.brk.BreakpointMessageHandler;
import org.zaproxy.zap.extension.httppanel.Message;
import org.zaproxy.zap.extension.websocket.WebSocketMessage;
import org.zaproxy.zap.extension.websocket.WebSocketMessageDTO;
import org.zaproxy.zap.extension.websocket.ui.OptionsParamWebSocket;

/**
 * Wraps WebSocket specific options to determine if breakpoint should be applied
 * on given {@link WebSocketMessageDTO}.
 */
public class WebSocketBreakpointMessageHandler extends BreakpointMessageHandler {

	private OptionsParamWebSocket config;

	public WebSocketBreakpointMessageHandler(BreakPanel aBreakPanel, OptionsParamWebSocket config) {
		super(aBreakPanel);
		this.config = config;
	}

	/**
	 * Only break on all requests when 'Break on all' is enabled for WebSockets.
	 *
	 * @param aMessage
	 * @param isRequest
	 * @return True if it breaks on all requests.
	 */
	@Override
	protected boolean isBreakOnAllRequests(Message aMessage, boolean isRequest) {
		if (super.isBreakOnAllRequests(aMessage, isRequest)) {
			return isBreakOnAllWebSocket(aMessage, isRequest);
		}
    	return false;
	}

	/**
	 * Only break on all responses when 'Break on all' is enabled for WebSockets.
	 *
	 * @param aMessage
	 * @param isRequest
	 * @return True if it breaks on all responses.
	 */
	@Override
	protected boolean isBreakOnAllResponses(Message aMessage, boolean isRequest) {
		if (super.isBreakOnAllResponses(aMessage, isRequest)) {
			return isBreakOnAllWebSocket(aMessage, isRequest);
		}
    	return false;
	}

	/**
	 * Only break on stepping if opcode is allowed.
	 *
	 * @param aMessage
	 * @param isRequest
	 * @return True if it breaks on stepping through action.
	 */
	@Override
	protected boolean isBreakOnStepping(Message aMessage, boolean isRequest) {
		if (aMessage instanceof WebSocketMessageDTO && super.isBreakOnStepping(aMessage, isRequest)) {
			return isBreakOnOpcode(((WebSocketMessageDTO) aMessage).opcode);
		}
		return false;
	}

	/**
	 * Helper that determines if breakpoint should be applied for 'All
	 * Requests/Responses' on this {@link WebSocketMessageDTO}.
	 *
	 * @param aMessage
	 * @param isRequest
	 * @return True if it should break on the HTTP request/response breakpoints.
	 */
	private boolean isBreakOnAllWebSocket(Message aMessage, boolean isRequest) {
		if (aMessage instanceof WebSocketMessageDTO && config.isBreakOnAll()) {
			return isBreakOnOpcode(((WebSocketMessageDTO) aMessage).opcode);
		}
		return false;
	}

	/**
	 * Check out if breakpoint should be applied on given
	 * {@link WebSocketMessageDTO#opcode}.
	 *
	 * @param opcode
	 * @return True if it should break on given opcode.
	 */
	private boolean isBreakOnOpcode(Integer opcode) {
		boolean shouldBreak = false;
		if (config.isBreakOnPingPong()) {
			// break on every message type
			shouldBreak = true;
		} else {
			// break only on non-ping/pong
			boolean isPing = opcode.equals(WebSocketMessage.OPCODE_PING);
			boolean isPong = opcode.equals(WebSocketMessage.OPCODE_PONG);

			if (!isPing && !isPong) {
				shouldBreak = true;
			}
		}
		return shouldBreak;
	}
}

redpajama_set_name: RedPajamaGithub


text:
var fs = require('fs');

module.exports = function(filename, text) {

	fs.writeFile(filename, text, function(err) {
		if (err) return handleError(err);

		fs.readFile(filename, {encoding: 'utf8'}, function(err, content) {
			if (err) return handleError(err);
			console.log(content);

			fs.unlink(filename, function(err) {
				if (err) return handleError(err);
				if (callback) callback(err, content);
			});
		});
	});
};

function handleError(err) {
	console.error(err);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.codejargon</groupId>
        <artifactId>fluentjdbc-parent</artifactId>
        <version>0.9.9-SNAPSHOT</version>
    </parent>
    <artifactId>fluentjdbc</artifactId>
    <name>FluentJdbc Core</name>
    <dependencies>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.184</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.derby</groupId>
            <artifactId>derby</artifactId>
            <version>10.11.1.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <version>2.3.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>test-jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
package com.zaradai.config;

import com.google.common.base.Strings;

/**
 * Provides a default implementation for {link ConfigurationSource }.
 * Default action is to try and type coerce given String representation and catch
 * any errors in the conversion.  If no value is found or the type cant be coerced then
 * a provided default value is returned.
 */
public abstract class AbstractConfigurationSource implements ConfigurationSource {
    @Override
    public void setup(String uri) throws ConfigurationException {
        if (uri == null) {
            throw new ConfigurationException("Invalid URI");
        }
    }

    @Override
    public boolean get(String key, boolean defaultValue) {
        String value = get(key);

        if (value == null) {
            return defaultValue;
        }

        return Boolean.parseBoolean(value);
    }

    @Override
    public int get(String key, int defaultValue) {
        String value = get(key);

        try {
            return Integer.parseInt(value);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    @Override
    public long get(String key, long defaultValue) {
        String value = get(key);

        try {
            return Long.parseLong(value);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    @Override
    public float get(String key, float defaultValue) {
        String value = get(key);

        try {
            return Float.parseFloat(value);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    @Override
    public double get(String key, double defaultValue) {
        String value = get(key);

        try {
            return Double.parseDouble(value);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    @Override
    public String get(String key, String defaultValue) {
        String value = get(key);

        if (Strings.isNullOrEmpty(value)) {
            return defaultValue;
        } else {
            return value;
        }
    }

    @Override
    public void set(String key, boolean value) {
        set(key, Boolean.toString(value));
    }

    @Override
    public void set(String key, int value) {
        set(key, Integer.toString(value));
    }

    @Override
    public void set(String key, long value) {
        set(key, Long.toString(value));
    }

    @Override
    public void set(String key, float value) {
        set(key, Float.toString(value));
    }

    @Override
    public void set(String key, double value) {
        set(key, Double.toString(value));
    }
}


text:
import sbt._

object Deps {

  val curatorFramework = "org.apache.curator" % "curator-framework" % "2.9.1"
  val curatorClient = "org.apache.curator" % "curator-client" % "2.9.1"
  val curatorDiscovery = "org.apache.curator" % "curator-x-discovery" % "2.9.1"

  // process lifecycle
  val twitterServer =
    ("com.twitter" %% "twitter-server" % "1.29.0")
      .exclude("com.twitter", "finagle-zipkin_2.12")

  def twitterUtil(mod: String) =
    "com.twitter" %% s"util-$mod" % "6.43.0"

  // networking
  def finagle(mod: String) =
    "com.twitter" %% s"finagle-$mod" % "6.44.0"

  def netty4(mod: String) =
    "io.netty" % s"netty-$mod" % "4.1.9.Final"

  val boringssl = "io.netty" % "netty-tcnative-boringssl-static" % "2.0.0.Final"

  def zkCandidate = "com.twitter.common.zookeeper" % "candidate" % "0.0.76"

  // Jackson (parsing)
  val jacksonVersion = "2.8.4"
  val jacksonCore =
    "com.fasterxml.jackson.core" % "jackson-core" % jacksonVersion
  val jacksonAnnotations =
    "com.fasterxml.jackson.core" % "jackson-annotations" % jacksonVersion
  val jacksonDatabind =
    "com.fasterxml.jackson.core" % "jackson-databind" % jacksonVersion
  val jacksonScala =
    "com.fasterxml.jackson.module" %% "jackson-module-scala" % jacksonVersion
  val jackson =
    jacksonCore :: jacksonAnnotations :: jacksonDatabind :: jacksonScala :: Nil

  val jacksonYaml =
    "com.fasterxml.jackson.dataformat" % "jackson-dataformat-yaml" % jacksonVersion

  // parses a variety of timestamp formats (like RFC3339)
  val jodaTime = Seq(
    "joda-time" % "joda-time"    % "2.7",
    "org.joda"  % "joda-convert" % "1.7"
  )

  // testing. duh.
  val scalatest = "org.scalatest" %% "scalatest" % "3.0.1"

  // guava
  val guava = "com.google.guava" % "guava" % "19.0"

  // jwt for Marathon API
  val jwt = "com.pauldijou" %% "jwt-core" % "0.12.1"

  val protobuf = "com.google.protobuf" % "protobuf-java" % "3.1.0"

  // statsd client
  val statsd = "com.datadoghq" % "java-dogstatsd-client" % "2.3"
}


text:
import * as types from 'actions/actionTypes';
import Posts from 'api/Posts';

/**
 *
 * @returns {{type: LOAD_POSTS_BEGIN}}
 */
export function postsLoadBegin() {
  return {
    type: types.LOAD_POSTS_BEGIN
  };
}

/**
 *
 * @param posts
 * @returns {{type: LOAD_POSTS_COMPLETE, posts: *}}
 */
export function postsLoadComplete(posts) {
  return {
    type: types.LOAD_POSTS_COMPLETE,
    posts
  };
}

/**
 *
 * @param {boolean} isAdmin
 * @returns {Function}
 */
export function postsLoad(isAdmin = false) {
  return (dispatch) => {
    dispatch(postsLoadBegin());

    return Posts.fetchAll(isAdmin)
      .then((posts) => {
        dispatch(postsLoadComplete(posts));
      })
      .catch((error) => {
        throw (error);
      });
  };
}

/**
 *
 * @returns {{type: LOAD_POSTS_BEGIN}}
 */
export function postLoadBegin() {
  return {
    type: types.LOAD_POST_BEGIN
  };
}

/**
 *
 * @param post
 * @returns {{type: LOAD_POSTS_COMPLETE, posts: *}}
 */
export function postLoadComplete(post) {
  return {
    type: types.LOAD_POST_COMPLETE,
    post
  };
}

/**
 *
 * @returns {{type: LOAD_POST_ERROR, error: Error}}
 */
export function postLoadError(error) {
  return {
    type: types.LOAD_POST_ERROR,
    error
  };
}

/**
 *
 * @returns {Function}
 */
export function postLoad(id) {
  return (dispatch) => {
    dispatch(postLoadBegin());

    return Posts.fetchById(id)
      .then((post) => {
        dispatch(postLoadComplete(post));
      })
      .catch((error) => {
        dispatch(postLoadError(error));
      });
  };
}


text:
/*
 * Created on May 8, 2005
 *
 */
namespace NPOI.SS.Formula.Eval
{
    /**
     * @author Amol S. Deshmukh < amolweb at ya hoo dot com >
     *
     */
    public class EqualEval : RelationalOperationEval
    {
        public override bool ConvertComparisonResult(int cmpResult)
        {
            return cmpResult == 0;
        }
    }
}


text:
/* global window */

import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import rafThrottle from 'raf-throttle';
import getScrollTop from '../utils/getScrollTop';

const ZINDEX = 1;

export const Container = styled.header`
  height: ${props => props.theme.height.header};
`;

export const Fixed = styled.div`
  z-index: ${ZINDEX};
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background-color: ${props => props.theme.color.grayLight};
  height: ${props => props.theme.height.header};
  box-shadow: ${props =>
    props.isTop ? 'none' : '0 1px 0 0 rgba(0, 0, 0, 0.05)'};
  transition: box-shadow cubic-bezier(0.47, 0, 0.75, 0.72) 0.2s;
  user-select: none;
`;

class LandingHeader extends React.PureComponent {
  static propTypes = {
    children: PropTypes.node.isRequired,
    offset: PropTypes.number,
  };

  static defaultProps = {
    offset: 40,
  };

  state = { isTop: true };

  componentDidMount = () => {
    window.addEventListener('scroll', this.onScroll);
    this.onScroll();
  };
  componentWillUnmount = () => {
    window.removeEventListener('scroll', this.onScroll);
    this.onScroll.cancel();
  };
  onScroll = rafThrottle(() => {
    this.setState({ isTop: getScrollTop() < this.props.offset });
  });

  render() {
    const { children, ...otherProps } = this.props;
    const { isTop } = this.state;

    return (
      <Container {...otherProps}>
        <Fixed isTop={isTop}>{children}</Fixed>
      </Container>
    );
  }
}

export default LandingHeader;


text:
/*
Package postgresql is a Metricbeat module that contains MetricSets.
*/
package postgresql


text:
define([
    "jquery",
    "./doodad-group",
    "./tile-layer",
    "./tile-set",
    "./util/rectangle",
    "./util/util"
], function (
    $,
    DoodadGroup,
    TileLayer,
    TileSet,
    Rectangle,
    Util
) {
    var Map = function (orientation, width, height, tileWidth, tileHeight) {
        this.version = null;
        this.bounds = Rectangle.atOrigin(width, height);
        this.orientation = orientation || Map.Orientation.ORTHOGONAL;
        this.tileInfo = {
            w: tileWidth || 0,
            h: tileHeight || 0
        };
        this.layers = [];
        this.tileSets = [];
        this.properties = {};
    };

    Map.Orientation = {
        ORTHOGONAL: "orthogonal",
        ISOMETRIC: "isometric",
        STAGGERED: "staggered"
    };

    Map.prototype.fitBoundsToLayers = function() {
        var w = 0;
        var h = 0;

        // TODO Finish this.
    };

    Map.prototype.addLayer = function (layer) {
        layer.map = this;
        return this.layers.push(layer);
    };

    Map.prototype.setLayerAt = function (index, layer) {
        layer.map = this;
        this.layers[index] = layer;
    };

    Map.prototype.insertLayerAt = function (index, layer) {
        layer.map = this;
        this.layers.splice(index, 0, layer);
    };

    Map.prototype.removeLayerAt = function (index) {
        var layer = this.layers[index];
        this.layers.splice(index, 1);
        return layer;
    };

    Map.prototype.removeAllLayers = function () {
        this.layers.length = 0;
    };

    Map.prototype.getTileLayers = function () {
        var tileLayers = [];
        $.each(this.layers, function (li, layer) {
            if (layer instanceof TileLayer) {
                tileLayers.push(layer);
            }
        });
        return tileLayers;
    };

    Map.prototype.getDoodadGroups = function () {
        var doodadGroups = [];
        $.each(this.layers, function (li, layer) {
            if (layer instanceof DoodadGroup) {
                doodadGroups.push(layer);
            }
        });
        return doodadGroups;
    };

    Map.prototype.addTileSet = function (tileSet) {
        if (tileSet === null) throw new Error("TileSet cannot be null");
        if ($.inArray(tileSet, this.tileSets) > -1) {
            return;
        }

        this.tileSets.push(tileSet);
    };

    Map.prototype.removeTileSetAt = function (index) {
        if (index >= this.tileSets.length) {
            return;
        }

        var map = this;
        var tileSet = this.tileSets[index];
        $.each(tileSet.tiles, function (ti, tile) {
            $.each(map.layers, function (li, layer) {
                if (layer instanceof TileLayer) layer.removeTile(tile);
            });
        });
        this.tileSets.splice(index, 1);
    };

    Map.prototype.findTileSet = function (globalId) {
        var target = null;
        $.each(this.tileSets, function (ti, tileSet) {
            if (this.firstGlobalId <= globalId) {
                target = tileSet;
            }
        });
        return target;
    };

    Map.prototype.findTile = function (globalId) {
        var tileSet = this.findTileSet(globalId);
        return tileSet.tiles[globalId - tileSet.firstGlobalId];
    };

    Map.prototype.getMaxGlobalId = function () {
        if (!this.tileSets.length) {
            return 0;
        }
        var tileSet = this.tileSets[this.tileSets.length - 1];
        return tileSet.firstGlobalId + tileSet.tiles.length - 1;
    };

    Map.prototype.swapTileSets = function(index1, index2) {

    };

    Map.prototype.toXML = function (options) {
        var xml = $.parseXML('<?xml version="1.0" encoding="UTF-8"?><map/>')
        var mapEl = $(xml).find("map").attr({
            version: this.version,
            orientation: this.orientation,
            width: this.bounds.w,
            height: this.bounds.h,
            tilewidth: this.tileInfo.w,
            tileheight: this.tileInfo.h
        });
        if (Util.size(this.properties)) {
            var propertiesEl = $("<properties>", xml);
            $.each(this.properties, function (k, v) {
                var propertyEl = $("<property>", xml).attr({ name: k, value: v });
                propertiesEl.append(propertyEl);
            });
            mapEl.append(propertiesEl);
        }

        // Export tile sets.
        $.each(this.tileSets, function (ti, tileSet) {
            mapEl.append(tileSet.toXML(xml, options));
        });

        // Export tile layers.
        $.each(this.layers, function (li, layer) {
            mapEl.append(layer.toXML(xml, options));
        });

        // TODO Export DoodadGroups.

        return mapEl;
    };

    Map.fromXML = function (xml, options) {
        var mapEl = $(xml).find("map");
        var map = new Map(
            mapEl.attr("orientation"),
            parseInt(mapEl.attr("width")),
            parseInt(mapEl.attr("height")),
            parseInt(mapEl.attr("tilewidth")),
            parseInt(mapEl.attr("tileheight"))
        );
        //
        map.version = mapEl.attr("version") || null;

        // Load properties.
        mapEl.find("properties:first property").each(function () {
            map.properties[$(this).attr("name")] = $(this).attr("value");
        });

        // Load tile sets.
        var tileSetPromises = [];
        mapEl.find("tileset").each(function () {
            tileSetPromises.push(TileSet.fromElement(this, options).done(function (tileSet) {
                map.addTileSet(tileSet);
            }));
        });

        var deferred = $.Deferred();
        $.when.apply($, tileSetPromises)
            .done(function () {
                // Load tile layers.
                mapEl.find("layer").each(function() {
                    map.addLayer(TileLayer.fromElement(this, map, options));
                });

                // Load doodad groups.
                // TODO Finish this.

                deferred.resolve(map);
            })
            .fail(function () {
                deferred.reject();
            });
        return deferred.promise();
    };

    return Map;
});


text:
<?xml version="1.0" encoding="utf-8"?>

<forrest:contract name="siteinfo-feedback"
xmlns:forrest="http://apache.org/forrest/templates/1.0">
  <description>

The feedback element will be used to construct a feedback link in the
    page appending: <a href="@href">{@to}</a>

Beware the link rewritting !

Forrest recognise links or e-mail address in the text of the site
        and automatically converts them into real links or mailto.

if the
        toattribute is of the following form :
        \xxx.yyy@zzz.wwwit is recognised as a mailto link and will
        be converted too.

To avoid this, you can
        escapethe conversion by prefixing the email adress by the '\'
        character :
        \
        \xxx.yyy@zzz.wwwwill not be converted.

(Note that none of the previous examples are rewritten because we
        used the '\' character in the source !).

  </description>
  <usage>
    <![CDATA[<forrest:contract name="siteinfo-feedback">
  <forrest:property name="siteinfo-feedback">
    <feedback to="\webmaster@example.org"
      href="\mailto:webmaster@example.org?subject=Feedback " >
      Send feedback about the website to:
    </feedback>
  </forrest:property>
</forrest:contract>]]>
</usage>
  <forrest:template xmlns:forrest="http://apache.org/forrest/templates/1.0"
  name="siteinfo-feedback" inputFormat="xsl">
    <xsl:stylesheet version="1.1"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:param name="siteinfo-feedback" />
      <xsl:param name="defaultVariables" select="'test.html'" />
      <xsl:variable name="path"
      select="$defaultVariables/*[@name='path']/@value" />
      <xsl:template match="/">
        <forrest:content>
          <forrest:part>

              <xsl:value-of select="$siteinfo-feedback/feedback" />
              <xsl:choose>
                <xsl:when test="$siteinfo-feedback/feedback/@href and not($siteinfo-feedback/feedback/@href='')">

                    <xsl:attribute name="href">
                      <xsl:value-of select="$siteinfo-feedback/feedback/@href" />
                      <xsl:value-of select="$path" />
                    </xsl:attribute>
                    <xsl:value-of select="$siteinfo-feedback/feedback/@to" />

                </xsl:when>
                <xsl:otherwise>
                  <xsl:value-of select="$siteinfo-feedback/feedback/@to" />
                </xsl:otherwise>
              </xsl:choose>

          </forrest:part>
        </forrest:content>
      </xsl:template>
    </xsl:stylesheet>
  </forrest:template>
</forrest:contract>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/theme_third_color"
    android:orientation="vertical"
    android:padding="5dp" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/tvpaid"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/paidtext"
            android:textColor="#085286"
            android:textSize="16sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="center_horizontal"
        android:orientation="horizontal"
        android:paddingTop="15dp"
        android:weightSum="2" >

        <TextView
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Amount Paid"
            android:textColor="@color/black"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/tvAmount"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="left"
            android:text="$22.90"
            android:textColor="@color/black"
            android:textSize="16sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="5dp"
        android:gravity="center_horizontal"
        android:orientation="horizontal"
        android:weightSum="2" >

        <TextView
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Transaction ID"
            android:textColor="@color/black"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/tvTransaction"
            android:layout_width="dip"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="left"
            android:text="7634 5678 3456"
            android:textColor="@color/black"
            android:textSize="16sp" />
    </LinearLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp" >

        <TextView
            android:id="@+id/tvpaidresult"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:gravity="center_horizontal"
            android:text="@string/paidresult"
            android:textColor="#0000ff"
            android:textSize="16sp"
            android:textStyle="italic" />

        <Button
            android:id="@+id/btnback"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginTop="50dp"
            android:background="@color/theme_main_color"
            android:text="@string/Back"
            android:textColor="@color/white"
            android:textSize="20sp" />
    </RelativeLayout>

</LinearLayout>


text:
package prop

import (
	"github.com/guelfey/go.dbus"
	"github.com/guelfey/go.dbus/introspect"
	"sync"
)

// EmitType controls how org.freedesktop.DBus.Properties.PropertiesChanged is
// emitted for a property. If it is EmitTrue, the signal is emitted. If it is
// EmitInvalidates, the signal is also emitted, but the new value of the property
// is not disclosed.
type EmitType byte

const (
	EmitFalse EmitType = iota
	EmitTrue
	EmitInvalidates
)

// ErrIfaceNotFound is the error returned to peers who try to access properties
// on interfaces that aren't found.
var ErrIfaceNotFound = &dbus.Error{"org.freedesktop.DBus.Properties.Error.InterfaceNotFound", nil}

// ErrPropNotFound is the error returned to peers trying to access properties
// that aren't found.
var ErrPropNotFound = &dbus.Error{"org.freedesktop.DBus.Properties.Error.PropertyNotFound", nil}

// ErrReadOnly is the error returned to peers trying to set a read-only
// property.
var ErrReadOnly = &dbus.Error{"org.freedesktop.DBus.Properties.Error.ReadOnly", nil}

// ErrInvalidArg is returned to peers if the type of the property that is being
// changed and the argument don't match.
var ErrInvalidArg = &dbus.Error{"org.freedesktop.DBus.Properties.Error.InvalidArg", nil}

// The introspection data for the org.freedesktop.DBus.Properties interface.
var IntrospectData = introspect.Interface{
	Name: "org.freedesktop.DBus.Properties",
	Methods: []introspect.Method{
		{
			Name: "Get",
			Args: []introspect.Arg{
				{"interface", "s", "in"},
				{"property", "s", "in"},
				{"value", "v", "out"},
			},
		},
		{
			Name: "GetAll",
			Args: []introspect.Arg{
				{"interface", "s", "in"},
				{"props", "a{sv}", "out"},
			},
		},
		{
			Name: "Set",
			Args: []introspect.Arg{
				{"interface", "s", "in"},
				{"property", "s", "in"},
				{"value", "v", "in"},
			},
		},
	},
	Signals: []introspect.Signal{
		{
			Name: "PropertiesChanged",
			Args: []introspect.Arg{
				{"interface", "s", "out"},
				{"changed_properties", "a{sv}", "out"},
				{"invalidates_properties", "as", "out"},
			},
		},
	},
}

// The introspection data for the org.freedesktop.DBus.Properties interface, as
// a string.
const IntrospectDataString = `
	<interface name="org.freedesktop.DBus.Introspectable">
		<method name="Get">
			<arg name="interface" direction="in" type="s"/>
			<arg name="property" direction="in" type="s"/>
			<arg name="value" direction="out" type="v"/>
		</method>
		<method name="GetAll">
			<arg name="interface" direction="in" type="s"/>
			<arg name="props" direction="out" type="a{sv}"/>
		</method>
		<method name="Set">
			<arg name="interface" direction="in" type="s"/>
			<arg name="property" direction="in" type="s"/>
			<arg name="value" direction="in" type="v"/>
		</method>
		<signal name="PropertiesChanged">
			<arg name="interface" type="s"/>
			<arg name="changed_properties" type="a{sv}"/>
			<arg name="invalidates_properties" type="as"/>
		</signal>
	</interface>
`

// Prop represents a single property. It is used for creating a Properties
// value.
type Prop struct {
	// Initial value. Must be a DBus-representable type.
	Value interface{}

	// If true, the value can be modified by calls to Set.
	Writable bool

	// Controls how org.freedesktop.DBus.Properties.PropertiesChanged is
	// emitted if this property changes.
	Emit EmitType

	// If not nil, anytime this property is changed by Set, this function is
	// called with an appropiate Change as its argument. If the returned error
	// is not nil, it is sent back to the caller of Set and the property is not
	// changed.
	Callback func(*Change) *dbus.Error
}

// Change represents a change of a property by a call to Set.
type Change struct {
	Props *Properties
	Iface string
	Name  string
	Value interface{}
}

// Properties is a set of values that can be made available to the message bus
// using the org.freedesktop.DBus.Properties interface. It is safe for
// concurrent use by multiple goroutines.
type Properties struct {
	m    map[string]map[string]*Prop
	mut  sync.RWMutex
	conn *dbus.Conn
	path dbus.ObjectPath
}

// New returns a new Properties structure that manages the given properties.
// The key for the first-level map of props is the name of the interface; the
// second-level key is the name of the property. The returned structure will be
// exported as org.freedesktop.DBus.Properties on path.
func New(conn *dbus.Conn, path dbus.ObjectPath, props map[string]map[string]*Prop) *Properties {
	p := &Properties{m: props, conn: conn, path: path}
	conn.Export(p, path, "org.freedesktop.DBus.Properties")
	return p
}

// Get implements org.freedesktop.DBus.Properties.Get.
func (p *Properties) Get(iface, property string) (dbus.Variant, *dbus.Error) {
	p.mut.RLock()
	defer p.mut.RUnlock()
	m, ok := p.m[iface]
	if !ok {
		return dbus.Variant{}, ErrIfaceNotFound
	}
	prop, ok := m[property]
	if !ok {
		return dbus.Variant{}, ErrPropNotFound
	}
	return dbus.MakeVariant(prop.Value), nil
}

// GetAll implements org.freedesktop.DBus.Properties.GetAll.
func (p *Properties) GetAll(iface string) (map[string]dbus.Variant, *dbus.Error) {
	p.mut.RLock()
	defer p.mut.RUnlock()
	m, ok := p.m[iface]
	if !ok {
		return nil, ErrIfaceNotFound
	}
	rm := make(map[string]dbus.Variant, len(m))
	for k, v := range m {
		rm[k] = dbus.MakeVariant(v.Value)
	}
	return rm, nil
}

// GetMust returns the value of the given property and panics if either the
// interface or the property name are invalid.
func (p *Properties) GetMust(iface, property string) interface{} {
	p.mut.RLock()
	defer p.mut.RUnlock()
	return p.m[iface][property].Value
}

// Introspection returns the introspection data that represents the properties
// of iface.
func (p *Properties) Introspection(iface string) []introspect.Property {
	p.mut.RLock()
	defer p.mut.RUnlock()
	m := p.m[iface]
	s := make([]introspect.Property, 0, len(m))
	for k, v := range m {
		p := introspect.Property{Name: k, Type: dbus.SignatureOf(v.Value).String()}
		if v.Writable {
			p.Access = "readwrite"
		} else {
			p.Access = "read"
		}
		s = append(s, p)
	}
	return s
}

// set sets the given property and emits PropertyChanged if appropiate. p.mut
// must already be locked.
func (p *Properties) set(iface, property string, v interface{}) {
	prop := p.m[iface][property]
	prop.Value = v
	switch prop.Emit {
	case EmitFalse:
		// do nothing
	case EmitInvalidates:
		p.conn.Emit(p.path, "org.freedesktop.DBus.Properties.PropertiesChanged",
			iface, map[string]dbus.Variant{}, []string{property})
	case EmitTrue:
		p.conn.Emit(p.path, "org.freedesktop.DBus.Properties.PropertiesChanged",
			iface, map[string]dbus.Variant{property: dbus.MakeVariant(v)},
			[]string{})
	default:
		panic("invalid value for EmitType")
	}
}

// Set implements org.freedesktop.Properties.Set.
func (p *Properties) Set(iface, property string, newv dbus.Variant) *dbus.Error {
	p.mut.Lock()
	defer p.mut.Unlock()
	m, ok := p.m[iface]
	if !ok {
		return ErrIfaceNotFound
	}
	prop, ok := m[property]
	if !ok {
		return ErrPropNotFound
	}
	if !prop.Writable {
		return ErrReadOnly
	}
	if newv.Signature() != dbus.SignatureOf(prop.Value) {
		return ErrInvalidArg
	}
	if prop.Callback != nil {
		err := prop.Callback(&Change{p, iface, property, newv.Value()})
		if err != nil {
			return err
		}
	}
	p.set(iface, property, newv.Value())
	return nil
}

// SetMust sets the value of the given property and panics if the interface or
// the property name are invalid.
func (p *Properties) SetMust(iface, property string, v interface{}) {
	p.mut.Lock()
	p.set(iface, property, v)
	p.mut.Unlock()
}


text:
<?php
/**
 * Class for converting Mime Types to extensions
 * PHP Version 5.3
 * Based on work by http://www.freeformatter.com/mime-types-list.html#mime-types-list.
 *
 * @author   Richard Seymour <web@bespoke.support>
 * @license  MIT
 *
 * @link     https://github.com/BespokeSupport/Mime
 */

namespace BespokeSupport\Mime;

use DOMDocument;
use Exception;

/**
 * Class FileMimesGenerator.
 */
class FileMimesGenerator
{
    /**
     * @static
     *
     * @param \Composer\Script\Event $event
     */
    public static function composerGenerate($event = null)
    {
        if ($event) {
            $event->getIO()->write('Generating BespokeSupport\Mime\FileMimes class');
        }

        $file = __DIR__ . '/../resources/mimes.csv';

        self::fetch($file);

        self::generate($file);
    }

    /**
     * Convert HTML page to CSV then create Mime listings.
     *
     * @param $file
     */
    public static function fetch($file)
    {
        $url = 'http://www.freeformatter.com/mime-types-list.html';

        // no need to download again if csv present
        if (file_exists($file)) {
            return;
        }

        $filePointerCsv = fopen($file, 'wb');
        $fileHtml = \dirname(__FILE__, 2) . '/resources/mimes.html';

        if (!file_exists($fileHtml)) {
            $contents = file_get_contents($url);
            file_put_contents($fileHtml, $contents);
        } else {
            $contents = file_get_contents($fileHtml);
        }

        $contents = preg_replace('/(.*)<tbody>/is', '', $contents);

        $contents = preg_replace('/<\/tbody>.*/is', '', $contents);

        try {
            $xml = new DOMDocument();

            @$xml->loadHTML($contents);

            $trs = $xml->getElementsByTagName('tr');

            for ($i = 0; $i < $trs->length; $i++) {
                $tr = $trs->item($i);

                $tds = $tr->childNodes;

                $nodeName = $tds->item(0);
                $nodeMime = $tds->item(2);
                $nodeFile = $tds->item(4);

                $extText = ($nodeFile->textContent === 'N/A') ? null : str_replace('.', '', $nodeFile->textContent);

                $extensions = explode(',', $extText);

                $extension = \count($extensions) ? trim(array_pop($extensions)) : $extText;

                fputcsv($filePointerCsv,
                    [
                        $nodeMime->textContent,
                        $nodeName->textContent,
                        $extension,
                    ],
                    ',',
                    '"'
                );
            }
        } catch (Exception $e) {
        }

        fclose($filePointerCsv);
    }

    /**
     * Generate FileMimes class.
     *
     * @param $file
     */
    public static function generate($file)
    {
        $filePointer = fopen($file, 'rb');

        $names = '';
        $extensions = '';

        $header = true;
        while (($row = fgetcsv($filePointer))) {
            if ($header) {
                $header = false;
                continue;
            }

            $mime = trim($row[0]);
            $name = trim(addslashes($row[1]));
            $extension = trim($row[2]);

            $extensions .= "\t\t'$mime' => '$extension',\n";
            $names .= "\t\t'$mime' => '$name',\n";
        }

        $class = '';
        $class .= self::getHeader();
        $class .= self::getFunctions();
        $class .= self::getPropertyMimesHeader();
        $class .= $extensions;
        $class .= self::getPropertyMimesFooter();
        $class .= self::getPropertyNamesHeader();
        $class .= $names;
        $class .= self::getPropertyNamesFooter();
        $class .= self::getFooter();

        file_put_contents(__DIR__ . '/FileMimes.php', $class);
    }

    /**
     * @return string
     */
    private static function getHeader()
    {
        return <<< EOF
<?php
/**
 * Class for converting Mime Types to extensions
 * PHP Version 5.3
 * Based on work by http://www.freeformatter.com/mime-types-list.html#mime-types-list
 *
 * @author   Richard Seymour <web@bespoke.support>
 * @license  MIT
 * @link     https://github.com/BespokeSupport/Mime
 */

namespace BespokeSupport\Mime;

/**
 * Class FileMimes
 * @package BespokeSupport\Mime
 */
class FileMimes
{

EOF;
    }

    /**
     * @return string
     */
    private static function getFooter()
    {
        return <<< 'EOF'

}

EOF;
    }

    /**
     * @return string
     */
    private static function getPropertyMimesHeader()
    {
        return <<< 'EOF'

    /**
     * @var array
     */
    protected static $mimes = array(

EOF;
    }

    /**
     * @return string
     */
    private static function getPropertyMimesFooter()
    {
        return <<< 'EOF'
    );
EOF;
    }

    /**
     * @return string
     */
    private static function getPropertyNamesHeader()
    {
        return <<< 'EOF'

    /**
     * @var array
     */
    protected static $names = array(

EOF;
    }

    /**
     * @return string
     */
    private static function getPropertyNamesFooter()
    {
        return <<< 'EOF'
    );
EOF;
    }

    /**
     * @return string
     */
    private static function getFunctions()
    {
        return <<< 'EOB'
    /**
     * @param $file
     * @return string
     */
    public static function read($file)
    {
        $path = (string)$file;

        if (!is_file($path) || !is_readable($path)) {
            return null;
        }

        $fInfoClass = new \finfo(FILEINFO_MIME_TYPE | FILEINFO_PRESERVE_ATIME);

        return $fInfoClass->buffer(file_get_contents((string)$file));
    }

    /**
     * @return string
     */
    public static function extension($file)
    {
        $spl = new \SplFileInfo($file);
        return $spl->isFile() ? $spl->getExtension() : null;
    }

    /**
     * @param null|string $mime
     * @return string
     */
    public static function getExtensionFromMime($mime = null)
    {
        if ($mime && array_key_exists($mime, self::$mimes)) {
            return self::$mimes[$mime];
        }

        return '';
    }

    /**
     * @param null $mime
     * @return string
     */
    public static function getNameFromMime($mime = null)
    {
        if ($mime && array_key_exists($mime, self::$names)) {
            return self::$names[$mime];
        }

        return '';
    }

    /**
     * @param null $extension
     * @return string|null
     */
    public static function getMimeFromExtension($extension = null)
    {
        if ($extension && ($extension = array_search($extension, self::$mimes))) {
            return $extension;
        }
        return null;
    }

    /**
     * @return array
     */
    public static function getMimes()
    {
        return self::$mimes;
    }

    /**
     * @return array
     */
    public static function getMimeNames()
    {
        return self::$names;
    }
EOB;
    }
}


text:
package org.springframework.http.converter.json;

import java.net.URI;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;

import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;

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

/**
 * Tests for serializing a {@link org.springframework.http.ProblemDetail} through
 * the Jackson library.
 *
 * @author Rossen Stoyanchev
 * @since 6.0
 */
public class ProblemDetailJacksonMixinTests {

	private final ObjectMapper mapper = new Jackson2ObjectMapperBuilder().build();

	@Test
	void writeStatusAndHeaders() throws Exception {
		testWrite(
				ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Missing header"),
				"{\"type\":\"about:blank\"," +
						"\"title\":\"Bad Request\"," +
						"\"status\":400," +
						"\"detail\":\"Missing header\"}");
	}

	@Test
	void writeCustomProperty() throws Exception {
		ProblemDetail problemDetail = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Missing header");
		problemDetail.setProperty("host", "abc.org");

		testWrite(problemDetail,
				"{\"type\":\"about:blank\"," +
						"\"title\":\"Bad Request\"," +
						"\"status\":400," +
						"\"detail\":\"Missing header\"," +
						"\"host\":\"abc.org\"}");
	}

	@Test
	void readCustomProperty() throws Exception {
		ProblemDetail problemDetail = this.mapper.readValue(
				"{\"type\":\"about:blank\"," +
						"\"title\":\"Bad Request\"," +
						"\"status\":400," +
						"\"detail\":\"Missing header\"," +
						"\"host\":\"abc.org\"}", ProblemDetail.class);

		assertThat(problemDetail.getType()).isEqualTo(URI.create("about:blank"));
		assertThat(problemDetail.getTitle()).isEqualTo("Bad Request");
		assertThat(problemDetail.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
		assertThat(problemDetail.getDetail()).isEqualTo("Missing header");
		assertThat(problemDetail.getProperties()).containsEntry("host", "abc.org");
	}

	private void testWrite(ProblemDetail problemDetail, String expected) throws Exception {
		String output = this.mapper.writeValueAsString(problemDetail);
		assertThat(output).isEqualTo(expected);
	}

}


text:
\hypertarget{_tcp_a_s_i_o_server_8hh}{\section{include/mognetwork/\-Tcp\-A\-S\-I\-O\-Server.hh File Reference}
\label{_tcp_a_s_i_o_server_8hh}\index{include/mognetwork/\-Tcp\-A\-S\-I\-O\-Server.\-hh@{include/mognetwork/\-Tcp\-A\-S\-I\-O\-Server.\-hh}}
}

Gère les threads d'écriture et de lecture.

{\ttfamily \#include $<$list$>$}\\*
{\ttfamily \#include \char`\"{}Tcp\-Server\-Socket.\-hh\char`\"{}}\\*
{\ttfamily \#include \char`\"{}Tcp\-A\-S\-I\-O\-Listener.\-hh\char`\"{}}\\*
{\ttfamily \#include \char`\"{}Tcp\-A\-S\-I\-O\-Writer.\-hh\char`\"{}}\\*
{\ttfamily \#include \char`\"{}I\-Protocol\-Factory.\-hh\char`\"{}}\\*
\subsection*{Classes}
\begin{DoxyCompactItemize}
\item
class \hyperlink{classmognetwork_1_1_tcp_a_s_i_o_server}{mognetwork\-::\-Tcp\-A\-S\-I\-O\-Server}
\begin{DoxyCompactList}\small\item\em Used to create a A\-S\-I\-O Server simply. \end{DoxyCompactList}\end{DoxyCompactItemize}
\subsection*{Namespaces}
\begin{DoxyCompactItemize}
\item
\hyperlink{namespacemognetwork}{mognetwork}
\end{DoxyCompactItemize}

\subsection{Detailed Description}
Gère les threads d'écriture et de lecture. \begin{DoxyAuthor}{Author}
Alex\-Mog
\end{DoxyAuthor}
\begin{DoxyVersion}{Version}
0.\-1
\end{DoxyVersion}


text:
#Data Lab: Manipulating Bits

##Introduction
The purpose of this assignment is to become more familiar with bit-level representations of integers (and floating point) numbers. You'll do this by solving a series of programming "puzzles." Many of these puzzles are quite artificial, but you'll find yourself thinking much more about bits in working your way through them.

##Logistics
All hand-ins are electronic. Clarifications and corrections will be posted on the course Piazza page. Grading will be done through electronic submission.

##Handout Instructions
Start by copying *datalab-handout.tar.gz* to a (protected) directory on a Linux machine in which you plan to do your work. We recommend the desktop or home directory of your virtual machine. Then give the command:

	unix> tar xvf datalab-handout.tar.gz

This will cause a number of files to be unpacked in the directory.  The only file you will be modifying and turning in is *bits.c*.

The *bits.c* file contains a skeleton for each of the programming puzzles. Your assignment is to complete each function skeleton using only *straightline* (no if/while/etc) code for the integer puzzles (i.e., no loops or conditionals) and a limited number of C arithmetic and logical operators. Specifically, you are *only* allowed to use the following eight operators:

	!  ̃ & ˆ | + << >>

A few of the functions further restrict this list.  Also, you are not allowed to use any constants longer than 8 bits,  but you can construct larger constants using 8 bit constants and operators.   See the comments in *bits.c* for detailed rules and a discussion of the desired coding style.

##The Puzzles

This section describes the puzzles that you will be solving in *bits.c*. Some of the puzzle are *bit manipulations* (treating the data as a vector of bits), some are focused on *two's complement artihmetic*, teaching bits as numbers. There are some extra credit problems that treat the bits as floating point numbers.

Each problem has a *Difficulty Rating* and *maximum number of operations*. The "Rating" field gives the difficulty rating (the number of points) for the puzzle, and the "Max ops" field gives the maximum number of operators you are allowed to use to implement each function.  See the comments in *bits.c* for more details on the desired behavior of the functions – each one describes the intended semantics, the rating and the allowed number of operations. You may also refer to the test functions in *tests.c*. These are used as reference functions to express the correct behavior of your functions, although they don't satisfy the coding rules for your functions.

### Floating-Point Operations
For Extra Credit, you can implement some common single-precision floating-point operations. In this section, you are allowed to use standard control structures (conditionals, loops), and you may use both *int* and *unsigned* data types, including arbitrary unsigned and integer constants. You may not use any unions, structs, or arrays. Most significantly, you may not use any floating point data types, operations, or constants. Instead, any floating-point operand will be passed to the function as having type *unsigned*, and any returned floating-point value will be of type *unsigned*. Your code should perform the bit manipulations that implement the specified floating point operations.

Table 1 describes a set of functions that operate on the bit-level representations of floating-point numbers. Refer to the comments in *bits.c* and the reference versions in *tests.c* for more information.

| Name | Description | Rating | Max Ops|
|:-----|:------------|--------|--------|
|float_abs(uf) | Compute \|f\| | 2 | 10 |
|float_half(uf)| Computer f/2 | 4 | 30 |

Table 1: Floating-Point Functions. Value *f* is the floating-point number having the same bit representation as the unsigned integer *uf*.

Functions *float_abs* and *float_half* must handle the full range of possible argument values, including not-a-number (NaN) and infinity. The IEEE standard does not specify precisely how to handle NaN's, and the IA32 behavior is a bit obscure. We will follow a convention that for any function returning a NaN value, it will return the one with bit representation 0x7FC00000.

The included program *fshow* helps you understand the structure of floating point numbers.  To compile *fshow*, switch to the handout directory and type:

	unix> make

You can use *fshow* to see what an arbitrary pattern represents as a floating-point number:

	unix> ./fshow 2080374784

	Floating point value 2.658455992e+36
	Bit Representation 0x7c000000, sign = 0, exponent = f8, fraction = 000000
	Normalized.  1.0000000000 X 2ˆ(121)

You can also give *fshow* hexadecimal and floating point values, and it will decipher their bit structure.

##Evaluation
This section only includes evaluation for the standard section, not the extra credit.

The assignment is scored in two parts - you will receive 60 percent of the overall score for having correctly functioning functions handed in on time and 40 percent for being able to correctly answer questions about how your functions work either in a grading interview or in class questions. If the interview grading isn't used 100 percent of your grade will come from the correctness of your assignment.

Your correctness score will be computed out of a maximum of 62 points based on the following distribution:

**34 of 62 points** Correctness points (correct output)

**28 of 62 points** Performance points (not exceeding the maximum operations)

*Correctness points.* The 14 puzzles you must solve have been given a difficulty rating between 1 and 4, such that their weighted sum totals to 34.  We will evaluate your functions using the *btest* program, which is described in the next section. You will get full credit for a puzzle if it passes all of the tests performed by *btest*, and no credit otherwise.

*Performance points.* Our main concern at this point in the course is that you can get the right answer. However, we want to instill in you a sense of keeping things as short and simple as you can.  Furthermore, some of the puzzles can be solved by brute force, but we want you to be more clever. Thus, for each function we've established a maximum number of operators that you are allowed to use for each function. This limit is very generous and is designed only to catch egregiously inefficient solutions. You will receive two points for each correct function that satisfies the operator limit.

###Extra Credit
You can receive up to 10% extra credit for this assignment by completing all of the floating point problems. If you are unfamiliar with IEEE floating point encoding you'll need to read the sections of the book on it as I won't be covering it in lecture on the assumption you learned it in a previous course.

###Autograding your work
We have included some autograding tools in the handout directory — *btest*, *dlc*, and *driver.pl* — to help you check the correctness of your work.

Note that the autograding script produces a report about 'points' – this doesn't align with what we've described above (which is what holds). This happens in part because of the presence of the extra problems.

* **btest:** This program checks the functional correctness of the functions in *bits.c*.  To build and use it, type the following two commands:

	unix> make
	unix> ./btest

	* Notice that you must rebuild *btest* each time you modify your *bits.c* file.
	* You'll find it helpful to work through the functions one at a time, testing each one as you go. You can use the *-f* flag to instruct *btest* to test only a single function:

			unix> ./btest -f bitAnd

	* You can feed it specific function arguments using the option flags *-1*, *-2*, and *-3*:

			unix> ./btest -f bitAnd -1 7 -2 0xf

	* Check the file *README* for documentation on running the *btest* program.

* **dlc:** This is a modified version of an ANSI C compiler from the MIT CILK group that you can use to check for compliance with the coding rules for each puzzle. The typical usage is:

	unix> ./dlc bits.c

	* The program runs silently unless it detects a problem, such as an illegal operator, too many operators, or non-straightline code in the integer puzzles. Running with the *-e* switch:

		unix> ./dlc -e bits.c

	* causes *dlc* to print counts of the number of operators used by each function. Type *./dlc -help* for a list of command line options.

* **driver.pl:** This is a driver program that uses *btest* and *dlc* to compute the correctness and performance points for your solution. It takes no arguments:

	unix> ./driver.pl

	* Your instructors will use *driver.pl* to evaluate your solution.
	* The default *driver.pl* script uses simple tests to check if your code is likely correct. A more comprehensive test is to involve *driver.pl -b*, which will use a **BDD** library to *prove* that your code handles all cases.  This is what the I'll likely use for grading, but this can be more time consuming. You should be fine just using *driver.pl* without the *-b* flag for testing.

##  Handin Instructions
Upload your *bits.c* file to Turnin by the due date. You can upload your file multiple times, and we encourage you upload often so you don't run into problems at the last minute or lose your work.

##Advice
* Don't include the *<stdio.h>* header file in your *bits.c* file, as it confuses *dlc* and results in some non-intuitive error messages.  You will still be able to use *printf* in your *bits.c* file for debugging without including the *<stdio.h>* header, although *gcc* will print a warning that you can ignore.

* The *dlc* program enforces a stricter form of C declarations than is the case for C++ or that is enforced by *gcc*. In particular, any declaration must appear in a block (what you enclose in curly braces) before any statement that is not a declaration. For example, it will complain about the following code:

	int foo(int x)
	    {
	      int a = x;
	      a *= 3;     /* Statement that is not a declaration */
	      int b = a;  /* ERROR: Declaration not allowed here */
	      b *= a;     // ERROR -- this comment style causes errors
	}

##The "Beat the Prof" Contest
For fun, we're offering an optional "Beat the Prof" contest that allows you to compete with other students and the instructor to develop the most efficient puzzles. The goal is to solve each Data Lab puzzle using the fewest number of operators. Students who match or beat the instructor's operator count for each puzzle are winners!

To submit your entry to the contest, type:

	unix> ./driver.pl -u ''Your Nickname''

Nicknames are limited to 35 characters and can contain  alphanumerics, apostrophes, commas, periods, dashes, underscores, and ampersands. Nicknames should not be offensive or crude. You can submit as often as you like. Your most recent submission will appear on a real-time scoreboard, identified only by your nickname. You can view the scoreboard by pointing your browser at:

http://bryancdixon.com:8080


text:
package org.springframework.boot.web.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Pattern;

import org.apache.catalina.startup.Tomcat;
import org.junit.jupiter.api.Test;

import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.predicate.RuntimeHintsPredicates;
import org.springframework.boot.web.server.MimeMappings.DefaultMimeMappings;
import org.springframework.boot.web.server.MimeMappings.Mapping;
import org.springframework.boot.web.server.MimeMappings.MimeMappingsRuntimeHints;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.test.util.ReflectionTestUtils;

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

/**
 * Tests for {@link MimeMappings}.
 *
 * @author Phillip Webb
 * @author Guirong Hu
 */
class MimeMappingsTests {

	@Test
	void defaultsCannotBeModified() {
		assertThatExceptionOfType(UnsupportedOperationException.class)
				.isThrownBy(() -> MimeMappings.DEFAULT.add("foo", "foo/bar"));
	}

	@Test
	void createFromExisting() {
		MimeMappings mappings = new MimeMappings();
		mappings.add("foo", "bar");
		MimeMappings clone = new MimeMappings(mappings);
		mappings.add("baz", "bar");
		assertThat(clone.get("foo")).isEqualTo("bar");
		assertThat(clone.get("baz")).isNull();
	}

	@Test
	void createFromMap() {
		Map<String, String> mappings = new HashMap<>();
		mappings.put("foo", "bar");
		MimeMappings clone = new MimeMappings(mappings);
		mappings.put("baz", "bar");
		assertThat(clone.get("foo")).isEqualTo("bar");
		assertThat(clone.get("baz")).isNull();
	}

	@Test
	void iterate() {
		MimeMappings mappings = new MimeMappings();
		mappings.add("foo", "bar");
		mappings.add("baz", "boo");
		List<MimeMappings.Mapping> mappingList = new ArrayList<>();
		for (MimeMappings.Mapping mapping : mappings) {
			mappingList.add(mapping);
		}
		assertThat(mappingList.get(0).getExtension()).isEqualTo("foo");
		assertThat(mappingList.get(0).getMimeType()).isEqualTo("bar");
		assertThat(mappingList.get(1).getExtension()).isEqualTo("baz");
		assertThat(mappingList.get(1).getMimeType()).isEqualTo("boo");
	}

	@Test
	void getAll() {
		MimeMappings mappings = new MimeMappings();
		mappings.add("foo", "bar");
		mappings.add("baz", "boo");
		List<MimeMappings.Mapping> mappingList = new ArrayList<>(mappings.getAll());
		assertThat(mappingList.get(0).getExtension()).isEqualTo("foo");
		assertThat(mappingList.get(0).getMimeType()).isEqualTo("bar");
		assertThat(mappingList.get(1).getExtension()).isEqualTo("baz");
		assertThat(mappingList.get(1).getMimeType()).isEqualTo("boo");
	}

	@Test
	void addNew() {
		MimeMappings mappings = new MimeMappings();
		assertThat(mappings.add("foo", "bar")).isNull();
	}

	@Test
	void addReplacesExisting() {
		MimeMappings mappings = new MimeMappings();
		mappings.add("foo", "bar");
		assertThat(mappings.add("foo", "baz")).isEqualTo("bar");
	}

	@Test
	void remove() {
		MimeMappings mappings = new MimeMappings();
		mappings.add("foo", "bar");
		assertThat(mappings.remove("foo")).isEqualTo("bar");
		assertThat(mappings.remove("foo")).isNull();
	}

	@Test
	void get() {
		MimeMappings mappings = new MimeMappings();
		mappings.add("foo", "bar");
		assertThat(mappings.get("foo")).isEqualTo("bar");
	}

	@Test
	void getMissing() {
		MimeMappings mappings = new MimeMappings();
		assertThat(mappings.get("foo")).isNull();
	}

	@Test
	void makeUnmodifiable() {
		MimeMappings mappings = new MimeMappings();
		mappings.add("foo", "bar");
		MimeMappings unmodifiable = MimeMappings.unmodifiableMappings(mappings);
		try {
			unmodifiable.remove("foo");
		}
		catch (UnsupportedOperationException ex) {
			// Expected
		}
		mappings.remove("foo");
		assertThat(unmodifiable.get("foo")).isNull();
	}

	@Test
	void mimeTypesInDefaultMappingsAreCorrectlyStructured() {
		String regName = "[A-Za-z0-9!#$&.+\\-^_]{1,127}";
		Pattern pattern = Pattern.compile("^" + regName + "\\/" + regName + "$");
		assertThat(MimeMappings.DEFAULT).allSatisfy((mapping) -> assertThat(mapping.getMimeType()).matches(pattern));
	}

	@Test
	void getCommonTypeOnDefaultMimeMappingsDoesNotLoadMappings() {
		DefaultMimeMappings mappings = new DefaultMimeMappings();
		assertThat(mappings.get("json")).isEqualTo("application/json");
		assertThat((Object) mappings).extracting("loaded").isNull();
	}

	@Test
	void getExoticTypeOnDefaultMimeMappingsLoadsMappings() {
		DefaultMimeMappings mappings = new DefaultMimeMappings();
		assertThat(mappings.get("123")).isEqualTo("application/vnd.lotus-1-2-3");
		assertThat((Object) mappings).extracting("loaded").isNotNull();
	}

	@Test
	void iterateOnDefaultMimeMappingsLoadsMappings() {
		DefaultMimeMappings mappings = new DefaultMimeMappings();
		assertThat(mappings).isNotEmpty();
		assertThat((Object) mappings).extracting("loaded").isNotNull();
	}

	@Test
	void commonMappingsAreSubsetOfAllMappings() {
		MimeMappings defaultMappings = new DefaultMimeMappings();
		MimeMappings commonMappings = (MimeMappings) ReflectionTestUtils.getField(DefaultMimeMappings.class, "COMMON");
		defaultMappings.getAll();
		for (Mapping commonMapping : commonMappings) {
			assertThat(defaultMappings.get(commonMapping.getExtension())).isEqualTo(commonMapping.getMimeType());
		}
	}

	@Test
	void lazyCopyWhenNotMutatedDelegates() {
		DefaultMimeMappings mappings = new DefaultMimeMappings();
		MimeMappings lazyCopy = MimeMappings.lazyCopy(mappings);
		assertThat(lazyCopy.get("json")).isEqualTo("application/json");
		assertThat((Object) mappings).extracting("loaded").isNull();
	}

	@Test
	void lazyCopyWhenMutatedCreatesCopy() {
		DefaultMimeMappings mappings = new DefaultMimeMappings();
		MimeMappings lazyCopy = MimeMappings.lazyCopy(mappings);
		lazyCopy.add("json", "other/json");
		assertThat(lazyCopy.get("json")).isEqualTo("other/json");
		assertThat((Object) mappings).extracting("loaded").isNotNull();
	}

	@Test
	void lazyCopyWhenMutatedCreatesCopyOnlyOnce() {
		MimeMappings mappings = new MimeMappings();
		mappings.add("json", "one/json");
		MimeMappings lazyCopy = MimeMappings.lazyCopy(mappings);
		assertThat(lazyCopy.get("json")).isEqualTo("one/json");
		mappings.add("json", "two/json");
		lazyCopy.add("json", "other/json");
		assertThat(lazyCopy.get("json")).isEqualTo("other/json");
	}

	@Test
	void mimeMappingsMatchesTomcatDefaults() throws IOException {
		Properties ourDefaultMimeMappings = PropertiesLoaderUtils
				.loadProperties(new ClassPathResource("mime-mappings.properties", getClass()));
		Properties tomcatDefaultMimeMappings = PropertiesLoaderUtils
				.loadProperties(new ClassPathResource("MimeTypeMappings.properties", Tomcat.class));
		assertThat(ourDefaultMimeMappings).isEqualTo(tomcatDefaultMimeMappings);
	}

	@Test
	void shouldRegisterHints() {
		RuntimeHints runtimeHints = new RuntimeHints();
		new MimeMappingsRuntimeHints().registerHints(runtimeHints, getClass().getClassLoader());
		assertThat(RuntimeHintsPredicates.resource()
				.forResource("org/springframework/boot/web/server/mime-mappings.properties")).accepts(runtimeHints);
	}

}


text:
package com.tle.web.wizard.standard.controls;

import com.google.common.collect.Lists;
import com.tle.common.Pair;
import com.tle.core.guice.Bind;
import com.tle.core.wizard.controls.HTMLControl;
import com.tle.core.wizard.controls.WizardPage;
import com.tle.web.sections.SectionInfo;
import com.tle.web.sections.SectionResult;
import com.tle.web.sections.SectionTree;
import com.tle.web.sections.ajax.*;
import com.tle.web.sections.ajax.handler.AjaxFactory;
import com.tle.web.sections.ajax.handler.AjaxMethod;
import com.tle.web.sections.equella.annotation.PlugKey;
import com.tle.web.sections.equella.annotation.PlugURL;
import com.tle.web.sections.equella.annotation.PluginResourceHandler;
import com.tle.web.sections.events.BookmarkEvent;
import com.tle.web.sections.events.RenderContext;
import com.tle.web.sections.events.RenderEventContext;
import com.tle.web.sections.jquery.JQueryStatement;
import com.tle.web.sections.jquery.libraries.effects.JQueryUIEffects;
import com.tle.web.sections.js.ElementId;
import com.tle.web.sections.js.JSExpression;
import com.tle.web.sections.js.generic.AppendedElementId;
import com.tle.web.sections.js.generic.expression.*;
import com.tle.web.sections.js.generic.function.ExternallyDefinedFunction;
import com.tle.web.sections.js.generic.function.IncludeFile;
import com.tle.web.sections.render.Label;
import com.tle.web.sections.result.util.IconLabel;
import com.tle.web.sections.result.util.IconLabel.Icon;
import com.tle.web.sections.standard.Link;
import com.tle.web.sections.standard.annotations.Component;
import com.tle.web.sections.standard.model.HtmlLinkState;
import com.tle.web.sections.standard.renderers.LinkRenderer;
import com.tle.web.wizard.WizardJSLibrary;
import com.tle.web.wizard.controls.CRepeater;
import com.tle.web.wizard.controls.GroupsCtrl.ControlGroup;
import com.tle.web.wizard.controls.WebControl;
import com.tle.web.wizard.controls.WebControlModel;
import com.tle.web.wizard.page.ControlResult;
import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("nls")
@Bind
public class Repeater extends GroupWebControl<Repeater.RepeaterModel> {
  private static final String CLASS_REMOVE = "repeater-remove";
  private static final String CLASS_MOVE = "repeater-move";
  private static final String CLASS_MOVE_UP = "move-up";
  private static final String CLASS_MOVE_DOWN = "move-down";

  static {
    PluginResourceHandler.init(Repeater.class);
  }

  @AjaxFactory private AjaxGenerator ajax;

  @PlugURL("js/repeater.js")
  private static String URL_REPEATERJS;

  @PlugKey("repeater.confirmremove")
  private static Label CONFIRM_REMOVE;

  private static final IncludeFile INCJS =
      new IncludeFile(URL_REPEATERJS, WizardJSLibrary.INCLUDE, JQueryUIEffects.SLIDE);
  private static ExternallyDefinedFunction REPEATER =
      new ExternallyDefinedFunction("repeater", INCJS);

  @Component private Link addButton;
  @Component private Link addTopButton;

  private CRepeater crepeater;
  private String addedDivId;

  @Override
  public void setWrappedControl(HTMLControl control) {
    crepeater = (CRepeater) control;
    super.setWrappedControl(control);
  }

  @Override
  public void registered(String id, SectionTree tree) {
    super.registered(id, tree);
    // @formatter:off
    addButton.addReadyStatements(
        new JQueryStatement(
            this,
            new FunctionCallExpression(
                REPEATER,
                new ObjectExpression(
                    "addAjax",
                    ajax.getAjaxFunction("addAjax"),
                    "addButton",
                    addButton,
                    "addTopButton",
                    addTopButton,
                    "disablers",
                    new ArrayExpression(
                        addButton.createDisableFunction(), addTopButton.createDisableFunction()),
                    "removeAjax",
                    ajax.getAjaxFunction("removeAjax"),
                    "swapIndexAjax",
                    ajax.getAjaxFunction("swapIndexAjax"),
                    "confirmRemoveMessage",
                    new RuntimeExpression() {
                      @Override
                      protected JSExpression createExpression(RenderContext info) {
                        return new StringExpression(CONFIRM_REMOVE.getText());
                      }
                    }))));
    // @formatter:on
    addedDivId = getSectionId() + "_groups";
  }

  @AjaxMethod
  public JSONResponseCallback addAjax(AjaxRenderContext context, boolean top) {
    getModel(context).setRenderMeOnly(true);
    final int numGroups = crepeater.getGroups().size();
    final String ajaxId = (top ? addedDivId : getSectionId() + "_gajax_" + numGroups);
    context.addAjaxDivs(ajaxId);
    context.setModalId(getSectionId());
    context.setFormBookmarkEvent(new BookmarkEvent(this, true, context));
    add(context, (top ? 0 : numGroups));
    return new JSONResponseCallback() {
      @Override
      public Object getResponseObject(AjaxRenderContext context) {
        return new RepeaterUpdate(context, context.getFullDOMResult(), ajaxId);
      }
    };
  }

  @AjaxMethod
  public JSONResponseCallback removeAjax(AjaxRenderContext context, int index) {
    getModel(context).setRenderMeOnly(true);
    context.addAjaxDivs(addedDivId);
    context.setModalId(getSectionId());
    context.setFormBookmarkEvent(new BookmarkEvent(this, true, context));
    remove(context, index);
    return new JSONResponseCallback() {
      @Override
      public Object getResponseObject(AjaxRenderContext context) {
        return new RepeaterUpdate(context, context.getFullDOMResult(), addedDivId);
      }
    };
  }

  @AjaxMethod
  public JSONResponseCallback swapIndexAjax(AjaxRenderContext context, int oldIndex, int newIndex) {
    getModel(context).setRenderMeOnly(true);
    context.addAjaxDivs(addedDivId);
    context.setModalId(getSectionId());
    swapIndex(oldIndex, newIndex);
    doEdits(context); // helps with the path overrides
    return new JSONResponseCallback() {
      @Override
      public Object getResponseObject(AjaxRenderContext context) {
        return new RepeaterUpdate(context, context.getFullDOMResult(), addedDivId);
      }
    };
  }

  @Override
  public void doEdits(SectionInfo info) {
    crepeater.setEmpty(false);

    // Check if we are removing a group.
    List<List<WebControl>> webGroups = getWebGroups();
    int size = webGroups.size();
    for (int i = size - 1; i >= 0; i--) {
      // path overrides for advanced script control
      final WizardPage wizardPage = crepeater.getWizardPage();
      wizardPage.pushPathOverride(crepeater, crepeater.getFirstTarget().getTarget(), i);

      List<WebControl> vGroup = webGroups.get(i);
      processGroup(vGroup, info);
      wizardPage.popPathOverride(crepeater);
    }
  }

  @Override
  public SectionResult renderHtml(RenderEventContext context) throws Exception {
    final RepeaterModel model = getModel(context);
    final List<RepeaterRenderedGroup> renderedGroups = new ArrayList<RepeaterRenderedGroup>();
    final List<List<WebControl>> groups = getWebGroups();

    // path overrides for advanced script control (freemarker)
    // push overrides for parent repeaters if this control is the only one
    // being rendered
    final WizardPage wizardPage = crepeater.getWizardPage();
    List<Pair<CRepeater, Integer>> parentChain =
        (model.isRenderMeOnly() ? pushParentOverrides(wizardPage) : null);

    int index = 0;
    for (List<WebControl> controls : groups) {
      wizardPage.pushPathOverride(crepeater, crepeater.getFirstTarget().getTarget(), index);

      List<ControlResult> results =
          getWebWizardPage().renderChildren(context, controls, getSectionId() + "_" + index);

      HtmlLinkState removeLink =
          new HtmlLinkState().addClass(getSectionId() + CLASS_REMOVE).addClass(CLASS_REMOVE);
      removeLink.setElementId(new AppendedElementId(this, "index" + index));
      removeLink.setDisablable(true);
      removeLink.addReadyStatements(
          new JQueryStatement(
              removeLink, new FunctionCallExpression("data", "repeater.index", index)));

      RepeaterRenderedGroup group = new RepeaterRenderedGroup(results);
      LinkRenderer remove = new LinkRenderer(removeLink);
      addDisabler(context, remove);
      group.setDeleteButton(remove);

      HtmlLinkState moveDown =
          new HtmlLinkState().addClass(CLASS_MOVE).addClass(getSectionId() + CLASS_MOVE_DOWN);
      moveDown.setElementId(new AppendedElementId(this, "moveDownIndex" + index));
      moveDown.setLabel(new IconLabel(Icon.DOWN, null));
      moveDown.setDisablable(true);
      moveDown.addReadyStatements(
          new JQueryStatement(
              moveDown, new FunctionCallExpression("data", "repeater.index", index)));

      LinkRenderer moveDownLink = new LinkRenderer(moveDown);
      addDisabler(context, moveDownLink);
      group.setMoveDownButton(moveDownLink);

      HtmlLinkState moveUp =
          new HtmlLinkState().addClass(CLASS_MOVE).addClass(getSectionId() + CLASS_MOVE_UP);
      moveUp.setElementId(new AppendedElementId(this, "moveUpIndex" + index));
      moveUp.setDisablable(true);
      moveUp.setLabel(new IconLabel(Icon.UP, null));
      moveUp.addReadyStatements(
          new JQueryStatement(moveUp, new FunctionCallExpression("data", "repeater.index", index)));

      LinkRenderer moveUpLink = new LinkRenderer(moveUp);
      addDisabler(context, moveUpLink);
      group.setMoveUpButton(moveUpLink);

      renderedGroups.add(group);

      wizardPage.popPathOverride(crepeater);
      index++;
    }
    popParentOverrides(wizardPage, parentChain);

    model.setRenderedGroups(renderedGroups);
    boolean disabled = (groups.size() >= crepeater.getMax());
    addButton.setDisabled(context, disabled);
    addTopButton.setDisabled(context, disabled);
    addDisablers(context, addButton, addTopButton);
    addDisableablesForControls(context);
    return viewFactory.createResult("repeater/repeater.ftl", context);
  }

  /**
   * @param wizardPage
   * @return A list of parents with the index of where the control sits within the parent
   */
  private List<Pair<CRepeater, Integer>> pushParentOverrides(WizardPage wizardPage) {
    final List<Pair<CRepeater, Integer>> parentChain = Lists.newArrayList();
    HTMLControl parent = crepeater.getParent();
    HTMLControl child = crepeater;
    while (parent != null) {
      if (parent instanceof CRepeater) // it will be
      {
        parentChain.add(
            new Pair<CRepeater, Integer>((CRepeater) parent, indexOf(((CRepeater) parent), child)));
      }

      child = parent;
      parent = parent.getParent();
    }

    if (parentChain.size() > 0) {
      for (int i = parentChain.size() - 1; i >= 0; i--) {
        Pair<CRepeater, Integer> rep = parentChain.get(i);
        CRepeater repeater2 = rep.getFirst();
        wizardPage.pushPathOverride(
            repeater2, repeater2.getFirstTarget().getTarget(), rep.getSecond());
      }
    }
    return parentChain;
  }

  /**
   * @param parent
   * @param child
   * @return The index of the group that this child is found in.
   */
  private int indexOf(CRepeater parent, HTMLControl child) {
    for (ControlGroup group : parent.getGroups()) {
      if (group.contains(child)) {
        return group.getIndex();
      }
    }
    throw new Error("Child not found in parent!");
  }

  private void popParentOverrides(
      WizardPage wizardPage, List<Pair<CRepeater, Integer>> parentChain) {
    if (parentChain != null) {
      for (int i = 0; i < parentChain.size(); i++) {
        Pair<CRepeater, Integer> rep = parentChain.get(i);
        CRepeater repeater = rep.getFirst();
        wizardPage.popPathOverride(repeater);
      }
    }
  }

  private void add(SectionInfo info, int index) {
    crepeater.addAndEvaluate(index);
    getWebWizardPage().ensureTreeAdded(info, false);
  }

  public void remove(SectionInfo info, int index) {
    crepeater.removeGroup(info, index);
  }

  public void swapIndex(int oldIndex, int newIndex) {
    if (newIndex < crepeater.getGroups().size() && newIndex >= 0) {
      crepeater.swapGroups(oldIndex, newIndex);
      // web groups
      List<List<WebControl>> webGroups = getWebGroups();
      List<WebControl> movingWeb = webGroups.get(oldIndex);
      webGroups.set(oldIndex, webGroups.get(newIndex));
      webGroups.set(newIndex, movingWeb);
    }
  }

  @Override
  public Class<RepeaterModel> getModelClass() {
    return RepeaterModel.class;
  }

  public static class RepeaterModel extends WebControlModel {
    private List<RepeaterRenderedGroup> renderedGroups;
    private boolean renderMeOnly;

    public List<RepeaterRenderedGroup> getRenderedGroups() {
      return renderedGroups;
    }

    public void setRenderedGroups(List<RepeaterRenderedGroup> renderedGroups) {
      this.renderedGroups = renderedGroups;
    }

    public boolean isRenderMeOnly() {
      return renderMeOnly;
    }

    public void setRenderMeOnly(boolean renderMeOnly) {
      this.renderMeOnly = renderMeOnly;
    }
  }

  public static class RepeaterRenderedGroup extends RenderedGroup {
    private LinkRenderer deleteButton;
    private LinkRenderer moveDownButton;
    private LinkRenderer moveUpButton;

    public RepeaterRenderedGroup(List<ControlResult> results) {
      super(results);
    }

    public void setMoveUpButton(LinkRenderer moveUp) {
      this.moveUpButton = moveUp;
    }

    public LinkRenderer getMoveUpButton() {
      return moveUpButton;
    }

    public void setMoveDownButton(LinkRenderer moveDown) {
      this.moveDownButton = moveDown;
    }

    public LinkRenderer getMoveDownButton() {
      return moveDownButton;
    }

    public LinkRenderer getDeleteButton() {
      return deleteButton;
    }

    public void setDeleteButton(LinkRenderer deleteButton) {
      this.deleteButton = deleteButton;
    }
  }

  public Link getAddButton() {
    return addButton;
  }

  public Link getAddTopButton() {
    return addTopButton;
  }

  public class RepeaterUpdate extends AbstractDOMResult {
    private final boolean disabled;
    private final String message;
    private AjaxCaptureResult added;

    public RepeaterUpdate(SectionInfo info, FullDOMResult result, String divId) {
      super(result);
      this.added = result != null ? new AjaxCaptureResult(result.getHtml().get(divId)) : null;
      Label message = Repeater.this.getMessage();
      this.message = message != null ? message.getText() : null;
      this.disabled = addButton.isDisabled(info);
    }
    /*
    		public RepeaterUpdate(SectionInfo info)
    		{
    			Label message = Repeater.this.getMessage();
    			this.message = message != null ? message.getText() : null;
    			this.disabled = addButton.isDisabled(info);
    		}
    */
    public boolean isDisabled() {
      return disabled;
    }

    public String getMessage() {
      return message;
    }

    public AjaxCaptureResult getAdded() {
      return added;
    }
  }

  @Override
  protected ElementId getIdForLabel() {
    return addButton;
  }
}


text:
typedef enum {
    FWButtonIconAttachmentLeft,
    FWButtonIconAttachmentRight,
    FWButtonIconAttachmentTop,
    FWButtonIconAttachmentBottom
} FWButtonIconAttachment;

@interface FWButton : UIButton
@property (nonatomic, assign) FWButtonIconAttachment iconAttachment;
- (void)layoutSubviews;
@end


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=Edge">
	<title>Beacon dashboard</title>
	<meta name="viewport" content="initial-scale=1.0, width=device-width">

	<link rel="stylesheet" href="//build.origami.ft.com/bundles/css?modules=o-techdocs@^4.0.4,o-fonts@^1.6.7,o-ft-icons@^2.3.6,o-table@^1.7.2,o-grid@^3.1.6,o-chat@^2.0.4,o-aside-panel@^1.3.2" />
	<link rel="stylesheet" href="{{#hashedAsset}}main.css{{/hashedAsset}}"/>

						FT

Beacon dashboard

					Progress

week 25

week 24

					Uniques

Overview

Trend

By page type

Geographically

By device

					Addiction

Daily

Weekly

					AB testing

AA

Homepage promo

Engaged follow

					Opt-ins

					Active usage

globalNavigation

homePageLoadMore

marketDataAPI

articleComments

articleRelatedContent

articleTOC

dynamicTertiaryNav

capiV2LinkedDataOrganisationHeader

follow

homePageMyFTPanel

homePageMyPageFeed

myPageTopicSuggestions

pagination

saveForLater

search

myFTReadingListOnArticle

					Flow

Galleries

MyFT Aggregate

MyFT Page

MyPageFeed

MyFT Emails

MyFT RSS Feeds

					Labs

Real-time stream

Real-time traffic map

					Most searched-for terms

					Navigation

					Frequency/Recency

Frequency/Recency

How are people using myFT?

					Dead letter office

					Meta beacon

				Be advised: This is an experimental series of dashboards for next.ft.com, not an audited set of statistics.

			{{{body}}}

			Can this dashboard be better? Ask about usage at http://asknext.ft.com

			Where does the data live? You'll need access for Keen IO

			Fancy a chat? Join the slack channel for #ft-next-usage

			Thinking of making your own dashboard? See the developers' guide to Measuring Next

			Want real-time data in next.ft.com? Install Mollydobbin for Chrome

			More questions? Email next.team@ft.com


text:
package com.zulip.android.helper;

import android.content.res.Resources;
import android.support.test.espresso.matcher.BoundedMatcher;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.zulip.android.R;
import com.zulip.android.models.Message;
import com.zulip.android.models.MessageType;
import com.zulip.android.viewholders.MessageHeaderParent;
import com.zulip.android.viewholders.MessageHolder;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;

public class Matchers {

    public static Matcher<View> withFirstId(final int id) {
        return new TypeSafeMatcher<View>() {
            Resources resources = null;
            boolean found = false;

            @Override
            public void describeTo(Description description) {
                String idDescription = Integer.toString(id);
                if (resources != null) {
                    try {
                        idDescription = resources.getResourceName(id);
                    } catch (Resources.NotFoundException e) {
                        // No big deal, will just use the int value.
                        idDescription = String.format("%s (resource name not found)", id);
                    }
                }
                description.appendText("with id: " + idDescription);
            }

            @Override
            public boolean matchesSafely(View view) {
                if (found) return false;
                resources = view.getResources();
                if (id == view.getId()) {
                    found = true;
                    return true;
                }
                return false;
            }
        };
    }

    public static Matcher<RecyclerView.ViewHolder> withMessageHolderAndClick(final MessageType messageType, final int id) {
        return new BoundedMatcher<RecyclerView.ViewHolder, MessageHolder>(MessageHolder.class) {
            private boolean found = false;

            @Override
            public void describeTo(Description description) {
                description.appendText("No ViewHolder found with text: " + messageType.toString());
            }

            @Override
            protected boolean matchesSafely(MessageHolder item) {
                if (found) return false;
                if (item.getLayoutPosition() < 0) return false;
                Message message = item.onItemClickListener.getMessageAtPosition(item.getLayoutPosition());
                if (message == null) return false;
                if (messageType == message.getType()) {
                    if (id == R.id.contentView) {
                        item.onItemClickListener.onItemClick(R.id.contentView, item.getLayoutPosition());
                    }
                    found = true;
                    return true;
                } else {
                    return false;
                }
            }
        };
    }

    public static Matcher<RecyclerView.ViewHolder> withMessageHolder(final String text, final int textViewId) {
        return new BoundedMatcher<RecyclerView.ViewHolder, MessageHolder>(MessageHolder.class) {
            private boolean found = false;

            @Override
            public void describeTo(Description description) {
                description.appendText("No ViewHolder found with text: ");
            }

            @Override
            protected boolean matchesSafely(MessageHolder item) {
                if (found) return false;
                found = ((TextView) item.itemView.findViewById(textViewId)).getText().toString().matches(text);
                return found;
            }
        };
    }

    public static Matcher<RecyclerView.ViewHolder> withMessageHeaderHolder(final MessageType messageType) {
        return new BoundedMatcher<RecyclerView.ViewHolder, MessageHeaderParent.MessageHeaderHolder>(MessageHeaderParent.MessageHeaderHolder.class) {
            private boolean found = false;

            @Override
            public void describeTo(Description description) {
                description.appendText("No ViewHolder found with text: " + messageType.toString());
            }

            @Override
            protected boolean matchesSafely(MessageHeaderParent.MessageHeaderHolder item) {
                if (found) return false;
                MessageHeaderParent messageHeaderParent = item.onItemClickListener.getMessageHeaderParentAtPosition(item.getLayoutPosition());
                found = (messageType == messageHeaderParent.getMessageType());
                return found;
            }
        };
    }
}


text:
<?php

namespace hipanel\modules\finance\logic\bill;

interface QuantityFormatterInterface
{
    /**
     * Returns textual user friendly representation of the quantity.
     * E.g. 20 days, 30 GB, 1 year.
     *
     * @return string
     */
    public function format(): string;

    /**
     * Returns numeric to be saved in DB.
     *
     * @return string
     */
    public function getValue(): string;

    /**
     * Returns numeric user friendly representation of the quantity.
     *
     * @return string
     */
    public function getClientValue(): string;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="description" content="Camber Calculator. Calculate camber with three simple measurements">
    <meta name="author" content="Erresen">
    <link rel="icon" href="../../favicon.ico">

	<title>Camber Calculator</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
	<link rel="stylesheet" href="camber.css?v=0.00004">


text:
package com.intellij.refactoring.typeMigration.rules.guava;

import com.intellij.psi.*;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiTypesUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author Dmitry Batkovich
 */
public class GuavaConversionUtil {

  @Nullable
  public static PsiType getFunctionReturnType(PsiExpression functionExpression) {
    if (functionExpression instanceof PsiFunctionalExpression) {
      return LambdaUtil.getFunctionalInterfaceReturnType((PsiFunctionalExpression)functionExpression);
    }
    PsiType currentType = functionExpression.getType();
    if (currentType == null) return null;

    while (true) {
      if (LambdaUtil.isFunctionalType(currentType)) {
        return LambdaUtil.getFunctionalInterfaceReturnType(currentType);
      }
      final PsiType[] superTypes = currentType.getSuperTypes();
      currentType = null;
      for (PsiType type : superTypes) {
        final PsiClass aClass = PsiTypesUtil.getPsiClass(type);
        if (aClass != null && InheritanceUtil.isInheritor(aClass, GuavaFunctionConversionRule.GUAVA_FUNCTION)) {
          currentType = type;
          break;
        }
      }
      if (currentType == null) {
        return null;
      }
    }
  }

  @NotNull
  public static PsiType addTypeParameters(@NotNull String baseClassQualifiedName, @Nullable PsiType type, @NotNull PsiElement context) {
    String parameterText = "";
    if (type != null) {
      final String canonicalText = type.getCanonicalText(false);
      if (canonicalText.contains("<")) {
        parameterText = canonicalText.substring(canonicalText.indexOf('<'));
      }
    }

    return JavaPsiFacade.getElementFactory(context.getProject()).createTypeFromText(baseClassQualifiedName + parameterText, context);
  }
}


text:
package org.codegist.crest.server.stubs.params.headers;

import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.util.List;

import static org.codegist.crest.server.utils.ToStrings.string;

/**
 * @author laurent.gilles@codegist.org
 */
@Produces("text/html;charset=UTF-8")
@Path("params/header/encoding")
public class EncodingsStub {

    @GET
    @Path("default")
    public String defaults(
            @HeaderParam("p1") String p1,
            @HeaderParam("p2") List<String> p2) {
        return String.format("default() p1=%s p2=%s", p1, string(p2));
    }

    @GET
    @Path("encoded")
    public String encoded(
            @HeaderParam("p1") String p1,
            @HeaderParam("p2") List<String> p2) {
        return String.format("encoded() p1=%s p2=%s", p1, string(p2));
    }

}