text:
<?php
namespace Vanio\DomainBundle\Pagination;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\Type;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Doctrine\ORM\Query\Expr\From;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\Query\Expr\Select;
use Doctrine\ORM\QueryBuilder;
use Happyr\DoctrineSpecification\Query\QueryModifier;

class OrderBy implements QueryModifier
{
    /** @var string[] */
    private $orderBy;

    /** @var string|bool|null */
    private $dqlAlias;

    /**
     * @param string|string[] $orderBy
     * @param string|bool|null $dqlAlias
     */
    public function __construct($orderBy, $dqlAlias = null)
    {
        $this->orderBy = is_array($orderBy) ? $orderBy : [$orderBy => 'ASC'];
        $this->dqlAlias = $dqlAlias;
    }

    /**
     * @param string $orderByString
     * @param string|bool|null $dqlAlias
     * @return self
     */
    public static function fromString(string $orderByString, $dqlAlias = null): self
    {
        $orderBy = [];

        foreach (preg_split('~,\s*~', $orderByString) as $order) {
            if (($order[0] ?? null) === '-') {
                $propertyPath = substr($order, 1);
                $direction = 'DESC';
            } else {
                list($propertyPath, $direction) = explode(' ', $order) + [null, 'ASC'];
            }

            $orderBy[$propertyPath] = $direction;
        }

        return new self($orderBy, $dqlAlias);
    }

    public function orderBy(): array
    {
        return $this->orderBy;
    }

    /**
     * @param QueryBuilder $queryBuilder
     * @param string $dqlAlias
     */
    public function modify(QueryBuilder $queryBuilder, $dqlAlias): void
    {
        if ($this->dqlAlias !== null) {
            $dqlAlias = $this->dqlAlias;
        }

        if ($dqlAlias === false) {
            foreach ($this->orderBy as $orderBy => $direction) {
                $queryBuilder->addOrderBy($orderBy, $direction);
            }

            return;
        }

        $classMetadata = $this->getClassMetadata($queryBuilder, $dqlAlias);
        $entityManager = $queryBuilder->getEntityManager();

        foreach ($this->orderBy as $propertyPath => $direction) {
            $currentClassMetadata = $classMetadata;
            $propertyPath = explode('.', $propertyPath);
            $currentDqlAlias = $this->joinAssociations($queryBuilder, $dqlAlias, $currentClassMetadata, $propertyPath);
            $path = $this->resolveEmbeddedPath($entityManager, $currentDqlAlias, $currentClassMetadata, $propertyPath);
            $databasePlatform = $entityManager->getConnection()->getDatabasePlatform();

            if (count($propertyPath) > 1 && $this->isJsonField($currentClassMetadata, $databasePlatform, $propertyPath[0])) {
                $this->orderByJsonField($queryBuilder, $path, $propertyPath, $direction);
            } elseif (count($propertyPath) === 1 && $currentClassMetadata->hasField($propertyPath[0])) {
                $queryBuilder->addOrderBy(sprintf('%s.%s', $path, $propertyPath[0]), $direction);
            }
        }
    }

    private function joinAssociations(
        QueryBuilder $queryBuilder,
        string $alias,
        ClassMetadataInfo &$classMetadata,
        array &$propertyPath
    ): string {
        $count = count($propertyPath) - 1;

        for ($i = 0; $i < $count; $i++) {
            if (!$classMetadata->hasAssociation($propertyPath[0])) {
                break;
            }

            $property = array_shift($propertyPath);
            $relation = sprintf('%s.%s', $alias, $property);

            if ($join = $this->getJoin($queryBuilder, $relation)) {
                $alias = $join->getAlias();
            } else {
                $alias = sprintf('%s_%s', $alias, $property);

                if ($i === 0) {
                    $alias = sprintf('__%s', $alias);
                }

                $queryBuilder->leftJoin($relation, $alias);
            }

            $class = $classMetadata->getAssociationTargetClass($property);
            $classMetadata = $queryBuilder->getEntityManager()->getClassMetadata($class);
        }

        return $alias;
    }

    private function resolveEmbeddedPath(
        EntityManager $entityManager,
        string $dqlAlias,
        ClassMetadataInfo &$classMetadata,
        array &$propertyPath
    ): string {
        $path = $dqlAlias;
        $count = count($propertyPath) - 1;

        for ($i = 0; $i < $count; $i++) {
            if ($embeddedClass = ($classMetadata->embeddedClasses[$propertyPath[0]]['class'] ?? null)) {
                $path = sprintf('%s.%s', $path, array_shift($propertyPath));
                $classMetadata = $entityManager->getClassMetadata($embeddedClass);
            }
        }

        return $path;
    }

    private function getClassMetadata(QueryBuilder $queryBuilder, string $alias): ClassMetadataInfo
    {
        /** @var From[] $froms */
        $froms = $queryBuilder->getDQLPart('from');

        foreach ($froms as $from) {
            if ($from->getAlias() === $alias) {
                return $queryBuilder->getEntityManager()->getClassMetadata($from->getFrom());
            }
        }

        throw new \InvalidArgumentException(sprintf(
            'QueryBuilder does not contain FROM clause with "%s" alias.',
            $alias
        ));
    }

    /**
     * @param QueryBuilder $queryBuilder
     * @param string $join
     * @return Join|null
     */
    private function getJoin(QueryBuilder $queryBuilder, string $join)
    {
        foreach ($queryBuilder->getDQLPart('join') as $joins) {
            foreach ($joins as $dqlPart) {
                /** @var Join $dqlPart */
                if ($dqlPart->getJoin() === $join) {
                    return $dqlPart;
                }
            }
        }

        return null;
    }

    private function isJsonField(
        ClassMetadataInfo $classMetadata,
        AbstractPlatform $databasePlatform,
        string $field
    ): bool {
        if (!$classMetadata->hasField($field)) {
            return false;
        }

        $type = Type::getType($classMetadata->getTypeOfField($field));
        $fieldMapping = $classMetadata->getFieldMapping($field);

        if (!$databasePlatform->hasNativeJsonType()) {
            return false;
        }

        return in_array(
            $type->getSQLDeclaration($fieldMapping, $databasePlatform),
            [$databasePlatform->getJsonTypeDeclarationSQL($fieldMapping), 'jsonb']
        );
    }

    /**
     * @param QueryBuilder $queryBuilder
     * @param string $path
     * @param string[] $propertyPath
     * @param string $direction
     */
    private function orderByJsonField(QueryBuilder $queryBuilder, string $path, array $propertyPath, string $direction)
    {
        $alias = sprintf('%s_%s', str_replace('.', '_', $path), implode('_', $propertyPath));
        $databasePlatform = $queryBuilder->getEntityManager()->getConnection()->getDatabasePlatform();
        $select = sprintf(
            'JSON_GET_PATH(%s.%s, %s) AS HIDDEN %s',
            $path,
            array_shift($propertyPath),
            implode(', ', array_map([$databasePlatform, 'quoteStringLiteral'], $propertyPath)),
            $alias
        );

        if (!$this->hasSelect($queryBuilder, $select)) {
            $queryBuilder->addSelect($select);
        }

        $queryBuilder->addOrderBy($alias, $direction);
    }

    private function hasSelect(QueryBuilder $queryBuilder, string $select): bool
    {
        /** @var Select[] $selects */
        $selects = $queryBuilder->getDQLPart('select');

        foreach ($selects as $s) {
            if (array_search($select, $s->getParts()) !== false) {
                return true;
            }
        }

        return false;
    }
}


text:
			Name
			Actions

		@foreach ($facility_plans as $facility_plan)

id}}">

{{$facility_plan->name or ''}}

					@foreach($facility_plan->facilities as $facility)

 - {{$facility->name or ''}}

					@endforeach

		@endforeach

redpajama_set_name: RedPajamaGithub


text: default['homebrew']['taps'] = {}


text:
* greet
    - utter_greet
* goodbye
    - action_restart
    - restart


text:
Underwear.defineMethod(Array.prototype, 'include', function() {
  return _.include.apply(_, [this].concat(_.toArray(arguments)));
});


text: ThisisTestForMVC


text:
module WOW::Definitions
  build 15595 do
    table :expansions do
      e   0,  :world_of_warcraft,       tc_value: 'WorldOfWarcraft',    label: 'World of Warcraft'
      e   1,  :the_burning_crusade,     tc_value: 'TheBurningCrusade',  label: 'The Burning Crusade'
      e   2,  :wrath_of_the_lich_king,  tc_value: 'WrathOfTheLichKing', label: 'Wrath of the Lich King'
      e   3,  :cataclysm,               tc_value: 'Cataclysm',          label: 'Cataclysm'
      e   4,  :mists_of_pandaria,       tc_value: 'MistsOfPandaria',    label: 'Mists of Pandaria'
    end
  end
end


text:
package org.assertj.core.error.future;

import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.error.future.ShouldBeCompletedExceptionally.shouldHaveCompletedExceptionally;

import java.util.concurrent.CompletableFuture;

import org.assertj.core.internal.TestDescription;
import org.junit.Test;

public class ShouldHaveCompletedExceptionally_create_Test {

  @Test
  public void should_create_error_message() throws Exception {
    String error = shouldHaveCompletedExceptionally(new CompletableFuture<Object>()).create(new TestDescription("TEST"));

    assertThat(error).isEqualTo(format("[TEST] %n" +
                                       "Expecting%n" +
                                       "  <CompletableFuture[Incomplete]>%n" +
                                       "to be completed exceptionally"));
  }

}


