text:
// Copyright (c) 2013 SharpYaml - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// -------------------------------------------------------------------------------
// SharpYaml is a fork of YamlDotNet https://github.com/aaubry/YamlDotNet
// published with the following license:
// -------------------------------------------------------------------------------
//
// Copyright (c) 2008, 2009, 2010, 2011, 2012 Antoine Aubry
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using SharpYaml.Events;

namespace SharpYaml.Schemas
{
	/// <summary>
	/// Base implementation for a based schema.
	/// </summary>
	public abstract class SchemaBase : IYamlSchema
	{
		private readonly Dictionary<string, string> shortTagToLongTag = new Dictionary<string, string>();
		private readonly Dictionary<string, string> longTagToShortTag = new Dictionary<string, string>();
		private readonly List<ScalarResolutionRule> scalarTagResolutionRules = new List<ScalarResolutionRule>();
		private readonly Dictionary<string, Regex> algorithms = new Dictionary<string, Regex>();

		private readonly Dictionary<string, List<ScalarResolutionRule>> mapTagToScalarResolutionRuleList =
			new Dictionary<string, List<ScalarResolutionRule>>();

		private readonly Dictionary<Type, List<ScalarResolutionRule>> mapTypeToScalarResolutionRuleList =
			new Dictionary<Type, List<ScalarResolutionRule>>();

		private readonly Dictionary<Type, string> mapTypeToShortTag = new Dictionary<Type, string>();
		private readonly Dictionary<string, Type> mapShortTagToType = new Dictionary<string, Type>();

		private int updateCountter;
		private bool needFirstUpdate = true;

		protected SchemaBase()
		{
			RegisterDefaultTagMappings();
		}

		/// <summary>
		/// The string short tag: !!str
		/// </summary>
		public const string StrShortTag = "!!str";

		/// <summary>
		/// The string long tag: tag:yaml.org,2002:str
		/// </summary>
		public const string StrLongTag = "tag:yaml.org,2002:str";

		public string ExpandTag(string shortTag)
		{
			if (shortTag == null)
				return null;

			string tagExpanded;
			return shortTagToLongTag.TryGetValue(shortTag, out tagExpanded) ? tagExpanded : shortTag;
		}

		public string ShortenTag(string longTag)
		{
			if (longTag == null)
				return null;

			string tagShortened;
			return longTagToShortTag.TryGetValue(longTag, out tagShortened) ? tagShortened : longTag;
		}

		public string GetDefaultTag(NodeEvent nodeEvent)
		{
			EnsureScalarRules();

			if (nodeEvent == null) throw new ArgumentNullException("nodeEvent");

			var mapping = nodeEvent as MappingStart;
			if (mapping != null)
			{
				return GetDefaultTag(mapping);
			}

			var sequence = nodeEvent as SequenceStart;
			if (sequence != null)
			{
				return GetDefaultTag(sequence);
			}

			var scalar = nodeEvent as Scalar;
			if (scalar != null)
			{
				object value;
				string tag;
				TryParse(scalar, false, out tag, out value);
				return tag;
			}

			throw new NotSupportedException("NodeEvent [{0}] not supported".DoFormat(nodeEvent.GetType().FullName));
		}

		public string GetDefaultTag(Type type)
		{
			if (type == null) throw new ArgumentNullException("type");
			EnsureScalarRules();

			string defaultTag;
			mapTypeToShortTag.TryGetValue(type, out defaultTag);
			return defaultTag;
		}

		public bool IsTagImplicit(string tag)
		{
			if (tag == null)
			{
				return true;
			}
			return shortTagToLongTag.ContainsKey(tag);
		}

		/// <summary>
		/// Registers a long/short tag association.
		/// </summary>
		/// <param name="shortTag">The short tag.</param>
		/// <param name="longTag">The long tag.</param>
		/// <exception cref="System.ArgumentNullException">
		/// shortTag
		/// or
		/// shortTag
		/// </exception>
		public void RegisterTag(string shortTag, string longTag)
		{
			if (shortTag == null) throw new ArgumentNullException("shortTag");
			if (longTag == null) throw new ArgumentNullException("longTag");

			shortTagToLongTag[shortTag] = longTag;
			longTagToShortTag[longTag] = shortTag;
		}

		/// <summary>
		/// Gets the default tag for a <see cref="MappingStart"/> event.
		/// </summary>
		/// <param name="nodeEvent">The node event.</param>
		/// <returns>The default tag for a map.</returns>
		protected abstract string GetDefaultTag(MappingStart nodeEvent);

		/// <summary>
		/// Gets the default tag for a <see cref="SequenceStart"/> event.
		/// </summary>
		/// <param name="nodeEvent">The node event.</param>
		/// <returns>The default tag for a seq.</returns>
		protected abstract string GetDefaultTag(SequenceStart nodeEvent);

		public virtual bool TryParse(Scalar scalar, bool parseValue, out string defaultTag, out object value)
		{
			if (scalar == null) throw new ArgumentNullException("scalar");

			EnsureScalarRules();

			defaultTag = null;
			value = null;

			// DoubleQuoted and SingleQuoted string are always decoded
			if (scalar.Style == ScalarStyle.DoubleQuoted || scalar.Style == ScalarStyle.SingleQuoted)
			{
				defaultTag = StrShortTag;
				if (parseValue)
				{
					value = scalar.Value;
				}
				return true;
			}

			// Parse only values if we have some rules
			if (scalarTagResolutionRules.Count > 0)
			{
				foreach (var rule in scalarTagResolutionRules)
				{
					var match = rule.Pattern.Match(scalar.Value);
					if (!match.Success) continue;

					defaultTag = rule.Tag;
					if (parseValue)
					{
						value = rule.Decode(match);
					}
					return true;
				}
			}
			else
			{
				// Expand the tag to a default tag.
				defaultTag = ShortenTag(scalar.Tag);
			}

			// Value was not successfully decoded
			return false;
		}

		public bool TryParse(Scalar scalar, Type type, out object value)
		{
			if (scalar == null) throw new ArgumentNullException("scalar");
			if (type == null) throw new ArgumentNullException("type");

			EnsureScalarRules();

			value = null;

			// DoubleQuoted and SingleQuoted string are always decoded
			if (type == typeof(string) && (scalar.Style == ScalarStyle.DoubleQuoted || scalar.Style == ScalarStyle.SingleQuoted))
			{
				value = scalar.Value;
				return true;
			}

			// Parse only values if we have some rules
			if (mapTypeToScalarResolutionRuleList.Count > 0)
			{
				List<ScalarResolutionRule> rules;
				if (mapTypeToScalarResolutionRuleList.TryGetValue(type, out rules))
				{
					foreach (var rule in rules)
					{
						var match = rule.Pattern.Match(scalar.Value);
						if (match.Success)
						{
							value = rule.Decode(match);
							return true;
						}
					}
				}
			}

			// Value was not successfully decoded
			return false;
		}

		public Type GetTypeForDefaultTag(string shortTag)
		{
			if (shortTag == null)
			{
				return null;
			}

			Type type;
			mapShortTagToType.TryGetValue(shortTag, out type);
			return type;
		}

		/// <summary>
		/// Prepare scalar rules. In the implementation of this method, should call <see cref="AddScalarRule{T}"/>
		/// </summary>
		protected virtual void PrepareScalarRules()
		{
		}

		/// <summary>
		/// Add a tag resolution rule that is invoked when <paramref name="regex" /> matches
		/// the <see cref="Scalar">Value of</see> a <see cref="Scalar" /> node.
		/// The tag is resolved to <paramref name="tag" /> and <paramref name="decode" /> is
		/// invoked when actual value of type <typeparamref name="T" /> is extracted from
		/// the node text.
		/// </summary>
		/// <typeparam name="T">Type of the scalar</typeparam>
		/// <param name="tag">The tag.</param>
		/// <param name="regex">The regex.</param>
		/// <param name="decode">The decode function.</param>
		/// <param name="encode">The encode function.</param>
		/// <example>
		///   <code>
		/// BeginUpdate(); // to avoid invoking slow internal calculation method many times.
		/// Add( ... );
		/// Add( ... );
		/// Add( ... );
		/// Add( ... );
		/// EndUpdate();   // automaticall invoke internal calculation method
		///   </code></example>
		protected void AddScalarRule<T>(string tag, string regex, Func<Match, T> decode, Func<T, string> encode)
		{
			// Make sure the tag is expanded to its long form
			var longTag = ShortenTag(tag);
			scalarTagResolutionRules.Add(new ScalarResolutionRule<T>(longTag, regex, decode, encode));
		}

		protected void RegisterDefaultTagMapping<T>(string tag, bool isDefault = false)
		{
			if (tag == null) throw new ArgumentNullException("tag");
			RegisterDefaultTagMapping(tag, typeof(T), isDefault);
		}

		protected void RegisterDefaultTagMapping(string tag, Type type, bool isDefault)
		{
			if (tag == null) throw new ArgumentNullException("tag");
			if (type == null) throw new ArgumentNullException("type");

			if (!mapTypeToShortTag.ContainsKey(type))
				mapTypeToShortTag.Add(type, tag);

			if (isDefault)
			{
				mapShortTagToType[tag] = type;
			}
		}

		/// <summary>
		/// Allows to register tag mapping for all primitive types (e.g. int -> !!int)
		/// </summary>
		protected virtual void RegisterDefaultTagMappings()
		{
		}

		private void EnsureScalarRules()
		{
			if (needFirstUpdate || updateCountter != scalarTagResolutionRules.Count)
			{
				PrepareScalarRules();
				Update();
				needFirstUpdate = false;
			}
		}

		private void Update()
		{
			// Tag to joined regexp source
			var mapTagToPartialRegexPattern = new Dictionary<string, string>();
			foreach (var rule in scalarTagResolutionRules)
			{
				if (!mapTagToPartialRegexPattern.ContainsKey(rule.Tag))
				{
					mapTagToPartialRegexPattern.Add(rule.Tag, rule.PatternSource);
				}
				else
				{
					mapTagToPartialRegexPattern[rule.Tag] += "|" + rule.PatternSource;
				}
			}

			// Tag to joined regexp
			algorithms.Clear();
			foreach (var entry in mapTagToPartialRegexPattern)
			{
				algorithms.Add(
					entry.Key,
					new Regex("^(" + entry.Value + ")$")
					);
			}

			// Tag to decoding methods
			mapTagToScalarResolutionRuleList.Clear();
			foreach (var rule in scalarTagResolutionRules)
			{
				if (!mapTagToScalarResolutionRuleList.ContainsKey(rule.Tag))
					mapTagToScalarResolutionRuleList[rule.Tag] = new List<ScalarResolutionRule>();
				mapTagToScalarResolutionRuleList[rule.Tag].Add(rule);
			}

			mapTypeToScalarResolutionRuleList.Clear();
			foreach (var rule in scalarTagResolutionRules)
			{
				var type = rule.GetTypeOfValue();
				if (!mapTypeToScalarResolutionRuleList.ContainsKey(type))
					mapTypeToScalarResolutionRuleList[type] = new List<ScalarResolutionRule>();
				mapTypeToScalarResolutionRuleList[type].Add(rule);
			}

			// Update the counter
			updateCountter = scalarTagResolutionRules.Count;
		}

