text:
SET FOREIGN_KEY_CHECKS = 0;

-- ---------------------------------------------------------------------
-- content
-- ---------------------------------------------------------------------

DROP TABLE IF EXISTS `content`;

CREATE TABLE `content`
(
    `id` INTEGER NOT NULL AUTO_INCREMENT,
    `contentRegistryID` INTEGER NOT NULL,
    `content` LONGTEXT,
    `localeID` INTEGER NOT NULL,
    PRIMARY KEY (`id`),
    UNIQUE INDEX `UNIQUE_CONTENTREFLOCALE` (`contentRegistryID`, `localeID`),
    INDEX `INDEX_CONTENTREF` (`contentRegistryID`),
    INDEX `INDEX_LOCALE` (`localeID`),
    CONSTRAINT `content_fk_7a9c06`
        FOREIGN KEY (`contentRegistryID`)
        REFERENCES `contentRegistry` (`id`),
    CONSTRAINT `content_fk_5579a0`
        FOREIGN KEY (`localeID`)
        REFERENCES `locale` (`id`)
) ENGINE=InnoDB;

-- ---------------------------------------------------------------------
-- contentRegistry
-- ---------------------------------------------------------------------

DROP TABLE IF EXISTS `contentRegistry`;

CREATE TABLE `contentRegistry`
(
    `id` INTEGER NOT NULL AUTO_INCREMENT,
    `reference` VARCHAR(255) NOT NULL,
    `contentTypeID` INTEGER NOT NULL,
    `dataFormat` VARCHAR(255),
    `contentCategoryID` INTEGER NOT NULL,
    `startDate` DATETIME DEFAULT '2014-01-01',
    `endDate` DATETIME DEFAULT '2099-12-31',
    `active` BOOL DEFAULT true,
    PRIMARY KEY (`id`),
    UNIQUE INDEX `reference` (`reference`),
    INDEX `INDEX_CategoryID` (`contentCategoryID`),
    INDEX `contentRegistry_fi_5cb791` (`contentTypeID`),
    CONSTRAINT `contentRegistry_fk_5cb791`
        FOREIGN KEY (`contentTypeID`)
        REFERENCES `contentType` (`id`)
) ENGINE=InnoDB;

-- ---------------------------------------------------------------------
-- contentType
-- ---------------------------------------------------------------------

DROP TABLE IF EXISTS `contentType`;

CREATE TABLE `contentType`
(
    `id` INTEGER NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(255),
    PRIMARY KEY (`id`)
) ENGINE=InnoDB;

-- ---------------------------------------------------------------------
-- contentCategory
-- ---------------------------------------------------------------------

DROP TABLE IF EXISTS `contentCategory`;

CREATE TABLE `contentCategory`
(
    `id` INTEGER NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(255),
    PRIMARY KEY (`id`)
) ENGINE=InnoDB;

-- ---------------------------------------------------------------------
-- locale
-- ---------------------------------------------------------------------

DROP TABLE IF EXISTS `locale`;

CREATE TABLE `locale`
(
    `id` INTEGER NOT NULL AUTO_INCREMENT,
    `title` VARCHAR(255) NOT NULL,
    `code` VARCHAR(255) NOT NULL,
    `sort` INTEGER NOT NULL,
    PRIMARY KEY (`id`),
    UNIQUE INDEX `code` (`code`)
) ENGINE=InnoDB;

-- ---------------------------------------------------------------------
-- node
-- ---------------------------------------------------------------------

DROP TABLE IF EXISTS `node`;

CREATE TABLE `node`
(
    `id` INTEGER NOT NULL AUTO_INCREMENT,
    `reference` VARCHAR(255),
    `contentID` INTEGER,
    `template` VARCHAR(45),
    `renderdata` TEXT,
    PRIMARY KEY (`id`),
    UNIQUE INDEX `REFERENCE_UNIQUE` (`reference`),
    INDEX `node_fi_8b39b8` (`contentID`),
    CONSTRAINT `node_fk_8b39b8`
        FOREIGN KEY (`contentID`)
        REFERENCES `contentRegistry` (`id`)
) ENGINE=InnoDB;

-- ---------------------------------------------------------------------
-- nodeToNode
-- ---------------------------------------------------------------------

DROP TABLE IF EXISTS `nodeToNode`;

CREATE TABLE `nodeToNode`
(
    `id` INTEGER NOT NULL AUTO_INCREMENT,
    `parent` INTEGER,
    `child` INTEGER,
    `sort` INTEGER,
    PRIMARY KEY (`id`),
    UNIQUE INDEX `PARENT_CHILD` (`parent`, `child`),
    INDEX `PARENT_KEY` (`parent`),
    INDEX `nodeToNode_fi_fe5e49` (`child`),
    CONSTRAINT `nodeToNode_fk_1c85f2`
        FOREIGN KEY (`parent`)
        REFERENCES `node` (`id`),
    CONSTRAINT `nodeToNode_fk_fe5e49`
        FOREIGN KEY (`child`)
        REFERENCES `node` (`id`)
) ENGINE=InnoDB;

# This restores the fkey checks, after having unset them earlier
SET FOREIGN_KEY_CHECKS = 1;

INSERT INTO `locale` (`title`, `code`, `sort`) VALUES ('Default', 'no-ne', '0');
UPDATE `locale` SET `id`='0' WHERE `id`='1';
ALTER TABLE `locale` AUTO_INCREMENT = 1;

INSERT INTO `contentType` (`name`) VALUES ( 'BonsaiNode' );
INSERT INTO `contentType` (`name`) VALUES ( 'Vocab' );

INSERT INTO `contentRegistry` (`contentTypeID`, `contentCategoryID`, `dataFormat`, `reference`, `startDate`, `endDate`, `active`) VALUES ( 1,0,null,'parent','2014-01-01 00:00:00','2099-12-31 00:00:00', true );
UPDATE `contentRegistry` SET `id`='0' WHERE `id`='1';
ALTER TABLE `contentRegistry` AUTO_INCREMENT = 1;

INSERT INTO `content` (`contentRegistryID`, `content`, `localeID`) VALUES ( 0,'Content Not Found',0);

INSERT INTO `node` (`reference`, `contentID`, `template`, `renderdata`) VALUES ('index', '0', 'page', '{ }');


text:
Senflamme
=========

Sexy html5 canvas experiment

redpajama_set_name: RedPajamaGithub


text:
package mcjty.deepresonance.compat;

import elec332.core.util.AbstractCompatHandler;
import mcjty.deepresonance.DeepResonance;
import net.minecraftforge.common.config.Configuration;
import org.apache.logging.log4j.Logger;

/**
 * Created by Elec332 on 5-8-2015.
 */
public class CompatHandler extends AbstractCompatHandler {

    public CompatHandler(Configuration config, Logger logger) {
        super(config, logger);
    }

    @Override
    public void loadList() {
        RF = isAPILoaded("CoFHAPI|energy");

        checkIfRfLoaded();
    }

    public static boolean RF = false;

    private void checkIfRfLoaded(){
        if (!RF) {
            DeepResonance.proxy.throwException(new RuntimeException("Missing API: RF-API"), 0);
        }
    }
}