text:
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/*

Godoc extracts and generates documentation for Go programs.

It has two modes.

Without the -http flag, it runs in command-line mode and prints plain text
documentation to standard output and exits. If both a library package and
a command with the same name exists, using the prefix cmd/ will force
documentation on the command rather than the library package. If the -src
flag is specified, godoc prints the exported interface of a package in Go
source form, or the implementation of a specific exported language entity:

	godoc fmt                # documentation for package fmt
	godoc fmt Printf         # documentation for fmt.Printf
	godoc cmd/go             # force documentation for the go command
	godoc -src fmt           # fmt package interface in Go source form
	godoc -src fmt Printf    # implementation of fmt.Printf

In command-line mode, the -q flag enables search queries against a godoc running
as a webserver. If no explicit server address is specified with the -server flag,
godoc first tries localhost:6060 and then http://golang.org.

	godoc -q Reader
	godoc -q math.Sin
	godoc -server=:6060 -q sin

With the -http flag, it runs as a web server and presents the documentation as a
web page.

	godoc -http=:6060

Usage:
	godoc [flag] package [name ...]

The flags are:
	-v
		verbose mode
	-q
		arguments are considered search queries: a legal query is a
		single identifier (such as ToLower) or a qualified identifier
		(such as math.Sin)
	-src
		print (exported) source in command-line mode
	-tabwidth=4
		width of tabs in units of spaces
	-timestamps=true
		show timestamps with directory listings
	-index
		enable identifier and full text search index
		(no search box is shown if -index is not set)
	-index_files=""
		glob pattern specifying index files; if not empty,
		the index is read from these files in sorted order
	-index_throttle=0.75
		index throttle value; a value of 0 means no time is allocated
		to the indexer (the indexer will never finish), a value of 1.0
		means that index creation is running at full throttle (other
		goroutines may get no time while the index is built)
	-links=true:
		link identifiers to their declarations
	-write_index=false
		write index to a file; the file name must be specified with
		-index_files
	-maxresults=10000
		maximum number of full text search results shown
		(no full text index is built if maxresults <= 0)
	-notes="BUG"
		regular expression matching note markers to show
		(e.g., "BUG|TODO", ".*")
	-html
		print HTML in command-line mode
	-goroot=$GOROOT
		Go root directory
	-http=addr
		HTTP service address (e.g., '127.0.0.1:6060' or just ':6060')
	-server=addr
		webserver address for command line searches
	-analysis=type,pointer
		comma-separated list of analyses to perform
    		"type": display identifier resolution, type info, method sets,
			'implements', and static callees
		"pointer" display channel peers, callers and dynamic callees
			(significantly slower)
		See http://golang.org/lib/godoc/analysis/help.html for details.
	-templates=""
		directory containing alternate template files; if set,
		the directory may provide alternative template files
		for the files in $GOROOT/lib/godoc
	-url=path
		print to standard output the data that would be served by
		an HTTP request for path
	-zip=""
		zip file providing the file system to serve; disabled if empty

By default, godoc looks at the packages it finds via $GOROOT and $GOPATH (if set).
This behavior can be altered by providing an alternative $GOROOT with the -goroot
flag.

When godoc runs as a web server and -index is set, a search index is maintained.
The index is created at startup.

The index contains both identifier and full text search information (searchable
via regular expressions). The maximum number of full text search results shown
can be set with the -maxresults flag; if set to 0, no full text results are
shown, and only an identifier index but no full text search index is created.

The presentation mode of web pages served by godoc can be controlled with the
"m" URL parameter; it accepts a comma-separated list of flag names as value:

	all	show documentation for all declarations, not just the exported ones
	methods	show all embedded methods, not just those of unexported anonymous fields
	src	show the original source code rather then the extracted documentation
	text	present the page in textual (command-line) form rather than HTML
	flat	present flat (not indented) directory listings using full paths

For instance, http://golang.org/pkg/math/big/?m=all,text shows the documentation
for all (not just the exported) declarations of package big, in textual form (as
it would appear when using godoc from the command line: "godoc -src math/big .*").

By default, godoc serves files from the file system of the underlying OS.
Instead, a .zip file may be provided via the -zip flag, which contains
the file system to serve. The file paths stored in the .zip file must use
slash ('/') as path separator; and they must be unrooted. $GOROOT (or -goroot)
must be set to the .zip file directory path containing the Go root directory.
For instance, for a .zip file created by the command:

	zip go.zip $HOME/go

one may run godoc as follows:

	godoc -http=:6060 -zip=go.zip -goroot=$HOME/go

Godoc documentation is converted to HTML or to text using the go/doc package;
see http://golang.org/pkg/go/doc/#ToHTML for the exact rules.
Godoc also shows example code that is runnable by the testing package;
see http://golang.org/pkg/testing/#hdr-Examples for the conventions.
See "Godoc: documenting Go code" for how to write good comments for godoc:
http://golang.org/doc/articles/godoc_documenting_go_code.html

*/
package main // import "golang.org/x/tools/cmd/godoc"


text:
/**
 * @file
 * @brief Backend API for emulated GPIO
 */

#ifndef ZEPHYR_INCLUDE_DRIVERS_GPIO_GPIO_EMUL_H_
#define ZEPHYR_INCLUDE_DRIVERS_GPIO_GPIO_EMUL_H_

#include <zephyr/types.h>
#include <drivers/gpio.h>

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @brief Emulated GPIO backend API
 * @defgroup gpio_emul Emulated GPIO
 * @ingroup gpio_interface
 * @{
 *
 * Behaviour of emulated GPIO is application-defined. As-such, each
 * application may
 *
 * - define a Device Tree overlay file to indicate the number of GPIO
 *   controllers as well as the number of pins for each controller
 * - register a callback with the GPIO controller using
 *   @ref gpio_add_callback to emulate "wiring"
 * - asynchronously call @ref gpio_emul_input_set and / or
 *   @ref gpio_emul_input_set_masked in order to emulate GPIO events
 *
 * An example of an appropriate Device Tree overlay file is in
 * tests/drivers/gpio/gpio_basic_api/boards/native_posix_64.overlay.
 *
 * An example of registering a callback to emulate "wiring" as well as
 * an example of calling @ref gpio_emul_input_set is in the file
 * tests/drivers/gpio/gpio_basic_api/src/main.c .
 */

/**
 * @brief Modify the values of one or more emulated GPIO input @p pins
 *
 * @param port The emulated GPIO port
 * @param pins The mask of pins that have changed
 * @param values New values to assign to @p pins
 *
 * @return 0 on success
 * @return -EINVAL if an invalid argument is provided
 */
int gpio_emul_input_set_masked(const struct device *port, gpio_port_pins_t pins,
			      gpio_port_value_t values);

/**
 * @brief Modify the value of one emulated GPIO input @p pin
 *
 * @param port The emulated GPIO port
 * @param pin The pin to modify
 * @param value New values to assign to @p pin
 *
 * @return 0 on success
 * @return -EINVAL if an invalid argument is provided
 */
static inline int gpio_emul_input_set(const struct device *port, gpio_pin_t pin,
				     int value)
{
	return gpio_emul_input_set_masked(port, BIT(pin), value ? BIT(pin) : 0);
}

/**
 * @brief Read the value of one or more emulated GPIO output @p pins
 *
 * @param port The emulated GPIO port
 * @param pins The mask of pins that have changed
 * @param values A pointer to where the value of @p pins will be stored
 *
 * @return 0 on success
 * @return -EINVAL if an invalid argument is provided
 */
int gpio_emul_output_get_masked(const struct device *port, gpio_port_pins_t pins,
			       gpio_port_value_t *values);

/**
 * @brief Read the value of one emulated GPIO output @p pin
 *
 * @param port The emulated GPIO port
 * @param pin The pin to read
 *
 * @return 0 or 1 on success
 * @return -EINVAL if an invalid argument is provided
 */
static inline int gpio_emul_output_get(const struct device *port, gpio_pin_t pin)
{
	int ret;
	gpio_port_value_t values;

	ret = gpio_emul_output_get_masked(port, BIT(pin), &values);
	if (ret == 0) {
		ret = (values & BIT(pin)) ? 1 : 0;
	}

	return ret;
}

/**
 * @brief Get @p flags for a given emulated GPIO @p pin
 *
 * For more information on available flags, see @ref gpio_interface.
 *
 * @param port The emulated GPIO port
 * @param pin The pin to retrieve @p flags for
 * @param flags a pointer to where the flags for @p pin will be stored
 *
 * @return 0 on success
 * @return -EINVAL if an invalid argument is provided
 */
int gpio_emul_flags_get(const struct device *port, gpio_pin_t pin, gpio_flags_t *flags);

/**
 * @}
 */

#ifdef __cplusplus
}
#endif

#endif /* ZEPHYR_INCLUDE_DRIVERS_GPIO_GPIO_EMUL_H_ */


text:
package fr.xebia.consumer;

import fr.xebia.pokemon.Pokemon;
import fr.xebia.pokemon.RxPokemonRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class RxObservablePokemonService {

    private RxPokemonRepository pokemonRepository;

    private Logger logger = LoggerFactory.getLogger(getClass());

    public RxObservablePokemonService(RxPokemonRepository pokemonRepository) {
        this.pokemonRepository = pokemonRepository;
    }

    public Observable<List<Pokemon>> fetchPokemons(String... names) {
        logger.info("Querying remote service using RX for {}", names);
        return Observable
                .from(Arrays.asList(names))
                .flatMap(name -> pokemonRepository.searchPokemon(name))
                .toList()
                .map(list -> list.stream()
                        .filter(Optional::isPresent)
                        .map(Optional::get)
                        .collect(Collectors.toList()));
    }

}


text:
using GroupDocs.Comparison.Options;
using System;
using System.Collections.Generic;
using System.IO;
using GroupDocs.Comparison.Words.Revision;

namespace GroupDocs.Comparison.Examples.CSharp.AdvancedUsage
{
	/// <summary>
	/// This class demonstrates how to get revisions from a document, process and save the result
	/// </summary>
	class AcceptRejectRevisions
	{
		/// <summary>
		/// This example demonstrates how to get revisions from document path
		/// </summary>
		public static void AcceptRejectRevisionsFromPath()
		{
			string outputDirectoryAccepted = Constants.GetOutputDirectoryPath(nameChildFolder: "AcceptRevisionsFromPath");
			string outputFileNameAccepted = Path.Combine(outputDirectoryAccepted, Constants.RESULT_REVISIONS);

			string outputDirectoryRejected = Constants.GetOutputDirectoryPath(nameChildFolder: "RejectRevisionsFromPath");
			string outputFileNameRejected = Path.Combine(outputDirectoryRejected, Constants.RESULT_REVISIONS);

			// Example of accepting some changes
			using (RevisionHandler revisionHandler = new RevisionHandler(Constants.SOURCE_REVISIONS))
			{
				List<RevisionInfo> revisionListForAccepted = revisionHandler.GetRevisions();
				foreach (RevisionInfo revision in revisionListForAccepted)
				{
					if (revision.Type == RevisionType.Insertion) revision.Action = RevisionAction.Accept;
				}

				revisionHandler.ApplyRevisionChanges(outputFileNameAccepted,
					new ApplyRevisionOptions() {Changes = revisionListForAccepted});
			}

			// Example of rejecting some changes
			using (RevisionHandler revisionHandler = new RevisionHandler(Constants.SOURCE_REVISIONS))
			{
				List<RevisionInfo> revisionListForRejected = revisionHandler.GetRevisions();
				foreach (RevisionInfo revision in revisionListForRejected)
				{
					if (revision.Type == RevisionType.Insertion) revision.Action = RevisionAction.Reject;
				}

				revisionHandler.ApplyRevisionChanges(outputFileNameRejected,
					new ApplyRevisionOptions() {Changes = revisionListForRejected});
			}

			Console.WriteLine(
				$"\nRevisions processed successfully.\nCheck output in {Directory.GetCurrentDirectory()}.");
		}

		/// <summary>
		/// This example demonstrates how to get revisions from document stream
		/// </summary>
		public static void AcceptRejectRevisionsFromStream()
		{
			Stream inputFileName = new FileStream(Constants.SOURCE_REVISIONS, FileMode.Open, FileAccess.ReadWrite);
			string outputDirectoryAccepted = Constants.GetOutputDirectoryPath(nameChildFolder: "AcceptRevisionsFromStream");
			Stream outputFileNameAccepted = File.Create(Path.Combine(outputDirectoryAccepted, Constants.RESULT_REVISIONS));

			// Example of accepting some changes
			using (RevisionHandler revisionHandler = new RevisionHandler(inputFileName))
			{
				List<RevisionInfo> revisionListForAccepted = revisionHandler.GetRevisions();
				foreach (RevisionInfo revision in revisionListForAccepted)
				{
					if (revision.Type == RevisionType.Insertion) revision.Action = RevisionAction.Accept;
				}

				revisionHandler.ApplyRevisionChanges(outputFileNameAccepted,
					new ApplyRevisionOptions() {Changes = revisionListForAccepted});
			}

			outputFileNameAccepted.Close();

			string outputDirectoryRejected = Constants.GetOutputDirectoryPath(nameChildFolder: "RejectRevisionsFromStream");
			Stream outputFileNameRejected = File.Create(Path.Combine(outputDirectoryRejected, Constants.RESULT_REVISIONS));

			// Example of rejecting some changes
			using (RevisionHandler revisionHandler = new RevisionHandler(inputFileName))
			{
				List<RevisionInfo> revisionListForRejected = revisionHandler.GetRevisions();
				foreach (RevisionInfo revision in revisionListForRejected)
				{
					if (revision.Type == RevisionType.Insertion) revision.Action = RevisionAction.Reject;
				}

				revisionHandler.ApplyRevisionChanges(outputFileNameRejected,
					new ApplyRevisionOptions() {Changes = revisionListForRejected});
			}

			inputFileName.Close();
			outputFileNameRejected.Close();

			Console.WriteLine(
				$"\nRevisions processed successfully.\nCheck output in {Directory.GetCurrentDirectory()}.");
		}