		private abstract class ScalarResolutionRule
		{
			public string Tag { get; protected set; }
			public Regex Pattern { get; protected set; }
			public string PatternSource { get; protected set; }
			public abstract object Decode(Match m);
			public abstract string Encode(object obj);
			public abstract Type GetTypeOfValue();
			public abstract bool HasEncoder();

			public bool IsMatch(string value)
			{
				return Pattern.IsMatch(value);
			}
		}

		private class ScalarResolutionRule<T> : ScalarResolutionRule
		{
			public ScalarResolutionRule(string shortTag, string regex, Func<Match, T> decoder, Func<T, string> encoder)
			{
				Tag = shortTag;
				PatternSource = regex;
				Pattern = new Regex("^(?:" + regex + ")$");
				Decoder = decoder;
				Encoder = encoder;
			}

			private readonly Func<Match, T> Decoder;
			private readonly Func<T, string> Encoder;

			public override object Decode(Match m)
			{
				return Decoder(m);
			}

			public override string Encode(object obj)
			{
				return Encoder((T) obj);
			}

			public override Type GetTypeOfValue()
			{
				return typeof (T);
			}

			public override bool HasEncoder()
			{
				return Encoder != null;
			}
		}
	}
}


text:
<!DOCTYPE html>

    <title>dc.js - Area Transitions Example</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="../css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="../css/dc.css"/>

    <button class="btn" onclick="transitionTest.stop()">stop</button>
    <button class="btn" onclick="button1()">left</button>
    <button class="btn" onclick="button2()">right</button>
    <button class="btn" onclick="button3()">middle</button>
    <button class="btn" onclick="button4()">stacks</button>

redpajama_set_name: RedPajamaGithub


text:
/* $Id$ */

package xmp;

import java.net.URL;

import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.SAXException;

import org.apache.xmlgraphics.xmp.Metadata;
import org.apache.xmlgraphics.xmp.XMPArray;
import org.apache.xmlgraphics.xmp.XMPConstants;
import org.apache.xmlgraphics.xmp.XMPParser;
import org.apache.xmlgraphics.xmp.XMPProperty;
import org.apache.xmlgraphics.xmp.XMPSerializer;
import org.apache.xmlgraphics.xmp.schemas.DublinCoreAdapter;
import org.apache.xmlgraphics.xmp.schemas.DublinCoreSchema;

/**
 * This example shows how to parse an XMP metadata file.
 */
public class ParseMetadata {

    private static void parseMetadata() throws TransformerException, SAXException {
        URL url = ParseMetadata.class.getResource("pdf-example.xmp");
        Metadata meta = XMPParser.parseXMP(url);
        XMPProperty prop;
        prop = meta.getProperty(XMPConstants.DUBLIN_CORE_NAMESPACE, "creator");
        XMPArray array;
        array = prop.getArrayValue();
        for (int i = 0, c = array.getSize(); i < c; i++) {
            System.out.println("Creator: " + array.getValue(i));
        }
        prop = meta.getProperty(XMPConstants.DUBLIN_CORE_NAMESPACE, "title");
        array = prop.getArrayValue();
        System.out.println("Default Title: " + array.getSimpleValue());
        System.out.println("German Title: " + array.getLangValue("de"));
        prop = meta.getProperty(XMPConstants.XMP_BASIC_NAMESPACE, "CreateDate");
        System.out.println("Creation Date: " + prop.getValue());
        prop = meta.getProperty(XMPConstants.XMP_BASIC_NAMESPACE, "CreatorTool");
        System.out.println("Creator Tool: " + prop.getValue());
        prop = meta.getProperty(XMPConstants.ADOBE_PDF_NAMESPACE, "Producer");
        System.out.println("Producer: " + prop.getValue());
        prop = meta.getProperty(XMPConstants.ADOBE_PDF_NAMESPACE, "PDFVersion");
        System.out.println("PDF version: " + prop.getValue());

        DublinCoreAdapter dc = DublinCoreSchema.getAdapter(meta);
        System.out.println("Default title: " + dc.getTitle());
        System.out.println("German title: " + dc.getTitle("de"));

        StreamResult res = new StreamResult(System.out);
        XMPSerializer.writeXML(meta, res);
    }

    /**
     * Command-line interface.
     * @param args the command-line arguments
     */
    public static void main(String[] args) {
        try {
            parseMetadata();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}


text:
<?php

namespace {{ namespace }}\Twig;

use Doctrine\ORM\EntityManager;
use Kunstmaan\NodeBundle\Entity\AbstractPage;

class NodeTranslationTwigExtension extends \Twig_Extension
{
    /**
     * @var EntityManager $em
     */
    private $em;

    /**
     * Constructor
     *
     * @param EntityManager $em
     */
    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    /**
     * Returns a list of functions to add to the existing list.
     *
     * @return array An array of functions
     */
    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('get_node_trans_by_node_id', array($this, 'getNodeTranslationByNodeId')),
        );
    }

    /**
     * Get the node translation object based on node id and language.
     *
     * @param int $nodeId
     * @param string $lang
     * @return NodeTranslation
     */
    public function getNodeTranslationByNodeId($nodeId, $lang)
    {
        $repo = $this->em->getRepository('KunstmaanNodeBundle:NodeTranslation');
        $qb = $repo->createQueryBuilder('nt')
            ->select('nt')
            ->innerJoin('nt.node', 'n', 'WITH', 'nt.node = n.id')
            ->where('n.deleted != 1')
            ->andWhere('nt.online = 1')
            ->andWhere('nt.lang = :lang')
            ->setParameter('lang', $lang)
            ->andWhere('n.id = :node_id')
            ->setParameter('node_id', $nodeId)
            ->setFirstResult(0)
            ->setMaxResults(1);

        return $qb->getQuery()->getOneOrNullResult();
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'node_translation_twig_extension';
    }
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;

using FluentAssertions.Common;
using FluentAssertions.Execution;

namespace FluentAssertions.Collections
{
    [DebuggerNonUserCode]
    public class GenericCollectionAssertions<T> :
        SelfReferencingCollectionAssertions<T, GenericCollectionAssertions<T>>
    {
        public GenericCollectionAssertions(IEnumerable<T> actualValue) : base(actualValue)
        {
        }

        ///
        /// Asserts that a collection is ordered in ascending order according to the value of the specified
        /// <paramref name="propertyExpression"/>.
        ///
        /// <param name="propertyExpression">
        /// A lambda expression that references the property that should be used to determine the expected ordering.
        /// </param>
        /// <param name="because">
        /// A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion
        /// is needed. If the phrase does not start with the word because, it is prepended automatically.
        /// </param>
        /// <param name="args">
        /// Zero or more objects to format using the placeholders in <see cref="because"/>.
        /// </param>
        public AndConstraint<GenericCollectionAssertions<T>> BeInAscendingOrder<TSelector>(
            Expression<Func<T, TSelector>> propertyExpression, string because = "", params object[] args)
        {
            return BeInAscendingOrder(propertyExpression, Comparer<TSelector>.Default, because, args);
        }

        ///
        /// Asserts that a collection is ordered in ascending order according to the value of the specified
        /// <see cref="IComparer{T}"/> implementation.
        ///
        /// <param name="comparer">
        /// The object that should be used to determine the expected ordering.
        /// </param>
        /// <param name="because">
        /// A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion
        /// is needed. If the phrase does not start with the word because, it is prepended automatically.
        /// </param>
        /// <param name="args">
        /// Zero or more objects to format using the placeholders in <see cref="because"/>.
        /// </param>
        public AndConstraint<GenericCollectionAssertions<T>> BeInAscendingOrder(
            IComparer<T> comparer, string because = "", params object[] args)
        {
            return BeInAscendingOrder(item => item, comparer, because, args);
        }

        ///
        /// Asserts that a collection is ordered in ascending order according to the value of the specified
        /// <paramref name="propertyExpression"/> and <see cref="IComparer{T}"/> implementation.
        ///
        /// <param name="propertyExpression">
        /// A lambda expression that references the property that should be used to determine the expected ordering.
        /// </param>
        /// <param name="comparer">
        /// The object that should be used to determine the expected ordering.
        /// </param>
        /// <param name="because">
        /// A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion
        /// is needed. If the phrase does not start with the word because, it is prepended automatically.
        /// </param>
        /// <param name="args">
        /// Zero or more objects to format using the placeholders in <see cref="because"/>.
        /// </param>
        public AndConstraint<GenericCollectionAssertions<T>> BeInAscendingOrder<TSelector>(
            Expression<Func<T, TSelector>> propertyExpression, IComparer<TSelector> comparer, string because = "", params object[] args)
        {
            return BeOrderedBy(propertyExpression, comparer, SortOrder.Ascending, because, args);
        }

        ///
        /// Asserts that a collection is ordered in descending order according to the value of the specified
        /// <paramref name="propertyExpression"/>.
        ///
        /// <param name="propertyExpression">
        /// A lambda expression that references the property that should be used to determine the expected ordering.
        /// </param>
        /// <param name="because">
        /// A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion
        /// is needed. If the phrase does not start with the word because, it is prepended automatically.
        /// </param>
        /// <param name="args">
        /// Zero or more objects to format using the placeholders in <see cref="because"/>.
        /// </param>
        public AndConstraint<GenericCollectionAssertions<T>> BeInDescendingOrder<TSelector>(
            Expression<Func<T, TSelector>> propertyExpression, string because = "", params object[] args)
        {
            return BeInDescendingOrder(propertyExpression, Comparer<TSelector>.Default, because, args);
        }

        ///
        /// Asserts that a collection is ordered in descending order according to the value of the specified
        /// <see cref="IComparer{T}"/> implementation.
        ///
        /// <param name="comparer">
        /// The object that should be used to determine the expected ordering.
        /// </param>
        /// <param name="because">
        /// A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion
        /// is needed. If the phrase does not start with the word because, it is prepended automatically.
        /// </param>
        /// <param name="args">
        /// Zero or more objects to format using the placeholders in <see cref="because"/>.
        /// </param>
        public AndConstraint<GenericCollectionAssertions<T>> BeInDescendingOrder(
            IComparer<T> comparer, string because = "", params object[] args)
        {
            return BeInDescendingOrder(item => item, comparer, because, args);
        }

        ///
        /// Asserts that a collection is ordered in descending order according to the value of the specified
        /// <paramref name="propertyExpression"/> and <see cref="IComparer{T}"/> implementation.
        ///
        /// <param name="propertyExpression">
        /// A lambda expression that references the property that should be used to determine the expected ordering.
        /// </param>
        /// <param name="comparer">
        /// The object that should be used to determine the expected ordering.
        /// </param>
        /// <param name="because">
        /// A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion
        /// is needed. If the phrase does not start with the word because, it is prepended automatically.
        /// </param>
        /// <param name="args">
        /// Zero or more objects to format using the placeholders in <see cref="because"/>.
        /// </param>
        public AndConstraint<GenericCollectionAssertions<T>> BeInDescendingOrder<TSelector>(
            Expression<Func<T, TSelector>> propertyExpression, IComparer<TSelector> comparer, string because = "", params object[] args)
        {
            return BeOrderedBy(propertyExpression, comparer, SortOrder.Descending, because, args);
        }

        private AndConstraint<GenericCollectionAssertions<T>> BeOrderedBy<TSelector>(
            Expression<Func<T, TSelector>> propertyExpression, IComparer<TSelector> comparer, SortOrder direction, string because, object[] args)
        {
            if (comparer == null)
            {
                throw new ArgumentNullException("comparer",
                    "Cannot assert collection ordering without specifying a comparer.");
            }

            if (IsValidProperty(propertyExpression, because, args))
            {
                IList<T> unordered = (Subject as IList<T>) ?? Subject.ToList();

                Func<T, TSelector> keySelector = propertyExpression.Compile();

                IOrderedEnumerable<T> expectation = (direction == SortOrder.Ascending)
                    ? unordered.OrderBy(keySelector, comparer)
                    : unordered.OrderByDescending(keySelector, comparer);

                var orderString = propertyExpression.GetMemberPath();
                orderString = orderString == "\"\"" ? string.Empty : " by " + orderString;

                Execute.Assertion
                    .ForCondition(unordered.SequenceEqual(expectation))
                    .BecauseOf(because, args)
                    .FailWith("Expected collection {0} to be ordered{1}{reason} and result in {2}.",
                        Subject, orderString, expectation);
            }

            return new AndConstraint<GenericCollectionAssertions<T>>(this);
        }

        private bool IsValidProperty<TSelector>(Expression<Func<T, TSelector>> propertyExpression, string because, object[] args)
        {
            if (propertyExpression == null)
            {
                throw new ArgumentNullException("propertyExpression",
                    "Cannot assert collection ordering without specifying a property.");
            }

            return Execute.Assertion
                .ForCondition(!ReferenceEquals(Subject, null))
                .BecauseOf(because, args)
                .FailWith("Expected collection to be ordered by {0}{reason} but found <null>.",
                    propertyExpression.GetMemberPath());
        }
    }
}


text:
/*
 * TextBox.h
 *
 *  Created on: Jul 17, 2013
 *      Author: drom
 */

#ifndef TEXTBOX_H_
#define TEXTBOX_H_

#include <drawing/DisplayBox.h>
#include <string>

using std::string;

class TextBox : public DisplayBox {

private:

