text:
using System;
using System.Collections.Generic;
using Xunit;

namespace System.Linq.Tests
{
    public class SingleOrDefaultTests : EnumerableTests
    {
        [Fact]
        public void SameResultsRepeatCallsIntQuery()
        {
            var q = from x in new[] { 0.12335f }
                    select x;

            Assert.Equal(q.SingleOrDefault(), q.SingleOrDefault());
        }

        [Fact]
        public void SameResultsRepeatCallsStringQuery()
        {
            var q = from x in new[] { "" }
                    select x;

            Assert.Equal(q.SingleOrDefault(string.IsNullOrEmpty), q.SingleOrDefault(string.IsNullOrEmpty));
        }

        [Fact]
        public void EmptyIList()
        {
            int?[] source = { };
            int? expected = null;

            Assert.Equal(expected, source.SingleOrDefault());
        }

        [Fact]
        public void SingleElementIList()
        {
            int[] source = { 4 };
            int expected = 4;

            Assert.Equal(expected, source.SingleOrDefault());
        }

        [Fact]
        public void ManyElementIList()
        {
            int[] source = { 4, 4, 4, 4, 4 };

            Assert.Throws<InvalidOperationException>(() => source.SingleOrDefault());
        }

        [Fact]
        public void EmptyNotIList()
        {
            IEnumerable<int> source = RepeatedNumberGuaranteedNotCollectionType(0, 0);
            int expected = default(int);

            Assert.Equal(expected, source.SingleOrDefault());
        }

        [Fact]
        public void SingleElementNotIList()
        {
            IEnumerable<int> source = RepeatedNumberGuaranteedNotCollectionType(-5, 1);
            int expected = -5;

            Assert.Equal(expected, source.SingleOrDefault());
        }

        [Fact]
        public void ManyElementNotIList()
        {
            IEnumerable<int> source = RepeatedNumberGuaranteedNotCollectionType(3, 5);

            Assert.Throws<InvalidOperationException>(() => source.SingleOrDefault());
        }

        [Fact]
        public void EmptySourceWithPredicate()
        {
            int[] source = { };
            int expected = default(int);

            Assert.Equal(expected, source.SingleOrDefault(i => i % 2 == 0));
        }

        [Fact]
        public void SingleElementPredicateTrue()
        {
            int[] source = { 4 };
            int expected = 4;

            Assert.Equal(expected, source.SingleOrDefault(i => i % 2 == 0));
        }

        [Fact]
        public void SingleElementPredicateFalse()
        {
            int[] source = { 3 };
            int expected = default(int);

            Assert.Equal(expected, source.SingleOrDefault(i => i % 2 == 0));
        }

        [Fact]
        public void ManyElementsPredicateFalseForAll()
        {
            int[] source = { 3, 1, 7, 9, 13, 19 };
            int expected = default(int);

            Assert.Equal(expected, source.SingleOrDefault(i => i % 2 == 0));
        }

        [Fact]
        public void ManyElementsPredicateTrueForLast()
        {
            int[] source = { 3, 1, 7, 9, 13, 19, 20 };
            int expected = 20;

            Assert.Equal(expected, source.SingleOrDefault(i => i % 2 == 0));
        }

        [Fact]
        public void ManyElementsPredicateTrueForFirstAndFifth()
        {
            int[] source = { 2, 3, 1, 7, 10, 13, 19, 9 };

            Assert.Throws<InvalidOperationException>(() => source.SingleOrDefault(i => i % 2 == 0));
        }

        [Theory]
        [InlineData(1, 100)]
        [InlineData(42, 100)]
        public void FindSingleMatch(int target, int range)
        {
            Assert.Equal(target, Enumerable.Range(0, range).SingleOrDefault(i => i == target));
        }

        [Theory]
        [InlineData(1, 100)]
        [InlineData(42, 100)]
        public void RunOnce(int target, int range)
        {
            Assert.Equal(target, Enumerable.Range(0, range).RunOnce().SingleOrDefault(i => i == target));
        }

        [Fact]
        public void ThrowsOnNullSource()
        {
            int[] source = null;
            Assert.Throws<ArgumentNullException>("source", () => source.SingleOrDefault());
            Assert.Throws<ArgumentNullException>("source", () => source.SingleOrDefault(i => i % 2 == 0));
        }

        [Fact]
        public void ThrowsOnNullPredicate()
        {
            int[] source = { };
            Func<int, bool> nullPredicate = null;
            Assert.Throws<ArgumentNullException>("predicate", () => source.SingleOrDefault(nullPredicate));
        }
    }
}


text:
package org.activiti.examples.bpmn.callactivity;

import static java.util.Collections.singletonMap;
import static org.assertj.core.api.Assertions.assertThat;

import java.util.HashMap;
import java.util.Map;

import org.activiti.engine.impl.test.PluggableActivitiTestCase;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.activiti.engine.test.Deployment;

/**
 */
public class CallActivityTest extends PluggableActivitiTestCase {

  @Deployment(resources = { "org/activiti/examples/bpmn/callactivity/orderProcess.bpmn20.xml", "org/activiti/examples/bpmn/callactivity/checkCreditProcess.bpmn20.xml" })
  public void testOrderProcessWithCallActivity() {
    // After the process has started, the 'verify credit history' task
    // should be active
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("orderProcess");
    TaskQuery taskQuery = taskService.createTaskQuery();
    Task verifyCreditTask = taskQuery.singleResult();
    assertThat(verifyCreditTask.getName()).isEqualTo("Verify credit history");

    // Verify with Query API
    ProcessInstance subProcessInstance = runtimeService.createProcessInstanceQuery().superProcessInstanceId(pi.getId()).singleResult();
    assertThat(subProcessInstance).isNotNull();
    assertThat(runtimeService.createProcessInstanceQuery().subProcessInstanceId(subProcessInstance.getId()).singleResult().getId()).isEqualTo(pi.getId());

    // Completing the task with approval, will end the subprocess and
    // continue the original process
    taskService.complete(verifyCreditTask.getId(), singletonMap("creditApproved", true));
    Task prepareAndShipTask = taskQuery.singleResult();
    assertThat(prepareAndShipTask.getName()).isEqualTo("Prepare and Ship");
  }

  @Deployment(resources = { "org/activiti/examples/bpmn/callactivity/mainProcess.bpmn20.xml", "org/activiti/examples/bpmn/callactivity/childProcess.bpmn20.xml" })
  public void testCallActivityWithModeledDataObjectsInSubProcess() {
    // After the process has started, the 'verify credit history' task should be active
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("mainProcess");
    TaskQuery taskQuery = taskService.createTaskQuery();
    Task verifyCreditTask = taskQuery.singleResult();
    assertThat(verifyCreditTask.getName()).isEqualTo("User Task 1");

    // Verify with Query API
    ProcessInstance subProcessInstance = runtimeService.createProcessInstanceQuery().superProcessInstanceId(pi.getId()).singleResult();
    assertThat(subProcessInstance).isNotNull();
    assertThat(runtimeService.createProcessInstanceQuery().subProcessInstanceId(subProcessInstance.getId()).singleResult().getId()).isEqualTo(pi.getId());

    assertThat(runtimeService.getVariable(subProcessInstance.getId(), "Name")).isEqualTo("Batman");
  }

  @Deployment(resources = { "org/activiti/examples/bpmn/callactivity/mainProcess.bpmn20.xml",
                            "org/activiti/examples/bpmn/callactivity/childProcess.bpmn20.xml",
                            "org/activiti/examples/bpmn/callactivity/mainProcessBusinessKey.bpmn20.xml",
                            "org/activiti/examples/bpmn/callactivity/mainProcessInheritBusinessKey.bpmn20.xml"})
  public void testCallActivityWithBusinessKey() {
    // No use of business key attributes
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("mainProcess");
    ProcessInstance subProcessInstance = runtimeService.createProcessInstanceQuery().superProcessInstanceId(pi.getId()).singleResult();
    assertThat(subProcessInstance.getBusinessKey()).isNull();

    // Modeled using expression: businessKey="${busKey}"
    Map<String,Object> variables = new HashMap<>();
    variables.put("busKey", "123");
    pi = runtimeService.startProcessInstanceByKey("mainProcessBusinessKey", variables);
    subProcessInstance = runtimeService.createProcessInstanceQuery().superProcessInstanceId(pi.getId()).singleResult();
    assertThat(subProcessInstance.getBusinessKey()).isEqualTo("123");

    // Inherit business key
    pi = runtimeService.startProcessInstanceByKey("mainProcessInheritBusinessKey", "123");
    subProcessInstance = runtimeService.createProcessInstanceQuery().superProcessInstanceId(pi.getId()).singleResult();
    assertThat(subProcessInstance.getBusinessKey()).isEqualTo("123");
  }

}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.camel.support;

import java.util.Collections;
import java.util.Map;
import java.util.Set;

/**
 * A special registry which is used for local beans.
 *
 * This {@link org.apache.camel.spi.Registry} is only intended to be used by camel-core.
 */
public final class LocalBeanRegistry extends SupplierRegistry {

    public LocalBeanRegistry() {
    }

    /**
     * Makes a copy of this registry
     */
    public LocalBeanRegistry copy() {
        LocalBeanRegistry copy = new LocalBeanRegistry();
        copy.putAll(this);
        return copy;
    }

    public Set<String> keys() {
        return Collections.unmodifiableSet(keySet());
    }