		/// <summary>
		/// This example demonstrates how to optimally handle all revisions
		/// </summary>
		public static void AcceptRejectAllRevisions()
		{
			string outputDirectoryAccepted = Constants.GetOutputDirectoryPath(nameChildFolder: "AcceptAllRevisions");
			string outputFileNameAccepted = Path.Combine(outputDirectoryAccepted, Constants.RESULT_REVISIONS);

			string outputDirectoryRejected = Constants.GetOutputDirectoryPath(nameChildFolder: "RejectAllRevisions");
			string outputFileNameRejected = Path.Combine(outputDirectoryRejected, Constants.RESULT_REVISIONS);

			// Example of accepting all changes
			using (RevisionHandler revisionHandler = new RevisionHandler(Constants.SOURCE_REVISIONS))
			{
				revisionHandler.ApplyRevisionChanges(outputFileNameAccepted,
					new ApplyRevisionOptions() { CommonHandler = RevisionAction.Accept });
			}

			// Example of rejecting all changes
			using (RevisionHandler revisionHandler = new RevisionHandler(Constants.SOURCE_REVISIONS))
			{
				revisionHandler.ApplyRevisionChanges(outputFileNameRejected,
					new ApplyRevisionOptions() { CommonHandler = RevisionAction.Reject });
			}

			Console.WriteLine(
				$"\nRevisions processed successfully.\nCheck output in {Directory.GetCurrentDirectory()}.");
		}
	}
}


text:
@interface PreferencesWindow () <NSToolbarDelegate>

@end

@implementation PreferencesWindow

#pragma mark Goop

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (id)init
{
	if((self = [super initWithWindowNibName:@"PreferencesWindow"]))
	{
		mPreferencesPanes = @{
            @"GeneralPane": [GeneralPane new],
            @"ArtModePane": [ArtModePane new],
            @"HotKeysPane": [HotKeysPane new],
            @"SocialPane": [SocialPane new],
            @"AdvancedPane": [AdvancedPane new],
        };
	}

	return self;
}

#pragma mark -

- (NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag
{
	PreferencesPane *pane = [mPreferencesPanes objectForKey:itemIdentifier];
	NSToolbarItem *paneItem = [[NSToolbarItem alloc] initWithItemIdentifier:itemIdentifier];

	[paneItem setLabel:pane.name];
	[paneItem setImage:pane.icon];

	[paneItem setTarget:self];
	[paneItem setAction:@selector(showPaneFrom:)];

	return paneItem;
}

- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar
{
	return @[
        NSToolbarFlexibleSpaceItemIdentifier,
        @"GeneralPane",
        @"SocialPane",
        @"ArtModePane",
        @"HotKeysPane",
        @"AdvancedPane",
        NSToolbarFlexibleSpaceItemIdentifier
    ];
}

- (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)toolbar
{
	return [self toolbarAllowedItemIdentifiers:toolbar];
}

- (NSArray *)toolbarSelectableItemIdentifiers:(NSToolbar *)toolbar
{
	return [self toolbarAllowedItemIdentifiers:toolbar];
}

- (void)setupToolbar
{
	NSToolbar *selectorToolbar = [[NSToolbar alloc] initWithIdentifier:@"PreferencesWindowToolbar"];
	[selectorToolbar setDelegate:self];
	[selectorToolbar setAllowsUserCustomization:NO];

	[selectorToolbar setSelectedItemIdentifier:@"GeneralPane"];

	[[self window] setToolbar:selectorToolbar];
}

#pragma mark -

- (void)windowDidLoad
{
	[[self window] center];

	[self setupToolbar];

	[self setSelectedPane:[mPreferencesPanes objectForKey:@"GeneralPane"]];
}

#pragma mark - Managing Panes

- (void)contentViewFrameDidChange:(NSNotification *)notification
{
	[self showPane:[oContentBox contentView]];
}

#pragma mark -

- (void)showPane:(NSView *)pane
{
	NSSize viewSize = [pane frame].size;
	NSSize contentBoxSize = [oContentBox frame].size;
	NSRect windowFrame = [[self window] frame];

	CGFloat topAreaHeight = (NSHeight(windowFrame) - contentBoxSize.height);
	windowFrame.size.height = viewSize.height + topAreaHeight;
	windowFrame.size.width = viewSize.width;
	windowFrame.origin.y = NSMaxY([[self window] frame]) - (viewSize.height + topAreaHeight);
	windowFrame.origin.x = round(NSMidX([[self window] frame]) - (viewSize.width / 2.0));

	[[NSNotificationCenter defaultCenter] removeObserver:self
													name:NSViewFrameDidChangeNotification
												  object:[oContentBox contentView]];

	[oContentBox setContentView:nil];
	[[self window] setFrame:windowFrame display:YES animate:YES];

	//This eliminates the stutter on the Art Mode pane
	NSDisableScreenUpdates();
	{
		[oContentBox setContentView:pane];
		[[self window] display];
	}
	NSEnableScreenUpdates();

	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(contentViewFrameDidChange:)
												 name:NSViewFrameDidChangeNotification
											   object:[oContentBox contentView]];
}

- (void)setSelectedPane:(PreferencesPane *)pane
{
	[mSelectedPane paneWillBeRemovedFromWindow:[self window]];

	[self showPane:[pane view]];
	mSelectedPane = pane;

	[mSelectedPane paneWasAddedToWindow:[self window]];
}

- (PreferencesPane *)selectedPane
{
	return mSelectedPane;
}

- (IBAction)showPaneFrom:(NSToolbarItem *)sender
{
	PreferencesPane *pane = [mPreferencesPanes objectForKey:[sender itemIdentifier]];
	[self setSelectedPane:pane];
}

#pragma mark - Showing Specific Panes

- (void)showGeneralPane
{
	[[[self window] toolbar] setSelectedItemIdentifier:@"GeneralPane"];
	[self setSelectedPane:[mPreferencesPanes objectForKey:@"GeneralPane"]];
}

- (void)showArtModePane
{
	[[[self window] toolbar] setSelectedItemIdentifier:@"ArtModePane"];
	[self setSelectedPane:[mPreferencesPanes objectForKey:@"ArtModePane"]];
}

- (void)showPlayKeysPane
{
	[[[self window] toolbar] setSelectedItemIdentifier:@"HotKeysPane"];
	[self setSelectedPane:[mPreferencesPanes objectForKey:@"HotKeysPane"]];
}

- (void)showSocialPane
{
	[[[self window] toolbar] setSelectedItemIdentifier:@"SocialPane"];
	[self setSelectedPane:[mPreferencesPanes objectForKey:@"SocialPane"]];
}

@end


text:
<configuration>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%level %logger{15} - %message%n%xException{5}</pattern>
        </encoder>
    </appender>

    <logger name="akka" level="DEBUG" />
    <logger name="com.teambytes" level="DEBUG" />

    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>

</configuration>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>概览列表 (ExcelUtils)</title>
<meta name="date" content="2015-10-27">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

所有类

程序包

net.sf.excelutils

net.sf.excelutils.tags

net.sf.excelutils.webwork


text:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activities.categories.CategoriesActivity">

    <include layout="@layout/toolbar_layout" />

    <androidx.core.widget.NestedScrollView
        android:id="@+id/main_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <LinearLayout
            android:id="@+id/layout_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:animateLayoutChanges="true"
            android:orientation="vertical"
            android:padding="16dp"
            android:visibility="gone">

            <TextView
                style="@style/Label"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/label_category_name" />

            <EditText
                android:id="@+id/input_category_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="4dp"
                android:hint="@string/placeholder_category_name"
                android:importantForAutofill="no"
                android:inputType="text"
                android:maxLines="1" />

            <ch.rmy.android.framework.ui.views.LabelledSpinner
                android:id="@+id/input_layout_type"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/label_category_layout_type" />

            <ch.rmy.android.framework.ui.views.LabelledSpinner
                android:id="@+id/input_background_type"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/label_category_background" />

            <TextView
                android:id="@+id/input_color"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="16dp"
                android:padding="8dp"
                android:paddingStart="12dp"
                android:paddingEnd="12dp"
                android:shadowColor="#aa000000"
                android:shadowDx="2"
                android:shadowDy="2"
                android:shadowRadius="5"
                android:textColor="#ffffff" />

            <ch.rmy.android.framework.ui.views.LabelledSpinner
                android:id="@+id/input_click_behavior"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/settings_click_behavior" />

        </LinearLayout>

    </androidx.core.widget.NestedScrollView>

    <include
        android:id="@+id/loading_indicator"
        layout="@layout/loading_indicator"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MongoRepositoryTests.Entities;
using Should;
using Xbehave;

namespace MongoRepository.Tests
{
    public class RepositoryTests
    {
        [Scenario]
        public void SomeStrangeTest()
        {
        }

        [Scenario]
        public void AddAndUpdateTest(IRepository<Customer> customers,
                                     IRepositoryManager<Customer> customersManager,
                                     Customer customer,
                                     Customer fetchedCustomer,
                                     Customer updatedCustomer)
        {
            "Given a clean test database, a new MongoRepository, and a MongoRepositoryManager".
                f(() =>
                {
                    MongoTestUtils.DropDb();
                    customers = new MongoRepository<Customer>();
                    customersManager = new MongoRepositoryManager<Customer>();
                });
            "Then the repository should not initially exist".
                f((() =>
                {
                    customersManager.Exists.ShouldBeFalse();
                }));

            "When inserting a new customer from Alaska".
                f((async () =>
                {
                    customer = new Customer
                    {
                        FirstName = "Bob",
                        LastName = "Dillon",
                        Phone = "0900999899",
                        Email = "Bob.dil@snailmail.com",
                        HomeAddress = new Address
                        {
                            Address1 = "North kingdom 15 west",
                            Address2 = "1 north way",
                            PostCode = "40990",
                            City = "George Town",
                            Country = "Alaska"
                        }
                    };
                    await customers.AddAsync(customer);
                }));
            "Then the repository should start to exist".
                f((() => customersManager.Exists.ShouldBeTrue()));
            "Then the customer should be given a new ID".
                f((() => customer.Id.ShouldNotBeNull()));
            "Then a customer from Alaska should exist in the repository".
                f(async () => (await customers.ExistsAsync(c => c.HomeAddress.Country == "Alaska")).ShouldBeTrue());

            "When the customer is fetched back from the repository".
                f(() => fetchedCustomer = customers.Single(c => c.FirstName == "Bob"));
            "Then it should have been retrieved".
                f(() => fetchedCustomer.ShouldNotBeNull());
            "Then its properties should match".
                f(() =>
                {
                    fetchedCustomer.Id.ShouldEqual(customer.Id);
                    fetchedCustomer.FirstName.ShouldEqual(customer.FirstName);
                    fetchedCustomer.LastName.ShouldEqual(customer.LastName);
                    fetchedCustomer.Phone.ShouldEqual(customer.Phone);
                    fetchedCustomer.Email.ShouldEqual(customer.Email);
                    fetchedCustomer.HomeAddress.Address1.ShouldEqual(customer.HomeAddress.Address1);
                    fetchedCustomer.HomeAddress.Address2.ShouldEqual(customer.HomeAddress.Address2);
                    fetchedCustomer.HomeAddress.PostCode.ShouldEqual(customer.HomeAddress.PostCode);
                    fetchedCustomer.HomeAddress.City.ShouldEqual(customer.HomeAddress.City);
                    fetchedCustomer.HomeAddress.Country.ShouldEqual(customer.HomeAddress.Country);
                });

            "When updating properties of the fetched customer".
                f(async () =>
                {
                    fetchedCustomer.Phone = "10110111";
                    fetchedCustomer.Email = "dil.bob@fastmail.org";
                    await customers.UpdateAsync(fetchedCustomer);
                });
            "When retrieving the customer again".
                f(async () => updatedCustomer = await customers.GetByIdAsync(customer.Id));
            "Then those properties should have been updated in the repository".
                f(() =>
                {
                    updatedCustomer.ShouldNotBeNull();
                    updatedCustomer.Phone.ShouldEqual(fetchedCustomer.Phone);
                    updatedCustomer.Email.ShouldEqual(fetchedCustomer.Email);
                });
            MongoTestUtils.DropDb();
        }