  string text;

public:

  TextBox(DrawingContext* context);
  virtual ~TextBox();

  void setText(const string& text);
  const string& getText();

  void draw();

};

#endif /* TEXTBOX_H_ */


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.plugin.util;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.BiFunction;

/**
 * @author Tony Vaagenes
 * @author ollivir
 */
public class Maps {
    public static <K, V> Map<K, V> combine(Map<K, V> left, Map<K, V> right, BiFunction<V, V, V> combiner) {
        Map<K, V> ret = new HashMap<>();
        Set<K> keysRight = new HashSet<>(right.keySet());

        left.forEach((k, v) -> {
            if (keysRight.contains(k)) {
                ret.put(k, combiner.apply(v, right.get(k)));
                keysRight.remove(k);
            } else {
                ret.put(k, v);
            }
        });
        keysRight.forEach(k -> ret.put(k, right.get(k)));

        return ret;
    }
}


text:
package org.umlg.sqlg.test;

import org.umlg.sqlg.AllTest;

/**
 * Date: 2014/07/16
 * Time: 12:11 PM
 */
public class PostgresAllTest extends AllTest {
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Conference Manager</title>
    <meta name="description" content="Conference Manager">
    <meta name="author" content="Heiko Kernbach & Michael Hackstein">

    <link href="style.css" rel="stylesheet">


text:
package org.apache.jackrabbit.webdav.simple;

import java.io.ByteArrayOutputStream;
import java.io.File;

import javax.jcr.Repository;
import javax.jcr.Session;

import junit.framework.TestCase;

import org.apache.commons.io.IOUtils;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.jackrabbit.util.Text;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LitmusTest extends TestCase {

    /**
     * Logger instance.
     */
    private static final Logger log = LoggerFactory.getLogger(LitmusTest.class);

    public void testLitmus() throws Exception {
        File dir = new File("target", "litmus");
        String litmus = System.getProperty("litmus", "litmus");

        if (Boolean.getBoolean("jackrabbit.test.integration")
                && isLitmusAvailable(litmus)) {
            final Repository repository = JcrUtils.getRepository(
                    "jcr-jackrabbit://" + Text.escapePath(dir.getCanonicalPath()));
            Session session = repository.login(); // for the TransientRepository
            try {
                Server server = new Server();

                ServerConnector connector = new ServerConnector(server);
                connector.setHost("localhost");
                connector.setPort(Integer.getInteger("litmus.port", 0));

                server.addConnector(connector);

                ServletHolder holder = new ServletHolder(
                        new SimpleWebdavServlet() {
                            @Override
                            public Repository getRepository() {
                                return repository;
                            }
                        });
                holder.setInitParameter("resource-config", "/config.xml");

                ServletContextHandler schandler = new ServletContextHandler(server, "/");
                schandler.addServlet(holder, "/*");

                server.start();
                try {
                    int port = connector.getLocalPort();
                    String url = "http://localhost:" + port + "/default";

                    ProcessBuilder builder =
                        new ProcessBuilder(litmus, url, "admin", "admin");
                    builder.directory(dir);
                    builder.redirectErrorStream();

                    assertLitmus(builder, "basic", 0);

                    assertLitmus(builder, "http", 0);

                    assertLitmus(builder, "props", 0);

                    // FIXME: JCR-2637: WebDAV shallow copy test failure
                    assertLitmus(builder, "copymove", 1);

                    // FIXME: JCR-2638: Litmus locks test failures
                    assertLitmus(builder, "locks", 1);
                } finally {
                    server.stop();
                }
            } finally {
                session.logout();
            }
        }
    }

    private void assertLitmus(
            ProcessBuilder builder, String tests, int exit) throws Exception {
        builder.environment().put("TESTS", tests);
        Process process = builder.start();
        IOUtils.copy(process.getInputStream(), System.out);
        assertEquals(exit, process.waitFor());
    }

    private static boolean isLitmusAvailable(String litmus) {
        try {
            ProcessBuilder builder = new ProcessBuilder(litmus, "--version");
            builder.redirectErrorStream();
            Process process = builder.start();

            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            IOUtils.copy(process.getInputStream(), buffer);
            int rv = process.waitFor();
            log.info("litmus version: {}", buffer.toString("US-ASCII").trim());

            return rv == 0;
        } catch (Exception e) {
            log.warn("litmus is not available: " + litmus, e);
            return false;
        }
    }

}


text:
{% extends 'forms/base_widget.html' %}
{% from 'message_box.html' import message_box %}

{% block html %}

                            {% trans %}
                                The selected category does not contain any events, only subcategories.
                                Please make sure that you really want to create an event there.
                            {% endtrans %}