    /**
     * Swaps the key which is used when this local registry have a number of bound beans that would clash with global
     * registry or endpoint registry in Camel. Then there is a check that validates for clashes and then re-assign key
     * names.
     *
     * @param oldKey the old key name
     * @param newKey the new key name
     */
    public void swapKey(String oldKey, String newKey) {
        Map<Class<?>, Object> value = remove(oldKey);
        if (value != null) {
            put(newKey, value);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cloud-resource-base</artifactId>
        <groupId>au.edu.unsw.cse.soc.federatedcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-resource-descriptions</artifactId>

</project>


text:
'''
Implements the ban-commit command

'''
from .gerritsite import SiteCommand
from .internal.cmdoptions import *  # noqa

class BanCommit(SiteCommand):
    '''
    Obtain a list of all(visible) groups on a site

    :param project: The repository name containingg the commit
    :param commit: The SHA-1 for the commit to be banned
    :param option_str: List of options to pass to the command

    '''

    __options = OptionSet(Option.valued('reason', spec='>=2.5'))
    __supported_versions = '>=2.5'

    def __init__(self, project, commit, option_str=''):
        self.__project = project
        self.__commit = commit

        if not (project and commit):
            raise ValueError('Project and Commit are required by the command')

        super(BanCommit, self).__init__(BanCommit.__supported_versions,
                                        BanCommit.__options,
                                        option_str)

    def execute_on(self, the_site):
        '''
        :param the_site: A :class:`Site` representing the site

        :returns:
            An empty list as the command has no return value
        '''
        self.check_support_for(the_site)
        the_site.execute(' '.join(['ban-commit',
                                   str(self._parsed_options),
                                   self.__project,
                                   self.__commit]
                                   ).strip())
        self._results = []
        return self._results

__all__ = ['BanCommit']


text:
package com.trickbz.pingerful.tasks;

public interface TaskCompletedBooleanCallback {

    void taskCompletedBooleanCallback(boolean result);

}


text:
((typeof define === "function" && define.amd && function (m) { define("samsam", m); }) ||
 (typeof module === "object" &&
      function (m) { module.exports = m(); }) || // Node
 function (m) { this.samsam = m(); } // Browser globals
)(function () {
    var o = Object.prototype;
    var div = typeof document !== "undefined" && document.createElement("div");

    function isNaN(value) {
        // Unlike global isNaN, this avoids type coercion
        // typeof check avoids IE host object issues, hat tip to
        // lodash
        var val = value; // JsLint thinks value !== value is "weird"
        return typeof value === "number" && value !== val;
    }

    function getClass(value) {
        // Returns the internal [[Class]] by calling Object.prototype.toString
        // with the provided value as this. Return value is a string, naming the
        // internal class, e.g. "Array"
        return o.toString.call(value).split(/[ \]]/)[1];
    }

    /**
     * @name samsam.isArguments
     * @param Object object
     *
     * Returns ``true`` if ``object`` is an ``arguments`` object,
     * ``false`` otherwise.
     */
    function isArguments(object) {
        if (getClass(object) === 'Arguments') { return true; }
        if (typeof object !== "object" || typeof object.length !== "number" ||
                getClass(object) === "Array") {
            return false;
        }
        if (typeof object.callee == "function") { return true; }
        try {
            object[object.length] = 6;
            delete object[object.length];
        } catch (e) {
            return true;
        }
        return false;
    }

    /**
     * @name samsam.isElement
     * @param Object object
     *
     * Returns ``true`` if ``object`` is a DOM element node. Unlike
     * Underscore.js/lodash, this function will return ``false`` if ``object``
     * is an *element-like* object, i.e. a regular object with a ``nodeType``
     * property that holds the value ``1``.
     */
    function isElement(object) {
        if (!object || object.nodeType !== 1 || !div) { return false; }
        try {
            object.appendChild(div);
            object.removeChild(div);
        } catch (e) {
            return false;
        }
        return true;
    }

    /**
     * @name samsam.keys
     * @param Object object
     *
     * Return an array of own property names.
     */
    function keys(object) {
        var ks = [], prop;
        for (prop in object) {
            if (o.hasOwnProperty.call(object, prop)) { ks.push(prop); }
        }
        return ks;
    }

    /**
     * @name samsam.isDate
     * @param Object value
     *
     * Returns true if the object is a ``Date``, or *date-like*. Duck typing
     * of date objects work by checking that the object has a ``getTime``
     * function whose return value equals the return value from the object's
     * ``valueOf``.
     */
    function isDate(value) {
        return typeof value.getTime == "function" &&
            value.getTime() == value.valueOf();
    }

    /**
     * @name samsam.isNegZero
     * @param Object value
     *
     * Returns ``true`` if ``value`` is ``-0``.
     */
    function isNegZero(value) {
        return value === 0 && 1 / value === -Infinity;
    }

    /**
     * @name samsam.equal
     * @param Object obj1
     * @param Object obj2
     *
     * Returns ``true`` if two objects are strictly equal. Compared to
     * ``===`` there are two exceptions:
     *
     *   - NaN is considered equal to NaN
     *   - -0 and +0 are not considered equal
     */
    function identical(obj1, obj2) {
        if (obj1 === obj2 || (isNaN(obj1) && isNaN(obj2))) {
            return obj1 !== 0 || isNegZero(obj1) === isNegZero(obj2);
        }
    }

    function isSet(val) {
        if (typeof Set !== 'undefined' && val instanceof Set) {
            return true;
        }
    }

    function isSubset(s1, s2, compare) {
        var values1 = Array.from(s1);
        var values2 = Array.from(s2);

        for (var i = 0; i < values1.length; i++) {
            var includes = false;

            for (var j = 0; j < values2.length; j++) {
                if (compare(values2[j], values1[i])) {
                    includes = true;
                    break;
                }
            }

            if (!includes) {
                return false;
            }
        }

        return true;
    }

    /**
     * @name samsam.deepEqual
     * @param Object obj1
     * @param Object obj2
     *
     * Deep equal comparison. Two values are "deep equal" if:
     *
     *   - They are equal, according to samsam.identical
     *   - They are both date objects representing the same time
     *   - They are both arrays containing elements that are all deepEqual
     *   - They are objects with the same set of properties, and each property
     *     in ``obj1`` is deepEqual to the corresponding property in ``obj2``
     *
     * Supports cyclic objects.
     */
    function deepEqualCyclic(obj1, obj2) {

        // used for cyclic comparison
        // contain already visited objects
        var objects1 = [],
            objects2 = [],
        // contain pathes (position in the object structure)
        // of the already visited objects
        // indexes same as in objects arrays
            paths1 = [],
            paths2 = [],
        // contains combinations of already compared objects
        // in the manner: { "$1['ref']$2['ref']": true }
            compared = {};

        /**
         * used to check, if the value of a property is an object
         * (cyclic logic is only needed for objects)
         * only needed for cyclic logic
         */
        function isObject(value) {

            if (typeof value === 'object' && value !== null &&
                    !(value instanceof Boolean) &&
                    !(value instanceof Date)    &&
                    !(value instanceof Number)  &&
                    !(value instanceof RegExp)  &&
                    !(value instanceof String)) {

                return true;
            }

            return false;
        }

        /**
         * returns the index of the given object in the
         * given objects array, -1 if not contained
         * only needed for cyclic logic
         */
        function getIndex(objects, obj) {

            var i;
            for (i = 0; i < objects.length; i++) {
                if (objects[i] === obj) {
                    return i;
                }
            }

            return -1;
        }

        // does the recursion for the deep equal check
        return (function deepEqual(obj1, obj2, path1, path2) {
            var type1 = typeof obj1;
            var type2 = typeof obj2;

            // == null also matches undefined
            if (obj1 === obj2 ||
                    isNaN(obj1) || isNaN(obj2) ||
                    obj1 == null || obj2 == null ||
                    type1 !== "object" || type2 !== "object") {

                return identical(obj1, obj2);
            }

            // Elements are only equal if identical(expected, actual)
            if (isElement(obj1) || isElement(obj2)) { return false; }

            var isDate1 = isDate(obj1), isDate2 = isDate(obj2);
            if (isDate1 || isDate2) {
                if (!isDate1 || !isDate2 || obj1.getTime() !== obj2.getTime()) {
                    return false;
                }
            }

            if (obj1 instanceof RegExp && obj2 instanceof RegExp) {
                if (obj1.toString() !== obj2.toString()) { return false; }
            }

            var class1 = getClass(obj1);
            var class2 = getClass(obj2);
            var keys1 = keys(obj1);
            var keys2 = keys(obj2);

            if (isArguments(obj1) || isArguments(obj2)) {
                if (obj1.length !== obj2.length) { return false; }
            } else {
                if (type1 !== type2 || class1 !== class2 ||
                        keys1.length !== keys2.length) {
                    return false;
                }
            }

            if (isSet(obj1) || isSet(obj2)) {
                if (!isSet(obj1) || !isSet(obj2) || obj1.size !== obj2.size) {
                    return false;
                }

                return isSubset(obj1, obj2, deepEqual);
            }

            var key, i, l,
                // following vars are used for the cyclic logic
                value1, value2,
                isObject1, isObject2,
                index1, index2,
                newPath1, newPath2;

            for (i = 0, l = keys1.length; i < l; i++) {
                key = keys1[i];
                if (!o.hasOwnProperty.call(obj2, key)) {
                    return false;
                }

                // Start of the cyclic logic

                value1 = obj1[key];
                value2 = obj2[key];

                isObject1 = isObject(value1);
                isObject2 = isObject(value2);

                // determine, if the objects were already visited
                // (it's faster to check for isObject first, than to
                // get -1 from getIndex for non objects)
                index1 = isObject1 ? getIndex(objects1, value1) : -1;
                index2 = isObject2 ? getIndex(objects2, value2) : -1;

                // determine the new pathes of the objects
                // - for non cyclic objects the current path will be extended
                //   by current property name
                // - for cyclic objects the stored path is taken
                newPath1 = index1 !== -1
                    ? paths1[index1]
                    : path1 + '[' + JSON.stringify(key) + ']';
                newPath2 = index2 !== -1
                    ? paths2[index2]
                    : path2 + '[' + JSON.stringify(key) + ']';

                // stop recursion if current objects are already compared
                if (compared[newPath1 + newPath2]) {
                    return true;
                }

                // remember the current objects and their pathes
                if (index1 === -1 && isObject1) {
                    objects1.push(value1);
                    paths1.push(newPath1);
                }
                if (index2 === -1 && isObject2) {
                    objects2.push(value2);
                    paths2.push(newPath2);
                }

                // remember that the current objects are already compared
                if (isObject1 && isObject2) {
                    compared[newPath1 + newPath2] = true;
                }

                // End of cyclic logic

                // neither value1 nor value2 is a cycle
                // continue with next level
                if (!deepEqual(value1, value2, newPath1, newPath2)) {
                    return false;
                }
            }

            return true;

        }(obj1, obj2, '$1', '$2'));
    }

    function arrayContains(array, subset, compare) {
        if (subset.length === 0) { return true; }
        var i, l, j, k;
        for (i = 0, l = array.length; i < l; ++i) {
            if (compare(array[i], subset[0])) {
                for (j = 0, k = subset.length; j < k; ++j) {
                    if ((i + j) >= l) { return false; }
                    if (!compare(array[i + j], subset[j])) { return false; }
                }
                return true;
            }
        }
        return false;
    }

    /**
     * @name samsam.match
     * @param Object object
     * @param Object matcher
     *
     * Compare arbitrary value ``object`` with matcher.
     */
    function match(object, matcher) {
        if (matcher && typeof matcher.test === "function") {
            return matcher.test(object);
        }

        if (typeof matcher === "function") {
            return matcher(object) === true;
        }

        if (typeof matcher === "string") {
            matcher = matcher.toLowerCase();
            var notNull = typeof object === "string" || !!object;
            return notNull &&
                (String(object)).toLowerCase().indexOf(matcher) >= 0;
        }

        if (typeof matcher === "number") {
            return matcher === object;
        }

        if (typeof matcher === "boolean") {
            return matcher === object;
        }

        if (typeof(matcher) === "undefined") {
            return typeof(object) === "undefined";
        }

        if (matcher === null) {
            return object === null;
        }

        if (isSet(object)) {
            return isSubset(matcher, object, match);
        }

        if (getClass(object) === "Array" && getClass(matcher) === "Array") {
            return arrayContains(object, matcher, match);
        }

        if (isDate(matcher)) {
            return isDate(object) && object.getTime() === matcher.getTime();
        }

        if (matcher && typeof matcher === "object") {
            if (matcher === object) {
                return true;
            }
            var prop;
            for (prop in matcher) {
                var value = object[prop];
                if (typeof value === "undefined" &&
                        typeof object.getAttribute === "function") {
                    value = object.getAttribute(prop);
                }
                if (matcher[prop] === null || typeof matcher[prop] === 'undefined') {
                    if (value !== matcher[prop]) {
                        return false;
                    }
                } else if (typeof  value === "undefined" || !match(value, matcher[prop])) {
                    return false;
                }
            }
            return true;
        }

        throw new Error("Matcher was not a string, a number, a " +
                        "function, a boolean or an object");
    }

    return {
        isArguments: isArguments,
        isElement: isElement,
        isDate: isDate,
        isNegZero: isNegZero,
        identical: identical,
        deepEqual: deepEqualCyclic,
        match: match,
        keys: keys
    };
});


text:
#include <pcl/point_types.h>
#include <pcl/impl/instantiate.hpp>
#include <pcl/features/principal_curvatures.h>
#include <pcl/features/impl/principal_curvatures.hpp>

// Instantiations of specific point types
#ifdef PCL_ONLY_CORE_POINT_TYPES
  PCL_INSTANTIATE_PRODUCT(PrincipalCurvaturesEstimation, ((pcl::PointXYZ)(pcl::PointXYZI)(pcl::PointXYZRGBA))((pcl::Normal))((pcl::PrincipalCurvatures)))
#else
  PCL_INSTANTIATE_PRODUCT(PrincipalCurvaturesEstimation, (PCL_XYZ_POINT_TYPES)(PCL_NORMAL_POINT_TYPES)((pcl::PrincipalCurvatures)))
  PCL_INSTANTIATE_PRODUCT(PrincipalCurvaturesEstimation, (PCL_XYZ_POINT_TYPES)(PCL_NORMAL_POINT_TYPES)((Eigen::MatrixXf)))
#endif


text:
package com.microrisc.simply.iqrf.dpa.v22x.typeconvertors;

import com.microrisc.simply.iqrf.dpa.v22x.types.LoadingResult;
import com.microrisc.simply.protocol.mapping.ConvertorFactoryMethod;
import com.microrisc.simply.typeconvertors.PrimitiveConvertor;
import com.microrisc.simply.typeconvertors.ValueConversionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Provides functionality for converting from {@link LoadingResultConvertor}
 * type values to proto values.
 *
 * @author Martin Strouhal
 */
public final class LoadingResultConvertor extends PrimitiveConvertor {

   /** Logger. */
   private static final Logger logger = LoggerFactory.getLogger(
           LoadingResultConvertor.class);

   private LoadingResultConvertor() {
   }

   /** Singleton. */
   private static final LoadingResultConvertor instance = new LoadingResultConvertor();

   /**
    * @return {@code LoadingResultConvertor} instance
    */
   @ConvertorFactoryMethod
   static public LoadingResultConvertor getInstance() {
      return instance;
   }

   /** Size of returned response. */
   static public final int TYPE_SIZE = 1;

   @Override
   public int getGenericTypeSize() {
      return TYPE_SIZE;
   }

   /**
    * Currently not supported. Throws {@code UnsupportedOperationException }.
    *
    * @throws UnsupportedOperationException
    */
   @Override
   public short[] toProtoValue(Object value) throws ValueConversionException {
      throw new UnsupportedOperationException("Not supported yet.");
   }

   @Override
   public Object toObject(short[] protoValue) throws ValueConversionException {
      logger.debug("toObject - start: protoValue={}", protoValue);
      LoadingResult result;
      if (protoValue.length >= TYPE_SIZE) {
         if (protoValue[0] == 1) {
            result = new LoadingResult(true);
         } else {
            result = new LoadingResult(false);
         }
      } else {
         logger.warn("Length of protoValue is 0 instead of 1.");
         result = new LoadingResult(false);
      }
      logger.debug("toObject - end: {}", result);
      return result;
   }
}


text:
module Paypal
  class Paypal
    include Options

  end
end


text:
Implements the *Selection algorithm* as described by Blum, Floyd, Pratt, Rivest, and Tarjan. It runs in `O(n)` time complexity with the best case being O(1) in case of a sorted array. Implementation is provided as `LinearTimeSelection` class contained in the package `io.gitbub.thehappybug.Algorithms`.

> See [http://en.wikipedia.org/wiki/Selection_algorithm](Wikipedia) for more information on the Selection algorithm.

## Compiling

The project can be compiled using `make` tool:

```
$ make
javac io/github/thehappybug/Algorithms/LinearTimeSelection.java
```

Optionally, documentation can be generated from the source files using Javadoc:

```
$ make docs
Loading source file io/github/thehappybug/Algorithms/LinearTimeSelection.java...
Constructing Javadoc information...
Standard Doclet version 1.7.0_75
Building tree for all the packages and classes...
Generating docs\io\github\thehappybug\Algorithms\LinearTimeSelection.html...
Generating docs\io\github\thehappybug\Algorithms\package-frame.html...
Generating docs\io\github\thehappybug\Algorithms\package-summary.html...
Generating docs\io\github\thehappybug\Algorithms\package-tree.html...
Generating docs\constant-values.html...
Building index for all the packages and classes...
Generating docs\overview-tree.html...
Generating docs\index-all.html...
Generating docs\deprecated-list.html...
Building index for all classes...
Generating docs\allclasses-frame.html...
Generating docs\allclasses-noframe.html...
Generating docs\index.html...
Generating docs\help-doc.html...
```

## Running

Run the class `LinearTimeSelection`'s `main` method using:

```
$ java io.github.thehappybug.Algorithms.LinearTimeSelection 5 sample_input.txt
5
```

The program requires two arguments: the position, `n` and a file containing a space-separated integer list.

## Documentation (Public)

**`public class LinearTimeSelection`**

Algorithm to select n-th element from a list

**`public static void main(String[] args)`**

Main program to select n-th element in an array Input file should contain space separated integer numbers.

 * **Parameters:** `args` — "Position" and "input filename" required as arguments to program

**`public LinearTimeSelection(List<Integer> list)`**

Create a selection algorithm bound to a list

 * **Parameters:** `list` — List

**`public int run(int order) throws IllegalArgumentException`**

Run the selection algorithm

 * **Parameters:** `order` — The position of element to find
 * **Returns:** Element found
 * **Exceptions:** `IllegalArgumentException` — If the position is out-of-bounds

## Documentation (Private)

**`private static List<Integer> readFromFile(String path) throws IOException`**

Read a space-separated integer list from file.

 * **Parameters:** `path` — Path of file
 * **Returns:** Integer list
 * **Exceptions:** `IOException` — Thrown when unable to open or read file

**`private int run(List<Integer> list, int order)`**

Run the selection algorithm on the given list

 * **Parameters:**
   * `list` — List
   * `order` — The position of element to be found
 * **Returns:** Element

**`private int choosePivot(List<Integer> list)`**

Choose a pivot from list using the median-of-medians method

 * **Parameters:** `list` — List
 * **Returns:** Pivot selected

**`private void swap(List<Integer> list, int a, int b)`**

Swap two integers in an array

 * **Parameters:**
   * `list` — List
   * `a` — position1
   * `b` — position2

**`private int partition(List<Integer> arr, int x)`**

Partition array based on a pibot

 * **Parameters:**
   * `arr` — Array to be partitioned
   * `x` — Pivot
 * **Returns:** New position of pivot


text:
define(function () { 'use strict';

    /* and datetime-local? Spec says "Nah!" */

    var dates = ['datetime', 'date', 'month', 'week', 'time'];

    var plain_numbers = ['number', 'range'];

    /* everything that returns something meaningful for valueAsNumber and
     * can have the step attribute */
    var numbers = dates.concat(plain_numbers, 'datetime-local');

    /* the spec says to only check those for syntax in validity.typeMismatch.
     * ¯\_(ツ)_/¯ */
    var type_checked = ['email', 'url'];

    var text = ['text', 'search', 'tel', 'password'].concat(type_checked);

    /* input element types, that are candidates for the validation API.
     * Missing from this set are: button, hidden, menu (from <button>), reset */
    var validation_candidates = ['checkbox', 'color', 'file', 'image', 'radio', 'submit'].concat(numbers, text);

    /**
     * check if an element is a candidate for constraint validation
     *
     * @see https://html.spec.whatwg.org/multipage/forms.html#barred-from-constraint-validation
     */
    function is_validation_candidate (element) {
      /* it must be any of those elements */
      if (element instanceof window.HTMLSelectElement || element instanceof window.HTMLTextAreaElement || element instanceof window.HTMLButtonElement || element instanceof window.HTMLInputElement) {

        /* it's type must be in the whitelist or missing (select, textarea) */
        if (!element.type || validation_candidates.indexOf(element.type) > -1) {

          /* it mustn't be disabled or readonly */
          if (!element.disabled && !element.readonly) {

            /* then it's a candidate */
            return true;
          }
        }
      }

      /* this is no HTML5 validation candidate... */
      return false;
    }

    /**
     * mark an object with a 'hyperform=true' property
     *
     * We use this to distinguish our properties from the native ones. Usage:
     * js> obj.hyperform === true
     */

    function mark (obj) {
      if (typeof obj !== 'object') {
        /* do it old style for primitive values */
        obj.hyperform = true;
      } else {
        Object.defineProperty(obj, 'hyperform', {
          value: true
        });
      }

      return obj;
    }

    function installer (property, descriptor) {
      return function (element) {
        delete element[property];
        Object.defineProperty(element, property, descriptor);
      };
    }

    function trigger_event (element, event, _ref) {
        var _ref$bubbles = _ref.bubbles;
        var bubbles = _ref$bubbles === undefined ? true : _ref$bubbles;
        var _ref$cancelable = _ref.cancelable;
        var cancelable = _ref$cancelable === undefined ? false : _ref$cancelable;

        if (!(event instanceof window.Event)) {
            var _event = document.createEvent('Event');
            _event.initEvent(event, bubbles, cancelable);
            event = _event;
        }
        element.dispatchEvent(event);
    }

    function sliceIterator(arr, i) {
      var _arr = [];
      var _n = true;
      var _d = false;
      var _e = undefined;

      try {
        for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
          _arr.push(_s.value);

          if (i && _arr.length === i) break;
        }
      } catch (err) {
        _d = true;
        _e = err;
      } finally {
        try {
          if (!_n && _i["return"]) _i["return"]();
        } finally {
          if (_d) throw _e;
        }
      }

      return _arr;
    }

    function _slicedToArray (arr, i) {
      if (Array.isArray(arr)) {
        return arr;
      } else if (Symbol.iterator in Object(arr)) {
        return sliceIterator(arr, i);
      } else {
        throw new TypeError("Invalid attempt to destructure non-iterable instance");
      }
    };

    /**
     * get previous and next valid values for a stepped input element
     *
     * TODO add support for date, time, ...
     */

    function get_next_valid (element) {
      var min = Number(element.getAttribute('min') || 0);
      var max = Number(element.getAttribute('max') || 100);
      var step = Number(element.getAttribute('step') || 1);
      var value = Number(element.value || 0);

      var prev = min + Math.floor((value - min) / step) * step;
      var next = min + (Math.floor((value - min) / step) + 1) * step;

      if (prev < min) {
        prev = null;
      } else if (prev > max) {
        prev = max;
      }

      if (next > max) {
        next = null;
      } else if (next < min) {
        next = min;
      }

      return [prev, next];
    }

    function sprintf (str) {
      for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        args[_key - 1] = arguments[_key];
      }

      var args_length = args.length;
      var global_index = 0;

      return str.replace(/%([0-9]+\$)?([sl])/g, function (match, position, type) {
        var local_index = global_index;
        if (position) {
          local_index = Number(position.replace(/\$$/, '')) - 1;
        }
        global_index += 1;

        var arg = '';
        if (args_length > local_index) {
          arg = args[local_index];
        }

        if (arg instanceof Date || typeof arg === 'number' || arg instanceof Number) {
          /* try getting a localized representation of dates and numbers, if the
           * browser supports this */
          if (type === 'l') {
            arg = (arg.toLocaleString || arg.toString).call(arg);
          } else {
            arg = arg.toString();
          }
        }

        return arg;
      });
    }

    var catalog = {};

    function _ (s) {
      if (s in catalog) {
        return catalog[s];
      }
      return s;
    }

    var message_store = new WeakMap();

    /**
     * return a new Date() representing the ISO date for a week number
     *
     * @see http://stackoverflow.com/a/16591175/113195
     */

    function get_date_from_week (week, year) {
      var date = new Date(Date.UTC(year, 0, 1 + (week - 1) * 7));

      if (date.getUTCDay() <= 4 /* thursday */) {
          date.setUTCDate(date.getUTCDate() - date.getUTCDay() + 1);
        } else {
        date.setUTCDate(date.getUTCDate() + 8 - date.getUTCDay());
      }

      return date;
    }

    /**
     * calculate a date from a string according to HTML5
     */
    function string_to_date (string, element_type) {
      var date = new Date(0);
      switch (element_type) {
        case 'datetime':
          if (!/^([0-9]{4,})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9])(?:\.([0-9]{1,3})))?$/.test(string)) {
            return null;
          }
          var ms = RegExp.$7;
          while (ms.length < 3) {
            ms += '0';
          }
          date.setUTCFullYear(Number(RegExp.$1));
          date.setUTCMonth(Number(RegExp.$2) - 1, Number(RegExp.$3));
          date.setUTCHours(Number(RegExp.$4), Number(RegExp.$5), Number(RegExp.$6 || 0), Number(ms));
          return date;

        case 'date':
          if (!/^([0-9]{4,})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$/.test(string)) {
            return null;
          }
          date.setUTCFullYear(Number(RegExp.$1));
          date.setUTCMonth(Number(RegExp.$2) - 1, Number(RegExp.$3));
          return date;

        case 'month':
          if (!/^([0-9]{4,})-(0[1-9]|1[012])$/.test(string)) {
            return null;
          }
          date.setUTCFullYear(Number(RegExp.$1));
          date.setUTCMonth(Number(RegExp.$2) - 1, 1);
          return date;

        case 'week':
          if (!/^([0-9]{4,})-W(0[1-9]|[1234][0-9]|5[0-3])$/.test(string)) {
            return null;
          }
          return get_date_from_week(Number(RegExp.$2), Number(RegExp.$1));

        case 'time':
          if (!/^([01][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9])(?:\.([0-9]{1,3}))?)?$/.test(string)) {
            return null;
          }
          date.setUTCHours(Number(RegExp.$1), Number(RegExp.$2), Number(RegExp.$3 || 0), Number(RegExp.$4 || 0));
          return date;
      }

      return null;
    }

    /**
     * test the max attribute
     *
     * we use Number() instead of parseFloat(), because an invalid attribute
     * value like "123abc" should result in an error.
     */
    function test_max (element) {

      if (!is_validation_candidate(element) || !element.value || !element.hasAttribute('max')) {
        /* we're not responsible here */
        return true;
      }

      var value = void 0,
          max = void 0;
      if (dates.indexOf(element.type) > -1) {
        value = 1 * string_to_date(element.value, element.type);
        max = 1 * (string_to_date(element.getAttribute('max'), element.type) || NaN);
      } else {
        value = Number(element.value);
        max = Number(element.getAttribute('max'));
      }

      return isNaN(max) || value <= max;
    }

    /**
     * test the maxlength attribute
     *
     * Allows empty input. If you do not want this, add the `required` attribute.
     */
    function test_maxlength (element) {
        return !is_validation_candidate(element) || !element.value || !element.hasAttribute('maxlength') || element.value.length >= parseInt(element.getAttribute('maxlength'), 10);
    }

    /**
     * test the min attribute
     *
     * we use Number() instead of parseFloat(), because an invalid attribute
     * value like "123abc" should result in an error.
     */
    function test_min (element) {

      if (!is_validation_candidate(element) || !element.value || !element.hasAttribute('min')) {
        /* we're not responsible here */
        return true;
      }

      var value = void 0,
          min = void 0;
      if (dates.indexOf(element.type) > -1) {
        value = 1 * string_to_date(element.value, element.type);
        min = 1 * (string_to_date(element.getAttribute('min'), element.type) || NaN);
      } else {
        value = Number(element.value);
        min = Number(element.getAttribute('min'));
      }

      return isNaN(min) || value >= min;
    }

    /**
     * test the minlength attribute
     *
     * Allows empty input. If you do not want this, add the `required` attribute.
     */
    function test_minlength (element) {
        return !is_validation_candidate(element) || !element.value || !element.hasAttribute('minlength') || element.value.length >= parseInt(element.getAttribute('minlength'), 10);
    }

    /**
     * test the pattern attribute
     */
    function test_pattern (element) {
        return !is_validation_candidate(element) || !element.value || !element.hasAttribute('pattern') || new RegExp('^(?:' + element.getAttribute('pattern') + ')$').test(element.value);
    }

    /**
     * test the required attribute
     */
    function test_required (element) {
      if (!is_validation_candidate(element) || !element.hasAttribute('required')) {
        /* nothing to do */
        return true;
      }

      switch (element.type) {
        case 'checkbox':
          return element.checked;
        //break;
        case 'radio':
          /* radio inputs have "required" fulfilled, if _any_ other radio
           * with the same name in this form is checked. */
          return element.checked || Array.prototype.filter.call(element.form.getElementsByName(element.name), function (radio) {
            return radio.form === element.form && radio.checked;
          }).length > 0;
        //break;
        default:
          return !!element.value;
      }
    }

    /**
     * calculate a date from a string according to HTML5
     */
    function string_to_number (string, element_type) {
      var rval = string_to_date(string, element_type);
      if (rval !== null) {
        return +rval;
      }
      /* not parseFloat, because we want NaN for invalid values like "1.2xxy" */
      return Number(string);
    }

    var default_step = {
      'datetime-local': 60,
      datetime: 60,
      time: 60
    };

    var step_scale_factor = {
      'datetime-local': 1000,
      datetime: 1000,
      date: 86400000,
      week: 604800000,
      time: 1000
    };

    var default_step_base = {
      week: -259200000
    };

    /**
     * test the step attribute
     *
     * @TODO type=month will get wrong results. We need to implement month-wide
     *       steps. See https://html.spec.whatwg.org/multipage/forms.html#month-state-%28type=month%29
     */
    function test_step (element) {

      if (!is_validation_candidate(element) || !element.value || numbers.indexOf(element.type) === -1 || (element.getAttribute('step') || '').toLowerCase() === 'any') {
        /* we're not responsible here */
        return true;
      }

      var step = element.getAttribute('step');
      if (step) {
        step = string_to_number(step, element.type);
      } else {
        step = default_step[element.type] || 1;
      }

      if (step <= 0 || isNaN(step)) {
        /* error in specified "step". We cannot validate against it, so the value
         * is true. */
        return true;
      }

      var scale = step_scale_factor[element.type] || 1;

      var value = string_to_number(element.value, element.type);
      var min = string_to_number(element.getAttribute('min') || element.getAttribute('value') || '', element.type);

      var base = min;
      if (isNaN(base)) {
        base = default_step_base[element.type] || 0;
      }

      var result = Math.abs(base - value) % (step * scale);

      return result < 0.00000001 ||
      /* crappy floating-point arithmetics! */
      result > step * scale - 0.00000001;
    }

    /* we use a dummy <a> where we set the href to test URL validity */
    var url_canary = document.createElement('a');

    /* see https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address */
    var email_pattern = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;

    /**
     * test the type-inherent syntax
     */
    function test_type (element) {
      if (!is_validation_candidate(element) || !element.value || type_checked.indexOf(element.type) === -1) {
        /* we're not responsible for this element */
        return true;
      }

      var is_valid = true;

      switch (element.type) {
        case 'url':
          url_canary.href = element.value;
          is_valid = url_canary.href === element.value || url_canary.href === element.value + '/';
          break;
        case 'email':
          if (element.hasAttribute('multiple')) {
            is_valid = element.value.split(',').map(function (item) {
              return item.trim();
            }).every(function (value) {
              return email_pattern.test(value);
            });
          } else {
            is_valid = email_pattern.test(element.value);
          }
          break;
      }

      return is_valid;
    }

    /**
     * Implement constraint checking functionality defined in the HTML5 standard
     *
     * @see https://html.spec.whatwg.org/multipage/forms.html#dom-cva-validity
     * @return bool true if the test fails [!], false otherwise
     */
    var validity_state_checkers = {
      badInput: function badInput(element) {
        // TODO
        return false;
      },

      customError: function customError(element) {
        var msg = message_store.get(element);
        var invalid = msg && 'is_custom' in msg;
        /* no need for message_store.set, because the message is already there. */
        return invalid;
      },

      patternMismatch: function patternMismatch(element) {
        var invalid = !test_pattern(element);
        if (invalid) {
          message_store.set(element, element.title ? sprintf(_('Please match the requested format: %s.'), element.title) : _('Please match the requested format.'));
        }
        return invalid;
      },

      rangeOverflow: function rangeOverflow(element) {
        var invalid = !test_max(element);

        if (invalid) {
          var msg = void 0;
          switch (element.type) {
            case 'date':
            case 'datetime':
            case 'datetime-local':
            case 'time':
              msg = sprintf(_('Please select a value that is no later than %l.'), element.value);
              break;
            // case 'number':
            default:
              msg = sprintf(_('Please select a value that is no more than %l.'), element.value);
              break;
          }
          message_store.set(element, msg);
        }

        return invalid;
      },

      rangeUnderflow: function rangeUnderflow(element) {
        var invalid = !test_min(element);

        if (invalid) {
          var msg = void 0;
          switch (element.type) {
            case 'date':
            case 'datetime':
            case 'datetime-local':
            case 'time':
              msg = sprintf(_('Please select a value that is no earlier than %l.'), element.value);
              break;
            // case 'number':
            default:
              msg = sprintf(_('Please select a value that is no less than %l.'), element.value);
              break;
          }
          message_store.set(element, msg);
        }

        return invalid;
      },

      stepMismatch: function stepMismatch(element) {
        var invalid = !test_step(element);

        if (invalid) {
          var _get_next_valid = get_next_valid(element);

          var _get_next_valid2 = _slicedToArray(_get_next_valid, 2);

          var min = _get_next_valid2[0];
          var max = _get_next_valid2[1];

          var sole = false;

          if (min === null) {
            sole = max;
          } else if (max === null) {
            sole = min;
          }

          if (sole !== false) {
            message_store.set(element, sprintf(_('Please select a valid value. The nearest valid value is %l.'), sole));
          } else {
            message_store.set(element, sprintf(_('Please select a valid value. The two nearest valid values are %l and %l.'), min, max));
          }
        }

        return invalid;
      },

      tooLong: function tooLong(element) {
        var invalid = !test_maxlength(element);

        if (invalid) {
          message_store.set(element, sprintf(_('Please shorten this text to %l characters or less (you are currently using %l characters).'), element.getAttribute('maxlength'), element.value.length));
        }

        return invalid;
      },

      tooShort: function tooShort(element) {
        var invalid = !test_minlength(element);

        if (invalid) {
          message_store.set(element, sprintf(_('Please lengthen this text to %l characters or more (you are currently using %l characters).'), element.getAttribute('maxlength'), element.value.length));
        }

        return invalid;
      },

      typeMismatch: function typeMismatch(element) {
        var invalid = !test_type(element);

        if (invalid) {
          var msg = _('Please use the appropriate format.');
          if (element.type === 'email') {
            if (element.hasAttribute('multiple')) {
              msg = _('Please enter a comma separated list of email addresses.');
            } else {
              msg = _('Please enter an email address.');
            }
          } else if (element.type === 'url') {
            msg = _('Please enter a URL.');
          }
          message_store.set(element, msg);
        }

        return invalid;
      },

      valueMissing: function valueMissing(element) {
        var invalid = !test_required(element);

        if (invalid) {
          var msg = _('Please fill out this field.');
          if (element.type === 'checkbox') {
            msg = _('Please check this box if you want to proceed.');
          } else if (element.type === 'radio') {
            msg = _('Please select one of these options.');
          } else if (element.type === 'file') {
            if (element.hasAttribute('multiple')) {
              msg = _('Please select one or more files.');
            } else {
              msg = _('Please select a file.');
            }
          } else if (element instanceof window.HTMLSelectElement) {
            msg = _('Please select an item in the list.');
          }
          message_store.set(element, msg);
        }

        return invalid;
      }

    };

    /**
     * TODO allow HTMLFieldSetElement, too
     */
    var ValidityState = function ValidityState(element) {
      if (!(element instanceof window.HTMLElement)) {
        throw new Error('cannot create a ValidityState for a non-element');
      }

      var cached = ValidityState.cache.get(element);
      if (cached) {
        return cached;
      }

      if (!(this instanceof ValidityState)) {
        /* working around a forgotten `new` */
        return new ValidityState(element);
      }

      this.element = element;
      ValidityState.cache.set(element, this);
    };

    var ValidityStatePrototype = {};
    ValidityState.prototype = ValidityStatePrototype;

    ValidityState.cache = new WeakMap();

    /**
     * copy functionality from the validity checkers to the ValidityState
     * prototype
     */
    for (var prop in validity_state_checkers) {
      Object.defineProperty(ValidityStatePrototype, prop, {
        configurable: true,
        enumerable: true,
        get: function (func) {
          return function () {
            return func(this.element);
          };
        }(validity_state_checkers[prop]),
        set: undefined
      });
    }

    /**
     * the "valid" property calls all other validity checkers and returns true,
     * if all those return false.
     */
    Object.defineProperty(ValidityStatePrototype, 'valid', {
      configurable: true,
      enumerable: true,
      get: function get() {
        for (var _prop in validity_state_checkers) {
          if (validity_state_checkers[_prop](this.element)) {
            return false;
          }
        }
        return true;
      },
      set: undefined
    });

    mark(ValidityStatePrototype);

    /**
     * publish a convenience function to replace the native element.validity
     */
    ValidityState.install = installer('validity', {
      configurable: true,
      enumerable: true,
      get: function get() {
        return ValidityState(this);
      }
    });

    /**
     * check an element's validity with respect to it's form
     */
    function checkValidity() {
      /* jshint -W040 */

      /* if this is a <form>, check validity of all child inputs */
      if (this instanceof window.HTMLFormElement) {
        return Array.prototype.every.call(this.elements, checkValidity);
      }

      /* default is true, also for elements that are no validation candidates */
      var valid = true;

      if (is_validation_candidate(this)) {
        valid = ValidityState(this).valid;
        if (!valid) {
          trigger_event(this, 'invalid', { cancelable: true });
        }
      }
      /* jshint +W040 */

      return valid;
    }

    /**
     * publish a convenience function to replace the native element.checkValidity
     */
    checkValidity.install = installer('checkValidity', {
      configurable: true,
      enumerable: true,
      value: checkValidity,
      writable: true
    });

    mark(checkValidity);

    var Renderer = {

      show_warning: function show_warning(element) {
        var msg = message_store.get(element);
        if (msg) {
          window.alert(msg);
        }
      },

      set: function set(renderer, action) {
        Renderer[renderer] = action;
      }

    };

    /**
     * check element's validity and report an error back to the user
     */
    function reportValidity() {
      /* jshint -W040 */

      /* if this is a <form>, check validity of all child inputs */
      if (this instanceof window.HTMLFormElement) {
        return Array.prototype.every.call(this.elements, reportValidity);
      }

      var valid = checkValidity.call(this);
      if (!valid) {
        /* TODO suppress warning, if checkValidity's invalid event is canceled. */
        Renderer.show_warning(this);
      }
      /* jshint +W040 */
      return valid;
    }

    /**
     * publish a convenience function to replace the native element.reportValidity
     */
    reportValidity.install = installer('reportValidity', {
      configurable: true,
      enumerable: true,
      value: reportValidity,
      writable: true
    });

    mark(reportValidity);

    /**
     * TODO allow HTMLFieldSetElement, too
     */
    function setCustomValidity(msg) {
      msg.is_custom = true;
      /* jshint -W040 */
      message_store.set(this, msg);
      /* jshint +W040 */
    }

    /**
     * publish a convenience function to replace the native element.setCustomValidity
     */
    setCustomValidity.install = installer('setCustomValidity', {
      configurable: true,
      enumerable: true,
      get: setCustomValidity,
      set: undefined
    });

    mark(setCustomValidity);

    /**
     * TODO allow HTMLFieldSetElement, too
     */
    function validationMessage() {
      /* jshint -W040 */
      var msg = message_store.get(this);
      /* jshint +W040 */
      if (!msg) {
        return '';
      }
      return msg;
    }

    /**
     * publish a convenience function to replace the native element.validationMessage
     */
    validationMessage.install = installer('validationMessage', {
      configurable: true,
      enumerable: true,
      get: validationMessage,
      set: undefined
    });

    mark(validationMessage);

    /* For a given date, get the ISO week number
     *
     * Source: http://stackoverflow.com/a/6117889/113195
     *
     * Based on information at:
     *
     *    http://www.merlyn.demon.co.uk/weekcalc.htm#WNR
     *
     * Algorithm is to find nearest thursday, it's year
     * is the year of the week number. Then get weeks
     * between that date and the first day of that year.
     *
     * Note that dates in one year can be weeks of previous
     * or next year, overlap is up to 3 days.
     *
     * e.g. 2014/12/29 is Monday in week  1 of 2015
     *      2012/1/1   is Sunday in week 52 of 2011
     */

    function get_week_of_year (d) {
      /* Copy date so don't modify original */
      d = new Date(+d);
      d.setUTCHours(0, 0, 0);
      /* Set to nearest Thursday: current date + 4 - current day number
       * Make Sunday's day number 7 */
      d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
      /* Get first day of year */
      var yearStart = new Date(d.getUTCFullYear(), 0, 1);
      /* Calculate full weeks to nearest Thursday */
      var weekNo = Math.ceil(((d - yearStart) / 86400000 + 1) / 7);
      /* Return array of year and week number */
      return [d.getUTCFullYear(), weekNo];
    }

    function pad(num) {
      var size = arguments.length <= 1 || arguments[1] === undefined ? 2 : arguments[1];

      var s = num + '';
      while (s.length < size) {
        s = '0' + s;
      }
      return s;
    }

    /**
     * calculate a string from a date according to HTML5
     */
    function date_to_string(date, element_type) {
      switch (element_type) {
        case 'datetime':
          return date_to_string(date, 'date') + 'T' + date_to_string(date, 'time');

        case 'datetime-local':
          return sprintf('%s-%s-%sT%s:%s:%s.%s', date.getFullYear(), pad(date.getMonth() + 1), pad(date.getDate()), pad(date.getHours()), pad(date.getMinutes()), pad(date.getSeconds()), pad(date.getMilliseconds(), 3)).replace(/(:00)?\.000$/, '');

        case 'date':
          return sprintf('%s-%s-%s', date.getUTCFullYear(), pad(date.getUTCMonth() + 1), pad(date.getUTCDate()));

        case 'month':
          return sprintf('%s-%s', date.getUTCFullYear(), pad(date.getUTCMonth() + 1));

        case 'week':
          var params = get_week_of_year(date);
          return sprintf.call(null, '%s-W%s', params[0], pad(params[1]));

        case 'time':
          return sprintf('%s:%s:%s.%s', pad(date.getUTCHours()), pad(date.getUTCMinutes()), pad(date.getUTCSeconds()), pad(date.getUTCMilliseconds(), 3)).replace(/(:00)?\.000$/, '');
      }

      return null;
    }

    /**
     * implement the valueAsDate functionality
     *
     * @see https://html.spec.whatwg.org/multipage/forms.html#dom-input-valueasdate
     */
    function valueAsDate() {
      var value = arguments.length <= 0 || arguments[0] === undefined ? undefined : arguments[0];

      /* jshint -W040 */
      if (dates.indexOf(this.type) > -1) {
        if (value !== undefined) {
          /* setter: value must be null or a Date() */
          if (value === null) {
            this.value = '';
          } else if (value instanceof Date) {
            if (isNaN(value.getTime())) {
              this.value = '';
            } else {
              this.value = date_to_string(value, this.type);
            }
          } else {
            throw new window.DOMException('valueAsDate setter encountered invalid value', 'TypeError');
          }
          return;
        }

        var value_date = string_to_date(this.value, this.type);
        return value_date instanceof Date ? value_date : null;
      } else if (value !== undefined) {
        /* trying to set a date on a not-date input fails */
        throw new window.DOMException('valueAsDate setter cannot set date on this element', 'InvalidStateError');
      }
      /* jshint +W040 */

      return null;
    }

    valueAsDate.install = installer('valueAsDate', {
      configurable: true,
      enumerable: true,
      get: valueAsDate,
      set: valueAsDate
    });

    mark(valueAsDate);

    /**
     * implement the valueAsNumber functionality
     *
     * @see https://html.spec.whatwg.org/multipage/forms.html#dom-input-valueasnumber
     */
    function valueAsNumber() {
      var value = arguments.length <= 0 || arguments[0] === undefined ? undefined : arguments[0];

      /* jshint -W040 */
      if (numbers.indexOf(this.type) > -1) {
        if (this.type === 'range' && this.hasAttribute('multiple')) {
          /* @see https://html.spec.whatwg.org/multipage/forms.html#do-not-apply */
          return NaN;
        }

        if (value !== undefined) {
          /* setter: value must be NaN or a finite number */
          if (isNaN(value)) {
            this.value = '';
          } else if (typeof value === 'number' && window.isFinite(value)) {
            try {
              /* try setting as a date, but... */
              valueAsDate.call(this, new Date(value));
            } catch (e) {
              /* ... when valueAsDate is not responsible, ... */
              if (!(e instanceof window.DOMException)) {
                throw e;
              }
              /* ... set it via Number.toString(). */
              this.value = value.toString();
            }
          } else {
            throw new window.DOMException('valueAsNumber setter encountered invalid value', 'TypeError');
          }
          return;
        }

        return string_to_number(this.value, this.type);
      } else if (value !== undefined) {
        /* trying to set a number on a not-number input fails */
        throw new window.DOMException('valueAsNumber setter cannot set number on this element', 'InvalidStateError');
      }
      /* jshint +W040 */

      return NaN;
    }

    valueAsNumber.install = installer('valueAsNumber', {
      configurable: true,
      enumerable: true,
      get: valueAsNumber,
      set: valueAsNumber
    });

    mark(valueAsNumber);

    /**
     * check, if an element will be subject to HTML5 validation
     */
    function willValidate() {
      /* jshint -W040 */
      return is_validation_candidate(this);
      /* jshint +W040 */
    }

    /**
     * publish a convenience function to replace the native element.willValidate
     */
    willValidate.install = installer('willValidate', {
      configurable: true,
      enumerable: true,
      get: willValidate,
      set: undefined
    });

    mark(willValidate);

    var version = '0.1.4';

    /**
     * public hyperform interface:
     */
    var hyperform = {

      version: version,

      checkValidity: checkValidity,

      reportValidity: reportValidity,

      setCustomValidity: setCustomValidity,

      validationMessage: validationMessage,

      ValidityState: ValidityState,

      valueAsDate: valueAsDate,

      valueAsNumber: valueAsNumber,

      willValidate: willValidate,

      capture: function capture(form) {
        var els;
        if (form === window || form instanceof window.HTMLDocument) {
          /* install on the prototypes, when called for the document */
          els = [window.HTMLInputElement.prototype, window.HTMLSelectElement.prototype, window.HTMLTextAreaElement.prototype];
        } else if (form instanceof window.HTMLFormElement || form instanceof window.HTMLFieldSetElement) {
          els = form.elements;
        }

        var els_length = els.length;
        for (var i = 0; i < els_length; i++) {
          checkValidity.install(els[i]);
          reportValidity.install(els[i]);
          setCustomValidity.install(els[i]);
          validationMessage.install(els[i]);
          ValidityState.install(els[i]);
          valueAsDate.install(els[i]);
          valueAsNumber.install(els[i]);
          willValidate.install(els[i]);
        }
      }
    };

    window.hyperform = hyperform;

});