        [Scenario]
        public async Task ComplexEntityTest()
        {
            MongoTestUtils.DropDb();
            IRepository<Customer> customerRepo = new MongoRepository<Customer>();
            IRepository<Product> productRepo = new MongoRepository<Product>();

            var customer = new Customer
            {
                FirstName = "Erik",
                LastName = "Swaun",
                Phone = "123 99 8767",
                Email = "erick@mail.com",
                HomeAddress = new Address
                {
                    Address1 = "Main bulevard",
                    Address2 = "1 west way",
                    PostCode = "89560",
                    City = "Tempare",
                    Country = "Arizona"
                }
            };

            var order = new Order {PurchaseDate = DateTime.Now.AddDays(-2)};
            var shampoo = await productRepo.AddAsync(new Product {Name = "Palmolive Shampoo", Price = 5});
            var paste = await productRepo.AddAsync(new Product {Name = "Mcleans Paste", Price = 4});
            order.Items = new[]
            {
                new OrderItem {Product = shampoo, Quantity = 1},
                new OrderItem {Product = paste, Quantity = 2}
            };

            customer.Orders = new[]
            {
                order
            };

            await customerRepo.AddAsync(customer);

            customer.Id.ShouldNotBeNull();
            customer.Orders[0].Items[0].Product.Id.ShouldNotBeNull();

            // get the orders
            var theOrders = customerRepo.Where(c => c.Id == customer.Id).Select(c => c.Orders).ToList();
            var theOrderItems = theOrders[0].Select(o => o.Items);

            theOrders.ShouldNotBeNull();
            theOrderItems.ShouldNotBeNull();

            MongoTestUtils.DropDb();
        }

        [Scenario]
        public async Task BatchTest()
        {
            MongoTestUtils.DropDb();

            IRepository<Customer> customerRepo = new MongoRepository<Customer>();
            var custlist = new List<Customer>(new[]
            {
                new Customer {FirstName = "Customer A"},
                new Customer {FirstName = "Client B"},
                new Customer {FirstName = "Customer C"},
                new Customer {FirstName = "Client D"},
                new Customer {FirstName = "Customer E"},
                new Customer {FirstName = "Client F"},
                new Customer {FirstName = "Customer G"}
            });

            //Insert batch
            await customerRepo.AddManyAsync(custlist);

            var count = await customerRepo.CountAsync();
            count.ShouldEqual(7);
            string notExpectedValue = new string('0', 24);
            foreach (Customer c in custlist)
                c.Id.ShouldNotEqual(notExpectedValue);

            //Update batch
            foreach (Customer c in custlist)
                c.LastName = c.FirstName;
            await customerRepo.UpdateAsync(custlist);

            foreach (Customer c in customerRepo)
                c.FirstName.ShouldEqual(c.LastName);

            //Delete by criteria
            await customerRepo.DeleteAsync(f => f.FirstName.StartsWith("Client"));

            count = await customerRepo.CountAsync();
            count.ShouldEqual(4);

            //Delete specific object
            await customerRepo.DeleteAsync(custlist[0]);

            //Test AsQueryable
            var selectedcustomers = from cust in customerRepo
                                    where cust.LastName.EndsWith("C") || cust.LastName.EndsWith("G")
                                    select cust;

            selectedcustomers.ToList().Count.ShouldEqual(2);

            count = await customerRepo.CountAsync();
            count.ShouldEqual(3);

            //Drop entire repo
            await new MongoRepositoryManager<Customer>().DropAsync();

            count = await customerRepo.CountAsync();
            count.ShouldEqual(0);

            MongoTestUtils.DropDb();
        }

        [Scenario]
        public async Task CollectionNamesTest()
        {
            MongoTestUtils.DropDb();

            var a = new MongoRepository<Animal>();
            var am = new MongoRepositoryManager<Animal>();
            var va = new Dog();
            am.Exists.ShouldBeFalse();
            await a.UpdateAsync(va);
            am.Exists.ShouldBeTrue();
            var animal = await a.GetByIdAsync(va.Id);
            animal.ShouldBeType<Dog>();
            am.Name.ShouldEqual("AnimalsTest");
            a.RepositoryName.ShouldEqual("AnimalsTest");

            var cl = new MongoRepository<CatLike>();
            var clm = new MongoRepositoryManager<CatLike>();
            var vcl = new Lion();
            clm.Exists.ShouldBeFalse();
            await cl.UpdateAsync(vcl);
            clm.Exists.ShouldBeTrue();
            var catLike = await cl.GetByIdAsync(vcl.Id);
            catLike.ShouldBeType<Lion>();
            clm.Name.ShouldEqual("Catlikes");
            cl.RepositoryName.ShouldEqual("Catlikes");

            var b = new MongoRepository<Bird>();
            var bm = new MongoRepositoryManager<Bird>();
            var vb = new Bird();
            bm.Exists.ShouldBeFalse();
            await b.UpdateAsync(vb);
            bm.Exists.ShouldBeTrue();
            var bird = await b.GetByIdAsync(vb.Id);
            bird.ShouldBeType<Bird>();
            bm.Name.ShouldEqual("Birds");
            b.RepositoryName.ShouldEqual("Birds");

            var l = new MongoRepository<Lion>();
            var lm = new MongoRepositoryManager<Lion>();
            var vl = new Lion();

            //Assert.IsFalse(lm.Exists);   //Should already exist (created by cl)
            await l.UpdateAsync(vl);
            lm.Exists.ShouldBeTrue();
            var lion = await l.GetByIdAsync(vl.Id);
            lion.ShouldBeType<Lion>();
            lm.Name.ShouldEqual("Catlikes");
            l.RepositoryName.ShouldEqual("Catlikes");

            var d = new MongoRepository<Dog>();
            var dm = new MongoRepositoryManager<Dog>();
            var vd = new Dog();

            //Assert.IsFalse(dm.Exists);
            await d.UpdateAsync(vd);
            dm.Exists.ShouldBeTrue();
            var dog = await d.GetByIdAsync(vd.Id);
            dog.ShouldBeType<Dog>();
            dm.Name.ShouldEqual("AnimalsTest");
            d.RepositoryName.ShouldEqual("AnimalsTest");

            var m = new MongoRepository<Bird>();
            var mm = new MongoRepositoryManager<Bird>();
            var vm = new Macaw();

            //Assert.IsFalse(mm.Exists);
            await m.UpdateAsync(vm);
            mm.Exists.ShouldBeTrue();
            var macaw = await m.GetByIdAsync(vm.Id);
            macaw.ShouldBeType<Macaw>();
            mm.Name.ShouldEqual("Birds");
            m.RepositoryName.ShouldEqual("Birds");

            var w = new MongoRepository<Whale>();
            var wm = new MongoRepositoryManager<Whale>();
            var vw = new Whale();
            wm.Exists.ShouldBeFalse();
            await w.UpdateAsync(vw);
            wm.Exists.ShouldBeTrue();
            var whale = await w.GetByIdAsync(vw.Id);
            whale.ShouldBeType<Whale>();
            wm.Name.ShouldEqual("Whale");
            w.RepositoryName.ShouldEqual("Whale");

            MongoTestUtils.DropDb();
        }

        [Scenario]
        public async Task CustomIdTest()
        {
            MongoTestUtils.DropDb();

            var x = new MongoRepository<CustomIDEntity>();
            var xm = new MongoRepositoryManager<CustomIDEntity>();

            await x.AddAsync(new CustomIDEntity {Id = "aaa"});

            xm.Exists.ShouldBeTrue();
            var aaa = await x.GetByIdAsync("aaa");
            aaa.ShouldBeType<CustomIDEntity>();
            aaa.Id.ShouldEqual("aaa");

            await x.DeleteAsync("aaa");
            0L.ShouldEqual(await x.CountAsync());

            var y = new MongoRepository<CustomIDEntityCustomCollection>();
            var ym = new MongoRepositoryManager<CustomIDEntityCustomCollection>();

            await y.AddAsync(new CustomIDEntityCustomCollection {Id = "xyz"});

            ym.Exists.ShouldBeTrue();
            ym.Name.ShouldEqual("MyTestCollection");
            y.RepositoryName.ShouldEqual("MyTestCollection");
            var xyz = await y.GetByIdAsync("xyz");
            xyz.ShouldBeType<CustomIDEntityCustomCollection>();

            await y.DeleteAsync("xyz");
            0L.ShouldEqual(await y.CountAsync());

            MongoTestUtils.DropDb();
        }

        [Scenario]
        public async Task CustomIdTypeTest()
        {
            MongoTestUtils.DropDb();

            var xint = new MongoRepository<IntCustomer, int>();
            await xint.AddAsync(new IntCustomer {Id = 1, Name = "Test A"});
            await xint.AddAsync(new IntCustomer {Id = 2, Name = "Test B"});

            var yint = await xint.GetByIdAsync(2);
            yint.Name.ShouldEqual("Test B");

            await xint.DeleteAsync(2);
            1L.ShouldEqual(await xint.CountAsync());

            MongoTestUtils.DropDb();
        }

        [Scenario]
        public async Task OverrideCollectionName()
        {
            MongoTestUtils.DropDb();

            IRepository<Customer> customerRepo =
                new MongoRepository<Customer>("mongodb://localhost/MongoRepositoryTests", "TestCustomers123");
            await customerRepo.AddAsync(new Customer {FirstName = "Test"});
            customerRepo.Single().FirstName.ShouldEqual("Test");
            customerRepo.RepositoryName.ShouldEqual("TestCustomers123");

            IRepositoryManager<Customer> customerRepoManager =
                new MongoRepositoryManager<Customer>("mongodb://localhost/MongoRepositoryTests", "TestCustomers123");
            customerRepoManager.Name.ShouldEqual("TestCustomers123");

            MongoTestUtils.DropDb();
        }