        <button type="button"
                class="i-button"
                id="categorynav-button-{{ field.id }}"
                data-title='{% trans %}Choose category{% endtrans %}'>
            {%- trans %}Choose category{% endtrans -%}
        </button>
        <input type="hidden" id="{{ field.id }}" name="{{ field.name }}" value="{{ field._value() | tojson | forceescape }}">

{% endblock %}

{% block javascript %}

{% endblock %}


text:
sap.ui.define(['sap/f/semantic/SemanticButton'], function(SemanticButton) {
	"use strict";

	/**
	* Constructor for a new DeleteAction.
	* @param {string} [sId] ID for the new control, generated automatically if no ID is given
	* @param {object} [mSettings] Optional initial settings for the new control:  a map/JSON-object with initial property values, event listeners etc. for the new object
	*
	* @class
	* A semantic-specific button, eligible for the deleteAction aggregation of the
	* {@link sap.f.semantic.SemanticPage} to be placed in its title.
	*
	* @extends sap.f.semantic.SemanticButton
	*
	* @author SAP SE
	* @version ${version}
	*
	* @constructor
	* @public
	* @since 1.46.0
	* @alias sap.f.semantic.DeleteAction
	*/
	var DeleteAction = SemanticButton.extend("sap.f.semantic.DeleteAction", /** @lends sap.f.semantic.DeleteAction.prototype */ {
		metadata: {
			library: "sap.f"
		}
	});

	return DeleteAction;
});


text:
# -*- coding: utf-8 -*-
"""

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""
from PyQt4.QtCore import QSettings, QTranslator, qVersion, QCoreApplication, QUrl, QObject, pyqtSlot, QVariant
from PyQt4.QtGui import QAction, QIcon, QIntValidator, QValidator
from qgis.core import QgsVectorLayer, QgsField, QgsGeometry, QgsPoint, QgsFeature, QgsMapLayerRegistry
from qgis.gui import QgsMessageBar
from qgis.utils import iface
# Initialize Qt resources from file resources.py
import resources_rc
# Import the code for the dialog
from foursquare_poi_grabber_dialog import FoursquarePOIGrabberDialog
import datetime
import urllib2
import json
import os.path

class Foo(QObject):
    @pyqtSlot(str, result=str)
    def get_lat(self, value):
        global lat
        lat = value
        return lat

    @pyqtSlot(str, result=str)
    def get_lon(self, value):
        global lon
        lon = value
        return lon

class FoursquarePOIGrabber:
    """QGIS Plugin Implementation."""
    def enableJavaScript(self):
        self.dlg.webView_gmap.page().mainFrame().addToJavaScriptWindowObject("foo", self.foo)

    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        global validator
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'FoursquarePOIGrabber_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        # Create the dialog (after translation) and keep reference
        self.dlg = FoursquarePOIGrabberDialog()
        self.dlg.setFixedSize(640, 320)
        self.foo = Foo()

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&4sq POI Grabber')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'FoursquarePOIGrabber')
        self.toolbar.setObjectName(u'FoursquarePOIGrabber')

        validator = QIntValidator()
        self.dlg.lineEdit_radius.setValidator(validator)
        self.dlg.lineEdit_radius.setMaxLength(6)
        self.dlg.lineEdit_radius.textChanged.connect(self.check_state)
        self.dlg.lineEdit_radius.editingFinished.connect(self.check_radius)

        self.dlg.webView_gmap.loadFinished.connect(self.enableJavaScript)
        self.dlg.webView_gmap.load(QUrl('http://yilmazturk.info/poigrabber/gmap.html'))

        self.dlg.pushButton_fetchPOI.clicked.connect(self.get_poi)

        self.populate_combobox()

    def check_state(self):
        state = validator.validate(self.dlg.lineEdit_radius.text(), 0)[0]
        if state == QValidator.Acceptable:
            color = '#c4df9b'
            self.dlg.lineEdit_radius.setStyleSheet('QLineEdit { background-color: %s }' % color)
        elif state == QValidator.Intermediate:
            color = '#fff79a'
            self.dlg.lineEdit_radius.setStyleSheet('QLineEdit { background-color: %s }' % color)
        else:
            color = '#f6989d'
            self.dlg.lineEdit_radius.setStyleSheet('QLineEdit { background-color: %s }' % color)

    def check_radius(self):
        if int(self.dlg.lineEdit_radius.text()) > 100000:
            color = '#f6989d'
            self.dlg.lineEdit_radius.setStyleSheet('QLineEdit { background-color: %s }' % color)
            iface.messageBar().pushMessage(u"Error:", u" The maximum supported radius is currently 100,000 meters.",
                                           level=QgsMessageBar.CRITICAL, duration=5)
        else:
            pass

    def get_poi(self):
        try:
            client_id = self.dlg.lineEdit_clientID.text()
            client_secret = self.dlg.lineEdit_clientSecret.text()
            radius = self.dlg.lineEdit_radius.text()
            category_name = self.dlg.comboBox_category.currentText()
            category_id = foursquare_categories[category_name]
            current_date = str(datetime.datetime.now().date()).replace("-", "")
            url = "https://api.foursquare.com/v2/venues/search?ll=%s,%s&radius=%s&intent=browse&categoryId=%s&limit=50&client_id=%s&client_secret=%s&v=%s" % (lat, lon, radius, category_id, client_id, client_secret, current_date)

            req = urllib2.Request(url)
            opener = urllib2.build_opener()
            f = opener.open(req)
            data = json.loads(f.read())

            json_object_count = len(data['response']['venues'])

            if json_object_count == 0:
                iface.messageBar().pushMessage(u"Info:", "Unfortunately, there is no POI at the specified location...",
                                               level=QgsMessageBar.INFO, duration=5)
            else:
                iface.messageBar().pushMessage(u"Info:", str(json_object_count) + " POI(s) fetched for " +
                                               category_name + " category", level=QgsMessageBar.SUCCESS, duration=5)

                poi_id = []
                poi_name = []
                poi_lon = []
                poi_lat = []

                for i in range(0, json_object_count):
                    poi_id.append(data['response']['venues'][i]['id'])
                    poi_name.append(data['response']['venues'][i]['name'])
                    poi_lon.append(data['response']['venues'][i]['location']['lng'])
                    poi_lat.append(data['response']['venues'][i]['location']['lat'])

                coord_pairs = []

                layer_name = "POI - %s" % category_name
                memory_layer = QgsVectorLayer("Point?crs=epsg:4326", layer_name, "memory")
                memory_layer.startEditing()
                provider = memory_layer.dataProvider()
                provider.addAttributes([QgsField("FoursqID", QVariant.String), QgsField("Name",  QVariant.String), QgsField("Category", QVariant.String), QgsField("Date", QVariant.String)])

                for fsid, name, x, y in zip(poi_id, poi_name, poi_lon, poi_lat):
                    geometry = QgsGeometry.fromPoint(QgsPoint(x, y))
                    feature = QgsFeature()
                    feature.setGeometry(geometry)
                    feature.setAttributes([fsid, name, category_name, current_date])
                    coord_pairs.append(feature)

                memory_layer.dataProvider().addFeatures(coord_pairs)
                memory_layer.updateExtents()
                memory_layer.commitChanges()
                QgsMapLayerRegistry.instance().addMapLayer(memory_layer)
        except:
            iface.messageBar().pushMessage(u"Error:", "Please make sure to drop a pin on Google Map or fill in all \
                                            the fields!", level=QgsMessageBar.CRITICAL, duration=5)

    def populate_combobox(self):
        global foursquare_categories
        foursquare_categories = {
            "Medical - Hospital": "4bf58dd8d48988d196941735",
            "Medical - Dentist's Office": "4bf58dd8d48988d178941735",
            "Medical - Veterinarian": "4d954af4a243a5684765b473",
            "Education - University": "4bf58dd8d48988d1ae941735",
            "Education - High School": "4bf58dd8d48988d13d941735",
            "Education - Elementary School": "4f4533804b9074f6e4fb0105",
            "Culture & Arts - Museum": "4bf58dd8d48988d181941735",
            "Culture & Arts - Theater": "4bf58dd8d48988d137941735",
            "Culture & Arts - Movie Theater": "4bf58dd8d48988d17f941735",
            "Food": "4d4b7105d754a06374d81259",
            "Food - Cafe": "4bf58dd8d48988d16d941735",
            "Food - Bar": "4bf58dd8d48988d116941735",
            "Office": "4bf58dd8d48988d124941735",
            "Finance - ATM": "52f2ab2ebcbc57f1066b8b56",
            "Finance - Bank": "4bf58dd8d48988d10a951735",
            "Spiritual - Mosque": "4bf58dd8d48988d138941735",
            "Spiritual - Church": "4bf58dd8d48988d132941735",
            "Spiritual - Synagogue": "4bf58dd8d48988d139941735",
            "Hotel": "4bf58dd8d48988d1fa931735",
            "Service - Gas Station": "4bf58dd8d48988d113951735",
            "Service - Supermarket": "52f2ab2ebcbc57f1066b8b46",
            "Service - Barbershop": "4bf58dd8d48988d110951735",
            "Service - Laundry Service": "4bf58dd8d48988d1fc941735",
            "Service - Car Wash": "4f04ae1f2fb6e1c99f3db0ba",
            "Service - Rental Car": "4bf58dd8d48988d1ef941735",
            "Transport - Bus Stop": "52f2ab2ebcbc57f1066b8b4f",
            "Transport - Metro Station": "4bf58dd8d48988d1fd931735",
            "Transport - Tram Station": "52f2ab2ebcbc57f1066b8b51",
            "Transport - Taxi": "4bf58dd8d48988d130951735",
            "Transport - Parking": "4c38df4de52ce0d596b336e1"
        }

        category_list = []
        for category in foursquare_categories.keys():
            category_list.append(category)
        self.dlg.comboBox_category.addItems(sorted(category_list))

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        """Get the translation for a string using Qt translation API.

        We implement this ourselves since we do not inherit QObject.

        :param message: String for translation.
        :type message: str, QString