text:
<?php
/**
 * Base controller.
 * Author: Roman Hinex
 * Date: 03.12.14
 * Time: 6:41
 */

namespace Core\Base;

use Core\System\Request;
use Core\System\Translation;
use Core\System\View;
use Models\Extended\User;

abstract class Controller
{
	protected $request;
	protected $user;
	protected $display;
	protected $translation;

	final function __construct()
	{
		$this->request      = Request::main();
		$this->user         = User::main();
		$this->display      = View::main();
		$this->translation  = Translation::main();
	}

	public function runBefore()
	{
	}

	public function runAfter()
	{
	}
}


text:
'use strict'

/**
 * init bookshelf connection
 * @type {[type]}
 * 用法如下
    const bookshelf = require('./base')();
    var Users = bookshelf.Model.extend({
        tableName: 'users'
    });

    module.exports = Users;

 */
let Bookshelf = null,
    dbConfig = require('../config/db.dev.conf.js');
module.exports = function() {

    if (Bookshelf) {
        return Bookshelf;
    }

    var knex = require('knex')(dbConfig);

    Bookshelf = require('bookshelf')(knex);

    /**
     * This solves the circular module dependency problem created by Bookshelf models
     * in a previous commit #38d98bb4c33e91b636a3538bd546ebe7f5077328
     **/
    Bookshelf.plugin('registry');

    return Bookshelf;
};