        #region Reproduce issue: https://mongorepository.codeplex.com/discussions/433878

        public abstract class BaseItem : IEntity
        {
            public string Id { get; set; }
        }

        public abstract class BaseA : BaseItem
        {
        }

        public class SpecialA : BaseA
        {
        }

        [Scenario]
        public void Discussion433878()
        {
            MongoTestUtils.DropDb();

            var specialRepository = new MongoRepository<SpecialA>();
            specialRepository.ShouldNotBeNull();

            MongoTestUtils.DropDb();
        }

        #endregion

        #region Reproduce issue: https://mongorepository.codeplex.com/discussions/572382

        public abstract class ClassA : Entity
        {
            public string Prop1 { get; set; }
        }

        public class ClassB : ClassA
        {
            public string Prop2 { get; set; }
        }

        public class ClassC : ClassA
        {
            public string Prop3 { get; set; }
        }

        [Scenario]
        public async Task Discussion572382()
        {
            MongoTestUtils.DropDb();

            var repo = new MongoRepository<ClassA>
            {
                new ClassB {Prop1 = "A", Prop2 = "B"},
                new ClassC {Prop1 = "A", Prop3 = "C"}
            };

            long count = await repo.CountAsync();
            count.ShouldEqual(2);

            repo.OfType<ClassA>().Count().ShouldEqual(2);
            repo.OfType<ClassB>().Count().ShouldEqual(1);
            repo.OfType<ClassC>().Count().ShouldEqual(1);

            MongoTestUtils.DropDb();
        }

        #endregion
    }
}


text:
package org.apache.maven.repository.internal;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.apache.maven.model.DependencyManagement;
import org.apache.maven.model.DistributionManagement;
import org.apache.maven.model.License;
import org.apache.maven.model.Model;
import org.apache.maven.model.Prerequisites;
import org.apache.maven.model.Relocation;
import org.apache.maven.model.Repository;
import org.apache.maven.model.building.DefaultModelBuilderFactory;
import org.apache.maven.model.building.DefaultModelBuildingRequest;
import org.apache.maven.model.building.FileModelSource;
import org.apache.maven.model.building.ModelBuilder;
import org.apache.maven.model.building.ModelBuildingException;
import org.apache.maven.model.building.ModelBuildingRequest;
import org.apache.maven.model.building.ModelProblem;
import org.apache.maven.model.resolution.UnresolvableModelException;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.sonatype.aether.RepositoryEvent.EventType;
import org.sonatype.aether.RepositoryException;
import org.sonatype.aether.RepositorySystemSession;
import org.sonatype.aether.RequestTrace;
import org.sonatype.aether.artifact.Artifact;
import org.sonatype.aether.artifact.ArtifactType;
import org.sonatype.aether.artifact.ArtifactTypeRegistry;
import org.sonatype.aether.graph.Dependency;
import org.sonatype.aether.graph.Exclusion;
import org.sonatype.aether.impl.ArtifactDescriptorReader;
import org.sonatype.aether.impl.ArtifactResolver;
import org.sonatype.aether.impl.RemoteRepositoryManager;
import org.sonatype.aether.impl.RepositoryEventDispatcher;
import org.sonatype.aether.impl.VersionResolver;
import org.sonatype.aether.transfer.ArtifactNotFoundException;
import org.sonatype.aether.util.DefaultRequestTrace;
import org.sonatype.aether.util.artifact.ArtifactProperties;
import org.sonatype.aether.util.artifact.DefaultArtifact;
import org.sonatype.aether.util.artifact.DefaultArtifactType;
import org.sonatype.aether.util.listener.DefaultRepositoryEvent;
import org.sonatype.aether.repository.WorkspaceRepository;
import org.sonatype.aether.resolution.ArtifactDescriptorException;
import org.sonatype.aether.resolution.ArtifactDescriptorRequest;
import org.sonatype.aether.resolution.ArtifactDescriptorResult;
import org.sonatype.aether.resolution.ArtifactRequest;
import org.sonatype.aether.resolution.ArtifactResolutionException;
import org.sonatype.aether.resolution.ArtifactResult;
import org.sonatype.aether.resolution.VersionRequest;
import org.sonatype.aether.resolution.VersionResolutionException;
import org.sonatype.aether.resolution.VersionResult;
import org.sonatype.aether.spi.locator.Service;
import org.sonatype.aether.spi.locator.ServiceLocator;
import org.sonatype.aether.spi.log.Logger;
import org.sonatype.aether.spi.log.NullLogger;

/**
 * @author Benjamin Bentmann
 */
@Component( role = ArtifactDescriptorReader.class )
public class DefaultArtifactDescriptorReader
    implements ArtifactDescriptorReader, Service
{

    @SuppressWarnings( "unused" )
    @Requirement
    private Logger logger = NullLogger.INSTANCE;

    @Requirement
    private RemoteRepositoryManager remoteRepositoryManager;

    @Requirement
    private VersionResolver versionResolver;

    @Requirement
    private ArtifactResolver artifactResolver;

    @Requirement
    private RepositoryEventDispatcher repositoryEventDispatcher;

    @Requirement
    private ModelBuilder modelBuilder;

    public void initService( ServiceLocator locator )
    {
        setLogger( locator.getService( Logger.class ) );
        setRemoteRepositoryManager( locator.getService( RemoteRepositoryManager.class ) );
        setVersionResolver( locator.getService( VersionResolver.class ) );
        setArtifactResolver( locator.getService( ArtifactResolver.class ) );
        setRepositoryEventDispatcher( locator.getService( RepositoryEventDispatcher.class ) );
        modelBuilder = locator.getService( ModelBuilder.class );
        if ( modelBuilder == null )
        {
            setModelBuilder( new DefaultModelBuilderFactory().newInstance() );
        }
    }

    public DefaultArtifactDescriptorReader setLogger( Logger logger )
    {
        this.logger = ( logger != null ) ? logger : NullLogger.INSTANCE;
        return this;
    }

    public DefaultArtifactDescriptorReader setRemoteRepositoryManager( RemoteRepositoryManager remoteRepositoryManager )
    {
        if ( remoteRepositoryManager == null )
        {
            throw new IllegalArgumentException( "remote repository manager has not been specified" );
        }
        this.remoteRepositoryManager = remoteRepositoryManager;
        return this;
    }

    public DefaultArtifactDescriptorReader setVersionResolver( VersionResolver versionResolver )
    {
        if ( versionResolver == null )
        {
            throw new IllegalArgumentException( "version resolver has not been specified" );
        }
        this.versionResolver = versionResolver;
        return this;
    }

    public DefaultArtifactDescriptorReader setArtifactResolver( ArtifactResolver artifactResolver )
    {
        if ( artifactResolver == null )
        {
            throw new IllegalArgumentException( "artifact resolver has not been specified" );
        }
        this.artifactResolver = artifactResolver;
        return this;
    }

    public DefaultArtifactDescriptorReader setRepositoryEventDispatcher( RepositoryEventDispatcher repositoryEventDispatcher )
    {
        if ( repositoryEventDispatcher == null )
        {
            throw new IllegalArgumentException( "repository event dispatcher has not been specified" );
        }
        this.repositoryEventDispatcher = repositoryEventDispatcher;
        return this;
    }

    public DefaultArtifactDescriptorReader setModelBuilder( ModelBuilder modelBuilder )
    {
        if ( modelBuilder == null )
        {
            throw new IllegalArgumentException( "model builder has not been specified" );
        }
        this.modelBuilder = modelBuilder;
        return this;
    }

    public ArtifactDescriptorResult readArtifactDescriptor( RepositorySystemSession session,
                                                            ArtifactDescriptorRequest request )
        throws ArtifactDescriptorException
    {
        ArtifactDescriptorResult result = new ArtifactDescriptorResult( request );

        Model model = loadPom( session, request, result );

        if ( model != null )
        {
            ArtifactTypeRegistry stereotypes = session.getArtifactTypeRegistry();

            for ( Repository r : model.getRepositories() )
            {
                result.addRepository( ArtifactDescriptorUtils.toRemoteRepository( r ) );
            }

            for ( org.apache.maven.model.Dependency dependency : model.getDependencies() )
            {
                result.addDependency( convert( dependency, stereotypes ) );
            }

            DependencyManagement mngt = model.getDependencyManagement();
            if ( mngt != null )
            {
                for ( org.apache.maven.model.Dependency dependency : mngt.getDependencies() )
                {
                    result.addManagedDependency( convert( dependency, stereotypes ) );
                }
            }

            Map<String, Object> properties = new LinkedHashMap<String, Object>();

            Prerequisites prerequisites = model.getPrerequisites();
            if ( prerequisites != null )
            {
                properties.put( "prerequisites.maven", prerequisites.getMaven() );
            }

            List<License> licenses = model.getLicenses();
            properties.put( "license.count", Integer.valueOf( licenses.size() ) );
            for ( int i = 0; i < licenses.size(); i++ )
            {
                License license = licenses.get( i );
                properties.put( "license." + i + ".name", license.getName() );
                properties.put( "license." + i + ".url", license.getUrl() );
                properties.put( "license." + i + ".comments", license.getComments() );
                properties.put( "license." + i + ".distribution", license.getDistribution() );
            }

            result.setProperties( properties );
        }

        return result;
    }

    private Model loadPom( RepositorySystemSession session, ArtifactDescriptorRequest request,
                           ArtifactDescriptorResult result )
        throws ArtifactDescriptorException
    {
        RequestTrace trace = DefaultRequestTrace.newChild( request.getTrace(), request );

        Set<String> visited = new LinkedHashSet<String>();
        for ( Artifact artifact = request.getArtifact();; )
        {
            try
            {
                VersionRequest versionRequest =
                    new VersionRequest( artifact, request.getRepositories(), request.getRequestContext() );
                versionRequest.setTrace( trace );
                VersionResult versionResult = versionResolver.resolveVersion( session, versionRequest );

                artifact = artifact.setVersion( versionResult.getVersion() );
            }
            catch ( VersionResolutionException e )
            {
                result.addException( e );
                throw new ArtifactDescriptorException( result );
            }

            if ( !visited.add( artifact.getGroupId() + ':' + artifact.getArtifactId() + ':' + artifact.getBaseVersion() ) )
            {
                RepositoryException exception =
                    new RepositoryException( "Artifact relocations form a cycle: " + visited );
                invalidDescriptor( session, trace, artifact, exception );
                if ( session.isIgnoreInvalidArtifactDescriptor() )
                {
                    return null;
                }
                result.addException( exception );
                throw new ArtifactDescriptorException( result );
            }

            Artifact pomArtifact = ArtifactDescriptorUtils.toPomArtifact( artifact );

            ArtifactResult resolveResult;
            try
            {
                ArtifactRequest resolveRequest =
                    new ArtifactRequest( pomArtifact, request.getRepositories(), request.getRequestContext() );
                resolveRequest.setTrace( trace );
                resolveResult = artifactResolver.resolveArtifact( session, resolveRequest );
                pomArtifact = resolveResult.getArtifact();
                result.setRepository( resolveResult.getRepository() );
            }
            catch ( ArtifactResolutionException e )
            {
                if ( e.getCause() instanceof ArtifactNotFoundException )
                {
                    missingDescriptor( session, trace, artifact, (Exception) e.getCause() );
                    if ( session.isIgnoreMissingArtifactDescriptor() )
                    {
                        return null;
                    }
                }
                result.addException( e );
                throw new ArtifactDescriptorException( result );
            }

            Model model;
            try
            {
                ModelBuildingRequest modelRequest = new DefaultModelBuildingRequest();
                modelRequest.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL );
                modelRequest.setProcessPlugins( false );
                modelRequest.setTwoPhaseBuilding( false );
                modelRequest.setSystemProperties( toProperties( session.getUserProperties(),
                                                                session.getSystemProperties() ) );
                modelRequest.setModelCache( DefaultModelCache.newInstance( session ) );
                modelRequest.setModelResolver( new DefaultModelResolver( session, trace.newChild( modelRequest ),
                                                                         request.getRequestContext(), artifactResolver,
                                                                         remoteRepositoryManager,
                                                                         request.getRepositories() ) );
                if ( resolveResult.getRepository() instanceof WorkspaceRepository )
                {
                    modelRequest.setPomFile( pomArtifact.getFile() );
                }
                else
                {
                    modelRequest.setModelSource( new FileModelSource( pomArtifact.getFile() ) );
                }

                model = modelBuilder.build( modelRequest ).getEffectiveModel();
            }
            catch ( ModelBuildingException e )
            {
                for ( ModelProblem problem : e.getProblems() )
                {
                    if ( problem.getException() instanceof UnresolvableModelException )
                    {
                        result.addException( problem.getException() );
                        throw new ArtifactDescriptorException( result );
                    }
                }
                invalidDescriptor( session, trace, artifact, e );
                if ( session.isIgnoreInvalidArtifactDescriptor() )
                {
                    return null;
                }
                result.addException( e );
                throw new ArtifactDescriptorException( result );
            }

            Relocation relocation = getRelocation( model );

            if ( relocation != null )
            {
                result.addRelocation( artifact );
                artifact =
                    new RelocatedArtifact( artifact, relocation.getGroupId(), relocation.getArtifactId(),
                                           relocation.getVersion() );
                result.setArtifact( artifact );
            }
            else
            {
                return model;
            }
        }
    }

    private Properties toProperties( Map<String, String> dominant, Map<String, String> recessive )
    {
        Properties props = new Properties();
        if ( recessive != null )
        {
            props.putAll( recessive );
        }
        if ( dominant != null )
        {
            props.putAll( dominant );
        }
        return props;
    }

    private Relocation getRelocation( Model model )
    {
        Relocation relocation = null;
        DistributionManagement distMngt = model.getDistributionManagement();
        if ( distMngt != null )
        {
            relocation = distMngt.getRelocation();
        }
        return relocation;
    }

    private Dependency convert( org.apache.maven.model.Dependency dependency, ArtifactTypeRegistry stereotypes )
    {
        ArtifactType stereotype = stereotypes.get( dependency.getType() );
        if ( stereotype == null )
        {
            stereotype = new DefaultArtifactType( dependency.getType() );
        }

        boolean system = dependency.getSystemPath() != null && dependency.getSystemPath().length() > 0;

        Map<String, String> props = null;
        if ( system )
        {
            props = Collections.singletonMap( ArtifactProperties.LOCAL_PATH, dependency.getSystemPath() );
        }

        Artifact artifact =
            new DefaultArtifact( dependency.getGroupId(), dependency.getArtifactId(), dependency.getClassifier(), null,
                                 dependency.getVersion(), props, stereotype );

        List<Exclusion> exclusions = new ArrayList<Exclusion>( dependency.getExclusions().size() );
        for ( org.apache.maven.model.Exclusion exclusion : dependency.getExclusions() )
        {
            exclusions.add( convert( exclusion ) );
        }

        Dependency result = new Dependency( artifact, dependency.getScope(), dependency.isOptional(), exclusions );

        return result;
    }

    private Exclusion convert( org.apache.maven.model.Exclusion exclusion )
    {
        return new Exclusion( exclusion.getGroupId(), exclusion.getArtifactId(), "*", "*" );
    }

    private void missingDescriptor( RepositorySystemSession session, RequestTrace trace, Artifact artifact,
                                    Exception exception )
    {
        DefaultRepositoryEvent event =
            new DefaultRepositoryEvent( EventType.ARTIFACT_DESCRIPTOR_MISSING, session, trace );
        event.setArtifact( artifact );
        event.setException( exception );

        repositoryEventDispatcher.dispatch( event );
    }

    private void invalidDescriptor( RepositorySystemSession session, RequestTrace trace, Artifact artifact,
                                    Exception exception )
    {
        DefaultRepositoryEvent event =
            new DefaultRepositoryEvent( EventType.ARTIFACT_DESCRIPTOR_INVALID, session, trace );
        event.setArtifact( artifact );
        event.setException( exception );

        repositoryEventDispatcher.dispatch( event );
    }

}