        :returns: Translated version of message.
        :rtype: QString
        """
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('FoursquarePOIGrabber', message)

    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        add_to_menu=True,
        add_to_toolbar=True,
        status_tip=None,
        whats_this=None,
        parent=None):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            self.toolbar.addAction(action)

        if add_to_menu:
            self.iface.addPluginToMenu(
                self.menu,
                action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/FoursquarePOIGrabber/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'4sq POI Grabber'),
            callback=self.run,
            parent=self.iface.mainWindow())

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&4sq POI Grabber'),
                action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    def run(self):
        """Run method that performs all the real work"""
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            pass
            # Do something useful here - delete the line containing pass and
            # substitute with your code.


text:
require 'cdrouter'
require 'date'

sess = CDRouter::Session.new
sess.base_url     = "https://10.0.1.179"
sess.api_token    = "5a21f9c7"
sess.debug        = false

begin
  puts "Connecting to #{sess.base_url}"
  puts "Found CDRouter version " + sess.version
rescue => exception
  puts "Unable to determine the CDRouter Web API version from #{sess.base_url}"
  puts "Error: " + exception.message
  exit
end

# -- Find results older than 5 years
puts "Find all results older than 5 years"
sess.results.list(:filter => "created<=" + (DateTime.now - 365 * 5).to_s).each do |r|
  puts "Found result " + r.name
  sess.results.delete( r.result_id )
end


text:
package api.forum.thread;

import api.son.MySon;
import api.soup.MySoup;
import api.util.CouldNotLoadException;
import api.util.Tuple;

import java.util.ArrayList;
import java.util.List;

/**
 * For getting API response and working with information
 * for viewing a forum thread
 *
 * @author Gwindow
 */
public class ForumThread {
	/**
	 * The API response
	 */
	private Response response;

	/**
	 * The status of the API response and error if an error occurred
	 */
	private String status, error;

	/**
	 * The thread id
	 */
	private transient int id;

	/**
	 * The page of the thread being viewed.
	 */
	private transient int page;

	/**
	 * Get some page of a forum thread
	 *
	 * @param id the thread id
	 * @param page page of to view
	 */
	public static ForumThread thread(int id, int page){
		String url = "ajax.php?action=forum&type=viewthread&threadid=" + id
			+ "&page=" + page + "&auth=" + MySoup.getAuthKey();
		ForumThread thread = (ForumThread)MySon.toObject(url, ForumThread.class);
		if (thread != null){
			thread.id = id;
			thread.page = page;
		}
		return thread;
	}

	/**
	 * Get the first page of a forum thread
	 *
	 * @param id   the thread id
	 */
	public static ForumThread thread(int id){
		return thread(id, 1);
	}

	/**
	 * Get the forum thread viewing the page containing the post
	 *
	 * @param id     the thread id
	 * @param postId the post id of the post to view
	 */
	public static ForumThread threadAtPost(int id, int postId){
		String url = "ajax.php?action=forum&type=viewthread&threadid=" + id
			+ "&postid=" + postId + "&auth=" + MySoup.getAuthKey();
		ForumThread thread = (ForumThread)MySon.toObject(url, ForumThread.class);
		if (thread != null && thread.getStatus()){
			thread.id = id;
			thread.page = thread.getResponse().getCurrentPage().intValue();
		}
		return thread;
	}

	/**
	 * Check if a next page of results is available
	 *
	 * @return True if a next page is available
	 */
	public boolean hasNextPage(){
		return response.getCurrentPage() != null && response.getCurrentPage().intValue() < response.getPages().intValue();
	}

	/**
	 * Get the next page of search results. Returns null if there is
	 * no next page
	 *
	 * @return the next page of search results
	 */
	public ForumThread nextPage(){
		return hasNextPage() ? thread(id, page + 1) : null;
	}

	/**
	 * Check if a previous page of results is available
	 *
	 * @return True if a previous page is available
	 */
	public boolean hasPreviousPage(){
		return response.getCurrentPage() != null && response.getCurrentPage().intValue() > 1;
	}

	/**
	 * Get the previous page of search results. Returns null if there is
	 * no previous page
	 *
	 * @return the previous page of search results
	 */
	public ForumThread previousPage(){
		return hasPreviousPage() ? thread(id, page - 1) : null;
	}

	/**
	 * Get the thread URL
	 *
	 * @return the thread URL
	 */
	public String getUrl(){
		return "forums.php?action=viewthread&threadid=" + id + "&page=" + page;
	}

	/**
	 * Post a reply to a thread
	 *
	 * @param id        thread id of the thread to post too
	 * @param body      the body text of the post to make
	 * @param subscribe if we want to subscribe to thread as well
	 * @return true if successful
	 */
	public static boolean postReply(int id, String body, boolean subscribe){
		if (body.length() > 0){
			try {
				String url = "forums.php?action=new&forumid=" + id;
				List<Tuple<String, String>> list = new ArrayList<Tuple<String, String>>();
				list.add(new Tuple<String, String>("action", "reply"));
				list.add(new Tuple<String, String>("auth", MySoup.getAuthKey()));
				list.add(new Tuple<String, String>("thread", String.valueOf(id)));
				list.add(new Tuple<String, String>("body", body));
				if (subscribe){
					list.add(new Tuple<String, String>("subscribe", "checked"));
				}
				MySoup.postMethod(url, list);
			}
			catch (CouldNotLoadException e){
				e.printStackTrace();
				return false;
			}
			return true;
		}
		return false;
	}

	/**
	 * Post a reply to this thread
	 *
	 * @param body      body text to post
	 * @param subscribe if we should subscribe to the thread
	 * @return true if successful
	 */
	public boolean postReply(String body, boolean subscribe){
		return postReply(id, body, subscribe);
	}

	/**
	 * Subscribe to the ForumThread
	 *
	 * @return true if successful
	 */
	public boolean subscribe(){
		return getResponse().isSubscribed() || subscribe(id);
	}

	public static boolean subscribe(int thread){
		return MySoup.pressLink("userhistory.php?action=thread_subscribe&topicid=" + thread + "&auth=" + MySoup.getAuthKey());
	}

	/**
	 * Unsubscribe from the ForumThread
	 *
	 * @return true if successful
	 */
	public boolean unsubscribe(){
		return !getResponse().isSubscribed() || unsubscribe(id);
	}

	public static boolean unsubscribe(int thread){
		return MySoup.pressLink("userhistory.php?action=thread_subscribe&topicid=" + thread + "&auth=" + MySoup.getAuthKey());
	}

	/**
	 * Get the API response
	 *
	 * @return the API response
	 */
	public Response getResponse(){
		return response;
	}

	/**
	 * Get the status of the API response
	 *
	 * @return True if successful
	 */
	public boolean getStatus(){
		return status.equalsIgnoreCase("success");
	}

	public String getError(){
		return error;
	}

	/**
	 * Get the thread id
	 *
	 * @return the thread id
	 */
	public int getId(){
		return id;
	}

	/**
	 * Get the page number being viewed
	 *
	 * @return the page number
	 */
	public int getPage(){
		return page;
	}

	/**
	 * Get the number of pages
	 */
	public int getPages(){
		return response.getPages().intValue();
	}

	@Override
	public String toString(){
		return "ForumThread [id=" + id + ", page=" + page + "  hasNextPage=" + hasNextPage()
			+ ", hasPreviousPage=" + hasPreviousPage() + ", getUrl=" + getUrl()
			+ ", getResponse=" + getResponse() + ", getStatus=" + getStatus() + "]";
	}
}


text:
package com.consol.citrus.config.xml.parser;

import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * @author Christoph Deppisch
 */
public class GroovyScriptMessageBuilderParserTest {

    @Test
    public void shouldLookupTestConfigParser() {
        Assert.assertTrue(CitrusXmlConfigParser.lookup("script").containsKey("groovy"));
        Assert.assertEquals(CitrusXmlConfigParser.lookup("script").get("groovy").getClass(), GroovyScriptMessageBuilderParser.class);

        Assert.assertTrue(CitrusXmlConfigParser.lookup("script", "groovy").isPresent());
    }

}


text:
module.exports = {
   databaseName: "ChocolateDB",
   username: "WillieWonka",
   password: "Snozberries"
};


text:
#ifndef DEF_H
#define DEF_H
#ifdef CLANG
//this allows Eigen to compile under -Wall
#pragma clang diagnostic ignored "-Wdeprecated-register"
//Not every function uses the full interface
#pragma clang diagnostic ignored "-Wunused-parameter"
#endif
#ifdef MPI
extern "C"{
#include <mpi.h>
}
#endif
#include <complex>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <memory>
#include <functional>
//some commands to help with effeciency
#ifdef ICC
#define restr restrict
#define ALIGNED(x) __assume_aligned(x, 16)
#define MAKE_ALIGNED __declspec(align(16))
#define PREDICT(x, val) __builtin_expect(x, val)
#define PREFETCH(x)
#endif

#ifdef CLANG
#define restr __restrict__
#define ALIGNED(x)
#define PREDICT(x, val) x
#define MAKE_ALIGNED alignas(16)
#define PREFETCH(x)
#endif

#ifdef GCC
#define restr __restrict__
#define ALIGNED(x)
#define PREDICT(x, val) __builtin_expect(x, val)
#define MAKE_ALIGNED
#define alignas(x)
#define PREFETCH(x)
#endif
class item;
typedef std::complex<double> comp;
const static comp Id = comp(0, 1);
//#define NUM_TIME_STEPS (256) //number of time points
//#define LENGTH_T (60) //length of t-domain
//parameters taken from matlab main file
//can move to input parameters as well
//but for now these are defines
constexpr double D =-.4;
constexpr double K =(.1);
constexpr double A =(2.0/3.0);
constexpr double B =(1.0/3.0); //need to find a real value for this
constexpr double tau= (.1);
constexpr double Gamma= (.1);
constexpr double RTlength= (1.5);
constexpr double PI =(3.14159);
class item;
class _fatal{
    public:
        _fatal(){};
};
class _warning{
    public:
        _warning(){};
};
const static _fatal FATAL_ERROR;
const static _warning WARNING;
//don't add an exit procedure more than 2^31 times or else interger overflow will get you...
/*!Adds a procedure to be called upon program abortion. The functions are called in the order inserted,
 * and the engine always inserts a destructor after initializing every class.
 *
 * Don't treat this function like a destructor, it is only for things that are run
 * when a fatal error has occured (such as aborting mpi, writing held data, etc)
 * not for calling delete on some pointers
 *
 */
int add_exit_procedure(const std::function<void()>& fnc);

void remove_exit_procedure(int id);
void err(std::string message, std::string function, std::string file, _fatal f);
void err(std::string message, std::string function, std::string file, _warning w);
void err(std::string message, std::string function, std::string file, const item* p, _fatal f);
void err(std::string message, std::string function, std::string file, const item* p, _warning f);
void err(std::string message, std::string function, std::string file, std::shared_ptr<item> p, _fatal f);
void err(std::string message, std::string function, std::string file, std::shared_ptr<item> p, _warning f);

void trim(std::string& curline, const std::string& val = "\n\r\t ");
void ltoken(std::string& tok, std::string& str, std::string delim=" ");
std::string get_unique_name(std::string base = "");
#endif


text:
<?php

namespace app\modules\admin;

use yii\web\AssetBundle;

class AdminModule extends \yii\base\Module
{
    public $controllerNamespace = 'app\modules\admin\controllers';

    public function init()
    {
        parent::init();

        $this->setAliases([
            '@AppAssetAdmin' => __DIR__ . '/assets'
        ]);

    }
}


text:
  <input type="radio" ng-model="bounty.bounty_expiration" value="3" />
  3 months

  <input type="radio" ng-model="bounty.bounty_expiration" value="6" />
  6 months

  <input type="radio" ng-model="bounty.bounty_expiration" value="never" />
  Never Expire


text:
var request = require('request');
var inspect = require('util').inspect;
request(
	'http://localhost:4001/redirect',
	function(err, res, body) {
		if (err) { throw err; }
		console.log(inspect({
		err: err,
		res: {
			statusCode: res.statusCode
		},
		body: JSON.parse(body)
	}))
});


text:
package core.aws.local.ec2;

import core.aws.env.Environment;
import core.aws.local.DependencyResolvers;
import core.aws.local.LocalResourceLoader;
import core.aws.local.ResourceNode;
import core.aws.resource.Resources;
import core.aws.resource.ec2.InstanceProfile;
import core.aws.util.Files;

/**
 * @author neo
 */
public class InstanceProfileLoader implements LocalResourceLoader {
    @Override
    public void load(ResourceNode node, Resources resources, DependencyResolvers resolvers, Environment env) {
        final InstanceProfile instanceProfile = resources.add(new InstanceProfile(node.id));
        instanceProfile.name = env.name + "-" + node.id;
        instanceProfile.policy = Files.text(env.envDir.resolve(node.requiredString("policy")));
    }
}


text:
"""

"""

__version__='90.12.4.0.dev1'

import warnings
warnings.filterwarnings("ignore")

import sys
import logging

import pandas as pd
import geopandas

import matplotlib.pyplot as plt
import matplotlib
from matplotlib import cm

import contextily as cx

logger = logging.getLogger('PT3S')
if __name__ == "__main__":
    logger.debug("{0:s}{1:s}".format('in MODULEFILE: __main__ Context:','.'))
else:
    logger.debug("{0:s}{1:s}{2:s}{3:s}".format('in MODULEFILE: Not __main__ Context: ','__name__: ',__name__," ."))

class NFDError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

class NFD():

    """
    Raises:
        NFDError
    """

    def __init__(self):
        self.name = 'NFD'

    def plotNFD( gdf_FWVB
                ,gdf_ROHR

                # Layout FWVB

                ,colors_FWVB = ['green', 'red']
                ,color_FWVB_under = 'green'
                ,color_FWVB_over = 'red'

                ,cmap_color_FWVB = 'W0'
                ,norm_min_FWVB = None
                ,norm_max_FWVB = None

                ,FWVB_markerscaling_col = 'W0'
                ,FWVB_markerscaling_fac = 0.3

                ,FWVB_edgecolor = 'White'

                # Layout ROHR

                ,colors_ROHR = ['lightgray', 'dimgray']
                ,color_ROHR_under = 'magenta'
                ,color_ROHR_over = 'lime'

                ,cmap_color_ROHR = 'DI'
                ,norm_min_ROHR = None
                ,norm_max_ROHR = None

                ,ROHR_linewidth_col = 'DI'
                ,ROHR_linewidth_fac =  0.005

                # Legend FWVB

                ,legend_FWVB_label = None
                ,legend_FWVB_label_shrink = 1.

                ,yTicks = None
                ,yTickLabels = None

                # Karte
                ,LabelsOnTop = False
                ,Map_resolution = 15

                ):

        """
        Die Funktion plottet FWVB und ROHRe auf Hintergrundkarte.
        """

        logStr = "{0:s}.{1:s}: ".format(__name__, sys._getframe().f_code.co_name)
        logger.debug("{0:s}{1:s}".format(logStr,'Start.'))

        fig = plt.gcf()
        ax = plt.gca()

        #Erstellen der Colormap fuer die FWVB
        # ---
        if norm_min_FWVB == None:
            norm_min_FWVB=gdf_FWVB[cmap_color_FWVB].min()
        if norm_max_FWVB == None:
            norm_max_FWVB=gdf_FWVB[cmap_color_FWVB].max()
        norm_FWVB_color = plt.Normalize(vmin=norm_min_FWVB, vmax=norm_max_FWVB)
        cmap_FWVB = matplotlib.colors.LinearSegmentedColormap.from_list('FWVB', colors_FWVB, N = 256)
        cmap_FWVB.set_under(color_FWVB_under)
        cmap_FWVB.set_over(color_FWVB_over)

        # fuer u.a. Linienstaerke des Markers
        norm_FWVB_size = plt.Normalize(vmin = gdf_FWVB[FWVB_markerscaling_col].min(), vmax = gdf_FWVB[FWVB_markerscaling_col].max()) #Festlegen wie diese Spalte normiert werden soll

        #Erstellen der Colormap fuer die Rohre
        # ---
        if norm_min_ROHR == None:
            norm_min_ROHR=gdf_ROHR[cmap_color_ROHR].min()
        if norm_max_ROHR == None:
            norm_max_ROHR=gdf_ROHR[cmap_color_ROHR].max()
        norm_ROHR_color = plt.Normalize(vmin=norm_min_ROHR, vmax=norm_max_ROHR)
        cmap_ROHR = matplotlib.colors.LinearSegmentedColormap.from_list('ROHR', colors_ROHR, N = 256)
        cmap_ROHR.set_under(color_ROHR_under)
        cmap_ROHR.set_over(color_ROHR_over)

        try:
            gdf_FWVB.plot(ax = ax
                        ,marker = '.'
                        ,markersize = gdf_FWVB[FWVB_markerscaling_col] * FWVB_markerscaling_fac #Markersize ist abhaengig von der zum Markerscaling ausgewaehlten Spalte und einem Faktor
                        ,c = cmap_FWVB(norm_FWVB_color(gdf_FWVB[cmap_color_FWVB])) #Einfaerben der Marker entsprechend der definierten Colormap und ausgewaehlten Spalte
                        ,edgecolor = FWVB_edgecolor #FWVB Randfarbe des Markers
                        ,linewidth = norm_FWVB_size(gdf_FWVB[FWVB_markerscaling_col]) / 2 #FWVB Randdicke, abhaengig von der zum Markerscaling ausgewaehlten Spalte. Die Randdicke wird im Anschluss nochmal durch 2 geteilt.
                        ,alpha =  0.9 - (norm_FWVB_size(gdf_FWVB[FWVB_markerscaling_col]) / 2) #FWVB Durchsichtigkeit, abhaengig von der zum Markerscaling ausgewaehlten Spalte. Mit dem Teilen durch 2 ist die maximale Durchsichtigkeit bei 0.5 (0 bei Kleinen-0.5 bei Grossen). Um dies umzudrehen zieht man von 1 ab. Hier wird von 0.9 abgezogen. Damit sind kleinsten FWVB immer noch leicht durchsichtig und die Groessten trotzdem noch erkennbar (0.9 bei Kleinen - 0.4 bei Grossen)
                        ,zorder = 2) #Reihenfolge zu den anderen geploteten Objekten (je hoeher die Zahl, desto hoeher die geplottete Ebene; Hoehe im Sinne von Vorder- und Hintergrund)

            #if Anzeigen_ROHR:

            #    if ROHR_Ampel:
            gdf_ROHR.plot(ax = ax
                                    ,zorder = 1
                                    ,linewidth = gdf_ROHR[ROHR_linewidth_col] * ROHR_linewidth_fac
                                    ,color = cmap_ROHR(norm_ROHR_color(gdf_ROHR[cmap_color_ROHR])))

            #    else:
            #        gdf_ROHR.plot(ax = ax
            #                        ,zorder = 1
            #                        ,linewidth = gdf_ROHR[column_ROHR_Dicke] * ROHR_dicke
            #                        ,color = color_ROHR)

            if LabelsOnTop:
                cx.add_basemap(ax, crs=gdf_FWVB.crs.to_string(), source = cx.providers.CartoDB.PositronNoLabels, zoom = Map_resolution)
                cx.add_basemap(ax, crs=gdf_FWVB.crs.to_string(), source = cx.providers.CartoDB.PositronOnlyLabels, zoom = Map_resolution)
            else:
                cx.add_basemap(ax, crs=gdf_FWVB.crs.to_string(), source = cx.providers.CartoDB.Positron, zoom = Map_resolution)

            if legend_FWVB_label == None:
                legend_FWVB_label=cmap_color_FWVB

            cbar=fig.colorbar(cm.ScalarMappable(norm = norm_FWVB_color, cmap = cmap_FWVB)
                        ,ax = ax
                        ,label = legend_FWVB_label
                        ,shrink = legend_FWVB_label_shrink
                        ,ticks=yTicks
                        ,pad = 0.01)
            if yTickLabels != None:
                cbar.ax.set_yticklabels(yTickLabels)

            plt.axis('off')

        except NFDError:
            raise
        except Exception as e:
            logStrFinal="{:s}Exception: Line: {:d}: {!s:s}: {:s}".format(logStr,sys.exc_info()[-1].tb_lineno,type(e),str(e))
            logger.error(logStrFinal)
            raise NFDError(logStrFinal)
        finally:
            logger.debug("{0:s}{1:s}".format(logStr,'_Done.'))
            return


text:
package com.google.template.soy.soytree;

import static com.google.template.soy.soytree.TemplateSubject.assertThatTemplateContent;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Tests for {@link ForNode}.
 *
 * @author brndn@google.com (Brendan Linn)
 */
@RunWith(JUnit4.class)
public final class ForNodeTest {

  @Test
  public void testInvalidForeachUsage() {
    assertThatTemplateContent("{for $x in $var}{/for}")
        .causesError("Invalid 'for' command text")
        .at(1, 1);
  }

  @Test
  public void testForRangeOutOfRange() {
    assertThatTemplateContent("{for $x in range(2147483648, 2147483649, 2147483650)}{/for}")
        .causesError("Range specification is too large: 2,147,483,648")
        .causesError("Range specification is too large: 2,147,483,649")
        .causesError("Range specification is too large: 2,147,483,650")
        .at(1, 1);
  }
}


text:
import { findIndex } from "../index";
export = findIndex;


text:
export const defaultState = {
    selected_card_ids: [],
    toggle: false
};

export default function reducer(state = defaultState, action) {
    switch (action.type) {
        case "CARD_ID_FILTER_ADD":
            const currentCardIds = [...state.selected_card_ids];

            // prevent duplicates
            if (!currentCardIds.includes(action.payload.card_id)) {
                currentCardIds.push(action.payload.card_id);
            }

            return {
                ...state,
                selected_card_ids: currentCardIds
            };

        case "CARD_ID_FILTER_REMOVE":
            const currentCardIds2 = [...state.selected_card_ids];

            const removeIndex = currentCardIds2.findIndex(cardId => cardId === action.payload.card_id);
            if (removeIndex === -1) return state;

            currentCardIds2.splice(removeIndex, 1);

            return {
                ...state,
                selected_card_ids: currentCardIds2
            };

        case "CARD_ID_FILTER_TOGGLE":
            return {
                ...state,
                toggle: !state.toggle
            };

        case "CARD_ID_FILTER_CLEAR":
        case "GENERAL_FILTER_RESET":
            return {
                ...defaultState
            };
    }
    return state;
}


text:
require File.expand_path('../../spec_helper', __FILE__)

describe PasswordsController do
  render_views

  before(:each) do
    generate_default_settings_with_mocks
  end

  describe "Reset password" do
    before(:each) do
      @forgetful_user = FactoryBot.create(:user, :login => "forgetful_jones", :password => "password", :password_confirmation => "password", :email => "valid@test.com")

      @params = { :login => @forgetful_user.login }

      # Stub User.find_by_login because of an rspec-related bug using the dynamic finder
      allow(User).to receive(:find_by_login) do |*login|
        User.where(login: login).first
      end

    end

    describe "security questions" do
      before(:each) do
        Array.new(3) { |i| SecurityQuestion.create({ :question => "test #{i}", :answer => "test" }) }.each { |q| @forgetful_user.security_questions << q }

        @questions_params = {
          :user_id => @forgetful_user.id
        }

        @answers_params = {
          :user_id => @forgetful_user.id,
          :security_questions => {
            :question0 => { :id => @forgetful_user.security_questions[0].id, :answer => "test" },
            :question1 => { :id => @forgetful_user.security_questions[1].id, :answer => "test" },
            :question2 => { :id => @forgetful_user.security_questions[2].id, :answer => "test" },
          }
        }
      end

      it "will ask the correct security questions" do
        post :questions, params: @questions_params

        @forgetful_user.security_questions.each do |q|
          expect(@response.body).to include(q.question)
        end
      end

      it "will allow the user to reset their password if they answer their questions correctly" do
        post :check_questions, params: @answers_params

        password = assigns[:password]
        expect(password).not_to be_nil
        expect(@response).to redirect_to(change_password_path(password.reset_code))
      end

      it "will reject incorrect answers" do
        @answers_params[:security_questions][:question2][:answer] = "wrong"

        post :check_questions, params: @answers_params

        expect(@response).to redirect_to(password_questions_path(@forgetful_user))
        expect(flash['error']).not_to be_nil
      end

      it "will raise an error if the user submits an answer to a question that does not belong to the current user" do
        # This is evidence of tampering, so we want to make sure it doesn't get through
        @answers_params[:security_questions][:question2][:id] += 500

        post :check_questions, params: @answers_params
        expect(response.status).to eq(404)
      end
    end
  end

  # TODO: auto-generated
  describe '#login' do
    it 'GET login' do
      get :login

      expect(response).to have_http_status(:ok)
    end
  end

  # TODO: auto-generated
  describe '#questions' do
    it 'GET questions' do
      get :questions, params: { user_id: 0 }

      expect(response).to have_http_status(:not_found)
    end
  end

  # TODO: auto-generated
  describe '#reset' do
    it 'GET reset' do
      get :reset, params: { reset_code: 'test' }

      expect(response).to have_http_status(:redirect)
    end
  end

  # TODO: auto-generated
  describe '#update_users_password' do
    xit 'GET update_users_password' do
      get :update_users_password, params: { user_reset_password: { password: 'password' } }

      expect(response).to have_http_status(:ok)
    end
  end

  # TODO: auto-generated
  describe '#update' do
    it 'PATCH update' do
      put :update, params: { id: 1 }

      expect(response).to have_http_status(:not_found)
    end
  end

end


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using Azuria.Api.v1.DataModels.User;
using Azuria.Api.v1.Input.User;
using Azuria.Authentication;
using Azuria.ErrorHandling;
using Azuria.Middleware;
using Azuria.Requests.Builder;
using Azuria.Test.Core.Helpers;
using Moq;
using NUnit.Framework;

namespace Azuria.Test.Authentication
{
    [TestFixture]
    public class DefaultLoginManagerTest
    {
        private const string LoginTokenHeaderName = "proxer-api-token";

        [Test]
        public void AddAuthenticationInformation_AddsCorrectInfosTest()
        {
            IProxerClient client = ProxerClient.Create(new char[32]);

            char[] loginToken = RandomHelper.GetRandomString(255).ToCharArray();
            var defaultLoginManager = new DefaultLoginManager(client, loginToken);

            IRequestBuilder request = new RequestBuilder(new Uri("http://proxer.me/api"), client).WithLoginCheck();
            bool added = defaultLoginManager.AddAuthenticationInformation(request);
            Assert.True(added);
            Assert.True(request.Headers.ContainsKey(LoginTokenHeaderName));
            Assert.AreEqual(loginToken.ToString(), request.Headers[LoginTokenHeaderName]);
        }

        [Test]
        public void AddAuthenticationInformation_SkipsIfLoginNotNeededTest()
        {
            IProxerClient client = ProxerClient.Create(new char[32]);

            char[] loginToken = RandomHelper.GetRandomString(255).ToCharArray();
            var defaultLoginManager = new DefaultLoginManager(client, loginToken);

            IRequestBuilder request = new RequestBuilder(new Uri("http://proxer.me/api"), client).WithLoginCheck(false);
            bool added = defaultLoginManager.AddAuthenticationInformation(request);
            Assert.False(added);
            Assert.False(request.Headers.ContainsKey(LoginTokenHeaderName));
        }

        [Test]
        public void AddAuthenticationInformation_SkipsIfRequestContainsAuthInfosTest()
        {
            IProxerClient client = ProxerClient.Create(new char[32]);

            char[] loginToken = RandomHelper.GetRandomString(255).ToCharArray();
            var defaultLoginManager = new DefaultLoginManager(client, loginToken);

            IRequestBuilder request =
                new RequestBuilder(new Uri("http://proxer.me/api"), client)
                    .WithLoginCheck(false)
                    .WithHeader(LoginTokenHeaderName, "token");
            bool added = defaultLoginManager.AddAuthenticationInformation(request);
            Assert.False(added);
            Assert.True(request.Headers.ContainsKey(LoginTokenHeaderName));
            Assert.AreEqual("token", request.Headers[LoginTokenHeaderName]);
        }

        [Test]
        public void AddAuthenticationInformation_SkipsIfTokenInvalidTest()
        {
            IProxerClient client = ProxerClient.Create(new char[32]);

            char[] loginToken = RandomHelper.GetRandomString(42).ToCharArray();
            var defaultLoginManager = new DefaultLoginManager(client, loginToken);

            IRequestBuilder request = new RequestBuilder(new Uri("http://proxer.me/api"), client).WithLoginCheck();
            bool added = defaultLoginManager.AddAuthenticationInformation(request);
            Assert.False(added);
            Assert.False(request.Headers.ContainsKey(LoginTokenHeaderName));

            defaultLoginManager = new DefaultLoginManager(client);

            added = defaultLoginManager.AddAuthenticationInformation(request);
            Assert.False(added);
            Assert.False(request.Headers.ContainsKey(LoginTokenHeaderName));
        }

        [Test]
        public void ContainsAuthenticationInformationTest()
        {
            IProxerClient client = ProxerClient.Create(new char[32]);
            var loginManager = new DefaultLoginManager(client, RandomHelper.GetRandomString(255).ToCharArray());
            var request = new RequestBuilder(new Uri("https://proxer.me/api"), client);

            Assert.False(loginManager.ContainsAuthenticationInformation(request));
            request.WithHeader("proxer-api-token", loginManager.LoginToken.ToString());
            Assert.True(loginManager.ContainsAuthenticationInformation(request));
        }

        [Test]
        public void InvalidateLoginTest()
        {
            IProxerClient client = ProxerClient.Create(new char[32]);
            DefaultLoginManager loginManager = CreateLoggedInManager(new char[255], client);

            IRequestBuilder request = new RequestBuilder(new Uri("https://proxer.me/api"), client).WithLoginCheck();
            Assert.False(loginManager.AddAuthenticationInformation(request));
            Assert.True(loginManager.IsLoginProbablyValid());
            loginManager.InvalidateLogin();
            Assert.True(loginManager.AddAuthenticationInformation(request));
            Assert.False(loginManager.IsLoginProbablyValid());
        }

        [Test]
        public void IsLoginProbablyValid_InvalidIfLoginNeverPerformedTest()
        {
            IProxerClient client = ProxerClient.Create(new char[32]);
            var loginManager = new DefaultLoginManager(client, new char[255]);

            Assert.False(loginManager.IsLoginProbablyValid());
        }

        [Test]
        public void IsLoginProbablyValid_ValidIfJustLoggedInTest()
        {
            //TODO: The other cases are hard to test. Maybe search for a package on github that helps with DateTime manipulation?
            IProxerClient client = ProxerClient.Create(new char[32]);
            DefaultLoginManager loginManager = CreateLoggedInManager(new char[255], client);

            Assert.True(loginManager.IsLoginProbablyValid());
        }

        [Test]
        public async Task PerformLoginTest()
        {
            // Mock of a middleware that returns a successful response
            var middlewareMock = new Mock<IMiddleware>();

            var successDataModel = new LoginDataModel
            {
                UserId = 1,
                Token = RandomHelper.GetRandomString(255)
            };
            middlewareMock
                .Setup(middleware => middleware.InvokeWithResult(It.IsAny<IRequestBuilderWithResult<LoginDataModel>>(),
                    It.IsAny<MiddlewareAction<LoginDataModel>>(), It.IsAny<CancellationToken>()))
                .ReturnsAsync(() => new ProxerResult<LoginDataModel>(successDataModel));

            CancellationToken cancellationToken = new CancellationTokenSource().Token;
            IProxerClient client = ProxerClient.Create(new char[32],
                options => options.Pipeline = new Pipeline(new[] {middlewareMock.Object}));
            var loginManager = new DefaultLoginManager(client);

            IProxerResult<LoginDataModel> result = await loginManager.PerformLoginAsync(
                new LoginInput("username", "password"), cancellationToken
            );
            Assert.True(result.Success);
            Assert.IsEmpty(result.Exceptions);

            Assert.AreEqual(successDataModel.Token, loginManager.LoginToken);
            Assert.True(loginManager.IsLoginProbablyValid());
        }

        [Test]
        public async Task PerformLoginWith2FaTokenTest()
        {
            // Mock of a middleware that returns a successful response
            var middlewareMock = new Mock<IMiddleware>();

            var successDataModel = new LoginDataModel
            {
                UserId = 1,
                Token = RandomHelper.GetRandomString(255)
            };
            middlewareMock
                .Setup(middleware => middleware.InvokeWithResult(It.IsAny<IRequestBuilderWithResult<LoginDataModel>>(),
                    It.IsAny<MiddlewareAction<LoginDataModel>>(), It.IsAny<CancellationToken>()))
                .ReturnsAsync(() => new ProxerResult<LoginDataModel>(successDataModel));

            // Begin tests
            CancellationToken cancellationToken = new CancellationTokenSource().Token;
            IProxerClient client = ProxerClient.Create(new char[32],
                options => options.Pipeline = new Pipeline(new[] {middlewareMock.Object}));
            var loginManager = new DefaultLoginManager(client);

            IProxerResult<LoginDataModel> result = await loginManager.PerformLoginAsync(
                new LoginInput("username", "password", new string(new char[6])),
                cancellationToken
            );
            Assert.True(result.Success);
            Assert.IsEmpty(result.Exceptions);

            Assert.AreEqual(successDataModel.Token, loginManager.LoginToken);
            Assert.True(loginManager.IsLoginProbablyValid());
        }

        [Test]
        public async Task PerformLogoutTest()
        {
            // Mock of a middleware that returns a successful response
            var middlewareMock = new Mock<IMiddleware>();

            var successDataModel = new LoginDataModel
            {
                UserId = 1,
                Token = RandomHelper.GetRandomString(255)
            };
            middlewareMock
                .Setup(middleware => middleware.Invoke(It.IsAny<IRequestBuilder>(),
                    It.IsAny<MiddlewareAction>(), It.IsAny<CancellationToken>()))
                .ReturnsAsync(() => new ProxerResult());

            // Begin tests
            CancellationToken cancellationToken = new CancellationTokenSource().Token;
            IProxerClient client = ProxerClient.Create(new char[32],
                options => options.Pipeline = new Pipeline(new[] {middlewareMock.Object}));
            var loginManager = new DefaultLoginManager(client);

            IProxerResult result = await loginManager.PerformLogoutAsync(cancellationToken);
            Assert.True(result.Success);
            Assert.IsEmpty(result.Exceptions);

            Assert.Null(loginManager.LoginToken);
            Assert.False(loginManager.IsLoginProbablyValid());
        }

        [Test]
        public void UpdateTest()
        {
            IProxerClient client = ProxerClient.Create(new char[32]);
            var loginManager = new DefaultLoginManager(client, new char[255]);
            Assert.False(loginManager.IsLoginProbablyValid());

            var request = new RequestBuilder(new Uri("http://proxer.me/api"), client);

            // request does not contain any login information and the login manager was not logged in
            // => the login manager is still not logged in
            loginManager.Update(request, new ProxerResult());
            Assert.False(loginManager.IsLoginProbablyValid());

            bool added = loginManager.AddAuthenticationInformation(request.WithLoginCheck());
            Assert.True(added);

            loginManager.Update(request, new ProxerResult());
            Assert.True(loginManager.IsLoginProbablyValid());
        }

        private static DefaultLoginManager CreateLoggedInManager(char[] loginToken, IProxerClient client)
        {
            var loginManager = new DefaultLoginManager(client, loginToken);
            IRequestBuilder request = new RequestBuilder(new Uri("http://proxer.me/api"), client).WithLoginCheck();
            loginManager.AddAuthenticationInformation(request);
            loginManager.Update(request, new ProxerResult());

            return loginManager;
        }

        // Returns the first instance from the pipeline or null
        private static DefaultLoginManager TryFindLoginManager(IPipeline pipeline)
        {
            foreach (IMiddleware middleware in pipeline.Middlewares)
                if (middleware is LoginMiddleware loginMiddleware)
                    if (loginMiddleware.LoginManager is DefaultLoginManager instance)
                        return instance;

            return null;
        }
    }
}


text:
createdb safecity -T template_postgis
./manage syncdb
./manage load_srids
./manage load_centerline -t
./manage load_aliases


text:
package com.graphhopper.routing;

import com.graphhopper.routing.weighting.BeelineWeightApproximator;
import com.graphhopper.routing.weighting.WeightApproximator;
import com.graphhopper.routing.weighting.Weighting;
import com.graphhopper.storage.Graph;
import com.graphhopper.storage.NodeAccess;
import com.graphhopper.util.Helper;
import com.graphhopper.util.PMap;

import static com.graphhopper.util.Parameters.Algorithms.*;
import static com.graphhopper.util.Parameters.Algorithms.AltRoute.*;

/**
 * A simple factory creating normal algorithms (RoutingAlgorithm) without preparation.
 * <p>
 *
 * @author Peter Karich
 */
public class RoutingAlgorithmFactorySimple implements RoutingAlgorithmFactory {
    @Override
    public RoutingAlgorithm createAlgo(Graph g, AlgorithmOptions opts) {
        RoutingAlgorithm ra;
        String algoStr = opts.getAlgorithm();
        Weighting weighting = g.wrapWeighting(opts.getWeighting());
        if (DIJKSTRA_BI.equalsIgnoreCase(algoStr)) {
            ra = new DijkstraBidirectionRef(g, weighting, opts.getTraversalMode());
        } else if (DIJKSTRA.equalsIgnoreCase(algoStr)) {
            ra = new Dijkstra(g, weighting, opts.getTraversalMode());

        } else if (ASTAR_BI.equalsIgnoreCase(algoStr) || Helper.isEmpty(algoStr)) {
            AStarBidirection aStarBi = new AStarBidirection(g, weighting,
                    opts.getTraversalMode());
            aStarBi.setApproximation(getApproximation(ASTAR_BI, opts.getHints(), weighting, g.getNodeAccess()));
            ra = aStarBi;

        } else if (DIJKSTRA_ONE_TO_MANY.equalsIgnoreCase(algoStr)) {
            ra = new DijkstraOneToMany(g, weighting, opts.getTraversalMode());

        } else if (ASTAR.equalsIgnoreCase(algoStr)) {
            AStar aStar = new AStar(g, weighting, opts.getTraversalMode());
            aStar.setApproximation(getApproximation(ASTAR, opts.getHints(), opts.getWeighting(), g.getNodeAccess()));
            ra = aStar;

        } else if (ALT_ROUTE.equalsIgnoreCase(algoStr)) {
            AlternativeRoute altRouteAlgo = new AlternativeRoute(g, weighting, opts.getTraversalMode());
            altRouteAlgo.setMaxPaths(opts.getHints().getInt(MAX_PATHS, 2));
            altRouteAlgo.setMaxWeightFactor(opts.getHints().getDouble(MAX_WEIGHT, 1.4));
            altRouteAlgo.setMaxShareFactor(opts.getHints().getDouble(MAX_SHARE, 0.6));
            altRouteAlgo.setMinPlateauFactor(opts.getHints().getDouble("alternative_route.min_plateau_factor", 0.2));
            altRouteAlgo.setMaxExplorationFactor(opts.getHints().getDouble("alternative_route.max_exploration_factor", 1));
            ra = altRouteAlgo;

        } else {
            throw new IllegalArgumentException("Algorithm " + algoStr + " not found in " + getClass().getName());
        }

        ra.setMaxVisitedNodes(opts.getMaxVisitedNodes());
        return ra;
    }

    public static WeightApproximator getApproximation(String prop, PMap opts, Weighting weighting, NodeAccess na) {
        String approxAsStr = opts.getString(prop + ".approximation", "BeelineSimplification");
        double epsilon = opts.getDouble(prop + ".epsilon", 1);

        BeelineWeightApproximator approx = new BeelineWeightApproximator(na, weighting);
        approx.setEpsilon(epsilon);
        if ("BeelineSimplification".equals(approxAsStr))
            approx.setDistanceCalc(Helper.DIST_PLANE);
        else if ("BeelineAccurate".equals(approxAsStr))
            approx.setDistanceCalc(Helper.DIST_EARTH);
        else
            throw new IllegalArgumentException("Approximation " + approxAsStr + " not found in " + RoutingAlgorithmFactorySimple.class.getName());

        return approx;
    }
}


text:
namespace Microsoft.Azure.Management.HealthcareApis.Models
{
    using Microsoft.Rest;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Setting indicating whether the service has a managed identity
    /// associated with it.
    /// </summary>
    public partial class ServiceManagedIdentityIdentity
    {
        /// <summary>
        /// Initializes a new instance of the ServiceManagedIdentityIdentity
        /// class.
        /// </summary>
        public ServiceManagedIdentityIdentity()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the ServiceManagedIdentityIdentity
        /// class.
        /// </summary>
        /// <param name="type">Type of identity being specified, currently
        /// SystemAssigned and None are allowed. Possible values include:
        /// 'None', 'SystemAssigned', 'UserAssigned',
        /// 'SystemAssigned,UserAssigned'</param>
        /// <param name="principalId">The service principal ID of the system
        /// assigned identity. This property will only be provided for a system
        /// assigned identity.</param>
        /// <param name="tenantId">The tenant ID of the system assigned
        /// identity. This property will only be provided for a system assigned
        /// identity.</param>
        public ServiceManagedIdentityIdentity(string type, System.Guid? principalId = default(System.Guid?), System.Guid? tenantId = default(System.Guid?), IDictionary<string, UserAssignedIdentity> userAssignedIdentities = default(IDictionary<string, UserAssignedIdentity>))
        {
            Type = type;
            PrincipalId = principalId;
            TenantId = tenantId;
            UserAssignedIdentities = userAssignedIdentities;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets type of identity being specified, currently
        /// SystemAssigned and None are allowed. Possible values include:
        /// 'None', 'SystemAssigned', 'UserAssigned',
        /// 'SystemAssigned,UserAssigned'
        /// </summary>
        [JsonProperty(PropertyName = "type")]
        public string Type { get; set; }

        /// <summary>
        /// Gets the service principal ID of the system assigned identity. This
        /// property will only be provided for a system assigned identity.
        /// </summary>
        [JsonProperty(PropertyName = "principalId")]
        public System.Guid? PrincipalId { get; private set; }

        /// <summary>
        /// Gets the tenant ID of the system assigned identity. This property
        /// will only be provided for a system assigned identity.
        /// </summary>
        [JsonProperty(PropertyName = "tenantId")]
        public System.Guid? TenantId { get; private set; }

        /// <summary>
        /// </summary>
        [JsonProperty(PropertyName = "userAssignedIdentities")]
        public IDictionary<string, UserAssignedIdentity> UserAssignedIdentities { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (Type == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "Type");
            }
        }
    }
}


text:
package org.codehaus.xfire.gen.jsr181;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;

public final class NamespaceUtil {
    private static final Set<String> KEYWORDS = new HashSet<String>(Arrays
        .asList(new String[] {"abstract", "boolean", "break", "byte", "case", "catch", "char", "class",
                              "const", "continue", "default", "do", "double", "else", "extends", "final",
                              "finally", "float", "for", "goto", "if", "implements", "import", "instanceof",
                              "int", "interface", "long", "native", "new", "package", "private", "protected",
                              "public", "return", "short", "static", "strictfp", "super", "switch",
                              "synchronized", "this", "throw", "throws", "transient", "try", "void",
                              "volatile", "while", "true", "false", "null", "assert", "enum"}));

    private NamespaceUtil() {
        // complete
    }

    public static String getPackageName(String nameSpaceURI) {
        int idx = nameSpaceURI.indexOf(':');
        String scheme = "";
        if (idx >= 0) {
            scheme = nameSpaceURI.substring(0, idx);
            if ("http".equalsIgnoreCase(scheme) || "urn".equalsIgnoreCase(scheme)) {
                nameSpaceURI = nameSpaceURI.substring(idx + 1);
            }
        }

        List<String> tokens = tokenize(nameSpaceURI, "/: ");
        if (tokens.size() == 0) {
            return null;
        }

        if (tokens.size() > 1) {
            String lastToken = tokens.get(tokens.size() - 1);
            idx = lastToken.lastIndexOf('.');
            if (idx > 0) {
                lastToken = lastToken.substring(0, idx);
                tokens.set(tokens.size() - 1, lastToken);
            }
        }

        String domain = tokens.get(0);
        idx = domain.indexOf(':');
        if (idx >= 0) {
            domain = domain.substring(0, idx);
        }
        List<String> r = reverse(tokenize(domain, "urn".equals(scheme) ? ".-" : "."));
        if ("www".equalsIgnoreCase(r.get(r.size() - 1))) {
            // remove leading www
            r.remove(r.size() - 1);
        }

        // replace the domain name with tokenized items
        tokens.addAll(1, r);
        tokens.remove(0);

        // iterate through the tokens and apply xml->java name algorithm
        for (int i = 0; i < tokens.size(); i++) {

            // get the token and remove illegal chars
            String token = tokens.get(i);
            token = removeIllegalIdentifierChars(token);

            // this will check for reserved keywords
            if (contiansReservedKeywords(token)) {
                token = '_' + token;
            }

            tokens.set(i, token.toLowerCase());
        }

        // concat all the pieces and return it
        return combine(tokens, '.');
    }

    public static String getNamespace(String packageName) {
        if (packageName == null || packageName.length() == 0) {
            return null;
        }
        StringTokenizer tokenizer = new StringTokenizer(packageName, ".");
        String[] tokens;
        if (tokenizer.countTokens() == 0) {
            tokens = new String[0];
        } else {
            tokens = new String[tokenizer.countTokens()];
            for (int i = tokenizer.countTokens() - 1; i >= 0; i--) {
                tokens[i] = tokenizer.nextToken();
            }
        }
        StringBuffer namespace = new StringBuffer("http://");
        String dot = "";
        for (int i = 0; i < tokens.length; i++) {
            if (i == 1) {
                dot = ".";
            }
            namespace.append(dot + tokens[i]);
        }
        namespace.append('/');
        return namespace.toString();
    }

    private static List<String> tokenize(String str, String sep) {
        StringTokenizer tokens = new StringTokenizer(str, sep);
        List<String> r = new ArrayList<String>();

        while (tokens.hasMoreTokens()) {
            r.add(tokens.nextToken());
        }
        return r;
    }

    private static String removeIllegalIdentifierChars(String token) {
        StringBuffer newToken = new StringBuffer();
        for (int i = 0; i < token.length(); i++) {
            char c = token.charAt(i);

            if (i == 0 && !Character.isJavaIdentifierStart(c)) {
                // prefix an '_' if the first char is illegal
                newToken.append("_" + c);
            } else if (!Character.isJavaIdentifierPart(c)) {
                // replace the char with an '_' if it is illegal
                newToken.append('_');
            } else {
                // add the legal char
                newToken.append(c);
            }
        }
        return newToken.toString();
    }

    private static String combine(List r, char sep) {
        StringBuilder buf = new StringBuilder(r.get(0).toString());

        for (int i = 1; i < r.size(); i++) {
            buf.append(sep);
            buf.append(r.get(i));
        }

        return buf.toString();
    }

    private static <T> List<T> reverse(List<T> a) {
        List<T> r = new ArrayList<T>();

        for (int i = a.size() - 1; i >= 0; i--) {
            r.add(a.get(i));
        }
        return r;
    }

    private static boolean contiansReservedKeywords(String token) {
        return KEYWORDS.contains(token);
    }
}