text:
module Bosh::Core
  class Shell
    def initialize(stdout = $stdout)
      @stdout = stdout
    end

    def run(command, options = {})
      output_lines = run_command(command, options)
      output_lines = tail(output_lines, options)

      command_output = output_lines.join("\n")
      report(command, command_output, options)
      command_output
    end

    private

    attr_reader :stdout

    def run_command(command, options)
      stdout.puts command if options[:output_command]
      lines = []

      if options[:env]
        # Wrap in a shell because existing api to Shell#run takes a string
        # which makes it really hard to pass it to popen with custom environment.
         popen_args = [options[:env], ENV['SHELL'] || 'bash', '-c', command]
      else
        popen_args = command
      end

      io = IO.popen(popen_args)
      io.each do |line|
        stdout.puts line.chomp
        lines << line.chomp
      end

      io.close

      lines
    end

    def tail(lines, options)
      line_number = options[:last_number]
      line_number ? lines.last(line_number) : lines
    end

    def report(cmd, command_output, options)
      return if command_exited_successfully?

      redacted_cmd = cmd
      if options[:redact]
        redacted_cmd = redacted_cmd.gsub(/#{options[:redact].join('|')}/, "[REDACTED]")
      end

      err_msg = "Failed: '#{redacted_cmd}' from #{pwd}, with exit status #{$?.to_i}\n\n #{command_output}"
      options[:ignore_failures] ? stdout.puts("#{err_msg}, continuing anyway") : raise(err_msg)
    end

    def command_exited_successfully?
      $?.success?
    end

    def pwd
      Dir.pwd
    rescue Errno::ENOENT
      'a deleted directory'
    end
  end
end


text:
<?php

declare(strict_types=1);

namespace {

    use PentagonalProject\App\Rest\Util\Hook;

    /**
     * @return Hook
     */
    return function () : Hook {
        return new Hook();
    };
}


text:
package uk.co.jemos.podam.typeManufacturers;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.integration.core.MessagingTemplate;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import uk.co.jemos.podam.api.AttributeMetadata;
import uk.co.jemos.podam.api.DataProviderStrategy;
import uk.co.jemos.podam.api.ObjectStrategy;
import uk.co.jemos.podam.api.PodamUtils;
import uk.co.jemos.podam.common.*;

import javax.validation.Constraint;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.ws.Holder;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Type Manufacturer utility class.
 *
 * Created by tedonema on 01/07/2015.
 *
 * @since 6.0.0.RELEASE
 */
public final class TypeManufacturerUtil {

    /** The application logger */
    private static final Logger LOG = LoggerFactory.getLogger(TypeManufacturerUtil.class);

    /** Non instantiable. */
    private TypeManufacturerUtil() {
        throw new AssertionError("Non instantiable");
    }

    /**
     * Obtains a type value
     * @param strategy The Data Provider strategy
     * @param channel The Message Channel where to send/receive the message for the required value
     * @param attributeMetadata The AttributeMetadata information
     * @param qualifier The class of the requested type
     * @return The type value
     */
    public static Object getTypeValue(DataProviderStrategy strategy,
                                      MessageChannel channel,
                                      AttributeMetadata attributeMetadata,
                                      String qualifier) {
        Object retValue = null;

        TypeManufacturerParamsWrapper wrapper =
                new TypeManufacturerParamsWrapper(strategy, attributeMetadata);

        Message<? extends Object> message = (Message<? extends Object>) MessageBuilder.withPayload(wrapper).setHeader(
                PodamConstants.HEADER_NAME, qualifier)
                .build();

        MessagingTemplate template = new MessagingTemplate();
        retValue = template.sendAndReceive(channel, message).getPayload();
        return retValue;
    }

    /**
     * Obtains a type value
     * @param strategy The Data Provider strategy
     * @param channel The Message Channel where to send/receive the message for the required value
     * @param attributeMetadata The AttributeMetadata information
     * @param genericAttributeType The generic attribute type
     *@param qualifier The class of the requested type  @return The type value
     */
    public static Object getTypeValueForGenericTypes(DataProviderStrategy strategy,
                                                     MessageChannel channel,
                                                     AttributeMetadata attributeMetadata,
                                                     Type genericAttributeType,
                                                     Map<String, Type> genericTypesArgumentsMap,
                                                     String qualifier) {
        Object retValue = null;

        TypeManufacturerParamsWrapperForGenericTypes wrapper =
                new TypeManufacturerParamsWrapperForGenericTypes(strategy, attributeMetadata, genericTypesArgumentsMap,
                        genericAttributeType);

        Message<?> message = (Message<?>) MessageBuilder.withPayload(wrapper).setHeader(
                PodamConstants.HEADER_NAME, qualifier).build();

        MessagingTemplate template = new MessagingTemplate();
        //retValue = template.sendAndReceive(channel, message).getPayload();
        retValue = template.sendAndReceive(channel,message).getPayload();
        return retValue;
    }

    /**
     * It returns a {@link AttributeStrategy} if one was specified in
     * annotations, or {@code null} otherwise.
     *
     * @param annotations
     *            The list of annotations
     * @param attributeType
     *            Type of attribute expected to be returned
     * @return {@link AttributeStrategy}, if {@link PodamStrategyValue} or bean
     *         validation constraint annotation was found among annotations
     * @throws IllegalAccessException
     *         if attribute strategy cannot be instantiated
     * @throws InstantiationException
     *         if attribute strategy cannot be instantiated
     */
    public static AttributeStrategy<?> findAttributeStrategy(DataProviderStrategy strategy,
            List<Annotation> annotations, Class<?> attributeType)
            throws InstantiationException, IllegalAccessException {

        List<Annotation> localAnnotations = new ArrayList<Annotation>(annotations);
        Iterator<Annotation> iter = localAnnotations.iterator();
        while (iter.hasNext()) {
            Annotation annotation = iter.next();
            if (annotation instanceof PodamStrategyValue) {
                PodamStrategyValue strategyAnnotation = (PodamStrategyValue) annotation;
                return strategyAnnotation.value().newInstance();
            }

			/* Find real class out of proxy */
            Class<? extends Annotation> annotationClass = annotation.getClass();
            if (Proxy.isProxyClass(annotationClass)) {
                Class<?>[] interfaces = annotationClass.getInterfaces();
                if (interfaces.length == 1) {
                    @SuppressWarnings("unchecked")
                    Class<? extends Annotation> tmp = (Class<? extends Annotation>) interfaces[0];
                    annotationClass = tmp;
                }
            }

            Class<AttributeStrategy<?>> attrStrategyClass;
            if ((attrStrategyClass = strategy.getStrategyForAnnotation(annotationClass)) != null) {
                return attrStrategyClass.newInstance();
            }

            if (annotation.annotationType().getAnnotation(Constraint.class) != null) {
                if (annotation instanceof NotNull) {
					/* We don't need to do anything for NotNull constraint */
                    iter.remove();
                } else if (!NotNull.class.getPackage().equals(annotationClass.getPackage())) {
                    LOG.warn("Please, registrer AttributeStratergy for custom "
                            + "constraint {}, in DataProviderStrategy! Value "
                            + "will be left to null", annotation);
                }
            } else {
                iter.remove();
            }
        }

        AttributeStrategy<?> retValue = null;
        if (!localAnnotations.isEmpty()
                && !Collection.class.isAssignableFrom(attributeType)
                && !Map.class.isAssignableFrom(attributeType)
                && !attributeType.isArray()) {

            retValue = new BeanValidationStrategy(localAnnotations, attributeType);
        }

        return retValue;
    }

    /**
     * Fills type agruments map
     *

     * This method places required and provided types for object creation into a
     * map, which will be used for type mapping.
     *

     *
     * @param typeArgsMap
     *            a map to fill
     * @param pojoClass
     *            Typed class
     * @param genericTypeArgs
     *            Type arguments provided for a generics object by caller
     * @return Array of unused provided generic type arguments
     * @throws IllegalStateException
     *             If number of typed parameters doesn't match number of
     *             provided generic types
     */
    public static Type[] fillTypeArgMap(final Map<String, Type> typeArgsMap,
                                  final Class<?> pojoClass, final Type[] genericTypeArgs) {

        TypeVariable<?>[] array = pojoClass.getTypeParameters();
        List<TypeVariable<?>> typeParameters = new ArrayList<TypeVariable<?>>(Arrays.asList(array));
        Iterator<TypeVariable<?>> iterator = typeParameters.iterator();
		/* Removing types, which are already in typeArgsMap */
        while (iterator.hasNext()) {
            if (typeArgsMap.containsKey(iterator.next().getName())) {
                iterator.remove();
            }
        }

        List<Type> genericTypes = new ArrayList<Type>(Arrays.asList(genericTypeArgs));
        Iterator<Type> iterator2 = genericTypes.iterator();
		/* Removing types, which are type variables */
        while (iterator2.hasNext()) {
            if (iterator2.next() instanceof TypeVariable) {
                iterator2.remove();
            }
        }

        if (typeParameters.size() > genericTypes.size()) {
            String msg = pojoClass.getCanonicalName()
                    + " is missing generic type arguments, expected "
                    + typeParameters + " found "
                    + Arrays.toString(genericTypeArgs);
            throw new IllegalStateException(msg);
        }

        int i;
        for (i = 0; i < typeParameters.size(); i++) {
            typeArgsMap.put(typeParameters.get(i).getName(), genericTypes.get(0));
            genericTypes.remove(0);
        }
        Type[] genericTypeArgsExtra;
        if (genericTypes.size() > 0) {
            genericTypeArgsExtra = genericTypes.toArray(new Type[genericTypes.size()]);
        } else {
            genericTypeArgsExtra = PodamConstants.NO_TYPES;
        }

		/* Adding types, which were specified during inheritance */
        Class<?> clazz = pojoClass;
        while (clazz != null) {
            Type superType = clazz.getGenericSuperclass();
            clazz = clazz.getSuperclass();
            if (superType instanceof ParameterizedType) {
                ParameterizedType paramType = (ParameterizedType) superType;
                Type[] actualParamTypes = paramType.getActualTypeArguments();
                TypeVariable<?>[] paramTypes = clazz.getTypeParameters();
                for (i = 0; i < actualParamTypes.length
                        && i < paramTypes.length; i++) {
                    if (actualParamTypes[i] instanceof Class) {
                        typeArgsMap.put(paramTypes[i].getName(),
                                actualParamTypes[i]);
                    }
                }
            }
        }

        return genericTypeArgsExtra;
    }

    /**
     * Searches for annotation with information about collection/map size
     * and filling strategies
     *
     * @param annotations
     *        a list of annotations to inspect
     * @param collectionElementType
     *        a collection element type
     * @param elementStrategyHolder
     *        a holder to pass found element strategy back to the caller,
     *        can be null
     * @param keyStrategyHolder
     *        a holder to pass found key strategy back to the caller,
     *        can be null
     * @return
     *        A number of element in collection or null, if no annotation was
     *        found
     * @throws InstantiationException
     *        A strategy cannot be instantiated
     * @throws IllegalAccessException
     *        A strategy cannot be instantiated
     */
    public static Integer findCollectionSize( DataProviderStrategy strategy,
                                        List<Annotation> annotations,
                                        Class<?> collectionElementType,
                                        Holder<AttributeStrategy<?>> elementStrategyHolder,
                                        Holder<AttributeStrategy<?>> keyStrategyHolder)
            throws InstantiationException, IllegalAccessException {

        // If the user defined a strategy to fill the collection elements,
        // we use it
        Size size = null;
        for (Annotation annotation : annotations) {
            if (annotation instanceof PodamCollection) {

                PodamCollection collectionAnnotation = (PodamCollection) annotation;
                if (null != elementStrategyHolder) {

                    Class<? extends AttributeStrategy<?>> attributeStrategy
                            = collectionAnnotation.collectionElementStrategy();
                    if (null == attributeStrategy || ObjectStrategy.class.isAssignableFrom(attributeStrategy)) {
                        attributeStrategy = collectionAnnotation.mapElementStrategy();
                    }
                    if (null != attributeStrategy) {
                        elementStrategyHolder.value = attributeStrategy.newInstance();
                    }
                }
                if (null != keyStrategyHolder) {

                    Class<? extends AttributeStrategy<?>> attributeStrategy
                            = collectionAnnotation.mapKeyStrategy();
                    if (null != attributeStrategy) {
                        keyStrategyHolder.value = attributeStrategy.newInstance();
                    }
                }
                return collectionAnnotation.nbrElements();

            } else if (annotation instanceof Size) {

                size = (Size) annotation;
            }
        }

        Integer nbrElements = strategy
                .getNumberOfCollectionElements(collectionElementType);

        if (null != size) {
            if (nbrElements > size.max()) {
                nbrElements = size.max();
            }
            if (nbrElements < size.min()) {
                nbrElements = size.min();
            }
        }

        return nbrElements;
    }

    /**
     * It returns {@code true} if this class is a wrapper class, {@code false}
     * otherwise
     *
     * @param candidateWrapperClass
     *            The class to check
     * @return {@code true} if this class is a wrapper class, {@code false}
     *         otherwise
     */
    public static boolean isWrapper(Class<?> candidateWrapperClass) {

        return candidateWrapperClass.equals(Byte.class) ? true
                : candidateWrapperClass.equals(Boolean.class) ? true
                : candidateWrapperClass.equals(Character.class) ? true
                : candidateWrapperClass.equals(Short.class) ? true
                : candidateWrapperClass
                .equals(Integer.class) ? true
                : candidateWrapperClass
                .equals(Long.class) ? true
                : candidateWrapperClass
                .equals(Float.class) ? true
                : candidateWrapperClass
                .equals(Double.class) ? true
                : false;
    }

    /**
     * Utility to merge actual types with supplied array of generic type
     * substitutions
     *
     * @param actualTypes
     *            an array of types used for field or POJO declaration
     * @param suppliedTypes
     *            an array of supplied types for generic type substitution
     * @param typeArgsMap
     *            a map relating the generic class arguments ("<T, V>" for
     *            example) with their actual types
     * @return An array of merged actual and supplied types with generic types
     *            resolved
     */
    public static Type[] mergeActualAndSuppliedGenericTypes(
            Type[] actualTypes, Type[] suppliedTypes,
            Map<String, Type> typeArgsMap) {

        List<Type> resolvedTypes = new ArrayList<Type>();
        List<Type> substitutionTypes = new ArrayList<Type>(Arrays.asList(suppliedTypes));
        for (int i = 0; i < actualTypes.length; i++) {

            Type type = null;
            if (actualTypes[i] instanceof TypeVariable) {
                type = typeArgsMap.get(((TypeVariable<?>)actualTypes[i]).getName());
            } else if (actualTypes[i] instanceof Class) {
                type = actualTypes[i];
            } else if (actualTypes[i] instanceof WildcardType) {
                AtomicReference<Type[]> methodGenericTypeArgs
                        = new AtomicReference<Type[]>(PodamConstants.NO_TYPES);
                type = TypeManufacturerUtil.resolveGenericParameter(actualTypes[i], typeArgsMap,
                        methodGenericTypeArgs);
            }
            if (type != null) {
                resolvedTypes.add(type);
                if (!substitutionTypes.isEmpty() && substitutionTypes.get(0).equals(type)) {
                    substitutionTypes.remove(0);
                }
            }
        }
        Type[] resolved = resolvedTypes.toArray(new Type[resolvedTypes.size()]);
        Type[] supplied = substitutionTypes.toArray(new Type[substitutionTypes.size()]);
        return mergeTypeArrays(resolved, supplied);
    }

    /**
     * Utility method to merge two arrays
     *
     * @param original
     *            The main array
     * @param extra
     *            The additional array, optionally may be null
     * @return A merged array of original and extra arrays
     */
    public static Type[] mergeTypeArrays(Type[] original, Type[] extra) {

        Type[] merged;

        if (extra != null) {
            merged = new Type[original.length + extra.length];
            System.arraycopy(original, 0, merged, 0, original.length);
            System.arraycopy(extra, 0, merged, original.length, extra.length);
        } else {
            merged = original;
        }

        return merged;
    }

    /**
     * Given a collection type it returns an instance
     *
     *

     *
The default type for a {@link List} is an {@link ArrayList}

     *
The default type for a {@link Queue} is a {@link LinkedList}

     *
The default type for a {@link Set} is a {@link HashSet}

     *

     *
     * @param collectionType
     *            The collection type *
     * @param defaultValue
     *            Default value for the collection, can be null
     * @return an instance of the collection type or null
     */
    public static Collection<? super Object> resolveCollectionType(
            Class<?> collectionType, Collection<? super Object> defaultValue) {

        Collection<? super Object> retValue = null;

        // Default list and set are ArrayList and HashSet. If users
        // wants a particular collection flavour they have to initialise
        // the collection
        if (null != defaultValue &&
                (defaultValue.getClass().getModifiers() & Modifier.PRIVATE) == 0) {
			/* Default collection, which is not immutable */
            retValue = defaultValue;
        } else {
            if (Queue.class.isAssignableFrom(collectionType)) {
                if (collectionType.isAssignableFrom(LinkedList.class)) {
                    retValue = new LinkedList<Object>();
                }
            } else if (Set.class.isAssignableFrom(collectionType)) {
                if (collectionType.isAssignableFrom(HashSet.class)) {
                    retValue = new HashSet<Object>();
                }
            } else {
                if (collectionType.isAssignableFrom(ArrayList.class)) {
                    retValue = new ArrayList<Object>();
                }
            }
            if (null != retValue && null != defaultValue) {
                retValue.addAll(defaultValue);
            }
        }
        return retValue;
    }
    /**
     * It resolves generic parameter type
     *
     *
     * @param paramType
     *            The generic parameter type
     * @param typeArgsMap
     *            A map of resolved types
     * @param methodGenericTypeArgs
     *            Return value posible generic types of the generic parameter
     *            type
     * @return value for class representing the generic parameter type
     */
    public static Class<?> resolveGenericParameter(Type paramType,
                                             Map<String, Type> typeArgsMap,
                                             AtomicReference<Type[]> methodGenericTypeArgs) {

        Class<?> parameterType = null;

        //Safe copy
        Map<String, Type> localMap = new HashMap<String, Type>(typeArgsMap);

        methodGenericTypeArgs.set(PodamConstants.NO_TYPES);
        if (paramType instanceof TypeVariable<?>) {
            final TypeVariable<?> typeVariable = (TypeVariable<?>) paramType;
            final Type type = localMap.get(typeVariable.getName());
            if (type != null) {
                parameterType = resolveGenericParameter(type, localMap,
                        methodGenericTypeArgs);
            }
        } else if (paramType instanceof ParameterizedType) {
            ParameterizedType pType = (ParameterizedType) paramType;
            parameterType = (Class<?>) pType.getRawType();
            methodGenericTypeArgs.set(pType.getActualTypeArguments());
        } else if (paramType instanceof WildcardType) {
            WildcardType wType = (WildcardType) paramType;
            Type[] bounds = wType.getLowerBounds();
            String msg;
            if (bounds != null && bounds.length > 0) {
                msg = "Lower bounds:";
            } else {
                bounds = wType.getUpperBounds();
                msg = "Upper bounds:";
            }
            if (bounds != null && bounds.length > 0) {
                LOG.debug(msg + Arrays.toString(bounds));
                parameterType = resolveGenericParameter(bounds[0], localMap,
                        methodGenericTypeArgs);
            }
        } else if (paramType instanceof Class) {
            parameterType = (Class<?>) paramType;
        }

        if (parameterType == null) {
            LOG.warn("Unrecognized type {}. Will use Object instead",
                    paramType);
            parameterType = Object.class;
        }
        return parameterType;
    }

    /**
     * It manufactures and returns a default instance for each map type
     *
     *

     * The default implementation for a {@link ConcurrentMap} is
     * {@link ConcurrentHashMap}
     *

     *
     *

     * The default implementation for a {@link SortedMap} is a {@link TreeMap}
     *

     *
     *

     * The default Map is none of the above was recognised is a {@link HashMap}
     *

     *
     * @param mapType
     *            The attribute type implementing Map
     * @param defaultValue
     *            Default value for map
     * @return A default instance for each map type or null
     *
     */
    public static Map<? super Object, ? super Object> resolveMapType(
            Class<?> mapType, Map<? super Object, ? super Object> defaultValue) {

        Map<? super Object, ? super Object> retValue = null;

        if (null != defaultValue &&
                (defaultValue.getClass().getModifiers() & Modifier.PRIVATE) == 0) {
			/* Default map, which is not immutable */
            retValue = defaultValue;
        } else {
            if (SortedMap.class.isAssignableFrom(mapType)) {
                if (mapType.isAssignableFrom(TreeMap.class)) {
                    retValue = new TreeMap<Object, Object>();
                }
            } else if (ConcurrentMap.class.isAssignableFrom(mapType)) {
                if (mapType.isAssignableFrom(ConcurrentHashMap.class)) {
                    retValue = new ConcurrentHashMap<Object, Object>();
                }
            } else {
                if (mapType.isAssignableFrom(HashMap.class)) {
                    retValue = new HashMap<Object, Object>();
                }
            }
        }

        return retValue;

    }

    /**
     * It retrieves the value for the {@link PodamStrategyValue} annotation with
     * which the attribute was annotated
     *
     * @param attributeType
     *            The attribute type, used for type checking
     * @param attributeStrategy
     *            The {@link AttributeStrategy} to use
     * @return The value for the {@link PodamStrategyValue} annotation with
     *         which the attribute was annotated
     * @throws IllegalArgumentException
     *             If the type of the data strategy defined for the
     *             {@link PodamStrategyValue} annotation is not assignable to
     *             the annotated attribute. This de facto guarantees type
     *             safety.
     */
    public static Object returnAttributeDataStrategyValue(Class<?> attributeType,
                                                    AttributeStrategy<?> attributeStrategy)
            throws IllegalArgumentException {

        Object retValue = attributeStrategy.getValue();

        if (retValue != null) {
            Class<?> desiredType = attributeType.isPrimitive() ?
                    PodamUtils.primitiveToBoxedType(attributeType) : attributeType;
            if (!desiredType.isAssignableFrom(retValue.getClass())) {
                String errMsg = "The type of the Podam Attribute Strategy is not "
                        + attributeType.getName() + " but "
                        + retValue.getClass().getName()
                        + ". An exception will be thrown.";
                LOG.error(errMsg);
                throw new IllegalArgumentException(errMsg);
            }
        }

        return retValue;

    }

}


text:
<?php

declare(strict_types=1);

return [
    'service2' => \DI\factory(function () {
        $value = new \stdClass();
        $value->foo = 'bar';

        return $value;
    }),
    'DI\Test\IntegrationTest\Issues\Issue72\Class1' => \DI\create()
            ->constructor(\DI\get('service2')),
];


text:
namespace Springboard365.Core
{
    using System;
    using System.Linq.Expressions;

    public interface IAttributeUtilities
    {
        TAttribute GetAttributeFor<TAttribute, TTargetType>(Expression<Func<TTargetType, object>> expression)
            where TAttribute : Attribute;
    }
}


text:
require 'ffi/udis86/types'

require 'ffi'

module FFI
  module UDis86
    extend FFI::Library

    ffi_lib ['udis86', 'libudis86.so.0']

    attach_function :ud_init, [:pointer], :void
    attach_function :ud_set_mode, [:pointer, :uint8], :void
    attach_function :ud_set_pc, [:pointer, :uint64], :void
    attach_function :ud_set_input_hook, [:pointer, :ud_input_callback], :void
    attach_function :ud_set_input_buffer, [:pointer, :pointer, :size_t], :void
    attach_function :ud_set_input_file, [:pointer, :pointer], :void
    attach_function :ud_set_vendor, [:pointer, :uint8], :void
    attach_function :ud_set_syntax, [:pointer, :ud_translator_callback], :void
    attach_function :ud_input_skip, [:pointer, :size_t], :void
    attach_function :ud_input_end, [:pointer], :int
    attach_function :ud_decode, [:pointer], :uint
    attach_function :ud_disassemble, [:pointer], :uint
    attach_function :ud_translate_intel, [:pointer], :void
    attach_function :ud_translate_att, [:pointer], :void
    attach_function :ud_insn_asm, [:pointer], :string
    attach_function :ud_insn_ptr, [:pointer], :pointer
    attach_function :ud_insn_off, [:pointer], :uint64
    attach_function :ud_insn_hex, [:pointer], :string
    attach_function :ud_insn_len, [:pointer], :uint
    attach_function :ud_insn_opr, [:pointer], :pointer
    attach_function :ud_opr_is_sreg, [:pointer], :int
    attach_function :ud_opr_is_gpr, [:pointer], :int
    attach_function :ud_insn_mnemonic, [:pointer], :ud_mnemonic_code
    attach_function :ud_lookup_mnemonic, [:ud_mnemonic_code], :string
    attach_function :ud_set_user_opaque_data, [:pointer, :pointer], :void
    attach_function :ud_get_user_opaque_data, [:pointer], :pointer
    attach_function :ud_set_asm_buffer, [:pointer, :pointer, :size_t], :void
    attach_function :ud_set_sym_resolver, [:pointer, :ud_sym_resolver_callback], :void
  end
end


text:
import './ltrim';
import './rtrim';
import './toBoolean';
import './toDate';
import './toFloat';
import './toInt';
import './toString';
import './trim';
import './between';
import './betweenWith';
import './escape';
import './lowercase';
import './max';
import './maxWith';
import './min';
import './minWith';
import './numberWithCommas';
import './unescape';
import './uppercase';


text:
{{ .Title }}

Published on {{ .Date.Format "Jan 2, 2006" }}

  {{ .Content }}

  Spot a mistake? Have something to add? Let me know!

I'd love to receive your feedback. Please fill in the form below and it'll reach me.

    As a general rule, I won't answer individual requests for help — if you need help with something I'd recommend
    describing the problem in a relevant public forum such as Stack Overflow or a language/tech-specific
    subreddit. That way you get access to lots of potential people who may be able to help, and the response is
    available publicly for anyone else with the same issue in the future.


text:
package org.commoncrawl.util.shared;

import java.util.Collection;
import java.util.Iterator;

/**
 * A class for efficiently matching Strings against a set of
 * suffixes. Zero-length Strings are ignored.
 */
public class SuffixStringMatcher extends TrieStringMatcher {

	/**
	 * Creates a new PrefixStringMatcher which will match
	 * Strings with any suffix in the supplied array.
	 */
	public SuffixStringMatcher(String[] suffixes) {
		super();
		for (int i = 0; i < suffixes.length; i++)
			addPatternBackward(suffixes[i]);
	}

	/**
	 * Creates a new PrefixStringMatcher which will match
	 * Strings with any suffix in the supplied
	 * Collection
	 */
	public SuffixStringMatcher(Collection suffixes) {
		super();
		Iterator iter = suffixes.iterator();
		while (iter.hasNext())
			addPatternBackward((String) iter.next());
	}

	/**
	 * Returns true if the given String is matched by a suffix in the
	 * trie
	 */
	public boolean matches(String input) {
		TrieNode node = root;
		for (int i = input.length() - 1; i >= 0; i--) {
			node = node.getChild(input.charAt(i));
			if (node == null)
				return false;
			if (node.isTerminal())
				return true;
		}
		return false;
	}

	/**
	 * Returns the shortest suffix of input that is matched,
	 * or null if no match exists.
	 */
	public String shortestMatch(String input) {
		TrieNode node = root;
		for (int i = input.length() - 1; i >= 0; i--) {
			node = node.getChild(input.charAt(i));
			if (node == null)
				return null;
			if (node.isTerminal())
				return input.substring(i);
		}
		return null;
	}

	/**
	 * Returns the longest suffix of input that is matched,
	 * or null if no match exists.
	 */
	public String longestMatch(String input) {
		TrieNode node = root;
		String result = null;
		for (int i = input.length() - 1; i >= 0; i--) {
			node = node.getChild(input.charAt(i));
			if (node == null)
				break;
			if (node.isTerminal())
				result = input.substring(i);
		}
		return result;
	}

	/** Returns true if an exact match is found
	 *
	 * @param argv
	 */
	public boolean exactMatch(String input) {
		TrieNode node = root;
		for (int i = input.length() - 1; i >= 0; i--) {
			node = node.getChild(input.charAt(i));
			if (node == null)
				break;
			if (i == 0 && node.isTerminal()) {
				return true;
			}
		}
		return false;
	}

	public static final void main(String[] argv) {
		SuffixStringMatcher matcher = new SuffixStringMatcher(new String[] { "a", "abcd", "bcd", "bcdefg", "defg",
				"aac", "baz", "foo", "foobar" });

		String[] tests = { "a", "ac", "abcd", "abcdefg", "apple", "aa", "aac", "aaccca", "abaz", "baz", "bazooka",
				"fo", "foobar", "kite", };

		for (int i = 0; i < tests.length; i++) {
			System.out.println("testing: " + tests[i]);
			System.out.println("   matches: " + matcher.matches(tests[i]));
			System.out.println("  shortest: " + matcher.shortestMatch(tests[i]));
			System.out.println("   longest: " + matcher.longestMatch(tests[i]));

		}
		System.out.println("   exact: " + matcher.exactMatch("foobar"));
		System.out.println("   not exact: " + matcher.exactMatch("fooba"));
		System.out.println("   not exact: " + matcher.exactMatch("foobarz"));
		System.out.println("   exact: " + matcher.exactMatch("foo"));

	}
}


text:
package com.indeed.proctor.consumer;

import com.indeed.proctor.common.model.Payload;
import org.junit.Test;

import javax.annotation.Nullable;
import java.util.Collections;
import java.util.Map;

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

public class AbstractGroupsPayloadTest {

    public static final String MAP_KEY = "fooKey";
    private final GroupsPayloadTestClass subclass = new GroupsPayloadTestClass();

    @Test
    public void testConvertToStringValue() {
        // not sure is this behavior is required
        assertThat(subclass.convertToStringValue(makeStubMapPayload(MAP_KEY, null), MAP_KEY)).isNull();
        assertThatThrownBy(() -> subclass.convertToStringValue(makeStubMapPayload(MAP_KEY, 42), MAP_KEY))
                .isInstanceOf(ClassCastException.class)
                .hasMessageContaining("42");
        assertThat(subclass.convertToStringValue(makeStubMapPayload(MAP_KEY, "footest"), MAP_KEY)).isEqualTo("footest");
        assertThatThrownBy(() -> subclass.convertToStringValue(makeStubMapPayload("notexist", "footest"), MAP_KEY))
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessageContaining(MAP_KEY)
                .hasMessageContaining("notexist");
    }

    @Test
    public void testConvertToDoubleValue() {
        assertThatThrownBy(() -> subclass.convertToDoubleValue(makeStubMapPayload(MAP_KEY, null), MAP_KEY))
                .isInstanceOf(NullPointerException.class)
                .hasMessageContaining(MAP_KEY);
        assertThatThrownBy(() -> subclass.convertToDoubleValue(makeStubMapPayload(MAP_KEY, "foo"), MAP_KEY))
                .isInstanceOf(ClassCastException.class)
                .hasMessageContaining("foo");
        assertThat(subclass.convertToDoubleValue(makeStubMapPayload(MAP_KEY, 42), MAP_KEY)).isEqualTo(42.0);
        assertThatThrownBy(() -> subclass.convertToDoubleValue(makeStubMapPayload("notexist", "footest"), MAP_KEY))
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessageContaining(MAP_KEY)
                .hasMessageContaining("notexist");
    }

    @Test
    public void testConvertToLongValue() {
        assertThatThrownBy(() -> subclass.convertToLongValue(makeStubMapPayload(MAP_KEY, null), MAP_KEY))
                .isInstanceOf(NullPointerException.class)
                .hasMessageContaining(MAP_KEY);
        assertThatThrownBy(() -> subclass.convertToLongValue(makeStubMapPayload(MAP_KEY, "foo"), MAP_KEY))
                .isInstanceOf(ClassCastException.class)
                .hasMessageContaining("foo");
        assertThat(subclass.convertToLongValue(makeStubMapPayload(MAP_KEY, 42), MAP_KEY)).isEqualTo(42L);
        assertThat(subclass.convertToLongValue(makeStubMapPayload(MAP_KEY, 42.3), MAP_KEY)).isEqualTo(42L);
        assertThatThrownBy(() -> subclass.convertToLongValue(makeStubMapPayload("notexist", "footest"), MAP_KEY))
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessageContaining(MAP_KEY)
                .hasMessageContaining("notexist");
    }

    @Test
    public void testConvertToStringArray() {
        assertThatThrownBy(() -> subclass.convertToStringArray(makeStubMapPayload(MAP_KEY, null), MAP_KEY))
                .isInstanceOf(NullPointerException.class)
                .hasMessageContaining(MAP_KEY);
        assertThat(subclass.convertToStringArray(makeStubMapPayload(MAP_KEY, singletonList("footest")), MAP_KEY)).isEqualTo(new String[]{"footest"});
        assertThatThrownBy(() -> subclass.convertToStringArray(makeStubMapPayload(MAP_KEY, singletonList(42)), MAP_KEY))
                .isInstanceOf(ClassCastException.class)
                .hasMessageContaining("42");
        // not sure if this behavior is required
        assertThat(subclass.convertToStringArray(makeStubMapPayload(MAP_KEY, singletonList(null)), MAP_KEY)).isEqualTo(new String[]{null});
        assertThatThrownBy(() -> subclass.convertToStringArray(makeStubMapPayload("notexist", "footest"), MAP_KEY))
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessageContaining(MAP_KEY)
                .hasMessageContaining("notexist");
    }

    @Test
    public void testConvertToDoubleArray() {
        assertThatThrownBy(() -> subclass.convertToDoubleArray(makeStubMapPayload(MAP_KEY, null), MAP_KEY))
                .isInstanceOf(NullPointerException.class)
                .hasMessageContaining(MAP_KEY);
        assertThatThrownBy(() -> subclass.convertToDoubleArray(makeStubMapPayload(MAP_KEY, singletonList(null)), MAP_KEY))
                .isInstanceOf(NullPointerException.class)
                .hasMessageContaining(MAP_KEY);
        assertThatThrownBy(() -> subclass.convertToLongArray(makeStubMapPayload(MAP_KEY, "foo"), MAP_KEY))
                .isInstanceOf(ClassCastException.class)
                .hasMessageContaining("foo");
        assertThat(subclass.convertToDoubleArray(makeStubMapPayload(MAP_KEY, singletonList(42)), MAP_KEY)).isEqualTo(new Double[]{42.0});
        assertThatThrownBy(() -> subclass.convertToDoubleArray(makeStubMapPayload("notexist", "footest"), MAP_KEY))
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessageContaining(MAP_KEY)
                .hasMessageContaining("notexist");
    }

    @Test
    public void testConvertToLongArray() {
        assertThatThrownBy(() -> subclass.convertToLongArray(makeStubMapPayload(MAP_KEY, null), MAP_KEY))
                .isInstanceOf(NullPointerException.class)
                .hasMessageContaining(MAP_KEY);
        assertThatThrownBy(() -> subclass.convertToLongArray(makeStubMapPayload(MAP_KEY, singletonList(null)), MAP_KEY))
                .isInstanceOf(NullPointerException.class)
                .hasMessageContaining(MAP_KEY);
        assertThatThrownBy(() -> subclass.convertToLongArray(makeStubMapPayload(MAP_KEY, "foo"), MAP_KEY))
                .isInstanceOf(ClassCastException.class)
                .hasMessageContaining("foo");
        assertThat(subclass.convertToLongArray(makeStubMapPayload(MAP_KEY, singletonList(42)), MAP_KEY)).isEqualTo(new Long[]{42L});
        assertThatThrownBy(() -> subclass.convertToLongArray(makeStubMapPayload("notexist", "footest"), MAP_KEY))
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessageContaining(MAP_KEY)
                .hasMessageContaining("notexist");
    }

    private static <T> Payload makeStubMapPayload(@Nullable final String key, final T mapValue) {
        final Payload payload = new Payload();
        final Map<String, Object> map = Collections.singletonMap(key, mapValue);
        payload.setMap(map);
        return payload;
    }

    private static class GroupsPayloadTestClass extends AbstractGroupsPayload {
    }
}


text:
<!DOCTYPE html>

  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta charset="UTF-8" />
  <title>
   Closure Unit Tests - goog.ui.PopupBase
  </title>

    Mouse and key target

    Auto-hide partner

    Popup Contents Here.

    Move offscreen popup contents here.


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Runtime.CompilerServices;

namespace System.Text.Utf8
{
    public static class Utf8Encoder
    {
        // To get this to compile with dotnet cli, we need to temporarily un-binary the magic values
        private const byte b0000_0111U = 7;
        private const byte b0000_1111U = 15;
        private const byte b0001_1111U = 31;
        private const byte b0011_1111U = 63;
        private const byte b0111_1111U = 127;
        private const byte b1000_0000U = 128;
        private const byte b1100_0000U = 192;
        private const byte b1110_0000U = 224;
        private const byte b1111_0000U = 240;
        private const byte b1111_1000U = 248;

        #region Decoder
        // Should this be public?
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static bool TryGetNumberOfEncodedBytesFromFirstByte(byte first, out int numberOfBytes)
        {
            if ((first & b1000_0000U) == 0)
            {
                numberOfBytes = 1;
                return true;
            }

            if ((first & b1110_0000U) == b1100_0000U)
            {
                numberOfBytes = 2;
                return true;
            }

            if ((first & b1111_0000U) == b1110_0000U)
            {
                numberOfBytes = 3;
                return true;
            }

            if ((first & b1111_1000U) == b1111_0000U)
            {
                numberOfBytes = 4;
                return true;
            }

            numberOfBytes = default(int);
            return false;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static bool TryGetFirstByteCodePointValue(byte first, out UnicodeCodePoint codePoint, out int encodedBytes)
        {
            if (!TryGetNumberOfEncodedBytesFromFirstByte(first, out encodedBytes))
            {
                codePoint = default(UnicodeCodePoint);
                return false;
            }

            switch (encodedBytes)
            {
                case 1:
                    codePoint = (UnicodeCodePoint)(first & b0111_1111U);
                    return true;
                case 2:
                    codePoint = (UnicodeCodePoint)(first & b0001_1111U);
                    return true;
                case 3:
                    codePoint = (UnicodeCodePoint)(first & b0000_1111U);
                    return true;
                case 4:
                    codePoint = (UnicodeCodePoint)(first & b0000_0111U);
                    return true;
                default:
                    codePoint = default(UnicodeCodePoint);
                    encodedBytes = 0;
                    return false;
            }
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static bool TryReadCodePointByte(byte nextByte, ref UnicodeCodePoint codePoint)
        {
            uint current = nextByte;
            if ((current & b1100_0000U) != b1000_0000U)
                return false;

            codePoint = new UnicodeCodePoint((codePoint.Value << 6) | (b0011_1111U & current));
            return true;
        }

        public static bool TryDecodeCodePoint(Span<byte> buffer, out UnicodeCodePoint codePoint, out int encodedBytes)
        {
            if (buffer.Length == 0)
            {
                codePoint = default(UnicodeCodePoint);
                encodedBytes = default(int);
                return false;
            }

            byte first = buffer[0];
            if (!TryGetFirstByteCodePointValue(first, out codePoint, out encodedBytes))
                return false;

            if (buffer.Length < encodedBytes)
                return false;

            // TODO: Should we manually inline this for values 1-4 or will compiler do this for us?
            for (int i = 1; i < encodedBytes; i++)
            {
                if (!TryReadCodePointByte(buffer[i], ref codePoint))
                    return false;
            }

            return true;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static bool TryFindEncodedCodePointBytesCountGoingBackwards(Span<byte> buffer, out int encodedBytes)
        {
            encodedBytes = 1;
            Span<byte> it = buffer;
            // TODO: Should we have something like: Span<byte>.(Slice from the back)
            for (; encodedBytes <= UnicodeConstants.Utf8MaxCodeUnitsPerCodePoint; encodedBytes++, it = it.Slice(0, it.Length - 1))
            {
                if (it.Length == 0)
                {
                    encodedBytes = default(int);
                    return false;
                }

                // TODO: Should we have Span<byte>.Last?
                if (Utf8CodeUnit.IsFirstCodeUnitInEncodedCodePoint((Utf8CodeUnit)it[it.Length - 1]))
                {
                    // output: encodedBytes
                    return true;
                }
            }

            // Invalid unicode character or stream prematurely ended (which is still invalid character in that stream)
            encodedBytes = default(int);
            return false;
        }

        // TODO: Name TBD
        // TODO: optimize?
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool TryDecodeCodePointBackwards(Span<byte> buffer, out UnicodeCodePoint codePoint, out int encodedBytes)
        {
            if (TryFindEncodedCodePointBytesCountGoingBackwards(buffer, out encodedBytes))
            {
                int realEncodedBytes;
                // TODO: Inline decoding, as the invalid surrogate check can be done faster
                bool ret = TryDecodeCodePoint(buffer.Slice(buffer.Length - encodedBytes), out codePoint, out realEncodedBytes);
                if (ret && encodedBytes != realEncodedBytes)
                {
                    // invalid surrogate character
                    // we know the character length by iterating on surrogate characters from the end
                    // but the first byte of the character has also encoded length
                    // seems like the lengths don't match
                    return false;
                }
                return true;
            }

            codePoint = default(UnicodeCodePoint);
            encodedBytes = default(int);
            return false;
        }
        #endregion

        #region Encoder
        // Should this be public?
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        internal static int GetNumberOfEncodedBytes(UnicodeCodePoint codePoint)
        {
            if (codePoint.Value <= 0x7F)
            {
                return 1;
            }

            if (codePoint.Value <= 0x7FF)
            {
                return 2;
            }

            if (codePoint.Value <= 0xFFFF)
            {
                return 3;
            }

            if (codePoint.Value <= 0x1FFFFF)
            {
                return 4;
            }

            return 0;
        }

        public static bool TryEncodeCodePoint(UnicodeCodePoint codePoint, Span<byte> buffer, out int encodedBytes)
        {
            if (!UnicodeCodePoint.IsSupportedCodePoint(codePoint))
            {
                encodedBytes = 0;
                return false;
            }

            encodedBytes = GetNumberOfEncodedBytes(codePoint);
            if (encodedBytes > buffer.Length)
            {
                encodedBytes = 0;
                return false;
            }

            switch (encodedBytes)
            {
                case 1:
                    buffer[0] = (byte)(b0111_1111U & codePoint.Value);
                    return true;
                case 2:
                    byte b0 = (byte)(((codePoint.Value >> 6) & b0001_1111U) | b1100_0000U);
                    byte b1 = (byte)(((codePoint.Value >> 0) & b0011_1111U) | b1000_0000U);
                    buffer.Write((ushort)(b0 | b1 << 8));
                    return true;
                case 3:
                    b0 = (byte)(((codePoint.Value >> 12) & b0000_1111U) | b1110_0000U);
                    b1 = (byte)(((codePoint.Value >> 6) & b0011_1111U) | b1000_0000U);
                    buffer.Write((ushort)(b0 | b1 << 8));
                    buffer[2] = (byte)(((codePoint.Value >> 0) & b0011_1111U) | b1000_0000U);
                    return true;
                case 4:
                    b0 = (byte)(((codePoint.Value >> 18) & b0000_0111U) | b1111_0000U);
                    b1 = (byte)(((codePoint.Value >> 12) & b0011_1111U) | b1000_0000U);
                    byte b2 = (byte)(((codePoint.Value >> 6) & b0011_1111U) | b1000_0000U);
                    byte b3 = (byte)(((codePoint.Value >> 0) & b0011_1111U) | b1000_0000U);
                    buffer.Write((uint)(b0 | b1 << 8 | b2 << 16 | b3 << 24));
                    return true;
                default:
                    return false;
            }
        }
        #endregion
    }
}


text:
sudo apt -y install lm-sensors
sudo apt -y install imwheel
sudo apt -y install xmodmap
sudo apt -y install xsel


text:
package log_test

import (
	"fmt"

	"github.com/cri-o/cri-o/internal/log"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/sirupsen/logrus"
)

var _ = t.Describe("HookFilter", func() {
	t.Describe("NewFilterHook", func() {
		It("should succeed to create", func() {
			// Given
			// When
			res, err := log.NewFilterHook("")

			// Then
			Expect(err).To(BeNil())
			Expect(res).NotTo(BeNil())
		})

		It("should fail to create with invalid filter", func() {
			// Given
			// When
			res, err := log.NewFilterHook("(")

			// Then
			Expect(err).NotTo(BeNil())
			Expect(res).To(BeNil())
		})
	})

	t.Describe("Levels", func() {
		It("should work for all log levels", func() {
			// Given
			hook, err := log.NewFilterHook("")
			Expect(err).To(BeNil())

			// When
			res := hook.Levels()

			// Then
			Expect(res).To(Equal(logrus.AllLevels))
		})
	})

	t.Describe("Fire", func() {
		It("should succeed to filter", func() {
			// Given
			hook, err := log.NewFilterHook("none")
			Expect(err).To(BeNil())
			entry := &logrus.Entry{
				Message: "this message will be filtered out",
			}

			// When
			res := hook.Fire(entry)

			// Then
			Expect(res).To(BeNil())
			Expect(entry.Message).To(BeEmpty())
		})

		It("should succeed to filter byte slice", func() {
			// Given
			hook, err := log.NewFilterHook("")
			Expect(err).To(BeNil())
			entry := &logrus.Entry{
				Message: fmt.Sprintf("a slice: %v", []byte{1, 2, 3, 4}),
				Level:   logrus.DebugLevel,
			}

			// When
			res := hook.Fire(entry)

			// Then
			Expect(res).To(BeNil())
			Expect(entry.Message).To(Equal("A slice: [FILTERED]"))
		})
	})
})


text:
#pragma once

#include <gloperate/gloperate_api.h>
#include <gloperate/input/input.h>
#include <gloperate/painter/AbstractCapability.h>

namespace gloperate
{

/**
*  @brief
*    Capability that enables receiving direct mouse and keyboard events
*
*    If a painter supports this capability, it will be supplied with mouse
*    and keyboard events from the viewer. Usually, the abstract interaction
*    interfaces should be used instead, but this capability is important for
*    implementing interoperability with other renderig systems.
*/
class GLOPERATE_API AbstractInputCapability : public AbstractCapability
{
public:
    /**
    *  @brief
    *    Constructor
    */
    AbstractInputCapability();

    /**
    *  @brief
    *    Destructor
    */
    virtual ~AbstractInputCapability();

    /**
    *  @brief
    *    Called on mouse move
    *
    *  @param[in] x
    *    X position
    *  @param[in] y
    *    Y position
    */
    virtual void onMouseMove(int x, int y) = 0;

    /**
    *  @brief
    *    Called on mouse pressed
    *
    *  @param[in] x
    *    X position
    *  @param[in] y
    *    Y position
    *  @param[in] button
    *    Mouse button
    */
    virtual void onMousePress(int x, int y, gloperate::MouseButton button) = 0;

    /**
    *  @brief
    *    Called on mouse released
    *
    *  @param[in] x
    *    X position
    *  @param[in] y
    *    Y position
    *  @param[in] button
    *    Mouse button
    */
    virtual void onMouseRelease(int x, int y, gloperate::MouseButton button) = 0;

    /**
    *  @brief
    *    Called on mouse double-click
    *
    *  @param[in] x
    *    X position
    *  @param[in] y
    *    Y position
    *  @param[in] button
    *    Mouse button
    */
    virtual void onMouseDoubleClick(int x, int y, gloperate::MouseButton button) = 0;

    /**
    *  @brief
    *    Called on mouse wheel event
    *
    *  @param[in] dx
    *    X delta
    *  @param[in] y
    *    Y delta
    */
    virtual void onMouseWheel(int dx, int dy) = 0;

    /**
    *  @brief
    *    Called on key down
    *
    *  @param[in] key
    *    Key
    */
    virtual void onKeyDown(gloperate::Key key) = 0;

    /**
    *  @brief
    *    Called on key up
    *
    *  @param[in] key
    *    Key
    */
    virtual void onKeyUp(gloperate::Key key) = 0;
};

} // namespace gloperate


text:
package org.eclipse.collections.impl;

import java.io.Serializable;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Optional;

import org.eclipse.collections.api.BooleanIterable;
import org.eclipse.collections.api.ByteIterable;
import org.eclipse.collections.api.CharIterable;
import org.eclipse.collections.api.DoubleIterable;
import org.eclipse.collections.api.FloatIterable;
import org.eclipse.collections.api.IntIterable;
import org.eclipse.collections.api.LazyIterable;
import org.eclipse.collections.api.LongIterable;
import org.eclipse.collections.api.RichIterable;
import org.eclipse.collections.api.ShortIterable;
import org.eclipse.collections.api.bag.MutableBag;
import org.eclipse.collections.api.bag.sorted.MutableSortedBag;
import org.eclipse.collections.api.block.function.Function;
import org.eclipse.collections.api.block.function.Function0;
import org.eclipse.collections.api.block.function.Function2;
import org.eclipse.collections.api.block.function.primitive.BooleanFunction;
import org.eclipse.collections.api.block.function.primitive.ByteFunction;
import org.eclipse.collections.api.block.function.primitive.CharFunction;
import org.eclipse.collections.api.block.function.primitive.DoubleFunction;
import org.eclipse.collections.api.block.function.primitive.DoubleObjectToDoubleFunction;
import org.eclipse.collections.api.block.function.primitive.FloatFunction;
import org.eclipse.collections.api.block.function.primitive.FloatObjectToFloatFunction;
import org.eclipse.collections.api.block.function.primitive.IntFunction;
import org.eclipse.collections.api.block.function.primitive.IntObjectToIntFunction;
import org.eclipse.collections.api.block.function.primitive.LongFunction;
import org.eclipse.collections.api.block.function.primitive.LongObjectToLongFunction;
import org.eclipse.collections.api.block.function.primitive.ShortFunction;
import org.eclipse.collections.api.block.predicate.Predicate;
import org.eclipse.collections.api.block.predicate.Predicate2;
import org.eclipse.collections.api.block.procedure.Procedure;
import org.eclipse.collections.api.block.procedure.Procedure2;
import org.eclipse.collections.api.block.procedure.primitive.ObjectIntProcedure;
import org.eclipse.collections.api.collection.primitive.MutableBooleanCollection;
import org.eclipse.collections.api.collection.primitive.MutableByteCollection;
import org.eclipse.collections.api.collection.primitive.MutableCharCollection;
import org.eclipse.collections.api.collection.primitive.MutableDoubleCollection;
import org.eclipse.collections.api.collection.primitive.MutableFloatCollection;
import org.eclipse.collections.api.collection.primitive.MutableIntCollection;
import org.eclipse.collections.api.collection.primitive.MutableLongCollection;
import org.eclipse.collections.api.collection.primitive.MutableShortCollection;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.api.map.MapIterable;
import org.eclipse.collections.api.map.MutableMap;
import org.eclipse.collections.api.map.primitive.ObjectDoubleMap;
import org.eclipse.collections.api.map.primitive.ObjectLongMap;
import org.eclipse.collections.api.map.sorted.MutableSortedMap;
import org.eclipse.collections.api.multimap.Multimap;
import org.eclipse.collections.api.multimap.MutableMultimap;
import org.eclipse.collections.api.partition.PartitionIterable;
import org.eclipse.collections.api.set.MutableSet;
import org.eclipse.collections.api.set.sorted.MutableSortedSet;
import org.eclipse.collections.api.tuple.Pair;

/**
 * An unmodifiable view of a RichIterable.
 */
public class UnmodifiableRichIterable<T>
        implements RichIterable<T>, Serializable
{
    private static final long serialVersionUID = 1L;

    protected final RichIterable<T> iterable;

    protected UnmodifiableRichIterable(RichIterable<T> richIterable)
    {
        this.iterable = richIterable;
    }

    /**
     * This method will take a RichIterable and wrap it directly in a UnmodifiableRichIterable.
     */
    public static <E, RI extends RichIterable<E>> UnmodifiableRichIterable<E> of(RI iterable)
    {
        if (iterable == null)
        {
            throw new IllegalArgumentException("cannot create a UnmodifiableRichIterable for null");
        }
        return new UnmodifiableRichIterable<>(iterable);
    }

    @Override
    public <R extends Collection<T>> R select(Predicate<? super T> predicate, R target)
    {
        return this.iterable.select(predicate, target);
    }

    @Override
    public <P> RichIterable<T> selectWith(Predicate2<? super T, ? super P> predicate, P parameter)
    {
        return this.iterable.selectWith(predicate, parameter);
    }

    @Override
    public <P, R extends Collection<T>> R selectWith(Predicate2<? super T, ? super P> predicate, P parameter, R targetCollection)
    {
        return this.iterable.selectWith(predicate, parameter, targetCollection);
    }

    @Override
    public <R extends Collection<T>> R reject(Predicate<? super T> predicate, R target)
    {
        return this.iterable.reject(predicate, target);
    }

    @Override
    public <P> RichIterable<T> rejectWith(Predicate2<? super T, ? super P> predicate, P parameter)
    {
        return this.iterable.rejectWith(predicate, parameter);
    }

    @Override
    public <P, R extends Collection<T>> R rejectWith(Predicate2<? super T, ? super P> predicate, P parameter, R targetCollection)
    {
        return this.iterable.rejectWith(predicate, parameter, targetCollection);
    }

    @Override
    public PartitionIterable<T> partition(Predicate<? super T> predicate)
    {
        return this.iterable.partition(predicate);
    }

    @Override
    public <P> PartitionIterable<T> partitionWith(Predicate2<? super T, ? super P> predicate, P parameter)
    {
        return this.iterable.partitionWith(predicate, parameter);
    }

    @Override
    public <V, R extends Collection<V>> R collect(Function<? super T, ? extends V> function, R target)
    {
        return this.iterable.collect(function, target);
    }

    @Override
    public <P, V> RichIterable<V> collectWith(Function2<? super T, ? super P, ? extends V> function, P parameter)
    {
        return this.iterable.collectWith(function, parameter);
    }

    @Override
    public <P, V, R extends Collection<V>> R collectWith(Function2<? super T, ? super P, ? extends V> function, P parameter, R targetCollection)
    {
        return this.iterable.collectWith(function, parameter, targetCollection);
    }

    @Override
    public <V, R extends Collection<V>> R collectIf(Predicate<? super T> predicate, Function<? super T, ? extends V> function, R target)
    {
        return this.iterable.collectIf(predicate, function, target);
    }

    @Override
    public <V, R extends Collection<V>> R flatCollect(Function<? super T, ? extends Iterable<V>> function, R target)
    {
        return this.iterable.flatCollect(function, target);
    }

    @Override
    public boolean contains(Object object)
    {
        return this.iterable.contains(object);
    }

    @Override
    public boolean containsAllIterable(Iterable<?> source)
    {
        return this.iterable.containsAllIterable(source);
    }

    @Override
    public boolean containsAll(Collection<?> source)
    {
        return this.iterable.containsAll(source);
    }

    @Override
    public boolean containsAllArguments(Object... elements)
    {
        return this.iterable.containsAllArguments(elements);
    }

    @Override
    public Object[] toArray()
    {
        return this.iterable.toArray();
    }

    @Override
    public <T> T[] toArray(T[] a)
    {
        return this.iterable.toArray(a);
    }

    @Override
    public RichIterable<T> tap(Procedure<? super T> procedure)
    {
        this.forEach(procedure);
        return this;
    }

    @Override
    public void forEach(Procedure<? super T> procedure)
    {
        this.each(procedure);
    }

    @Override
    public void each(Procedure<? super T> procedure)
    {
        this.iterable.forEach(procedure);
    }

    @Override
    public void forEachWithIndex(ObjectIntProcedure<? super T> objectIntProcedure)
    {
        this.iterable.forEachWithIndex(objectIntProcedure);
    }

    @Override
    public <P> void forEachWith(Procedure2<? super T, ? super P> procedure, P parameter)
    {
        this.iterable.forEachWith(procedure, parameter);
    }

    @Override
    public boolean notEmpty()
    {
        return this.iterable.notEmpty();
    }

    @Override
    public boolean isEmpty()
    {
        return this.iterable.isEmpty();
    }

    @Override
    public int size()
    {
        return this.iterable.size();
    }

    @Override
    public T getFirst()
    {
        return this.iterable.getFirst();
    }

    @Override
    public T getLast()
    {
        return this.iterable.getLast();
    }

    @Override
    public T getOnly()
    {
        return this.iterable.getOnly();
    }

    @Override
    public RichIterable<T> select(Predicate<? super T> predicate)
    {
        return this.iterable.select(predicate);
    }

    @Override
    public RichIterable<T> reject(Predicate<? super T> predicate)
    {
        return this.iterable.reject(predicate);
    }

    @Override
    public <S> RichIterable<S> selectInstancesOf(Class<S> clazz)
    {
        return this.iterable.selectInstancesOf(clazz);
    }

    @Override
    public <V> RichIterable<V> collect(Function<? super T, ? extends V> function)
    {
        return this.iterable.collect(function);
    }

    @Override
    public BooleanIterable collectBoolean(BooleanFunction<? super T> booleanFunction)
    {
        return this.iterable.collectBoolean(booleanFunction);
    }

    @Override
    public <R extends MutableBooleanCollection> R collectBoolean(BooleanFunction<? super T> booleanFunction, R target)
    {
        return this.iterable.collectBoolean(booleanFunction, target);
    }

    @Override
    public ByteIterable collectByte(ByteFunction<? super T> byteFunction)
    {
        return this.iterable.collectByte(byteFunction);
    }

    @Override
    public <R extends MutableByteCollection> R collectByte(ByteFunction<? super T> byteFunction, R target)
    {
        return this.iterable.collectByte(byteFunction, target);
    }

    @Override
    public CharIterable collectChar(CharFunction<? super T> charFunction)
    {
        return this.iterable.collectChar(charFunction);
    }

    @Override
    public <R extends MutableCharCollection> R collectChar(CharFunction<? super T> charFunction, R target)
    {
        return this.iterable.collectChar(charFunction, target);
    }

    @Override
    public DoubleIterable collectDouble(DoubleFunction<? super T> doubleFunction)
    {
        return this.iterable.collectDouble(doubleFunction);
    }

    @Override
    public <R extends MutableDoubleCollection> R collectDouble(DoubleFunction<? super T> doubleFunction, R target)
    {
        return this.iterable.collectDouble(doubleFunction, target);
    }

    @Override
    public FloatIterable collectFloat(FloatFunction<? super T> floatFunction)
    {
        return this.iterable.collectFloat(floatFunction);
    }

    @Override
    public <R extends MutableFloatCollection> R collectFloat(FloatFunction<? super T> floatFunction, R target)
    {
        return this.iterable.collectFloat(floatFunction, target);
    }

    @Override
    public IntIterable collectInt(IntFunction<? super T> intFunction)
    {
        return this.iterable.collectInt(intFunction);
    }

    @Override
    public <R extends MutableIntCollection> R collectInt(IntFunction<? super T> intFunction, R target)
    {
        return this.iterable.collectInt(intFunction, target);
    }

    @Override
    public LongIterable collectLong(LongFunction<? super T> longFunction)
    {
        return this.iterable.collectLong(longFunction);
    }

    @Override
    public <R extends MutableLongCollection> R collectLong(LongFunction<? super T> longFunction, R target)
    {
        return this.iterable.collectLong(longFunction, target);
    }

    @Override
    public ShortIterable collectShort(ShortFunction<? super T> shortFunction)
    {
        return this.iterable.collectShort(shortFunction);
    }

    @Override
    public <R extends MutableShortCollection> R collectShort(ShortFunction<? super T> shortFunction, R target)
    {
        return this.iterable.collectShort(shortFunction, target);
    }

    @Override
    public <V> RichIterable<V> flatCollect(Function<? super T, ? extends Iterable<V>> function)
    {
        return this.iterable.flatCollect(function);
    }

    @Override
    public <V> RichIterable<V> collectIf(Predicate<? super T> predicate, Function<? super T, ? extends V> function)
    {
        return this.iterable.collectIf(predicate, function);
    }

    @Override
    public T detect(Predicate<? super T> predicate)
    {
        return this.iterable.detect(predicate);
    }

    @Override
    public <P> T detectWith(Predicate2<? super T, ? super P> predicate, P parameter)
    {
        return this.iterable.detectWith(predicate, parameter);
    }

    @Override
    public Optional<T> detectOptional(Predicate<? super T> predicate)
    {
        return this.iterable.detectOptional(predicate);
    }

    @Override
    public <P> Optional<T> detectWithOptional(Predicate2<? super T, ? super P> predicate, P parameter)
    {
        return this.iterable.detectWithOptional(predicate, parameter);
    }

    @Override
    public T detectIfNone(Predicate<? super T> predicate, Function0<? extends T> function)
    {
        return this.iterable.detectIfNone(predicate, function);
    }

    @Override
    public <P> T detectWithIfNone(Predicate2<? super T, ? super P> predicate, P parameter, Function0<? extends T> function)
    {
        return this.iterable.detectWithIfNone(predicate, parameter, function);
    }

    @Override
    public T min(Comparator<? super T> comparator)
    {
        return this.iterable.min(comparator);
    }

    @Override
    public T max(Comparator<? super T> comparator)
    {
        return this.iterable.max(comparator);
    }

    @Override
    public T min()
    {
        return this.iterable.min();
    }

    @Override
    public T max()
    {
        return this.iterable.max();
    }

    @Override
    public <V extends Comparable<? super V>> T minBy(Function<? super T, ? extends V> function)
    {
        return this.iterable.minBy(function);
    }

    @Override
    public <V extends Comparable<? super V>> T maxBy(Function<? super T, ? extends V> function)
    {
        return this.iterable.maxBy(function);
    }

    @Override
    public int count(Predicate<? super T> predicate)
    {
        return this.iterable.count(predicate);
    }

    @Override
    public <P> int countWith(Predicate2<? super T, ? super P> predicate, P parameter)
    {
        return this.iterable.countWith(predicate, parameter);
    }

    @Override
    public boolean anySatisfy(Predicate<? super T> predicate)
    {
        return this.iterable.anySatisfy(predicate);
    }

    @Override
    public <P> boolean anySatisfyWith(Predicate2<? super T, ? super P> predicate, P parameter)
    {
        return this.iterable.anySatisfyWith(predicate, parameter);
    }

    @Override
    public boolean allSatisfy(Predicate<? super T> predicate)
    {
        return this.iterable.allSatisfy(predicate);
    }

    @Override
    public <P> boolean allSatisfyWith(Predicate2<? super T, ? super P> predicate, P parameter)
    {
        return this.iterable.allSatisfyWith(predicate, parameter);
    }

    @Override
    public boolean noneSatisfy(Predicate<? super T> predicate)
    {
        return this.iterable.noneSatisfy(predicate);
    }

    @Override
    public <P> boolean noneSatisfyWith(Predicate2<? super T, ? super P> predicate, P parameter)
    {
        return this.iterable.noneSatisfyWith(predicate, parameter);
    }

    @Override
    public <IV> IV injectInto(IV injectedValue, Function2<? super IV, ? super T, ? extends IV> function)
    {
        return this.iterable.injectInto(injectedValue, function);
    }

    @Override
    public int injectInto(int injectedValue, IntObjectToIntFunction<? super T> function)
    {
        return this.iterable.injectInto(injectedValue, function);
    }

    @Override
    public long injectInto(long injectedValue, LongObjectToLongFunction<? super T> function)
    {
        return this.iterable.injectInto(injectedValue, function);
    }

    @Override
    public double injectInto(double injectedValue, DoubleObjectToDoubleFunction<? super T> function)
    {
        return this.iterable.injectInto(injectedValue, function);
    }

    @Override
    public float injectInto(float injectedValue, FloatObjectToFloatFunction<? super T> function)
    {
        return this.iterable.injectInto(injectedValue, function);
    }

    @Override
    public long sumOfInt(IntFunction<? super T> function)
    {
        return this.iterable.sumOfInt(function);
    }

    @Override
    public double sumOfFloat(FloatFunction<? super T> function)
    {
        return this.iterable.sumOfFloat(function);
    }

    @Override
    public long sumOfLong(LongFunction<? super T> function)
    {
        return this.iterable.sumOfLong(function);
    }

    @Override
    public double sumOfDouble(DoubleFunction<? super T> function)
    {
        return this.iterable.sumOfDouble(function);
    }

    @Override
    public <V> ObjectLongMap<V> sumByInt(Function<? super T, ? extends V> groupBy, IntFunction<? super T> function)
    {
        return this.iterable.sumByInt(groupBy, function);
    }

    @Override
    public <V> ObjectDoubleMap<V> sumByFloat(Function<? super T, ? extends V> groupBy, FloatFunction<? super T> function)
    {
        return this.iterable.sumByFloat(groupBy, function);
    }

    @Override
    public <V> ObjectLongMap<V> sumByLong(Function<? super T, ? extends V> groupBy, LongFunction<? super T> function)
    {
        return this.iterable.sumByLong(groupBy, function);
    }

    @Override
    public <V> ObjectDoubleMap<V> sumByDouble(Function<? super T, ? extends V> groupBy, DoubleFunction<? super T> function)
    {
        return this.iterable.sumByDouble(groupBy, function);
    }

    @Override
    public <R extends Collection<T>> R into(R target)
    {
        return this.iterable.into(target);
    }

    @Override
    public MutableList<T> toList()
    {
        return this.iterable.toList();
    }

    @Override
    public MutableList<T> toSortedList()
    {
        return this.iterable.toSortedList();
    }

    @Override
    public MutableList<T> toSortedList(Comparator<? super T> comparator)
    {
        return this.iterable.toSortedList(comparator);
    }

    @Override
    public <V extends Comparable<? super V>> MutableList<T> toSortedListBy(Function<? super T, ? extends V> function)
    {
        return this.iterable.toSortedListBy(function);
    }

    @Override
    public MutableSortedSet<T> toSortedSet()
    {
        return this.iterable.toSortedSet();
    }

    @Override
    public MutableSortedSet<T> toSortedSet(Comparator<? super T> comparator)
    {
        return this.iterable.toSortedSet(comparator);
    }

    @Override
    public <V extends Comparable<? super V>> MutableSortedSet<T> toSortedSetBy(Function<? super T, ? extends V> function)
    {
        return this.iterable.toSortedSetBy(function);
    }

    @Override
    public MutableSet<T> toSet()
    {
        return this.iterable.toSet();
    }

    @Override
    public MutableBag<T> toBag()
    {
        return this.iterable.toBag();
    }

    @Override
    public MutableSortedBag<T> toSortedBag()
    {
        return this.iterable.toSortedBag();
    }

    @Override
    public MutableSortedBag<T> toSortedBag(Comparator<? super T> comparator)
    {
        return this.iterable.toSortedBag(comparator);
    }

    @Override
    public <V extends Comparable<? super V>> MutableSortedBag<T> toSortedBagBy(Function<? super T, ? extends V> function)
    {
        return this.iterable.toSortedBagBy(function);
    }

    @Override
    public <NK, NV> MutableMap<NK, NV> toMap(
            Function<? super T, ? extends NK> keyFunction,
            Function<? super T, ? extends NV> valueFunction)
    {
        return this.iterable.toMap(keyFunction, valueFunction);
    }

    @Override
    public <NK, NV> MutableSortedMap<NK, NV> toSortedMap(
            Function<? super T, ? extends NK> keyFunction,
            Function<? super T, ? extends NV> valueFunction)
    {
        return this.iterable.toSortedMap(keyFunction, valueFunction);
    }

    @Override
    public <NK, NV> MutableSortedMap<NK, NV> toSortedMap(Comparator<? super NK> comparator,
            Function<? super T, ? extends NK> keyFunction,
            Function<? super T, ? extends NV> valueFunction)
    {
        return this.iterable.toSortedMap(comparator, keyFunction, valueFunction);
    }

    @Override
    public LazyIterable<T> asLazy()
    {
        return this.iterable.asLazy();
    }

    @Override
    public Iterator<T> iterator()
    {
        return new UnmodifiableIteratorAdapter<>(this.iterable.iterator());
    }

    @Override
    public String toString()
    {
        return this.iterable.toString();
    }

    @Override
    public String makeString()
    {
        return this.iterable.makeString();
    }

    @Override
    public String makeString(String separator)
    {
        return this.iterable.makeString(separator);
    }

    @Override
    public String makeString(String start, String separator, String end)
    {
        return this.iterable.makeString(start, separator, end);
    }

    @Override
    public void appendString(Appendable appendable)
    {
        this.iterable.appendString(appendable);
    }

    @Override
    public void appendString(Appendable appendable, String separator)
    {
        this.iterable.appendString(appendable, separator);
    }

    @Override
    public void appendString(Appendable appendable, String start, String separator, String end)
    {
        this.iterable.appendString(appendable, start, separator, end);
    }

    @Override
    public <V> Multimap<V, T> groupBy(Function<? super T, ? extends V> function)
    {
        return this.iterable.groupBy(function);
    }

    @Override
    public <V, R extends MutableMultimap<V, T>> R groupBy(
            Function<? super T, ? extends V> function,
            R target)
    {
        return this.iterable.groupBy(function, target);
    }

    @Override
    public <V> Multimap<V, T> groupByEach(Function<? super T, ? extends Iterable<V>> function)
    {
        return this.iterable.groupByEach(function);
    }

    @Override
    public <V, R extends MutableMultimap<V, T>> R groupByEach(
            Function<? super T, ? extends Iterable<V>> function,
            R target)
    {
        return this.iterable.groupByEach(function, target);
    }

    @Override
    public <V> MapIterable<V, T> groupByUniqueKey(Function<? super T, ? extends V> function)
    {
        return this.iterable.groupByUniqueKey(function);
    }

    @Override
    public <V, R extends MutableMap<V, T>> R groupByUniqueKey(
            Function<? super T, ? extends V> function,
            R target)
    {
        return this.iterable.groupByUniqueKey(function, target);
    }

    @Override
    public <S> RichIterable<Pair<T, S>> zip(Iterable<S> that)
    {
        return this.iterable.zip(that);
    }

    @Override
    public <S, R extends Collection<Pair<T, S>>> R zip(Iterable<S> that, R target)
    {
        return this.iterable.zip(that, target);
    }

    @Override
    public RichIterable<Pair<T, Integer>> zipWithIndex()
    {
        return this.iterable.zipWithIndex();
    }

    @Override
    public <R extends Collection<Pair<T, Integer>>> R zipWithIndex(R target)
    {
        return this.iterable.zipWithIndex(target);
    }

    @Override
    public RichIterable<RichIterable<T>> chunk(int size)
    {
        return this.iterable.chunk(size);
    }

    @Override
    public <K, V> MapIterable<K, V> aggregateInPlaceBy(Function<? super T, ? extends K> groupBy, Function0<? extends V> zeroValueFactory, Procedure2<? super V, ? super T> mutatingAggregator)
    {
        return this.iterable.aggregateInPlaceBy(groupBy, zeroValueFactory, mutatingAggregator);
    }

    @Override
    public <K, V> MapIterable<K, V> aggregateBy(Function<? super T, ? extends K> groupBy, Function0<? extends V> zeroValueFactory, Function2<? super V, ? super T, ? extends V> nonMutatingAggregator)
    {
        return this.iterable.aggregateBy(groupBy, zeroValueFactory, nonMutatingAggregator);
    }
}


text:
using System;
using System.Linq;
using Bytes2you.Validation.UnitTests.Testing.Helpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Bytes2you.Validation.UnitTests.ValidatableArgumentTests
{
    [TestClass]
    public class Constructors_Should
    {
        [TestMethod]
        public void ThrowArgumentNullException_WhenNameArgumentIsNull()
        {
            // Act & Assert.
            Ensure.ArgumentNullExceptionIsThrown(() =>
            {
                ValidatableArgument<int> argument = new ValidatableArgument<int>(null, 3);
            }, "name");
        }

        [TestMethod]
        public void ThrowArgumentException_WhenNameIsEmpty()
        {
            // Act & Assert.
            Ensure.ArgumentExceptionIsThrown(() =>
            {
                ValidatableArgument<int> argument = new ValidatableArgument<int>(string.Empty, 3);
            }, "name");
        }

        [TestMethod]
        public void SetAllGivenProperties()
        {
            // Arrange.
            string name = "name";
            int value = 5;

            // Act.
            ValidatableArgument<int> argument = new ValidatableArgument<int>(name, value);

            // Assert.
            Assert.AreEqual(name, argument.Name);
            Assert.AreEqual(value, argument.Value);
            Assert.IsFalse(argument.ValidationPredicates.Any());
        }

        [TestMethod]
        public void CopiesAllProperties_FromTheGivenIArgument()
        {
            // Arrange.
            IArgument<int> argument = new ValidatableArgument<int>("name", 5);

            // Act.
            ValidatableArgument<int> validatableArgument = new ValidatableArgument<int>(argument);

            // Assert.
            Assert.AreEqual(argument.Name, validatableArgument.Name);
            Assert.AreEqual(argument.Value, validatableArgument.Value);
        }
    }
}


text:
import ScorecardService from './scorecard.service';

const module = angular
  .module('app.common.scorecardService', [])
  .service('ScorecardService', ScorecardService);

export default module.name;


text:
package main

import (
	_ "embed"
	"html/template"
	"log"
	"net/http"
	"time"

	"golang.org/x/build/internal/coordinator/pool"
	"golang.org/x/build/internal/coordinator/pool/queue"
)

//go:embed templates/queues.html
var queuesTemplateStr string

var queuesTemplate = template.Must(baseTmpl.New("queues.html").Funcs(map[string]interface{}{
	"timeSince":     timeSince,
	"humanDuration": humanDuration,
}).Parse(queuesTemplateStr))

type QueuesResponse struct {
	Queues map[string]*queue.QuotaStats
}

func handleQueues(w http.ResponseWriter, _ *http.Request) {
	resp := QueuesResponse{Queues: map[string]*queue.QuotaStats{}}
	mergeStats := func(qs map[string]*queue.QuotaStats) {
		for name, stats := range qs {
			resp.Queues[name] = stats
		}
	}
	mergeStats(pool.ReversePool().QuotaStats())
	mergeStats(pool.EC2BuildetPool().QuotaStats())
	mergeStats(pool.NewGCEConfiguration().BuildletPool().QuotaStats())
	if err := queuesTemplate.Execute(w, resp); err != nil {
		log.Printf("handleQueues: %v", err)
	}
}

func timeSince(t time.Time) time.Duration {
	return time.Since(t)
}

// humanDuration is largely time.Duration's formatting, but modified
// to imprecisely format days, even though days may vary in length
// due to daylight savings time. Sub-second durations are
// represented as 0s.
func humanDuration(d time.Duration) string {
	var buf [32]byte
	w := len(buf)

	u := uint64(d)
	neg := d < 0
	if neg {
		u = -u
	}
	w--
	buf[w] = 's'

	_, u = fmtFrac(buf[:w], u, 9)

	// u is now integer seconds
	w = fmtInt(buf[:w], u%60)
	u /= 60

	// u is now integer minutes
	if u > 0 {
		w--
		buf[w] = 'm'
		w = fmtInt(buf[:w], u%60)
		u /= 60

		// u is now integer hours
		if u > 0 {
			w--
			buf[w] = 'h'
			w = fmtInt(buf[:w], u%24)
			u /= 24
			if u > 0 {
				w--
				buf[w] = 'd'
				w = fmtInt(buf[:w], u)
			}
		}
	}

	if neg {
		w--
		buf[w] = '-'
	}
	return string(buf[w:])
}

// fmtFrac is identical to fmtFrac in the time package.
func fmtFrac(buf []byte, v uint64, prec int) (nw int, nv uint64) {
	// Omit trailing zeros up to and including decimal point.
	w := len(buf)
	print := false
	for i := 0; i < prec; i++ {
		digit := v % 10
		print = print || digit != 0
		if print {
			w--
			buf[w] = byte(digit) + '0'
		}
		v /= 10
	}
	if print {
		w--
		buf[w] = '.'
	}
	return w, v
}

// fmtFrac is identical to fmtInt in the time package.
func fmtInt(buf []byte, v uint64) int {
	w := len(buf)
	if v == 0 {
		w--
		buf[w] = '0'
	} else {
		for v > 0 {
			w--
			buf[w] = byte(v%10) + '0'
			v /= 10
		}
	}
	return w
}


text:
package etcdhttp

import (
	"errors"
	"net/http"
	"net/http/httptest"
	"sort"
	"testing"

	etcdErr "github.com/coreos/mantle/Godeps/_workspace/src/github.com/coreos/etcd/error"
	"github.com/coreos/mantle/Godeps/_workspace/src/github.com/coreos/etcd/etcdserver"
	"github.com/coreos/mantle/Godeps/_workspace/src/github.com/coreos/etcd/etcdserver/etcdserverpb"
	"github.com/coreos/mantle/Godeps/_workspace/src/github.com/coreos/etcd/pkg/types"
	"github.com/coreos/mantle/Godeps/_workspace/src/github.com/coreos/etcd/raft/raftpb"
	"github.com/coreos/mantle/Godeps/_workspace/src/golang.org/x/net/context"
)

type fakeCluster struct {
	id         uint64
	clientURLs []string
	members    map[uint64]*etcdserver.Member
}

func (c *fakeCluster) ID() types.ID         { return types.ID(c.id) }
func (c *fakeCluster) ClientURLs() []string { return c.clientURLs }
func (c *fakeCluster) Members() []*etcdserver.Member {
	var sms etcdserver.SortableMemberSlice
	for _, m := range c.members {
		sms = append(sms, m)
	}
	sort.Sort(sms)
	return []*etcdserver.Member(sms)
}
func (c *fakeCluster) Member(id types.ID) *etcdserver.Member { return c.members[uint64(id)] }
func (c *fakeCluster) IsIDRemoved(id types.ID) bool          { return false }

// errServer implements the etcd.Server interface for testing.
// It returns the given error from any Do/Process/AddMember/RemoveMember calls.
type errServer struct {
	err error
}

func (fs *errServer) Start()           {}
func (fs *errServer) Stop()            {}
func (fs *errServer) ID() types.ID     { return types.ID(1) }
func (fs *errServer) Leader() types.ID { return types.ID(1) }
func (fs *errServer) Do(ctx context.Context, r etcdserverpb.Request) (etcdserver.Response, error) {
	return etcdserver.Response{}, fs.err
}
func (fs *errServer) Process(ctx context.Context, m raftpb.Message) error {
	return fs.err
}
func (fs *errServer) AddMember(ctx context.Context, m etcdserver.Member) error {
	return fs.err
}
func (fs *errServer) RemoveMember(ctx context.Context, id uint64) error {
	return fs.err
}
func (fs *errServer) UpdateMember(ctx context.Context, m etcdserver.Member) error {
	return fs.err
}

func TestWriteError(t *testing.T) {
	// nil error should not panic
	rec := httptest.NewRecorder()
	writeError(rec, nil)
	h := rec.Header()
	if len(h) > 0 {
		t.Fatalf("unexpected non-empty headers: %#v", h)
	}
	b := rec.Body.String()
	if len(b) > 0 {
		t.Fatalf("unexpected non-empty body: %q", b)
	}

	tests := []struct {
		err   error
		wcode int
		wi    string
	}{
		{
			etcdErr.NewError(etcdErr.EcodeKeyNotFound, "/foo/bar", 123),
			http.StatusNotFound,
			"123",
		},
		{
			etcdErr.NewError(etcdErr.EcodeTestFailed, "/foo/bar", 456),
			http.StatusPreconditionFailed,
			"456",
		},
		{
			err:   errors.New("something went wrong"),
			wcode: http.StatusInternalServerError,
		},
	}

	for i, tt := range tests {
		rw := httptest.NewRecorder()
		writeError(rw, tt.err)
		if code := rw.Code; code != tt.wcode {
			t.Errorf("#%d: code=%d, want %d", i, code, tt.wcode)
		}
		if idx := rw.Header().Get("X-Etcd-Index"); idx != tt.wi {
			t.Errorf("#%d: X-Etcd-Index=%q, want %q", i, idx, tt.wi)
		}
	}
}

func TestAllowMethod(t *testing.T) {
	tests := []struct {
		m  string
		ms []string
		w  bool
		wh string
	}{
		// Accepted methods
		{
			m:  "GET",
			ms: []string{"GET", "POST", "PUT"},
			w:  true,
		},
		{
			m:  "POST",
			ms: []string{"POST"},
			w:  true,
		},
		// Made-up methods no good
		{
			m:  "FAKE",
			ms: []string{"GET", "POST", "PUT"},
			w:  false,
			wh: "GET,POST,PUT",
		},
		// Empty methods no good
		{
			m:  "",
			ms: []string{"GET", "POST"},
			w:  false,
			wh: "GET,POST",
		},
		// Empty accepted methods no good
		{
			m:  "GET",
			ms: []string{""},
			w:  false,
			wh: "",
		},
		// No methods accepted
		{
			m:  "GET",
			ms: []string{},
			w:  false,
			wh: "",
		},
	}

	for i, tt := range tests {
		rw := httptest.NewRecorder()
		g := allowMethod(rw, tt.m, tt.ms...)
		if g != tt.w {
			t.Errorf("#%d: got allowMethod()=%t, want %t", i, g, tt.w)
		}
		if !tt.w {
			if rw.Code != http.StatusMethodNotAllowed {
				t.Errorf("#%d: code=%d, want %d", i, rw.Code, http.StatusMethodNotAllowed)
			}
			gh := rw.Header().Get("Allow")
			if gh != tt.wh {
				t.Errorf("#%d: Allow header=%q, want %q", i, gh, tt.wh)
			}
		}
	}
}


text:
#ifndef TILEDB_CONSISTENCY_H
#define TILEDB_CONSISTENCY_H

#include <iterator>
#include <map>

#include "tiledb/common/common.h"
#include "tiledb/common/logger.h"
#include "tiledb/sm/enums/query_type.h"
#include "tiledb/sm/filesystem/uri.h"

using namespace tiledb::common;

namespace tiledb::sm {

class Array;
class ConsistencySentry;

/**
 * Tracks the open arrays on disk, considering that a given
 * URI can have multiple open arrays.
 *
 * Intended to act as a singleton global.
 * There is only one (global) copy of this class used in practice.
 *
 * @invariant Each registry entry is contained in exactly one Sentry.
 */
class ConsistencyController {
  /**
   * Makes available the private APIs of ConsistencyController for array
   * registration and deregistration.
   */
  friend class ConsistencySentry;
  /**
   * Makes available internals of ConsistencyController for testing.
   */
  friend class WhiteboxConsistencyController;

 public:
  /**
   * Note: array openness and registration are not fully atomic. Upon array
   * registration, the array is considered to be only partially opened, so
   * requesting array data is prohibited. However, in order to maintain
   * consistency, registration must access the array's QueryType. As such, the
   * QueryType is stored in the multimap alongside its corresponding Array.
   */
  using array_entry = std::tuple<Array&, const QueryType>;
  using entry_type = std::multimap<const URI, array_entry>::const_iterator;

  /**
   * Constructor.
   *
   * Default constructed as the initial state of the singleton Controller with
   * no registered arrays.
   * Note: nothing can be registered in the singleton until an array is opened.
   */
  ConsistencyController() = default;

  /** Copy Constructor is deleted. */
  ConsistencyController(const ConsistencyController&) = delete;

  /** Move Constructor is deleted. */
  ConsistencyController(ConsistencyController&&) = delete;

  /** Copy assignment is deleted. */
  ConsistencyController& operator=(const ConsistencyController&) = delete;

  /** Move assignment is deleted. */
  ConsistencyController& operator=(ConsistencyController&&) = delete;

  /** Destructor. */
  ~ConsistencyController() = default;

  /**
   * Register the given Array as open.
   *
   * @return Sentry object whose lifespan is the same as the registration.
   */
  ConsistencySentry make_sentry(
      const URI uri, Array& array, const QueryType query_type);

  /** Returns true if the array is open, i.e. registered in the multimap. */
  bool is_open(const URI uri);

 private:
  /**
   * Wrapper around a multimap registration operation.
   *
   * Note: this function is private because it may only be called by the
   * ConsistencySentry constructor.
   *
   * Note: this function must not request any data from an array because array
   * openness and registration are not yet fully atomic.
   *
   * @pre the given URI is the root directory of the Array and is not empty.
   */
  entry_type register_array(
      const URI uri, Array& array, const QueryType query_type);

  /**
   * Wrapper around a multimap deregistration operation.
   *
   * Note: this function is private because it may only be called by the
   * ConsistencySentry destructor.
   *
   * Note: entry_type is passed as a value that is explicitly deleted from the
   * registration multimap upon ConsistencySentry destruction only.
   */
  void deregister_array(entry_type entry);

  /**
   * The open array registry.
   *
   * Note: QueryType must be stored in the multimap to avoid requesting data
   * from partially-opened arrays because array openness and registration are
   * not yet fully atomic.
   **/
  std::multimap<const URI, array_entry> array_registry_;

  /**
   * Mutex that protects atomicity between the existence of a
   * ConsistencySentry object and the multimap's registration.
   */
  std::mutex mtx_;
};

/**
 * Sentry class for ConsistencyController.
 *
 * @invariant Each Sentry contains exactly one Controller registration entry.
 * @invariant The ConsistencyController::entry_type must not be empty.
 * @pre invariant exception:
 * the entry_type may be empty ONLY in an rvalue during move construction.
 */
class ConsistencySentry {
 public:
  /** Constructor. */
  ConsistencySentry(
      ConsistencyController& registry, ConsistencyController::entry_type entry);

  /**
   * Move constructor.
   *
   * @pre uses transfer semantics to maintain the class invariants.
   **/
  ConsistencySentry(ConsistencySentry&& x);

  /** Copy Constructor is deleted to maintain the class invariants. */
  ConsistencySentry(const ConsistencySentry&) = delete;

  /** Copy assignment is deleted to maintain the class invariants. */
  ConsistencySentry& operator=(const ConsistencySentry&) = delete;

  /** Move assignment is unnecessary and thus deleted. */
  ConsistencySentry& operator=(ConsistencySentry&&) = delete;

  /** Destructor. */
  ~ConsistencySentry();

 private:
  /**
   * The ConsistencyController instance.
   *
   * @pre This MUST reference the same member that created the Sentry object.
   */
  ConsistencyController& parent_;

  /**
   * An entry within the registry structure of the parent
   * ConsistencyController object.
   */
  ConsistencyController::entry_type entry_;
};

}  // namespace tiledb::sm

#endif  // TILEDB_CONSISTENCY_H


text:
'use strict';

module.exports = {
    set: function (v) {
        this.setProperty('stroke-dasharray', v);
    },
    get: function () {
        return this.getPropertyValue('stroke-dasharray');
    },
    enumerable: true
};