text:
#ifndef NETWORKCODINGHEADER_H_
#define NETWORKCODINGHEADER_H_

#include <stddef.h>

#define OUTER_HEADER_SIZE                                              (sizeof(OuterHeader))
#define GET_OUTER_TYPE(pkt)                                             (((OuterHeader*)pkt)->type)
#define GET_OUTER_SIZE(pkt)                                             (((OuterHeader*)pkt)->size)
#define GET_OUTER_BLK_SEQ(pkt)                                     (((OuterHeader*)pkt)->blk_seq)
#define GET_OUTER_BLK_SIZE(pkt)                                     (((OuterHeader*)pkt)->blk_size)
#define GET_OUTER_MAX_BLK_SIZE(pkt)                           (((OuterHeader*)pkt)->max_blk_size)
#define GET_OUTER_FLAGS(pkt)                                         (((OuterHeader*)pkt)->flags)
#define GET_INNER_SIZE(pkt)                                              (((InnerHeader*)((unsigned char*)pkt + sizeof(OuterHeader)))->size)
#define GET_INNER_LAST_INDICATOR(pkt)                        (((InnerHeader*)((unsigned char*)pkt + sizeof(OuterHeader)))->last_indicator)
#define GET_INNER_CODE(pkt)                                           (((InnerHeader*)((unsigned char*)pkt + sizeof(OuterHeader)))->codes)
#define GET_INNER_PAYLOAD(pkt, max_block_size)         ((unsigned char*)pkt + sizeof(OuterHeader) + sizeof(InnerHeader) + (max_block_size-1))

#define ETHERNET_MTU                                                      (1500)
#define TOTAL_HEADER_SIZE(max_block_size)                  (sizeof(OuterHeader) + sizeof(InnerHeader) + (max_block_size-1))
#define MAX_PAYLOAD_SIZE(max_block_size)                  (ETHERNET_MTU - 20/*IP*/ - 8/*UDP*/ - TOTAL_HEADER_SIZE(max_block_size))
#define MAX_BUFFER_SIZE                                                  (ETHERNET_MTU - 20 - 8)

enum NC_PKT_TYPE : unsigned char{
    DATA_TYPE = 0,
    ACK_TYPE,
    REQ_CONNECT_TYPE,
    REP_CONNECT_TYPE
};

struct OuterHeader
{
    unsigned char type;
    unsigned short int size;          /*2*/
    unsigned short int blk_seq;    /*2*/
    unsigned char blk_size;          /*1*/
    unsigned char max_blk_size; /*1*/
    unsigned char flags;               /*1*/
    enum : unsigned char
    {
        FLAGS_ORIGINAL = 0x1,
        FLAGS_END_OF_BLK = 0x2
    };
}__attribute__((packed));

#define PRINT_OUTERHEADER(pkt)\
do\
{\
    printf("OUTERHDR [Size = %6hu][Block Seq = %6hu][Block Size = %3hhu][Flags = %hhx]\n", \
    ((OuterHeader*)pkt)->size, ((OuterHeader*)pkt)->blk_seq, ((OuterHeader*)pkt)->blk_size, ((OuterHeader*)pkt)->flags);\
}while(0)

struct InnerHeader
{
    unsigned short int size;          /*2*/
    unsigned char last_indicator;	/*1*/
    unsigned char codes[1];        /*blk_size*/
}__attribute__((packed));

#define PRINT_INNERHEADER(max_block_size, pkt)\
do\
{\
    printf("INNERHDR [Size = %6hu][Last Indicator = %2hhu][Code =", ((InnerHeader*)(pkt+sizeof(OuterHeader)))->size, ((InnerHeader*)(pkt+sizeof(OuterHeader)))->last_indicator);\
    for(unsigned char _tmp = 0 ; _tmp < max_block_size ; _tmp++)\
    {\
        printf(" %hhu", ((InnerHeader*)(pkt+sizeof(OuterHeader)))->codes[_tmp]);\
    }\
    printf("]\n");\
}while(0)

#define PRINT_CODE_BLOCK(max_block_size, buf)\
do\
{\
    printf("Code===\n");\
    for(unsigned char _tmp2 = 0 ; _tmp2 < max_block_size ; _tmp2++)\
    {\
        for(unsigned char _tmp3 = 0 ; _tmp3 < max_block_size ; _tmp3++)\
        {\
            printf("%4hhu", GET_INNER_CODE(buf[_tmp2].buffer)[_tmp3]);\
        }\
        printf("\n");\
    }\
}while(0)

struct Ack
{
    unsigned char type;
    unsigned short int blk_seq;    /*2*/
    unsigned char losses;             /*1*/
}__attribute__((packed));

struct Connect
{
    unsigned char type;
}__attribute__((packed));

enum BLOCK_SIZE: unsigned char
{
    SIZE2 = 0x1<<1,
    SIZE4 = 0x1<<2,
    SIZE8 = 0x1<<3,
    SIZE16 = 0x1<<4
};

struct NetworkCodingPktBuffer
{
    unsigned char buffer[MAX_BUFFER_SIZE];
};

// Key of tx_session_info for avltree
struct ip_port_key{
    unsigned int ip;
    unsigned short port;
}__attribute__((packed));
#endif


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<title>ADO Examples- Select</title>
<link rel="stylesheet" type="text/css" href="../../style.css" />

static void

Main >

.Net >

IO

Xml

Xml Patterns

ADO.Net

ADO Patterns

SQL

Linq2Sql

Entity Framework

WCF Data Services

ADO Examples- Select

ADO notes

ASP DataBinding notes

DataReader

private static List<Product> LoadViaDataReader(int catgeory)

 {

     List<Product> list = new List<Product>();

     string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

     using (SqlConnection conn = new SqlConnection(connectionString))

     {

         conn.Open();

         string sql = @"SELECT Id, Name, Price, AvailableFrom FROM Product WHERE Category_Id = @CATEGORY";

         using (SqlCommand cmd = new SqlCommand(sql, conn))

         {

             cmd.Parameters.AddWithValue("@CATEGORY", catgeory);

             using (SqlDataReader rdr = cmd.ExecuteReader())

             {

                 if (rdr.HasRows)

                 {

                     while (rdr.Read())

                         list.Add(CreateProduct(rdr));

                     //you could set DataSource = rdr directly

                     //rdr.NextResult(); //for multi-results

                 }

             }

         }

     }

     return list;

 }

 private static Product CreateProduct(IDataRecord rdr)

 {

     int id = rdr.GetInt32(0);

     string name = rdr["Name"].ToString();

     decimal price = rdr.GetDecimal(2);

     DateTime? date = null;

     if (!rdr.IsDBNull(3)) date = rdr.GetDateTime(3);

     //or... if (rdr["AvailableFrom"] != DBNull.Value) date = rdr["AvailableFrom"];

     //create the object

     Product p = new Product(id, name);

     p.AvailableFrom = date;

     p.Price = price;

     return p;

 }