text:
title: Steps in Euclid's algorithm
localeTitle: Euclid算法中的步骤
---
## 问题433:欧几里得算法中的步骤

这是一个存根。 [帮助我们的社区扩展它](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/project-euler/problem-433-steps-in-euclids-algorithm/index.md) 。

[这种快速风格指南有助于确保您的拉取请求被接受](https://github.com/freecodecamp/guides/blob/master/README.md) 。


text:
import unittest
import os
import selesame
from selenium import webdriver

class Test(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()

    def tearDown(self):
        self.driver.close()

    @classmethod
    def setUpClass(cls):
        path = os.getcwd().split(os.sep)

        for d in reversed(path[:]):
            if d != 'selesame':
                path.pop()
                continue

            break

        path.append("tests")
        path.append("www")

        cls.path = "file://" + os.sep.join(path)

    def getUrl(self, filename):
        return self.path + os.sep + filename

    def testNoHTMLTag(self):
        d = selesame.analyze(url = self.getUrl("nohtmltag.html"), driver = self.driver)

        for v in d.itervalues():
            for xpath in v:
                self.assertIsNotNone(self.driver.find_element_by_xpath(xpath))

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()


text:
  <commonheader></commonheader>

    <commonmenu class="layout-menu"></commonmenu>

      <navmenu></navmenu>

  <commonfooter></commonfooter>


text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
namespace ITCC.HTTP.Server.Enums
{
    public enum FileOperationStatus
    {
        Ok,
        JobQueued,
        BadParameters,
        NotFound,
        Conflict,
        FilesNotEnabled,
        Error
    }
}


text:
package consulo.javascript.lang.parsing;

import com.intellij.lang.PsiBuilder;
import com.intellij.lang.javascript.JSElementTypes;
import com.intellij.lang.javascript.JSTokenTypes;
import com.intellij.lang.javascript.JavaScriptBundle;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import consulo.javascript.ecmascript6.psi.impl.EcmaScript6ElementTypes;
import consulo.javascript.lang.JavaScriptTokenSets;
import consulo.javascript.localize.JavaScriptLocalize;
import consulo.logging.Logger;

import javax.annotation.Nonnull;

/**
 * @author VISTALL
 * @since 15.02.2016
 */
public class EcmaScriptStatementParsing extends StatementParsing
{
	private static final Logger LOGGER = Logger.getInstance(EcmaScriptStatementParsing.class);

	public EcmaScriptStatementParsing(EcmaScriptParsingContext context)
	{
		super(context);
	}

	@Override
	public void parseSourceElement(PsiBuilder builder)
	{
		final IElementType tokenType = builder.getTokenType();
		if(tokenType == JSTokenTypes.FUNCTION_KEYWORD)
		{
			getFunctionParsing().parseFunctionDeclaration(builder);
		}
		else if(tokenType == JSTokenTypes.EXPORT_KEYWORD && builder.lookAhead(1) == JSTokenTypes.DEFAULT_KEYWORD)
		{
			PsiBuilder.Marker mark = builder.mark();
			builder.advanceLexer();
			builder.advanceLexer();

			parseSourceElement(builder);

			mark.done(EcmaScript6ElementTypes.EXPORT_DEFAULT_ASSIGMENT);
		}
		else if(tokenType == JSTokenTypes.EXPORT_KEYWORD)
		{
			PsiBuilder.Marker mark = builder.mark();
			PsiBuilder.Marker attributeMark = builder.mark();
			builder.advanceLexer();
			attributeMark.done(JSElementTypes.ATTRIBUTE_LIST);

			IElementType nextType = builder.getTokenType();
			if(nextType == JSTokenTypes.FUNCTION_KEYWORD)
			{
				getFunctionParsing().parseFunctionNoMarker(builder, false, mark);
			}
			else if(nextType == JSTokenTypes.CLASS_KEYWORD)
			{
				parseClassWithMarker(builder, mark, false);
			}
			else if(nextType == JSTokenTypes.VAR_KEYWORD ||
					nextType == JSTokenTypes.CONST_KEYWORD ||
					nextType == JSTokenTypes.LET_KEYWORD)
			{
				parseVarStatementWithMarker(builder, false, mark);
			}
			else
			{
				mark.error("Expected function or variable");
			}
		}
		else
		{
			doParseStatement(builder, true);
		}
	}

	@Override
	protected boolean parseForLoopHeader(final PsiBuilder builder)
	{
		builder.advanceLexer();

		Parsing.checkMatches(builder, JSTokenTypes.LPAR, JavaScriptBundle.message("javascript.parser.message.expected.lparen"));
		final boolean empty;
		if(builder.getTokenType() == JSTokenTypes.VAR_KEYWORD || builder.getTokenType() == JSTokenTypes.LET_KEYWORD || builder.getTokenType() == JSTokenTypes.CONST_KEYWORD)
		{
			parseVarStatement(builder, true);
			empty = false;
		}
		else
		{
			empty = !getExpressionParsing().parseExpressionOptional(builder, false);
		}

		boolean forin = false;
		if(builder.getTokenType() == JSTokenTypes.SEMICOLON)
		{
			builder.advanceLexer();
			getExpressionParsing().parseExpressionOptional(builder);

			if(builder.getTokenType() == JSTokenTypes.SEMICOLON)
			{
				builder.advanceLexer();
			}
			else
			{
				builder.error(JavaScriptBundle.message("javascript.parser.message.expected.semicolon"));
			}
			getExpressionParsing().parseExpressionOptional(builder);
		}
		else if(isContextKeyword(builder, JSTokenTypes.OF_KEYWORD) || builder.getTokenType() == JSTokenTypes.IN_KEYWORD)
		{
			forin = true;
			if(empty)
			{
				builder.error(JavaScriptBundle.message("javascript.parser.message.expected.forloop.left.hand.side.expression.or.variable.declaration"));
			}

			if(builder.getTokenType() == JSTokenTypes.IN_KEYWORD)
			{
				builder.advanceLexer();
			}
			else
			{
				advanceContextKeyword(builder, JSTokenTypes.OF_KEYWORD);
			}

			getExpressionParsing().parseExpression(builder);
		}
		else
		{
			builder.error(JavaScriptBundle.message("javascript.parser.message.expected.forloop.in.of.or.semicolon"));
		}

		Parsing.checkMatches(builder, JSTokenTypes.RPAR, JavaScriptBundle.message("javascript.parser.message.expected.rparen"));
		return forin;
	}

	@Override
	protected void doParseStatement(PsiBuilder builder, boolean canHaveClasses)
	{
		if(canHaveClasses)
		{
			if(builder.getTokenType() == JSTokenTypes.IMPORT_KEYWORD)
			{
				parseImportStatement(builder);
				return;
			}
		}
		super.doParseStatement(builder, canHaveClasses);
	}

	private void parseImportStatement(final PsiBuilder builder)
	{
		final PsiBuilder.Marker importStatement = builder.mark();
		try
		{
			builder.advanceLexer();

			boolean wantFrom = true;

			if(builder.getTokenType() == JSTokenTypes.ASTERISK)
			{
				PsiBuilder.Marker bindingMark = builder.mark();

				builder.advanceLexer();

				if(isContextKeyword(builder, JSTokenTypes.AS_KEYWORD))
				{
					advanceContextKeyword(builder, JSTokenTypes.AS_KEYWORD);

					if(builder.getTokenType() == JSTokenTypes.IDENTIFIER)
					{
						builder.advanceLexer();
					}
					else
					{
						builder.error(JavaScriptLocalize.javascriptParserMessageExpectedIdentifier());
					}
				}

				bindingMark.done(EcmaScript6ElementTypes.IMPORTED_BINDING);
			}
			else if(JavaScriptTokenSets.STRING_LITERALS.contains(builder.getTokenType()))
			{
				builder.advanceLexer();
				wantFrom = false;
			}
			else
			{
				boolean firstBinding = true;

				while(!builder.eof())
				{
					if(builder.getTokenType() != JSTokenTypes.COMMA && !isIdentifierToken(builder) && builder.getTokenType() != JSTokenTypes.LBRACE)
					{
						break;
					}

					if(isContextKeyword(builder, JSTokenTypes.FROM_KEYWORD))
					{
						break;
					}

					if(!firstBinding)
					{
						Parsing.checkMatches(builder, JSTokenTypes.COMMA, "Comma expected");
					}

					if(builder.getTokenType() == JSTokenTypes.LBRACE)
					{
						PsiBuilder.Marker namedImportsMark = builder.mark();
						builder.advanceLexer();

						boolean first = true;
						while(!builder.eof())
						{
							if(builder.getTokenType() == JSTokenTypes.RBRACE)
							{
								break;
							}

							if(!first)
							{
								if(builder.getTokenType() == JSTokenTypes.COMMA)
								{
									builder.advanceLexer();
								}
								else
								{
									builder.error("Comma expected");
								}
							}

							first = false;

							if(builder.getTokenType() == JSTokenTypes.IDENTIFIER)
							{
								PsiBuilder.Marker importBindingMark = builder.mark();
								builder.advanceLexer();

								if(isContextKeyword(builder, JSTokenTypes.AS_KEYWORD))
								{
									PsiBuilder.Marker importSpecificMark = builder.mark();
									advanceContextKeyword(builder, JSTokenTypes.AS_KEYWORD);

									if(builder.getTokenType() == JSTokenTypes.IDENTIFIER)
									{
										builder.advanceLexer();

										importSpecificMark.done(EcmaScript6ElementTypes.IMPORT_SPECIFIER);
									}
									else
									{
										importSpecificMark.error("Expected identifier");
									}
								}

								importBindingMark.done(EcmaScript6ElementTypes.IMPORTED_BINDING);
							}
							else if(builder.getTokenType() != JSTokenTypes.RBRACE)
							{
								builder.error("Expected identifier");
								break;
							}
						}

						Parsing.checkMatches(builder, JSTokenTypes.RBRACE, "'}' expected");

						namedImportsMark.done(EcmaScript6ElementTypes.NAMED_IMPORTS);
					}
					else if(builder.getTokenType() == JSTokenTypes.IDENTIFIER)
					{
						PsiBuilder.Marker importBindingMark = builder.mark();
						builder.advanceLexer();
						importBindingMark.done(EcmaScript6ElementTypes.IMPORTED_BINDING);
					}
					else
					{
						builder.error(JavaScriptBundle.message("javascript.parser.message.expected.typename"));
						break;
					}

					firstBinding = false;
				}
			}

			if(wantFrom && isContextKeyword(builder, JSTokenTypes.FROM_KEYWORD))
			{
				advanceContextKeyword(builder, JSTokenTypes.FROM_KEYWORD);

				if(JavaScriptTokenSets.STRING_LITERALS.contains(builder.getTokenType()))
				{
					builder.advanceLexer();
				}
				else
				{
					builder.error("Expecte from target");
				}
			}

			checkForSemicolon(builder);
		}
		finally
		{
			importStatement.done(EcmaScript6ElementTypes.IMPORT_DECLARATION);
		}
	}

	@Override
	protected boolean doParseStatementSub(PsiBuilder builder, boolean canHaveClasses)
	{
		IElementType tokenType = builder.getTokenType();
		if(canHaveClasses)
		{
			if(tokenType == JSTokenTypes.CLASS_KEYWORD)
			{
				parseClass(builder, true);
				return true;
			}
		}
		return false;
	}

	private void parseClass(final PsiBuilder builder, boolean nameRequired)
	{
		parseClassWithMarker(builder, builder.mark(), nameRequired);
	}

	public void parseClassWithMarker(final PsiBuilder builder, final @Nonnull PsiBuilder.Marker clazz, boolean nameRequired)
	{
		builder.advanceLexer();

		if(builder.getTokenType() != JSTokenTypes.IDENTIFIER)
		{
			if(nameRequired)
			{
				builder.error(JavaScriptLocalize.javascriptParserMessageExpectedIdentifier());
			}
		}
		else
		{
			builder.advanceLexer();
		}

		if(builder.getTokenType() == JSTokenTypes.EXTENDS_KEYWORD)
		{
			parseReferenceList(builder);
		}

		parseClassBody(builder, BlockType.PACKAGE_OR_CLASS_BODY);
		clazz.done(JSElementTypes.CLASS);
	}

	protected void parseClassBody(final PsiBuilder builder, BlockType type)
	{
		if(builder.getTokenType() != JSTokenTypes.LBRACE)
		{
			builder.error(JavaScriptBundle.message("javascript.parser.message.expected.lbrace"));
			return;
		}

		builder.advanceLexer();
		while(builder.getTokenType() != JSTokenTypes.RBRACE)
		{
			if(builder.eof())
			{
				builder.error(JavaScriptLocalize.javascriptParserMessageMissingRbrace());
				return;
			}

			PsiBuilder.Marker attributeListMarker = builder.mark();
			if(expectStaticKeywordExpected(builder))
			{
				attributeListMarker.done(JSElementTypes.ATTRIBUTE_LIST);
			}
			else
			{
				attributeListMarker.drop();
				attributeListMarker = null;
			}

			IElementType tokenType = builder.getTokenType();
			if(tokenType != JSTokenTypes.IDENTIFIER && tokenType != JSTokenTypes.MULT)
			{
				if(attributeListMarker != null)
				{
					attributeListMarker.rollbackTo();
				}

				PsiBuilder.Marker mark = builder.mark();

				if(attributeListMarker != null)
				{
					PsiBuilder.Marker temp = builder.mark();
					expectStaticKeywordExpected(builder);
					temp.done(JSElementTypes.ATTRIBUTE_LIST);
				}

				builder.advanceLexer();
				mark.error("Expected identifier or *");
			}
			else
			{
				if(attributeListMarker != null)
				{
					attributeListMarker.rollbackTo();
				}

				PsiBuilder.Marker mark = builder.mark();

				if(attributeListMarker != null)
				{
					PsiBuilder.Marker temp = builder.mark();
					expectStaticKeywordExpected(builder);
					temp.done(JSElementTypes.ATTRIBUTE_LIST);
				}

				if(builder.getTokenType() == JSTokenTypes.MULT)
				{
					builder.advanceLexer();
				}
				else
				{
					if(isContextKeyword(builder, JSTokenTypes.GET_SET_TOKEN_SET) != null && builder.lookAhead(1) == JSTokenTypes.IDENTIFIER)
					{
						advanceContextKeyword(builder, JSTokenTypes.GET_SET_TOKEN_SET);
					}
				}

				if(!JSTokenTypes.IDENTIFIER_TOKENS_SET.contains(builder.getTokenType()))
				{
					builder.error(JavaScriptBundle.message("javascript.parser.message.expected.identifier"));
				}
				else
				{
					builder.advanceLexer();
				}

				getFunctionParsing().parseParameterList(builder);
				getStatementParsing().parseFunctionBody(builder);

				checkForSemicolon(builder);

				mark.done(JSElementTypes.FUNCTION_DECLARATION);
			}
		}

		builder.advanceLexer();
	}

	private boolean expectStaticKeywordExpected(PsiBuilder builder)
	{
		IElementType tokenType = builder.getTokenType();
		if(tokenType == JSTokenTypes.STATIC_KEYWORD)
		{
			builder.advanceLexer();
			return true;
		}
		else if(isContextKeyword(builder, TokenSet.create(JSTokenTypes.STATIC_KEYWORD)) != null)
		{
			if(builder.lookAhead(1) == JSTokenTypes.IDENTIFIER)
			{
				advanceContextKeyword(builder, TokenSet.create(JSTokenTypes.STATIC_KEYWORD));
				return true;
			}
		}
		return false;
	}

	private void parseReferenceList(final PsiBuilder builder)
	{
		final IElementType tokenType = builder.getTokenType();
		LOGGER.assertTrue(tokenType == JSTokenTypes.EXTENDS_KEYWORD || tokenType == JSTokenTypes.IMPLEMENTS_KEYWORD);
		final PsiBuilder.Marker referenceList = builder.mark();
		builder.advanceLexer();

		if(getExpressionParsing().parseQualifiedTypeName(builder))
		{
			while(builder.getTokenType() == JSTokenTypes.COMMA)
			{
				builder.advanceLexer();
				if(!getExpressionParsing().parseQualifiedTypeName(builder))
				{
					break;
				}
			}
		}
		referenceList.done(JSElementTypes.EXTENDS_LIST);
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2016 Goldman Sachs.
  ~ All rights reserved. This program and the accompanying materials
  ~ are made available under the terms of the Eclipse Public License v1.0
  ~ and Eclipse Distribution License v. 1.0 which accompany this distribution.
  ~ The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
  ~ and the Eclipse Distribution License is available at
  ~ http://www.eclipse.org/org/documents/edl-v10.php.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>test2</groupId>
    <artifactId>testparent2</artifactId>
    <version>1.0.0-SNAPSHOT</version>

    <packaging>pom</packaging>

    <name>Test Project 2 - this file shouldn't be updated</name>
</project>


text:
layout: post
title: Apollohq - Review - Part 2
tags:
- Projektmanagement
status: draft
type: post
published: false
meta:
  _edit_last: '1'
---

Activity Board

Every project space has an activity board. At a one glace you can tell what happened in the past day. Comes in very handy. I'm just wondering ho


text:
<?php

namespace App\Providers;

use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        /**
         * Frontend Events
         */

        /**
         * Authentication Events
         */
        \App\Events\Frontend\Auth\UserLoggedIn::class  => [
            \App\Listeners\Frontend\Auth\UserLoggedInListener::class,
        ],
        \App\Events\Frontend\Auth\UserLoggedOut::class => [
            \App\Listeners\Frontend\Auth\UserLoggedOutListener::class,
        ],
        \App\Events\Frontend\Auth\UserRegistered::class => [
            \App\Listeners\Frontend\Auth\UserRegisteredListener::class,
        ],
    ];

    /**
     * Register any other events for your application.
     *
     * @param  \Illuminate\Contracts\Events\Dispatcher  $events
     * @return void
     */
    public function boot(DispatcherContract $events)
    {
        parent::boot($events);

        //
    }
}


text:
import subprocess
import sys
from datetime import datetime

from fs.base import FS

from ._timefilter import TimeFilter

class DateAdded(TimeFilter):

    """Matches files by the time the file was added to a folder.

    **`date_added` is only available on macOS!**

    Args:
        years (int): specify number of years
        months (int): specify number of months
        weeks (float): specify number of weeks
        days (float): specify number of days
        hours (float): specify number of hours
        minutes (float): specify number of minutes
        seconds (float): specify number of seconds
        mode (str):
            either 'older' or 'newer'. 'older' matches files / folders last modified before
            the given time, 'newer' matches files / folders last modified within the given
            time. (default = 'older')

    Returns:
        {date_added}: The datetime the files / folders were added.
    """

    name = "date_added"

    def get_datetime(self, args: dict) -> datetime:
        if sys.platform != "darwin":
            raise EnvironmentError("date_added is only available on macOS")

        fs = args["fs"]  # type: FS
        fs_path = args["fs_path"]

        cmd = ["mdls", "-name", "kMDItemDateAdded", "-raw", fs.getsyspath(fs_path)]
        out = subprocess.check_output(cmd, encoding="utf-8").strip()
        dt = datetime.strptime(out, "%Y-%m-%d %H:%M:%S %z")
        return dt

    def __str__(self):
        return "[DateAdded] All files / folders added %s than %s" % (
            self._mode,
            self.timedelta,
        )


text:
import Redis from "../../lib/Redis";
import { expect } from "chai";

describe("watch-exec", () => {
  it("should support watch/exec transactions", () => {
    const redis1 = new Redis();
    return redis1
      .watch("watchkey")
      .then(() => {
        return redis1.multi().set("watchkey", "1").exec();
      })
      .then(function (result) {
        expect(result.length).to.eql(1);
        expect(result[0]).to.eql([null, "OK"]);
      });
  });

  it("should support watch/exec transaction rollback", () => {
    const redis1 = new Redis();
    const redis2 = new Redis();
    return redis1
      .watch("watchkey")
      .then(() => {
        return redis2.set("watchkey", "2");
      })
      .then(() => {
        return redis1.multi().set("watchkey", "1").exec();
      })
      .then(function (result) {
        expect(result).to.be.null;
      });
  });
});


text:
using PatternBuffer;
using System;
using System.Collections.Generic;
namespace Test.Map {
    public class ThingThingMapObject : IMapTestObject, IEquatable<ThingThingMapObject> {

        public const ushort TYPE_ID = 14;
        public ushort TypeId {
            get { return TYPE_ID; }
        }

        public Dictionary<Thing,Thing> ThingThingMap; // (required)

        public ThingThingMapObject() {
            this.ThingThingMap = default(Dictionary<Thing,Thing>);
        }

        public ThingThingMapObject(
            Dictionary<Thing,Thing> thingThingMap
        ) {
            this.ThingThingMap = thingThingMap;
        }

        public bool Equals(ThingThingMapObject other) {
            return this.Equals((object)other);
        }
        public override bool Equals(object other) {;
            if (Object.ReferenceEquals(this, other)) { return true; }
            if ( ! (other is ThingThingMapObject)) { return false; }
            ThingThingMapObject that = (ThingThingMapObject)other;
            if (this.GetHashCode() != that.GetHashCode()) return false;
            // ThingThingMap (required)
                if (this.ThingThingMap == null && that.ThingThingMap != null) { return false; }
                if (that.ThingThingMap != null && this.ThingThingMap == null) { return false; }
            if (that.ThingThingMap.Count != this.ThingThingMap.Count) { return false; }
            foreach (Thing key in this.ThingThingMap.Keys) {
                if ( ! that.ThingThingMap.ContainsKey(key)) { return false; }
            }
            return true;
        }

        public override int GetHashCode() {
            unchecked {
                int hash = 27;
                hash = (13*hash) + (this.ThingThingMap == null ? 0 : this.ThingThingMap.GetHashCode());
                return hash;
            }
        }
    }
}


text:
package com.tsystems.cargo.container.wso2.deployable;

import java.util.Locale;

import org.codehaus.cargo.container.spi.deployable.AbstractDeployable;

public abstract class AbstractWSO2Deployable extends AbstractDeployable
{

    private long deployTimeout = -1;

    public AbstractWSO2Deployable(String file)
    {
        super(file);
    }

    public long getDeployTimeout()
    {
        return deployTimeout;
    }

    public void setDeployTimeout(String deployTimeout)
    {
        this.deployTimeout = Long.valueOf(deployTimeout);
    }

    protected String parseApplication(String extension)
    {
        String name = getFileHandler().getName(getFile());

        int index = name.toLowerCase(Locale.ENGLISH).lastIndexOf(extension);
        if (index >= 0)
        {
            name = name.substring(0, index);
        }

        return name;
    }

}


text:
package com.google.gerrit.httpd.raw;

import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.common.base.MoreObjects;
import com.google.common.escape.Escaper;
import com.google.common.html.HtmlEscapers;
import com.google.common.io.ByteStreams;
import com.google.gerrit.common.TimeUtil;
import com.google.gwtexpui.linker.server.UserAgentRule;
import com.google.gwtexpui.server.CacheHeaders;

import org.eclipse.jgit.util.RawParseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

class RecompileGwtUiFilter implements Filter {
  private static final Logger log =
      LoggerFactory.getLogger(RecompileGwtUiFilter.class);

  private final boolean gwtuiRecompile =
      System.getProperty("gerrit.disable-gwtui-recompile") == null;
  private final UserAgentRule rule = new UserAgentRule();
  private final Set<String> uaInitialized = new HashSet<>();
  private final Path unpackedWar;
  private final Path gen;
  private final Path root;

  private String lastTarget;
  private long lastTime;

  RecompileGwtUiFilter(Path buckOut, Path unpackedWar) {
    this.unpackedWar = unpackedWar;
    gen = buckOut.resolve("gen");
    root = buckOut.getParent();
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse res,
      FilterChain chain) throws IOException, ServletException {
    String pkg = "gerrit-gwtui";
    String target = "ui_" + rule.select((HttpServletRequest) request);
    if (gwtuiRecompile || !uaInitialized.contains(target)) {
      String rule = "//" + pkg + ":" + target;
      // TODO(davido): instead of assuming specific Buck's internal
      // target directory for gwt_binary() artifacts, ask Buck for
      // the location of user agent permutation GWT zip, e. g.:
      // $ buck targets --show_output //gerrit-gwtui:ui_safari \
      //    | awk '{print $2}'
      String child = String.format("%s/__gwt_binary_%s__", pkg, target);
      File zip = gen.resolve(child).resolve(target + ".zip").toFile();

      synchronized (this) {
        try {
          build(root, gen, rule);
        } catch (BuildFailureException e) {
          displayFailure(rule, e.why, (HttpServletResponse) res);
          return;
        }

        if (!target.equals(lastTarget) || lastTime != zip.lastModified()) {
          lastTarget = target;
          lastTime = zip.lastModified();
          unpack(zip, unpackedWar.toFile());
        }
      }
      uaInitialized.add(target);
    }
    chain.doFilter(request, res);
  }

  private void displayFailure(String rule, byte[] why, HttpServletResponse res)
      throws IOException {
    res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    res.setContentType("text/html");
    res.setCharacterEncoding(UTF_8.name());
    CacheHeaders.setNotCacheable(res);

    Escaper html = HtmlEscapers.htmlEscaper();
    try (PrintWriter w = res.getWriter()) {
      w.write("<title>BUILD FAILED</title>");
      w.format("
%s FAILED
", html.escape(rule));
      w.write("
");
      w.write(html.escape(RawParseUtils.decode(why)));
      w.write("
");
      w.write("");
    }
  }

  @Override
  public void init(FilterConfig config) {
  }

  @Override
  public void destroy() {
  }

  private static void unpack(File srcwar, File dstwar) throws IOException {
    try (ZipFile zf = new ZipFile(srcwar)) {
      final Enumeration<? extends ZipEntry> e = zf.entries();
      while (e.hasMoreElements()) {
        final ZipEntry ze = e.nextElement();
        final String name = ze.getName();

        if (ze.isDirectory()
          || name.startsWith("WEB-INF/")
          || name.startsWith("META-INF/")
          || name.startsWith("com/google/gerrit/launcher/")
          || name.equals("Main.class")) {
          continue;
        }

        final File rawtmp = new File(dstwar, name);
        mkdir(rawtmp.getParentFile());
        rawtmp.deleteOnExit();

        try (FileOutputStream rawout = new FileOutputStream(rawtmp);
            InputStream in = zf.getInputStream(ze)) {
          final byte[] buf = new byte[4096];
          int n;
          while ((n = in.read(buf, 0, buf.length)) > 0) {
            rawout.write(buf, 0, n);
          }
        }
      }
    }
  }

  private static void build(Path root, Path gen, String target)
      throws IOException, BuildFailureException {
    log.info("buck build " + target);
    Properties properties = loadBuckProperties(gen);
    String buck = MoreObjects.firstNonNull(properties.getProperty("buck"), "buck");
    ProcessBuilder proc = new ProcessBuilder(buck, "build", target)
        .directory(root.toFile())
        .redirectErrorStream(true);
    if (properties.containsKey("PATH")) {
      proc.environment().put("PATH", properties.getProperty("PATH"));
    }
    long start = TimeUtil.nowMs();
    Process rebuild = proc.start();
    byte[] out;
    try (InputStream in = rebuild.getInputStream()) {
      out = ByteStreams.toByteArray(in);
    } finally {
      rebuild.getOutputStream().close();
    }

    int status;
    try {
      status = rebuild.waitFor();
    } catch (InterruptedException e) {
      throw new InterruptedIOException("interrupted waiting for " + buck);
    }
    if (status != 0) {
      throw new BuildFailureException(out);
    }

    long time = TimeUtil.nowMs() - start;
    log.info(String.format("UPDATED    %s in %.3fs", target, time / 1000.0));
  }

  private static Properties loadBuckProperties(Path gen)
      throws FileNotFoundException, IOException {
    Properties properties = new Properties();
    try (InputStream in = new FileInputStream(
        gen.resolve(Paths.get("tools/buck/buck.properties")).toFile())) {
      properties.load(in);
    }
    return properties;
  }

  @SuppressWarnings("serial")
  private static class BuildFailureException extends Exception {
    final byte[] why;

    BuildFailureException(byte[] why) {
      this.why = why;
    }
  }

  private static void mkdir(File dir) throws IOException {
    if (!dir.isDirectory()) {
      mkdir(dir.getParentFile());
      if (!dir.mkdir()) {
        throw new IOException("Cannot mkdir " + dir.getAbsolutePath());
      }
      dir.deleteOnExit();
    }
  }
}


text:
import { Mongo } from 'meteor/mongo';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';

/* eslint-disable object-shorthand */

export const Stuff = new Mongo.Collection('Stuff');

/**
 * Create the schema for Stuff
 */
export const StuffSchema = new SimpleSchema({
  name: {
    label: 'Name',
    type: String,
    optional: false,
    max: 20,
    autoform: {
      group: 'Stuff',
      placeholder: 'Bicycle',
    },
  },
  quantity: {
    label: 'Quantity',
    type: Number,
    optional: false,
    autoform: {
      group: 'Stuff',
      placeholder: '3',
    },
  },
});

Stuff.attachSchema(StuffSchema);