DataAdaptor/DataTable

private DataTable LoadViaDataTable(int catgeory)

{

    string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

    using (SqlConnection conn = new SqlConnection(connectionString))

    {

        //no need to explicitly open/close connection unless doing several fills

        string sql = @"SELECT Id, Name, Price, AvailableFrom FROM Product WHERE Category_Id = @CATEGORY";

        using (SqlCommand cmd = new SqlCommand(sql, conn))

        {

            cmd.Parameters.AddWithValue("@CATEGORY", catgeory);

            DataTable dt = InitDataTable();

            using (SqlDataAdapter da = new SqlDataAdapter(cmd))

            {

                //da.SelectCommand = cmd

                da.Fill(dt);

            }

            return dt;

        }

    }

}

private static DataTable InitDataTable()

{

    DataTable dt = new DataTable("Product");

    dt.Columns.Add("Id", typeof(int));

    dt.Columns.Add("Name", typeof(string));

    dt.Columns.Add("Price", typeof(decimal));

    dt.Columns.Add("AvailableFrom", typeof(DateTime));

    return dt;

}

SqlDataSource (Asp2)

Programmatic use- normally you bind directly.

private void UseSqlDataSourceProgrammatically(int category)

{

    //you could also handle the OnSelecting event to set parameters (which have to be strings)

    SqlDataSource1.SelectParameters[0].DefaultValue = category.ToString();

    //SqlDataSource.Select returns DataView if DataSourceMode=DataSet otherwise a IDataReader

    DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);

    GridView1.DataSource = dv;

    GridView1.DataBind();

}

Binding To An Asp GridView

Code behind (use any of the methods above):

GridView1.DataSource = LoadViaDataReader(1);

GridView1.DataBind();

Markup:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Id">

    <Columns>

    <asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True" SortExpression="Id" />

    <asp:BoundField DataField="Name" HeaderText="Name" />

    <asp:BoundField DataField="Price" HeaderText="Price" DataFormatString="{0:C}" HtmlEncode="false" />

    <asp:BoundField DataField="AvailableFrom" HeaderText="AvailableFrom" DataFormatString="{0:D}" HtmlEncode="false" />

    </Columns>

</asp:GridView>


text:
package com.mercury.platform.ui.adr.validator;

import lombok.Getter;

public abstract class FieldValidator<F, T> {
    @Getter
    protected T value;

    public abstract boolean validate(F value);
}


text:
package google

import (
	"fmt"
	"testing"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

func TestAccDataCatalogTagTemplateIamBindingGenerated(t *testing.T) {
	t.Parallel()

	context := map[string]interface{}{
		"random_suffix": randString(t, 10),
		"role":          "roles/viewer",
		"force_delete":  true,
	}

	vcrTest(t, resource.TestCase{
		PreCheck:  func() { testAccPreCheck(t) },
		Providers: testAccProviders,
		Steps: []resource.TestStep{
			{
				Config: testAccDataCatalogTagTemplateIamBinding_basicGenerated(context),
			},
			{
				ResourceName:      "google_data_catalog_tag_template_iam_binding.foo",
				ImportStateId:     fmt.Sprintf("projects/%s/locations/%s/tagTemplates/%s roles/viewer", getTestProjectFromEnv(), getTestRegionFromEnv(), fmt.Sprintf("tf_test_my_template%s", context["random_suffix"])),
				ImportState:       true,
				ImportStateVerify: true,
			},
			{
				// Test Iam Binding update
				Config: testAccDataCatalogTagTemplateIamBinding_updateGenerated(context),
			},
			{
				ResourceName:      "google_data_catalog_tag_template_iam_binding.foo",
				ImportStateId:     fmt.Sprintf("projects/%s/locations/%s/tagTemplates/%s roles/viewer", getTestProjectFromEnv(), getTestRegionFromEnv(), fmt.Sprintf("tf_test_my_template%s", context["random_suffix"])),
				ImportState:       true,
				ImportStateVerify: true,
			},
		},
	})
}

func TestAccDataCatalogTagTemplateIamMemberGenerated(t *testing.T) {
	t.Parallel()

	context := map[string]interface{}{
		"random_suffix": randString(t, 10),
		"role":          "roles/viewer",
		"force_delete":  true,
	}

	vcrTest(t, resource.TestCase{
		PreCheck:  func() { testAccPreCheck(t) },
		Providers: testAccProviders,
		Steps: []resource.TestStep{
			{
				// Test Iam Member creation (no update for member, no need to test)
				Config: testAccDataCatalogTagTemplateIamMember_basicGenerated(context),
			},
			{
				ResourceName:      "google_data_catalog_tag_template_iam_member.foo",
				ImportStateId:     fmt.Sprintf("projects/%s/locations/%s/tagTemplates/%s roles/viewer user:admin@hashicorptest.com", getTestProjectFromEnv(), getTestRegionFromEnv(), fmt.Sprintf("tf_test_my_template%s", context["random_suffix"])),
				ImportState:       true,
				ImportStateVerify: true,
			},
		},
	})
}

func TestAccDataCatalogTagTemplateIamPolicyGenerated(t *testing.T) {
	t.Parallel()

	context := map[string]interface{}{
		"random_suffix": randString(t, 10),
		"role":          "roles/viewer",
		"force_delete":  true,
	}

	vcrTest(t, resource.TestCase{
		PreCheck:  func() { testAccPreCheck(t) },
		Providers: testAccProviders,
		Steps: []resource.TestStep{
			{
				Config: testAccDataCatalogTagTemplateIamPolicy_basicGenerated(context),
			},
			{
				ResourceName:      "google_data_catalog_tag_template_iam_policy.foo",
				ImportStateId:     fmt.Sprintf("projects/%s/locations/%s/tagTemplates/%s", getTestProjectFromEnv(), getTestRegionFromEnv(), fmt.Sprintf("tf_test_my_template%s", context["random_suffix"])),
				ImportState:       true,
				ImportStateVerify: true,
			},
			{
				Config: testAccDataCatalogTagTemplateIamPolicy_emptyBinding(context),
			},
			{
				ResourceName:      "google_data_catalog_tag_template_iam_policy.foo",
				ImportStateId:     fmt.Sprintf("projects/%s/locations/%s/tagTemplates/%s", getTestProjectFromEnv(), getTestRegionFromEnv(), fmt.Sprintf("tf_test_my_template%s", context["random_suffix"])),
				ImportState:       true,
				ImportStateVerify: true,
			},
		},
	})
}

func testAccDataCatalogTagTemplateIamMember_basicGenerated(context map[string]interface{}) string {
	return Nprintf(`
resource "google_data_catalog_tag_template" "basic_tag_template" {
  tag_template_id = "tf_test_my_template%{random_suffix}"
  region = "us-central1"
  display_name = "Demo Tag Template"

  fields {
    field_id = "source"
    display_name = "Source of data asset"
    type {
      primitive_type = "STRING"
    }
    is_required = true
  }

  fields {
    field_id = "num_rows"
    display_name = "Number of rows in the data asset"
    type {
      primitive_type = "DOUBLE"
    }
  }

  fields {
    field_id = "pii_type"
    display_name = "PII type"
    type {
      enum_type {
        allowed_values {
          display_name = "EMAIL"
        }
        allowed_values {
          display_name = "SOCIAL SECURITY NUMBER"
        }
        allowed_values {
          display_name = "NONE"
        }
      }
    }
  }

  force_delete = "%{force_delete}"
}

resource "google_data_catalog_tag_template_iam_member" "foo" {
  tag_template = google_data_catalog_tag_template.basic_tag_template.name
  role = "%{role}"
  member = "user:admin@hashicorptest.com"
}
`, context)
}

func testAccDataCatalogTagTemplateIamPolicy_basicGenerated(context map[string]interface{}) string {
	return Nprintf(`
resource "google_data_catalog_tag_template" "basic_tag_template" {
  tag_template_id = "tf_test_my_template%{random_suffix}"
  region = "us-central1"
  display_name = "Demo Tag Template"

  fields {
    field_id = "source"
    display_name = "Source of data asset"
    type {
      primitive_type = "STRING"
    }
    is_required = true
  }

  fields {
    field_id = "num_rows"
    display_name = "Number of rows in the data asset"
    type {
      primitive_type = "DOUBLE"
    }
  }

  fields {
    field_id = "pii_type"
    display_name = "PII type"
    type {
      enum_type {
        allowed_values {
          display_name = "EMAIL"
        }
        allowed_values {
          display_name = "SOCIAL SECURITY NUMBER"
        }
        allowed_values {
          display_name = "NONE"
        }
      }
    }
  }

  force_delete = "%{force_delete}"
}

data "google_iam_policy" "foo" {
  binding {
    role = "%{role}"
    members = ["user:admin@hashicorptest.com"]
  }
}

resource "google_data_catalog_tag_template_iam_policy" "foo" {
  tag_template = google_data_catalog_tag_template.basic_tag_template.name
  policy_data = data.google_iam_policy.foo.policy_data
}
`, context)
}

func testAccDataCatalogTagTemplateIamPolicy_emptyBinding(context map[string]interface{}) string {
	return Nprintf(`
resource "google_data_catalog_tag_template" "basic_tag_template" {
  tag_template_id = "tf_test_my_template%{random_suffix}"
  region = "us-central1"
  display_name = "Demo Tag Template"

  fields {
    field_id = "source"
    display_name = "Source of data asset"
    type {
      primitive_type = "STRING"
    }
    is_required = true
  }

  fields {
    field_id = "num_rows"
    display_name = "Number of rows in the data asset"
    type {
      primitive_type = "DOUBLE"
    }
  }

  fields {
    field_id = "pii_type"
    display_name = "PII type"
    type {
      enum_type {
        allowed_values {
          display_name = "EMAIL"
        }
        allowed_values {
          display_name = "SOCIAL SECURITY NUMBER"
        }
        allowed_values {
          display_name = "NONE"
        }
      }
    }
  }

  force_delete = "%{force_delete}"
}

data "google_iam_policy" "foo" {
}

resource "google_data_catalog_tag_template_iam_policy" "foo" {
  tag_template = google_data_catalog_tag_template.basic_tag_template.name
  policy_data = data.google_iam_policy.foo.policy_data
}
`, context)
}

func testAccDataCatalogTagTemplateIamBinding_basicGenerated(context map[string]interface{}) string {
	return Nprintf(`
resource "google_data_catalog_tag_template" "basic_tag_template" {
  tag_template_id = "tf_test_my_template%{random_suffix}"
  region = "us-central1"
  display_name = "Demo Tag Template"

  fields {
    field_id = "source"
    display_name = "Source of data asset"
    type {
      primitive_type = "STRING"
    }
    is_required = true
  }

  fields {
    field_id = "num_rows"
    display_name = "Number of rows in the data asset"
    type {
      primitive_type = "DOUBLE"
    }
  }

  fields {
    field_id = "pii_type"
    display_name = "PII type"
    type {
      enum_type {
        allowed_values {
          display_name = "EMAIL"
        }
        allowed_values {
          display_name = "SOCIAL SECURITY NUMBER"
        }
        allowed_values {
          display_name = "NONE"
        }
      }
    }
  }

  force_delete = "%{force_delete}"
}

resource "google_data_catalog_tag_template_iam_binding" "foo" {
  tag_template = google_data_catalog_tag_template.basic_tag_template.name
  role = "%{role}"
  members = ["user:admin@hashicorptest.com"]
}
`, context)
}

func testAccDataCatalogTagTemplateIamBinding_updateGenerated(context map[string]interface{}) string {
	return Nprintf(`
resource "google_data_catalog_tag_template" "basic_tag_template" {
  tag_template_id = "tf_test_my_template%{random_suffix}"
  region = "us-central1"
  display_name = "Demo Tag Template"

  fields {
    field_id = "source"
    display_name = "Source of data asset"
    type {
      primitive_type = "STRING"
    }
    is_required = true
  }

  fields {
    field_id = "num_rows"
    display_name = "Number of rows in the data asset"
    type {
      primitive_type = "DOUBLE"
    }
  }

  fields {
    field_id = "pii_type"
    display_name = "PII type"
    type {
      enum_type {
        allowed_values {
          display_name = "EMAIL"
        }
        allowed_values {
          display_name = "SOCIAL SECURITY NUMBER"
        }
        allowed_values {
          display_name = "NONE"
        }
      }
    }
  }

  force_delete = "%{force_delete}"
}

resource "google_data_catalog_tag_template_iam_binding" "foo" {
  tag_template = google_data_catalog_tag_template.basic_tag_template.name
  role = "%{role}"
  members = ["user:admin@hashicorptest.com", "user:gterraformtest1@gmail.com"]
}
`, context)
}


text:
memoizeMidWare = (midWare) => (req, res, next = ()=>{}) => {
  const fn = () => {
    const cache = req._memoized = req._memoized || new Map;
    if (cache.has(midWare)) return cache.get(midWare);

    // We convert next() to an async function so we can obtain the return value
    // of the middleware
    let oldNext = next;
    next = () => Meteor.setTimeout(oldNext, 0);

    const result = midWare(req, res, next);
    cache.set(midWare, result);
    return result;
  };

  const Fiber = Promise.Fiber;
  const fiber = Fiber && Fiber.current;
  if (fiber) return fn();
  else return Fiber(fn).run();
};


text:
<?php
class Kwc_Form_Field_Abstract_UseViewCachePlugin extends Kwf_Component_Plugin_Abstract
    implements Kwf_Component_Plugin_Interface_UseViewCache
{
    public function useViewCache($renderer)
    {
        // Checking for specific post-data because there could be more forms on
        // one page and only one gets submited
        $id = $this->_componentId;
        while (strrpos($id, '-') !== false) {
            if (strrpos($id, '_') > strrpos($id, '-')) {
                //new page
                break;
            }
            $id = substr($id, 0, strrpos($id, '-'));
            if (isset($_REQUEST[$id.'-post'])) {
                return false;
            }
        }
        return true;
    }
}


text:
package io.libraft.agent.persistence;

import com.google.common.collect.Sets;
import io.libraft.agent.TestLoggingRule;
import io.libraft.agent.UnitTestCommand;
import io.libraft.agent.UnitTestCommandDeserializer;
import io.libraft.agent.UnitTestCommandSerializer;
import io.libraft.algorithm.LogEntry;
import io.libraft.algorithm.StorageException;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;

public final class JDBCLogTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(JDBCLogTest.class);

    private final Random random = new Random();
    private final UnitTestCommandSerializer commandSerializer = new UnitTestCommandSerializer();
    private final UnitTestCommandDeserializer commandDeserializer = new UnitTestCommandDeserializer();

    private JDBCLog jdbcLog;

    @Rule
    public TestLoggingRule testLoggingRule = new TestLoggingRule(LOGGER);

    @Before
    public void setup() throws StorageException {
        jdbcLog = new JDBCLog("jdbc:h2:mem:", "test", null, commandSerializer, commandDeserializer);
        jdbcLog.initialize();
    }

    @Test
    public void shouldInsertAndRetrieveSentinel() throws StorageException {
        jdbcLog.put(LogEntry.SENTINEL);

        assertThat(jdbcLog.get(0), equalTo(LogEntry.SENTINEL));
    }

    @Test
    public void shouldInsertAndRetrieveNoopEntry() throws StorageException {
        long index = random.nextInt(100);
        long term = random.nextInt(100);
        LOGGER.info("index:{} term:{}", index, term);

        LogEntry logEntry = new LogEntry.NoopEntry(index, term);
        jdbcLog.put(logEntry);

        assertThat(jdbcLog.get(index), equalTo(logEntry));
    }

    @Test
    public void shouldInsertAndRetrieveConfigurationEntry() throws StorageException {
        long index = random.nextInt(100);
        long term = random.nextInt(100);
        LOGGER.info("index:{} term:{}", index, term);

        LogEntry logEntry = new LogEntry.ConfigurationEntry(index, term, Sets.<String>newHashSet(), Sets.<String>newHashSet());
        jdbcLog.put(logEntry);

        assertThat(jdbcLog.get(index), equalTo(logEntry));
    }

    @Test
    public void shouldInsertAndRetrieveClientEntry() throws StorageException {
        long index = random.nextInt(100);
        long term = random.nextInt(100);
        String data = "TEST_01";
        LOGGER.info("index:{} term:{} data:{}", index, term, data);

        LogEntry logEntry = new LogEntry.ClientEntry(index, term, new UnitTestCommand(data));
        jdbcLog.put(logEntry);

        assertThat(jdbcLog.get(index), equalTo(logEntry));
    }

    @Test
    public void shouldInsertAndRetrieveEntryEvenWhenUpdatedMultipleTimesV1() throws StorageException {
        long index = random.nextInt(100);
        long term = random.nextInt(100);
        LOGGER.info("index:{} term:{}", index, term);

        LogEntry lastInsertedEntry = new LogEntry.NoopEntry(index, term);

        // start by putting a client entry, and end off with a NOOP entry
        jdbcLog.put(new LogEntry.ClientEntry(index, term, new UnitTestCommand("TEST_01")));
        jdbcLog.put(new LogEntry.ConfigurationEntry(index, term, Sets.<String>newHashSet(), Sets.<String>newHashSet()));
        jdbcLog.put(new LogEntry.ClientEntry(index, term, new UnitTestCommand("TEST_02")));
        jdbcLog.put(lastInsertedEntry);

        assertThat(jdbcLog.get(index), equalTo(lastInsertedEntry));
    }

    @Test
    public void shouldInsertAndRetrieveEntryEvenWhenUpdatedMultipleTimesV2() throws StorageException {
        long index = random.nextInt(100);
        long term = random.nextInt(100);
        String data = "TEST_01";
        LOGGER.info("index:{} term:{} data:{}", index, term, data);

        LogEntry lastInsertedEntry = new LogEntry.ClientEntry(index, term, new UnitTestCommand("TEST_01"));

        // start off with a NOOP entry and end with a client entry
        jdbcLog.put(new LogEntry.NoopEntry(index, term));
        jdbcLog.put(new LogEntry.ConfigurationEntry(index, term, Sets.<String>newHashSet(), Sets.<String>newHashSet()));
        jdbcLog.put(new LogEntry.ClientEntry(index, term, new UnitTestCommand("TEST_02")));
        jdbcLog.put(lastInsertedEntry);

        assertThat(jdbcLog.get(index), equalTo(lastInsertedEntry));
    }

    @Test
    public void shouldReturnNullWhenGetFirstIsCalledOnEmptyTable() throws StorageException {
        assertThat(jdbcLog.getFirst(), nullValue());
    }

    @Test
    public void shouldReturnFirstValueWhenGetFirstIsCalled() throws StorageException {
        LogEntry firstEntry = new LogEntry.NoopEntry(1, 3);

        // notice that I've inserted the rows out of order
        jdbcLog.put(new LogEntry.ClientEntry(3, 3, new UnitTestCommand("LAST")));
        jdbcLog.put(firstEntry);
        jdbcLog.put(new LogEntry.ClientEntry(2, 3, new UnitTestCommand("SECOND_LAST")));

        assertThat(jdbcLog.getFirst(), equalTo(firstEntry));
    }

    @Test
    public void shouldReturnNullWhenGetLastIsCalledOnEmptyTable() throws StorageException {
        assertThat(jdbcLog.getLast(), nullValue());
    }

    @Test
    public void shouldReturnLastValueWhenGetLastIsCalled() throws StorageException {
        LogEntry lastEntry = new LogEntry.ClientEntry(3, 3, new UnitTestCommand("LAST"));

        // notice that I've inserted the rows out of order
        jdbcLog.put(new LogEntry.NoopEntry(1, 3));
        jdbcLog.put(lastEntry);
        jdbcLog.put(new LogEntry.ClientEntry(2, 3, new UnitTestCommand("SECOND_LAST")));

        assertThat(jdbcLog.getLast(), equalTo(lastEntry));
    }

    @Test
    public void shouldTruncateLogWhenIndexOfExistingEntryIsSpecified() throws StorageException {
        jdbcLog.put(LogEntry.SENTINEL);
        jdbcLog.put(new LogEntry.NoopEntry(1, 1));
        jdbcLog.put(new LogEntry.NoopEntry(2, 1));
        jdbcLog.put(new LogEntry.NoopEntry(3, 1)); // <--- expect this to be the last entry after truncation
        jdbcLog.put(new LogEntry.NoopEntry(7, 1));
        jdbcLog.put(new LogEntry.NoopEntry(8, 1));
        jdbcLog.put(new LogEntry.NoopEntry(9, 1));

        jdbcLog.truncate(7);

        assertThat(jdbcLog.getLast(), Matchers.<LogEntry>equalTo(new LogEntry.NoopEntry(3, 1)));
    }

    @Test
    public void shouldTruncateLogIfIndexNotEqualToExistingEntryIndexIsSpecified() throws StorageException {
        jdbcLog.put(LogEntry.SENTINEL);
        jdbcLog.put(new LogEntry.NoopEntry(1, 1));
        jdbcLog.put(new LogEntry.NoopEntry(2, 1));
        jdbcLog.put(new LogEntry.NoopEntry(3, 1)); // <--- expect this to be the last entry after truncation
        jdbcLog.put(new LogEntry.NoopEntry(7, 1));
        jdbcLog.put(new LogEntry.NoopEntry(8, 1));
        jdbcLog.put(new LogEntry.NoopEntry(9, 1));

        jdbcLog.truncate(6); // notice how I specified an index that doesn't exist

        assertThat(jdbcLog.getLast(), Matchers.<LogEntry>equalTo(new LogEntry.NoopEntry(3, 1)));
    }

    @Test
    public void shouldNotTruncateLogIfIndexGreaterThanLastLogEntryIsSpecified() throws StorageException {
        jdbcLog.put(LogEntry.SENTINEL);
        jdbcLog.put(new LogEntry.NoopEntry(1, 1));
        jdbcLog.put(new LogEntry.NoopEntry(2, 1));
        jdbcLog.put(new LogEntry.NoopEntry(3, 1));
        jdbcLog.put(new LogEntry.NoopEntry(7, 1));
        jdbcLog.put(new LogEntry.NoopEntry(8, 1));
        jdbcLog.put(new LogEntry.NoopEntry(9, 1)); // <--- expect this to be the last entry after truncation

        jdbcLog.truncate(11);

        assertThat(jdbcLog.getLast(), Matchers.<LogEntry>equalTo(new LogEntry.NoopEntry(9, 1)));
    }
}