text:
using E03_DependencyInversion.Interfaces;

namespace E03_DependencyInversion.Models
{
    public class MultiplyStrategy : IStrategy
    {
        public int Calculate(int firstOperand, int secondOperand)
        {
            return firstOperand * secondOperand;
        }
    }
}


text:
package connection

import (
	"errors"
	"fmt"
	"os"
	"os/user"
	"strings"

	"github.com/sosedoff/pgweb/pkg/command"
)

func currentUser() (string, error) {
	u, err := user.Current()
	if err == nil {
		return u.Username, nil
	}

	name := os.Getenv("USER")
	if name != "" {
		return name, nil
	}

	return "", errors.New("Unable to detect OS user")
}

func FormatUrl(opts command.Options) (string, error) {
	url := opts.Url

	// Make sure to only accept urls in a standard format
	if !strings.HasPrefix(url, "postgres://") && !strings.HasPrefix(url, "postgresql://") {
		return "", errors.New("Invalid URL. Valid format: postgres://user:password@host:port/db?sslmode=mode")
	}

	// Special handling for local connections
	if strings.Contains(url, "localhost") || strings.Contains(url, "127.0.0.1") {
		if !strings.Contains(url, "?sslmode") {
			if opts.Ssl == "" {
				url += fmt.Sprintf("?sslmode=%s", "disable")
			} else {
				url += fmt.Sprintf("?sslmode=%s", opts.Ssl)
			}
		}
	}

	// Append sslmode parameter only if its defined as a flag and not present
	// in the connection string.
	if !strings.Contains(url, "?sslmode") && opts.Ssl != "" {
		url += fmt.Sprintf("?sslmode=%s", opts.Ssl)
	}

	return url, nil
}

func IsBlank(opts command.Options) bool {
	return opts.Host == "" && opts.User == "" && opts.DbName == "" && opts.Url == ""
}

func BuildString(opts command.Options) (string, error) {
	if opts.Url != "" {
		return FormatUrl(opts)
	}

	// Try to detect user from current OS user
	if opts.User == "" {
		u, err := currentUser()
		if err == nil {
			opts.User = u
		}
	}

	// Disable ssl for localhost connections, most users have it disabled
	if opts.Host == "localhost" || opts.Host == "127.0.0.1" {
		if opts.Ssl == "" {
			opts.Ssl = "disable"
		}
	}

	url := "postgres://"

	if opts.User != "" {
		url += opts.User
	}

	if opts.Pass != "" {
		url += fmt.Sprintf(":%s", opts.Pass)
	}

	url += fmt.Sprintf("@%s:%d", opts.Host, opts.Port)

	if opts.DbName != "" {
		url += fmt.Sprintf("/%s", opts.DbName)
	}

	if opts.Ssl != "" {
		url += fmt.Sprintf("?sslmode=%s", opts.Ssl)
	}

	return url, nil
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var expect = require('chai').expect,
    Rect = require('../../../../source/js/ward-lib/graphics/models/rect.js'),
    graphicsFunctions = require('../../../../source/js/ward-lib/graphics/models/graphics-functions.js');

describe('Rect', function () {
    var recta;

    before(function () {
        recta = graphicsFunctions.getRect(2, 3, 20, 10);
    });

    it('should be a function', function () {
        expect(Rect).to.be.a('function');
    });

    it('should have expected origin', function () {
        var origin = recta.origin;
        expect(origin.x).to.equal(2);
        expect(origin.y).to.equal(3);
    });

    it('should have expected size', function () {
        var size =  recta.size;
        expect(size.width).to.equal(20);
        expect(size.height).to.equal(10);
    });

    it('should equal another with same geometry', function () {
        var rectb = graphicsFunctions.getRect(2, 3, 20, 10);
        expect(recta.equals(rectb)).to.be.true;
    });

    it('should not equal another with different size', function () {
        var rectc = graphicsFunctions.getRect(2, 3, 10, 20);
        expect(recta.equals(rectc)).not.to.be.true;
    });

    it('should not equal another with different origin', function () {
        var rectd = graphicsFunctions.getRect(3, 2, 20, 10);
        expect(recta.equals(rectd)).not.to.be.true;
    });
});


text:
#include <stdlib.h>
#include <stdio.h>
#include "allocator_shm.h"
#include "shared_queue.h"
#include "process_monitor.h"
#include "logger.h"
#include "config.h"
#include <semaphore.h>
struct shared_data
{
sem_t sem;
};

int main ( int argc, char *argv[])
{

	/*
	 * Set the umask to 0777 so any process can read and write to the queues, etc.
	 */
	umask(0000);

	ipt_allocator_t *alloc_ptr = ipt_allocator_malloc_create(10*1024 *1024);
//	alloc_ptr->dump_stats(alloc_ptr);

	//ipt_allocator_t *alloc_ptr = ipt_allocator_shm_create(1024 *1024, IPT_TEST_ALLOCATOR_SHM_KEY);

	if ( alloc_ptr == NULL )
	{
		printf("Failed to allocate the shared allocator for the service engine\n");
		return -1;
	}

//	ipt_logger_t *lg_ptr = ipt_logger_create("ipt_logger_t", alloc_ptr);
//
	//alloc_ptr->dump_stats(alloc_ptr);

//	if ( lg_ptr == NULL )
//	{
//		printf("Failed to create the logger.\n");
//		return -1;
//	}
       //alloc_ptr->register_object(alloc_ptr, "dummmy", malloc(100));
	//alloc_ptr->malloc(alloc_ptr,strlen("dummy")+1);
	//alloc_ptr->malloc(alloc_ptr,strlen("dummy")+1);
        alloc_ptr->malloc(alloc_ptr,6);
	printf("-------------------------------------- after register --------------\n");
//	alloc_ptr->dump_stats(alloc_ptr);

	ipt_shared_queue_t *sq_ptr;
	if ( ( sq_ptr= ipt_shared_queue_create("shared_queue_t",alloc_ptr) ) == NULL)
        {
                return -1;
        }

	return 0;
}


text:
NYAlertViewController is a replacement for UIAlertController/UIAlertView with support for content views and UI customization.

![Example](https://github.com/nealyoung/NYAlertViewController/raw/master/header.png)

### Features
* Includes content view property for adding custom views to the alert view
* Block-based API similar to UIAlertController/UIAlertAction
* Support for all screen orientations and iPad screen sizes
* Easily add text fields with simple API identical to UIAlertController
* Choose between fade (similar to UIAlertController) or slide transition animations

### Installation
#### Manual
Add the files to your project manually by dragging the NYAlertViewController directory into your Xcode project.

#### CocoaPods
Add `pod 'NYAlertViewController'` to your Podfile, and run `pod install`.

### Usage Example
An Objective-C example project demonstrating customization options is included in the NYAlertViewControllerDemo directory.

#### Objective-C

```objc
// Import the class and create an NYAlertViewController instance
#import "NYAlertViewController.h"

// ...

// Set a title and message
NSString *title = @"Location Permission";
NSString *message = @"Set the alertViewContentView property to add custom views to the alert view";

// Customize appearance as desired
NYAlertViewControllerConfiguration *configuration = [NYAlertViewControllerConfiguration new];
configuration.contentViewInset = UIEdgeInsetsMake(12.0f, 8.0f, 8.0f, 8.0f);
configuration.alertViewBackgroundColor = [UIColor colorWithRed:0.23f green:0.23f blue:0.27f alpha:1.0f];
configuration.separatorColor = [UIColor colorWithRed:0.16f green:0.16f blue:0.2f alpha:1.0f];
configuration.titleTextColor = [UIColor whiteColor];
configuration.messageTextColor = [UIColor whiteColor];

configuration.buttonConfiguration = [NYAlertActionConfiguration new];
configuration.buttonConfiguration.titleColor = [UIColor whiteColor];

configuration.cancelButtonConfiguration.titleColor = [UIColor whiteColor];

// Set up alert actions
NYAlertAction *cancelAction = [[NYAlertAction alloc] initWithTitle:@"Later"
                                                             style:UIAlertActionStyleCancel
                                                           handler:nil];
NYAlertAction *okAction = [[NYAlertAction alloc] initWithTitle:@"Ok"
                                                         style:UIAlertActionStyleDefault
                                                       handler:^(NYAlertAction *action) {
                                                           [self doSomething];
                                                       }]];

NYAlertViewController *alertViewController = [[NYAlertViewController alloc] initWithOptions:configuration
                                                                                title:title
                                                                                message:message
                                                                                actions:@[cancelAction, okAction]];

// Optionally add a content view
UIImageView *iconImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"MapIcon"]];
iconImageView.contentMode = UIViewContentModeScaleAspectFit;
[iconImageView.heightAnchor constraintEqualToConstant:60.0f].active = YES;
alertViewController.alertViewContentView = iconImageView;

// Present the alert view controller
[self presentViewController:alertViewController animated:YES completion:nil];
```

### License
This project is released under the MIT License.


text:
#include "memtx_rtree.h"
#include "tuple.h"
#include "space.h"
#include "memtx_engine.h"
#include "errinj.h"
#include "fiber.h"
#include "small/small.h"

/* {{{ Utilities. *************************************************/

inline void extract_rectangle(struct rtree_rect *rect,
			      const struct tuple *tuple, struct key_def *kd)
{
        assert(kd->part_count == 1);
	const char *elems = tuple_field(tuple, kd->parts[0].fieldno);
	uint32_t size = mp_decode_array(&elems);
	switch (size) {
	case 1: // array
	{
		const char* elems = tuple_field(tuple, kd->parts[0].fieldno);
		uint32_t size = mp_decode_array(&elems);
		switch (size) {
		case 2: // point
			rect->lower_point.coords[0] =
				rect->upper_point.coords[0] =
				mp_decode_num(&elems, 0);
			rect->lower_point.coords[1] =
				rect->upper_point.coords[1] =
				mp_decode_num(&elems, 1);
			break;
		case 4:
			rect->lower_point.coords[0] = mp_decode_num(&elems, 0);
			rect->lower_point.coords[1] = mp_decode_num(&elems, 1);
			rect->upper_point.coords[0] = mp_decode_num(&elems, 2);
			rect->upper_point.coords[1] = mp_decode_num(&elems, 3);
			break;
		default:
			tnt_raise(ClientError, ER_UNSUPPORTED,
				  "R-Tree index", "Field should be array with "
				  "size 2 (point) or 4 (rectangle)");

		}
		break;
	}
	case 2: // point
		rect->lower_point.coords[0] =
			rect->upper_point.coords[0] =
			mp_decode_num(&elems, 0);
		rect->lower_point.coords[1] =
			rect->upper_point.coords[1] =
			mp_decode_num(&elems, 1);
		break;
	case 4:
		rect->lower_point.coords[0] = mp_decode_num(&elems, 0);
		rect->lower_point.coords[1] = mp_decode_num(&elems, 1);
		rect->upper_point.coords[0] = mp_decode_num(&elems, 2);
		rect->upper_point.coords[1] = mp_decode_num(&elems, 3);
		break;
	default:
		tnt_raise(ClientError, ER_UNSUPPORTED,
			  "R-Tree index", "Key should contain 2 (point) or 4 (rectangle) coordinates");

	}
	rtree_rect_normalize(rect);
}
/* {{{ MemtxRTree Iterators ****************************************/

struct index_rtree_iterator {
        struct iterator base;
        struct rtree_iterator impl;
};

static void
index_rtree_iterator_free(struct iterator *i)
{
	struct index_rtree_iterator *itr = (struct index_rtree_iterator *)i;
	rtree_iterator_destroy(&itr->impl);
        delete itr;
}

static struct tuple *
index_rtree_iterator_next(struct iterator *i)
{
	struct index_rtree_iterator *itr = (struct index_rtree_iterator *)i;
	return (struct tuple *)rtree_iterator_next(&itr->impl);
}

/* }}} */

/* {{{ MemtxRTree  **********************************************************/

MemtxRTree::~MemtxRTree()
{
	// Iterator has to be destroyed prior to tree
	if (m_position != NULL) {
		index_rtree_iterator_free(m_position);
		m_position = NULL;
	}
	rtree_destroy(&tree);
}

MemtxRTree::MemtxRTree(struct key_def *key_def)
  : Index(key_def)
{
	assert(key_def->part_count == 1);
	assert(key_def->parts[0].type = ARRAY);
	assert(key_def->is_unique == false);

	memtx_index_arena_init();
	rtree_init(&tree, MEMTX_EXTENT_SIZE,
		   memtx_index_extent_alloc, memtx_index_extent_free);
}

size_t
MemtxRTree::size() const
{
	return rtree_number_of_records(&tree);
}

size_t
MemtxRTree::bsize() const
{
	return rtree_used_size(&tree);
}

struct tuple *
MemtxRTree::findByKey(const char *key, uint32_t part_count) const
{
	rtree_rect rect;
        struct rtree_iterator iterator;
        rtree_iterator_init(&iterator);
        switch (part_count) {
	case 1:
	{
		uint32_t size = mp_decode_array(&key);
		switch (size) {
		case 2:
			rect.lower_point.coords[0] =
				rect.upper_point.coords[0] =
				mp_decode_num(&key, 0);
			rect.lower_point.coords[1] =
				rect.upper_point.coords[1] =
				mp_decode_num(&key, 1);
			break;
		case 4:
			rect.lower_point.coords[0] = mp_decode_num(&key, 0);
			rect.lower_point.coords[1] = mp_decode_num(&key, 1);
			rect.upper_point.coords[0] = mp_decode_num(&key, 2);
			rect.upper_point.coords[1] = mp_decode_num(&key, 3);
			break;
		default:
			assert(false);
		}
		break;
	}
	case 2:
		rect.lower_point.coords[0] =
			rect.upper_point.coords[0] =
			mp_decode_num(&key, 0);
		rect.lower_point.coords[1] =
			rect.upper_point.coords[1] =
			mp_decode_num(&key, 1);
		break;
	case 4:
		rect.lower_point.coords[0] = mp_decode_num(&key, 0);
		rect.lower_point.coords[1] = mp_decode_num(&key, 1);
		rect.upper_point.coords[0] = mp_decode_num(&key, 2);
		rect.upper_point.coords[1] = mp_decode_num(&key, 3);
		break;
	default:
		assert(false);
	}
        struct tuple *result = NULL;
        if (rtree_search(&tree, &rect, SOP_OVERLAPS, &iterator))
		result = (struct tuple *)rtree_iterator_next(&iterator);
        rtree_iterator_destroy(&iterator);
        return result;
}

struct tuple *
MemtxRTree::replace(struct tuple *old_tuple, struct tuple *new_tuple,
                    enum dup_replace_mode)
{
        struct rtree_rect rect;
        if (new_tuple) {
                extract_rectangle(&rect, new_tuple, key_def);
                rtree_insert(&tree, &rect, new_tuple);
        }
	if (old_tuple) {
                extract_rectangle(&rect, old_tuple, key_def);
                if (!rtree_remove(&tree, &rect, old_tuple))
                        old_tuple = NULL;
        }
        return old_tuple;
}

struct iterator *
MemtxRTree::allocIterator() const
{
	index_rtree_iterator *it = new index_rtree_iterator;
	memset(it, 0, sizeof(*it));
	rtree_iterator_init(&it->impl);
	if (it == NULL) {
		tnt_raise(ClientError, ER_MEMORY_ISSUE,
			  sizeof(struct index_rtree_iterator),
			  "MemtxRTree", "iterator");
	}
	it->base.next = index_rtree_iterator_next;
	it->base.free = index_rtree_iterator_free;
	return &it->base;
}

void
MemtxRTree::initIterator(struct iterator *iterator, enum iterator_type type,
                         const char *key, uint32_t part_count) const
{
        struct rtree_rect rect;
        index_rtree_iterator *it = (index_rtree_iterator *)iterator;
        switch (part_count) {
        case 0:
                if (type != ITER_ALL) {
                        tnt_raise(ClientError, ER_UNSUPPORTED,
				  "R-Tree index", "It is possible to omit key only for ITER_ALL");
                }
                break;
	case 1:
	{
		uint32_t size = mp_decode_array(&key);
		switch (size) {
		case 2:
			rect.lower_point.coords[0] =
				rect.upper_point.coords[0] =
				mp_decode_num(&key, 0);
			rect.lower_point.coords[1] =
				rect.upper_point.coords[1] =
				mp_decode_num(&key, 1);
			break;
		case 4:
			rect.lower_point.coords[0] = mp_decode_num(&key, 0);
			rect.lower_point.coords[1] = mp_decode_num(&key, 1);
			rect.upper_point.coords[0] = mp_decode_num(&key, 2);
			rect.upper_point.coords[1] = mp_decode_num(&key, 3);
			break;
		default:
			tnt_raise(ClientError, ER_UNSUPPORTED,
				  "R-Tree index", "Key should be array of 2 (point) "
				  "or 4 (rectangle) numeric coordinates");
		}
		break;
	}
	case 2:
		rect.lower_point.coords[0] =
			rect.upper_point.coords[0] =
			mp_decode_num(&key, 0);
		rect.lower_point.coords[1] =
			rect.upper_point.coords[1] =
			mp_decode_num(&key, 1);
		break;
	case 4:
		rect.lower_point.coords[0] = mp_decode_num(&key, 0);
		rect.lower_point.coords[1] = mp_decode_num(&key, 1);
		rect.upper_point.coords[0] = mp_decode_num(&key, 2);
		rect.upper_point.coords[1] = mp_decode_num(&key, 3);
		break;
	default:
		tnt_raise(ClientError, ER_UNSUPPORTED,
			  "R-Tree index", "Key contain 2 (point) "
			  "or 4 (rectangle) numeric coordinates");
	}
        spatial_search_op op;
        switch (type) {
        case ITER_ALL:
                op = SOP_ALL;
                break;
        case ITER_EQ:
                op = SOP_EQUALS;
                break;
        case ITER_GT:
                op = SOP_STRICT_CONTAINS;
                break;
        case ITER_GE:
                op = SOP_CONTAINS;
                break;
        case ITER_LT:
                op = SOP_STRICT_BELONGS;
                break;
        case ITER_LE:
                op = SOP_BELONGS;
                break;
        case ITER_OVERLAPS:
                op = SOP_OVERLAPS;
                break;
        case ITER_NEIGHBOR:
                op = SOP_NEIGHBOR;
                break;
        default:
                tnt_raise(ClientError, ER_UNSUPPORTED,
                          "R-Tree index", "Unsupported search operation for R-Tree");
        }
        rtree_search(&tree, &rect, op, &it->impl);
}

void
MemtxRTree::beginBuild()
{
	rtree_purge(&tree);
}


text:
"""Module with functions which are supposed to be as fast as possible"""
from stat import S_ISDIR
from git.compat import (
    byte_ord,
    defenc,
    xrange,
    text_type,
    bchr
)

__all__ = ('tree_to_stream', 'tree_entries_from_data', 'traverse_trees_recursive',
           'traverse_tree_recursive')

def tree_to_stream(entries, write):
    """Write the give list of entries into a stream using its write method
    :param entries: **sorted** list of tuples with (binsha, mode, name)
    :param write: write method which takes a data string"""
    ord_zero = ord('0')
    bit_mask = 7            # 3 bits set

    for binsha, mode, name in entries:
        mode_str = b''
        for i in xrange(6):
            mode_str = bchr(((mode >> (i * 3)) & bit_mask) + ord_zero) + mode_str
        # END for each 8 octal value

        # git slices away the first octal if its zero
        if byte_ord(mode_str[0]) == ord_zero:
            mode_str = mode_str[1:]
        # END save a byte

        # here it comes:  if the name is actually unicode, the replacement below
        # will not work as the binsha is not part of the ascii unicode encoding -
        # hence we must convert to an utf8 string for it to work properly.
        # According to my tests, this is exactly what git does, that is it just
        # takes the input literally, which appears to be utf8 on linux.
        if isinstance(name, text_type):
            name = name.encode(defenc)
        write(b''.join((mode_str, b' ', name, b'\0', binsha)))
    # END for each item

def tree_entries_from_data(data):
    """Reads the binary representation of a tree and returns tuples of Tree items
    :param data: data block with tree data (as bytes)
    :return: list(tuple(binsha, mode, tree_relative_path), ...)"""
    ord_zero = ord('0')
    space_ord = ord(' ')
    len_data = len(data)
    i = 0
    out = list()
    while i < len_data:
        mode = 0

        # read mode
        # Some git versions truncate the leading 0, some don't
        # The type will be extracted from the mode later
        while byte_ord(data[i]) != space_ord:
            # move existing mode integer up one level being 3 bits
            # and add the actual ordinal value of the character
            mode = (mode << 3) + (byte_ord(data[i]) - ord_zero)
            i += 1
        # END while reading mode

        # byte is space now, skip it
        i += 1

        # parse name, it is NULL separated

        ns = i
        while byte_ord(data[i]) != 0:
            i += 1
        # END while not reached NULL

        # default encoding for strings in git is utf8
        # Only use the respective unicode object if the byte stream was encoded
        name = data[ns:i]
        try:
            name = name.decode(defenc)
        except UnicodeDecodeError:
            pass
        # END handle encoding

        # byte is NULL, get next 20
        i += 1
        sha = data[i:i + 20]
        i = i + 20
        out.append((sha, mode, name))
    # END for each byte in data stream
    return out

def _find_by_name(tree_data, name, is_dir, start_at):
    """return data entry matching the given name and tree mode
    or None.
    Before the item is returned, the respective data item is set
    None in the tree_data list to mark it done"""
    try:
        item = tree_data[start_at]
        if item and item[2] == name and S_ISDIR(item[1]) == is_dir:
            tree_data[start_at] = None
            return item
    except IndexError:
        pass
    # END exception handling
    for index, item in enumerate(tree_data):
        if item and item[2] == name and S_ISDIR(item[1]) == is_dir:
            tree_data[index] = None
            return item
        # END if item matches
    # END for each item
    return None

def _to_full_path(item, path_prefix):
    """Rebuild entry with given path prefix"""
    if not item:
        return item
    return (item[0], item[1], path_prefix + item[2])

def traverse_trees_recursive(odb, tree_shas, path_prefix):
    """
    :return: list with entries according to the given binary tree-shas.
        The result is encoded in a list
        of n tuple|None per blob/commit, (n == len(tree_shas)), where
        * [0] == 20 byte sha
        * [1] == mode as int
        * [2] == path relative to working tree root
        The entry tuple is None if the respective blob/commit did not
        exist in the given tree.
    :param tree_shas: iterable of shas pointing to trees. All trees must
        be on the same level. A tree-sha may be None in which case None
    :param path_prefix: a prefix to be added to the returned paths on this level,
        set it '' for the first iteration
    :note: The ordering of the returned items will be partially lost"""
    trees_data = list()
    nt = len(tree_shas)
    for tree_sha in tree_shas:
        if tree_sha is None:
            data = list()
        else:
            data = tree_entries_from_data(odb.stream(tree_sha).read())
        # END handle muted trees
        trees_data.append(data)
    # END for each sha to get data for

    out = list()
    out_append = out.append

    # find all matching entries and recursively process them together if the match
    # is a tree. If the match is a non-tree item, put it into the result.
    # Processed items will be set None
    for ti, tree_data in enumerate(trees_data):
        for ii, item in enumerate(tree_data):
            if not item:
                continue
            # END skip already done items
            entries = [None for _ in range(nt)]
            entries[ti] = item
            sha, mode, name = item                          # its faster to unpack @UnusedVariable
            is_dir = S_ISDIR(mode)                          # type mode bits

            # find this item in all other tree data items
            # wrap around, but stop one before our current index, hence
            # ti+nt, not ti+1+nt
            for tio in range(ti + 1, ti + nt):
                tio = tio % nt
                entries[tio] = _find_by_name(trees_data[tio], name, is_dir, ii)
            # END for each other item data

            # if we are a directory, enter recursion
            if is_dir:
                out.extend(traverse_trees_recursive(
                    odb, [((ei and ei[0]) or None) for ei in entries], path_prefix + name + '/'))
            else:
                out_append(tuple(_to_full_path(e, path_prefix) for e in entries))
            # END handle recursion

            # finally mark it done
            tree_data[ii] = None
        # END for each item

        # we are done with one tree, set all its data empty
        del(tree_data[:])
    # END for each tree_data chunk
    return out

def traverse_tree_recursive(odb, tree_sha, path_prefix):
    """
    :return: list of entries of the tree pointed to by the binary tree_sha. An entry
        has the following format:
        * [0] 20 byte sha
        * [1] mode as int
        * [2] path relative to the repository
    :param path_prefix: prefix to prepend to the front of all returned paths"""
    entries = list()
    data = tree_entries_from_data(odb.stream(tree_sha).read())

    # unpacking/packing is faster than accessing individual items
    for sha, mode, name in data:
        if S_ISDIR(mode):
            entries.extend(traverse_tree_recursive(odb, sha, path_prefix + name + '/'))
        else:
            entries.append((sha, mode, path_prefix + name))
    # END for each item

    return entries


text:
<?php

/*
* Conversations module for TangoBB
* Everything that you want to display MUST be in the $content variable.
*/
if (!defined('BASEPATH')) {
    die();
}

$page_title = '';
$content = '';
$notice = '';

if ($PGET->g('id')) {

    $MYSQL->bind('id', $PGET->g('id'));
    $query = $MYSQL->query("SELECT * FROM {prefix}messages WHERE id = :id AND message_type = 1");

    if (!empty($query)) {

        if (isset($_POST['reply'])) {
            try {

                foreach ($_POST as $parent => $child) {
                    $_POST[$parent] = clean($child);
                }

                NoCSRF::check('csrf_token', $_POST);
                $cont = clean(emoji_to_text($_POST['content']));
                $time = time();

                if (!$cont) {
                    throw new Exception ($LANG['global_form_process']['all_fields_required']);
                } else {
                    if ($TANGO->sess->data['id'] == $query['0']['message_sender']) {
                        $receiver = $query['0']['message_receiver'];
                    } else {
                        $receiver = $query['0']['message_sender'];
                    }
                    $MYSQL->bindMore(
                        array(
                            'message_title' => 'RE: ' . $query['0']['message_title'],
                            'message_content' => $cont,
                            'message_time' => $time,
                            'origin_message' => $query['0']['id'],
                            'message_sender' => $TANGO->sess->data['id'],
                            'message_receiver' => $receiver
                        )
                    );

                    if ($MYSQL->query("INSERT INTO {prefix}messages (message_title, message_content, message_time, origin_message, message_sender, message_receiver, message_type) VALUES (:message_title, :message_content, :message_time, :origin_message, :message_sender, :message_receiver, 2)") > 0) {
                        redirect(SITE_URL . '/conversations.php/cmd/view/v/' . $query['0']['id']);
                    } else {
                        throw new Exception ($LANG['bb']['conversations']['error_sending_alt']);
                    }

                }

            } catch (Exception $e) {
                $notice .= $TANGO->tpl->entity(
                    'danger_notice',
                    'content',
                    $e->getMessage()
                );
            }
        }

        define('CSRF_TOKEN', NoCSRF::generate('csrf_token'));

        //Breadcrumbs
        $TANGO->tpl->addBreadcrumb(
            $LANG['bb']['forum'],
            SITE_URL . '/forum.php'
        );
        $TANGO->tpl->addBreadcrumb(
            $LANG['bb']['conversations']['page_conversations'],
            SITE_URL . '/conversations.php'
        );
        $TANGO->tpl->addBreadcrumb(
            $LANG['bb']['conversations']['page_reply'] . ' ' . $query['0']['message_title'],
            '#',
            true
        );
        $content = $TANGO->tpl->breadcrumbs();

        $page_title = $LANG['bb']['conversations']['page_reply'] . ' ' . $query['0']['message_title'];
        $content .= $notice . '
                    <form action="" method="POST">
                      ' . $FORM->build('hidden', '', 'csrf_token', array('value' => CSRF_TOKEN)) . '
                      ' . $FORM->build('textarea', '', 'content', array('id' => 'editor', 'style' => 'width:100%;height:300px;max-width:100%;min-width:100%;')) . '
                      <br />
                      ' . $FORM->build('submit', '', 'reply', array('value' => $LANG['bb']['conversations']['form_reply'])) . '
                    </form>';

    } else {
        redirect(SITE_URL . '/404.php');
    }

} else {
    redirect(SITE_URL . '/404.php');
}

?>


text:
package org.jboss.hal.testsuite.test.configuration.ejb;

import java.io.IOException;
import java.util.List;

import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.graphene.page.Page;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.dmr.ModelNode;
import org.jboss.hal.testsuite.Console;
import org.jboss.hal.testsuite.CrudOperations;
import org.jboss.hal.testsuite.creaper.ManagementClientProvider;
import org.jboss.hal.testsuite.fragment.FormFragment;
import org.jboss.hal.testsuite.page.configuration.EJBConfigurationPage;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.extras.creaper.core.online.ModelNodeResult;
import org.wildfly.extras.creaper.core.online.OnlineManagementClient;
import org.wildfly.extras.creaper.core.online.operations.Operations;

import static org.jboss.hal.dmr.ModelDescriptionConstants.CLASS;
import static org.jboss.hal.dmr.ModelDescriptionConstants.MODULE;
import static org.jboss.hal.testsuite.fixtures.EJBFixtures.SERVER_INTERCEPTORS;
import static org.jboss.hal.testsuite.fixtures.EJBFixtures.SI_CLASS_CREATE;
import static org.jboss.hal.testsuite.fixtures.EJBFixtures.SI_CLASS_DELETE;
import static org.jboss.hal.testsuite.fixtures.EJBFixtures.SI_MODULE_CREATE;
import static org.jboss.hal.testsuite.fixtures.EJBFixtures.SI_MODULE_DELETE;
import static org.jboss.hal.testsuite.fixtures.EJBFixtures.SUBSYSTEM_ADDRESS;
import static org.jboss.hal.testsuite.fixtures.EJBFixtures.serverInterceptor;

@RunWith(Arquillian.class)
public class ServerInterceptorsTest {

    private static final OnlineManagementClient client = ManagementClientProvider.createOnlineManagementClient();
    private static final Operations operations = new Operations(client);

    @BeforeClass
    public static void beforeClass() throws Exception {
        operations.writeListAttribute(SUBSYSTEM_ADDRESS, SERVER_INTERCEPTORS,
                serverInterceptor(SI_CLASS_DELETE, SI_MODULE_DELETE));
    }

    @AfterClass
    public static void tearDown() throws Exception {
        operations.undefineAttribute(SUBSYSTEM_ADDRESS, SERVER_INTERCEPTORS);
    }

    @Inject private Console console;
    @Inject private CrudOperations crud;
    @Page private EJBConfigurationPage page;
    private FormFragment form;

    @Before
    public void setUp() throws Exception {
        page.navigate();
        console.verticalNavigation().selectSecondary("ejb3-container-item", "ejb3-configuration-item");
        form = page.getConfigurationForm();
    }

    @Test
    public void create() throws Exception {
        crud.update(SUBSYSTEM_ADDRESS, form,
                form -> form.list(SERVER_INTERCEPTORS).add(SI_CLASS_CREATE + "," + SI_MODULE_CREATE),
                resourceVerifier -> resourceVerifier.verifyTrue("Server interceptors not updated",
                        this::verifyServerInterceptorCreated));
    }

    @Test
    public void delete() throws Exception {
        crud.update(SUBSYSTEM_ADDRESS, form,
                form -> form.list(SERVER_INTERCEPTORS).removeTags(),
                resourceVerifier -> resourceVerifier.verifyTrue("No server interceptors expected",
                        this::verifyServerInterceptorsDeleted));
    }

    private boolean verifyServerInterceptorCreated() throws IOException {
        ModelNodeResult result = operations.readAttribute(SUBSYSTEM_ADDRESS, SERVER_INTERCEPTORS);
        if (result.isSuccess()) {
            List<ModelNode> serverInterceptors = result.value().asList();
            return serverInterceptors.stream().anyMatch(node ->
                    org.jboss.hal.testsuite.fixtures.EJBFixtures.SI_CLASS_CREATE.equals(node.get(CLASS).asString()) && org.jboss.hal.testsuite.fixtures.EJBFixtures.SI_MODULE_CREATE.equals(node.get(MODULE).asString()));
        }
        return false;
    }

    private boolean verifyServerInterceptorsDeleted() throws IOException {
        ModelNodeResult result = operations.readAttribute(SUBSYSTEM_ADDRESS, SERVER_INTERCEPTORS);
        if (result.isSuccess()) {
            return !result.value().isDefined();
        }
        return false;
    }
}


text:
"""
    sphinx.make_mode
    ~~~~~~~~~~~~~~~~

    sphinx-build -M command-line handling.

    This replaces the old, platform-dependent and once-generated content
    of Makefile / make.bat.

    This is in its own module so that importing it is fast.  It should not
    import the main Sphinx modules (like sphinx.applications, sphinx.builders).

    :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

import warnings

from sphinx.cmd import make_mode
from sphinx.deprecation import RemovedInSphinx30Warning

BUILDERS = make_mode.BUILDERS

class Make(make_mode.Make):
    def __init__(self, *args):
        warnings.warn('sphinx.make_mode.Make is deprecated. '
                      'Please use sphinx.cmd.make_mode.Make instead.',
                      RemovedInSphinx30Warning, stacklevel=2)
        super().__init__(*args)

def run_make_mode(args):
    warnings.warn('sphinx.make_mode.run_make_mode() is deprecated. '
                  'Please use sphinx.cmd.make_mode.run_make_mode() instead.',
                  RemovedInSphinx30Warning, stacklevel=2)
    return make_mode.run_make_mode(args)


text:
<?xml version="1.0" encoding="UTF-8"?>
<arquillian xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://jboss.org/schema/arquillian" xsi:schemaLocation="http://jboss.org/schema/arquillian
                         http://jboss.org/schema/arquillian/arquillian_1_0.xsd">

    <defaultProtocol type="Servlet 3.0"/>

     <container qualifier="test" default="true">
        <configuration>
            <property name="jbossHome">${serverRoot}</property>
            <property name="serverConfig">${serverProfile:standalone-full.xml}</property>
            <property name="allowConnectingToRunningServer">true</property>
        </configuration>
    </container>

</arquillian>


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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>replay cache — MIT Kerberos Documentation</title>

    <link rel="stylesheet" href="../_static/agogo.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/kerb.css" type="text/css" />

    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="MIT Kerberos Documentation" href="../index.html" />
    <link rel="up" title="Kerberos V5 concepts" href="index.html" />
    <link rel="next" title="stash file" href="stash_file_def.html" />
    <link rel="prev" title="keytab" href="keytab_def.html" />

MIT Kerberos Documentation

        Contents |
        previous |
        next |
        index |
        Search |
    feedback

replay cache¶

A replay cache (or “rcache”) keeps track of all authenticators
recently presented to a service.  If a duplicate authentication
request is detected in the replay cache, an error message is sent to
the application program.

The replay cache interface, like the credential cache and
keytab interfaces, uses type:value strings to
indicate the type of replay cache and any associated cache naming
data to use.

Background information¶

Some Kerberos or GSSAPI services use a simple authentication mechanism
where a message is sent containing an authenticator, which establishes
the encryption key that the client will use for talking to the
service.  But nothing about that prevents an eavesdropper from
recording the messages sent by the client, establishing a new
connection, and re-sending or “replaying” the same messages; the
replayed authenticator will establish the same encryption key for the
new session, and the following messages will be decrypted and
processed.  The attacker may not know what the messages say, and can’t
generate new messages under the same encryption key, but in some
instances it may be harmful to the user (or helpful to the attacker)
to cause the server to see the same messages again a second time.  For
example, if the legitimate client sends “delete first message in
mailbox”, a replay from an attacker may delete another, different
“first” message.  (Protocol design to guard against such problems has
been discussed in RFC 4120.)

Even if one protocol uses further protection to verify that the client
side of the connection actually knows the encryption keys (and thus is
presumably a legitimate user), if another service uses the same
service principal name, it may be possible to record an authenticator
used with the first protocol and “replay” it against the second.

The replay cache mitigates these attacks somewhat, by keeping track of
authenticators that have been seen until their five-minute window
expires.  Different authenticators generated by multiple connections
from the same legitimate client will generally have different
timestamps, and thus will not be considered the same.

This mechanism isn’t perfect.  If a message is sent to one application
server but a man-in-the-middle attacker can prevent it from actually
arriving at that server, the attacker could then use the authenticator
(once!) against a different service on the same host.  This could be a
problem if the message from the client included something more than
authentication in the first message that could be useful to the
attacker (which is uncommon; in most protocols the server has to
indicate a successful authentication before the client sends
additional messages), or if the simple act of presenting the
authenticator triggers some interesting action in the service being
attacked.

Default rcache type¶

There is currently only one implemented kind of replay cache, called
dfl.  It stores replay data in one file, occasionally rewriting it
to purge old, expired entries.

The default type can be overridden by the KRB5RCACHETYPE
environment variable.

The placement of the replay cache file is determined by the following:

The KRB5RCACHEDIR environment variable;

If KRB5RCACHEDIR is unspecified, on UNIX, the library
will fall back to the environment variable TMPDIR, and then to
a temporary directory determined at configuration time such as
/tmp or /var/tmp; on Windows, it will check the environment
variables TEMP and TMP, and fall back to the directory C:\.

Performance issues¶

Several known minor performance issues that may occur when replay
cache is enabled on the Kerberos system include: delays due to writing
the authenticator data to disk slowing down response time for very
heavily loaded servers, and delays during the rewrite that may be
unacceptable to high-performance services.

For use cases where replays are adequately defended against for all
protocols using a given service principal name, or where performance
or other considerations outweigh the risk of replays, the special
replay cache type “none” can be specified:

KRB5RCACHETYPE=none

It doesn’t record any information about authenticators, and reports
that any authenticator seen is not a replay.

On this page

replay cache

Background information

Default rcache type

Performance issues

Table of contents

For users

For administrators

For application developers

For plugin module developers

Building Kerberos V5

Kerberos V5 concepts

Credential cache

keytab

replay cache

stash file

Supported date and time formats

Protocols and file formats

MIT Kerberos features

How to build this documentation from the source

Contributing to the MIT Kerberos Documentation

Resources

Full Table of Contents

Search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" size="18" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Release: 1.16

                © Copyright 1985-2017, MIT.

        Contents |
        previous |
        next |
        index |
        Search |
    feedback


text:
#if UNITY_EDITOR
using System.Xml;
using UnityEngine;

namespace QFramework
{
    public interface IMGUITextField : IMGUIView, IHasText<IMGUITextField>, IXMLToObjectConverter
    {
        BindableProperty<string> Content { get; }

        IMGUITextField PasswordMode();
    }

    internal class IMGUITextFieldView : IMGUIAbstractView, IMGUITextField
    {
        public IMGUITextFieldView()
        {
            Content = new BindableProperty<string>(string.Empty);

            mStyleProperty = new GUIStyleProperty(() => GUI.skin.textField);
        }

        public BindableProperty<string> Content { get; private set; }

        protected override void OnGUI()
        {
            if (mPasswordMode)
            {
                Content.Value = CrossPlatformGUILayout.PasswordField(Content.Value, Style.Value, LayoutStyles);
            }
            else
            {
                Content.Value = CrossPlatformGUILayout.TextField(Content.Value, Style.Value, LayoutStyles);
            }
        }

        private bool mPasswordMode = false;

        public IMGUITextField PasswordMode()
        {
            mPasswordMode = true;
            return this;
        }

        public IMGUITextField Text(string labelText)
        {
            Content.Value = labelText;
            return this;
        }

        public T Convert<T>(XmlNode node) where T : class
        {
            var textArea = EasyIMGUI.TextField();

            foreach (XmlAttribute nodeAttribute in node.Attributes)
            {
                if (nodeAttribute.Name == "Id")
                {
                    textArea.Id = nodeAttribute.Value;
                }
                else if (nodeAttribute.Name == "Text")
                {
                    textArea.Text(nodeAttribute.Value);
                }
            }

            return textArea as T;
        }
    }
}
#endif


text:
#ifndef __TestTextInput__
#define __TestTextInput__

#include "../TestBasic.h"

class TestTextInput : public TestBasic, public CCIMEDelegate
{
	public :

		static  TestTextInput*	create ( KDvoid );

	protected :

		virtual KDbool			init   ( KDvoid );
		virtual KDuint			count  ( KDvoid );
        virtual KDvoid			onExit ( KDvoid );

		virtual KDbool			ccTouchBegan ( CCTouch* pTouch, CCEvent* pEvent );

	protected :

		CCTextFieldTTF*			m_pTextField;
};

class TextFieldTTFDefaultTest : public TestTextInput
{
	public :

		virtual const KDchar*   subtitle ( KDvoid );
};

class TextFieldTTFActionTest : public TestTextInput, public CCTextFieldDelegate
{
	public :

		virtual const KDchar*	subtitle ( KDvoid );
		virtual KDvoid			onEnter  ( KDvoid );
		virtual	KDvoid			onExit   ( KDvoid );

		virtual KDbool			onTextFieldAttachWithIME ( CCTextFieldTTF* pSender );
		virtual KDbool			onTextFieldDetachWithIME ( CCTextFieldTTF* pSender );

		virtual KDbool			onTextFieldInsertText     ( CCTextFieldTTF* pSender, const KDchar* szText, KDsize uLen );
		virtual KDbool			onTextFieldDeleteBackward ( CCTextFieldTTF* pSender, const KDchar* szText, KDsize uLen );

		KDvoid					callbackRemoveNodeWhenDidAction ( CCNode* pNode );

	protected :

		KDuint					m_uLimit;
		KDsize					m_uLength;
		CCAction*				m_pAction;
};

#endif	// __TestTextInput__


text:
<?php

namespace Hautelook\ShipmentTracking\Provider;

use Guzzle\Http\Client;
use Guzzle\Http\ClientInterface;
use Guzzle\Http\Exception\HttpException;
use Hautelook\ShipmentTracking\Exception\Exception;
use Hautelook\ShipmentTracking\ShipmentEvent;
use Hautelook\ShipmentTracking\ShipmentInformation;

/**
 * @author Adrien Brault <adrien.brault@gmail.com>
 */
class LandmarkProvider implements ProviderInterface
{
    /**
     * @var string
     */
    private $username;

    /**
     * @var string
     */
    private $password;

    /**
     * @var string
     */
    private $url;

    /**
     * @var ClientInterface
     */
    private $httpClient;

    public function __construct(
        $username,
        $password,
        $url = null,
        ClientInterface $httpClient = null
    ) {
        $this->username = $username;
        $this->password = $password;
        $this->url = $url ?: 'https://mercury.landmarkglobal.com/api/api.php';
        $this->httpClient = $httpClient ?: new Client();
    }

    public function track($trackingNumber)
    {
        try {
            $response = $this->httpClient->get($this->url, array(), array(
                'query' => array(
                    'RQXML' => $this->createRequestXml($trackingNumber),
                ),
            ))->send();
        } catch (HttpException $e) {
            throw Exception::createFromHttpException($e);
        }

        return $this->parse($response->getBody(true));
    }

    private function createRequestXml($trackingNumber)
    {
<<<XML
<TrackRequest>
    <Login>
        <Username></Username>
        <Password></Password>
    </Login>
</TrackRequest>
XML;

        $requestXml = new \SimpleXMLElement('<TrackRequest/>');
        $requestXml->Login->Username = $this->username;
        $requestXml->Login->Password = $this->password;
        $requestXml->TrackingNumber = $trackingNumber;

        return $requestXml->asXML();
    }

    private function parse($xml)
    {
        try {
            $trackResponseXml = new \SimpleXMLElement($xml);
        } catch (\Exception $e) {
            throw Exception::createFromSimpleXMLException($e);
        }

        $events = array();
        foreach ($trackResponseXml->xpath('//Events/Event') as $eventXml) {
            $location = null;
            if ($eventXml->Location->count() > 0) {
                $location = (string) $eventXml->Location;
            }
            $status = (string) $eventXml->Status;
            $date = new \DateTime((string) $eventXml->DateTime);

            $shipmentEventType = null;

            if ('Item successfully delivered' === $status) {
                $shipmentEventType = ShipmentEvent::TYPE_DELIVERED;
            }

            $events[] = new ShipmentEvent($date, $status, $location, $shipmentEventType);
        }

        return new ShipmentInformation($events);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<switchyard xmlns="urn:switchyard-config:switchyard:1.0" xmlns:sca="http://docs.oasis-open.org/ns/opencsa/sca/200912"
  xmlns:camel="urn:switchyard-component-camel-core:config:1.0" xmlns:bean="urn:switchyard-component-bean:config:1.0">
  <sca:composite name="file8" targetNamespace="urn:com.redhat.issues.switchyard:file8:1.0">
    <sca:service name="GreetingService" promote="GreetingService/GreetingService">
      <camel:binding.uri name="hello" configURI="file:///tmp/issues?sorter=#sampleSorter">
        <operationSelector operationName="hello" />
      </camel:binding.uri>
    </sca:service>
    <sca:component name="GreetingService">
      <bean:implementation.bean class="com.redhat.issues.switchyard.file8.GreetingServiceImpl" />
      <sca:service name="GreetingService">
        <sca:interface.java interface="com.redhat.issues.switchyard.file8.GreetingService" />
      </sca:service>
    </sca:component>
  </sca:composite>
</switchyard>


text:
package com.knight.solid.local;

import org.openqa.selenium.WebDriver;
/**
 * @author Shawn Knight (shawn.knight.work@gmail.com)
 */
public interface LocalWebDriver {

	public WebDriver getWebDriver();

	public boolean isWebDriverType(String type);
}


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

import {AlbumsSubpage} from 'chrome://personalization/trusted/ambient/albums_subpage_element.js';
import {AmbientActionName, SetAlbumsAction, SetAmbientModeEnabledAction, SetAnimationThemeAction, SetTemperatureUnitAction, SetTopicSourceAction} from 'chrome://personalization/trusted/ambient/ambient_actions.js';
import {AmbientObserver} from 'chrome://personalization/trusted/ambient/ambient_observer.js';
import {AmbientSubpage} from 'chrome://personalization/trusted/ambient/ambient_subpage_element.js';
import {AnimationThemeItem} from 'chrome://personalization/trusted/ambient/animation_theme_item_element.js';
import {TopicSourceItem} from 'chrome://personalization/trusted/ambient/topic_source_item_element.js';
import {AmbientModeAlbum, AnimationTheme, TemperatureUnit, TopicSource} from 'chrome://personalization/trusted/personalization_app.mojom-webui.js';
import {Paths, PersonalizationRouter} from 'chrome://personalization/trusted/personalization_router_element.js';
import {emptyState} from 'chrome://personalization/trusted/personalization_state.js';
import {WallpaperGridItem} from 'chrome://personalization/trusted/wallpaper/wallpaper_grid_item_element.js';
import {CrRadioButtonElement} from 'chrome://resources/cr_elements/cr_radio_button/cr_radio_button.m.js';
import {assertDeepEquals, assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js';
import {TestBrowserProxy} from 'chrome://webui-test/test_browser_proxy.js';
import {waitAfterNextRender} from 'chrome://webui-test/test_util.js';

import {baseSetup, initElement, teardownElement} from './personalization_app_test_utils.js';
import {TestAmbientProvider} from './test_ambient_interface_provider.js';
import {TestPersonalizationStore} from './test_personalization_store.js';

export function getSelectedAlbums(
    albums: AmbientModeAlbum[], topicSource: TopicSource): AmbientModeAlbum[] {
  return albums.filter(
      album => album.topicSource === topicSource && album.checked);
}

export function AmbientSubpageTest() {
  let ambientSubpageElement: AmbientSubpage|null;
  let ambientProvider: TestAmbientProvider;
  let personalizationStore: TestPersonalizationStore;
  const routerOriginal = PersonalizationRouter.instance;
  const routerMock = TestBrowserProxy.fromClass(PersonalizationRouter);

  setup(() => {
    const mocks = baseSetup();
    ambientProvider = mocks.ambientProvider;
    personalizationStore = mocks.personalizationStore;
    AmbientObserver.initAmbientObserverIfNeeded();
    PersonalizationRouter.instance = () => routerMock;
  });

  teardown(async () => {
    await teardownElement(ambientSubpageElement);
    ambientSubpageElement = null;
    AmbientObserver.shutdown();
    PersonalizationRouter.instance = routerOriginal;
  });

  async function displayMainSettings(
      topicSource: TopicSource|null, temperatureUnit: TemperatureUnit|null,
      ambientModeEnabled: boolean,
      animationTheme = AnimationTheme.kSlideshow): Promise<AmbientSubpage> {
    personalizationStore.data.ambient.albums = ambientProvider.albums;
    personalizationStore.data.ambient.animationTheme = animationTheme;
    personalizationStore.data.ambient.topicSource = topicSource;
    personalizationStore.data.ambient.temperatureUnit = temperatureUnit;
    personalizationStore.data.ambient.ambientModeEnabled = ambientModeEnabled;
    const ambientSubpage =
        initElement(AmbientSubpage, {path: Paths.Ambient, queryParams: {}});
    personalizationStore.notifyObservers();
    await waitAfterNextRender(ambientSubpage);
    return Promise.resolve(ambientSubpage);
  }

  test('displays content', async () => {
    ambientSubpageElement = await displayMainSettings(
        /*topicSource=*/ null, /*temperatureUnit=*/ null,
        /*ambientModeEnabled=*/ false);

    const toggleRow =
        ambientSubpageElement.shadowRoot!.querySelector('toggle-row');
    assertTrue(!!toggleRow, 'toggle-row element exists');
    const toggleButton = toggleRow!.shadowRoot!.querySelector('cr-toggle');
    assertTrue(!!toggleButton, 'cr-toggle element exists');
    assertFalse(toggleButton!.checked);

    personalizationStore.data.ambient.ambientModeEnabled = true;
    personalizationStore.notifyObservers();
    await waitAfterNextRender(ambientSubpageElement);

    let spinner =
        ambientSubpageElement.shadowRoot!.querySelector('paper-spinner-lite');
    assertTrue(!!spinner, 'paper-spinner-lite element exists');
    assertTrue(spinner.active, 'paper-spinner-lite is active');

    personalizationStore.data.ambient.albums = ambientProvider.albums;
    personalizationStore.data.ambient.topicSource = TopicSource.kGooglePhotos;
    personalizationStore.data.ambient.temperatureUnit =
        TemperatureUnit.kFahrenheit;
    personalizationStore.notifyObservers();
    await waitAfterNextRender(ambientSubpageElement);

    spinner =
        ambientSubpageElement.shadowRoot!.querySelector('paper-spinner-lite');
    assertTrue(!!spinner, 'paper-spinner-lite still exists');
    assertEquals(getComputedStyle(spinner).display, 'none');

    const topicSource =
        ambientSubpageElement.shadowRoot!.querySelector('topic-source-list');
    assertTrue(!!topicSource, 'topic-source-list element exists');

    const weatherUnit =
        ambientSubpageElement.shadowRoot!.querySelector('ambient-weather-unit');
    assertTrue(!!weatherUnit);
  });

  test('sets ambient mode enabled in store on first load', async () => {
    personalizationStore.expectAction(
        AmbientActionName.SET_AMBIENT_MODE_ENABLED);
    ambientSubpageElement = await displayMainSettings(
        TopicSource.kArtGallery, TemperatureUnit.kFahrenheit,
        /*ambientModeEnabled=*/ false);

    await ambientProvider.whenCalled('setAmbientObserver');
    ambientProvider.updateAmbientObserver();

    const action = await personalizationStore.waitForAction(
                       AmbientActionName.SET_AMBIENT_MODE_ENABLED) as
        SetAmbientModeEnabledAction;
    assertTrue(action.enabled);
  });

  test('sets ambient mode when pref value changed', async () => {
    // Make sure state starts as expected.
    assertDeepEquals(emptyState(), personalizationStore.data);
    ambientSubpageElement = initElement(AmbientSubpage);
    await ambientProvider.whenCalled('setAmbientObserver');

    personalizationStore.expectAction(
        AmbientActionName.SET_AMBIENT_MODE_ENABLED);
    ambientProvider.ambientObserverRemote!.onAmbientModeEnabledChanged(
        /*ambientModeEnabled=*/ false);

    const action = await personalizationStore.waitForAction(
                       AmbientActionName.SET_AMBIENT_MODE_ENABLED) as
        SetAmbientModeEnabledAction;
    assertFalse(action.enabled);
  });

  test('sets ambient mode enabled when toggle row clicked', async () => {
    ambientSubpageElement = await displayMainSettings(
        TopicSource.kArtGallery, TemperatureUnit.kFahrenheit,
        /*ambientModeEnabled=*/ true);

    const toggleRow =
        ambientSubpageElement.shadowRoot!.querySelector('toggle-row');
    assertTrue(!!toggleRow);
    const toggleButton = toggleRow!.shadowRoot!.querySelector('cr-toggle');
    assertTrue(!!toggleButton);
    assertTrue(toggleButton!.checked);

    personalizationStore.setReducersEnabled(true);
    personalizationStore.expectAction(
        AmbientActionName.SET_AMBIENT_MODE_ENABLED);
    toggleRow.click();
    let action = await personalizationStore.waitForAction(
                     AmbientActionName.SET_AMBIENT_MODE_ENABLED) as
        SetAmbientModeEnabledAction;
    assertFalse(action.enabled);
    assertFalse(personalizationStore.data.ambient.ambientModeEnabled);
    assertFalse(toggleButton!.checked);

    personalizationStore.expectAction(
        AmbientActionName.SET_AMBIENT_MODE_ENABLED);
    toggleRow.click();
    action = await personalizationStore.waitForAction(
                 AmbientActionName.SET_AMBIENT_MODE_ENABLED) as
        SetAmbientModeEnabledAction;
    assertTrue(action.enabled);
    assertTrue(personalizationStore.data.ambient.ambientModeEnabled);
    assertTrue(toggleButton!.checked);
  });

  test('sets ambient mode enabled when toggle button clicked', async () => {
    ambientSubpageElement = await displayMainSettings(
        TopicSource.kArtGallery, TemperatureUnit.kFahrenheit,
        /*ambientModeEnabled=*/ true);

    const toggleRow =
        ambientSubpageElement.shadowRoot!.querySelector('toggle-row');
    assertTrue(!!toggleRow);
    const toggleButton = toggleRow!.shadowRoot!.querySelector('cr-toggle');
    assertTrue(!!toggleButton);
    assertTrue(toggleButton!.checked);

    personalizationStore.expectAction(
        AmbientActionName.SET_AMBIENT_MODE_ENABLED);
    toggleRow.$.toggle.click();
    let action = await personalizationStore.waitForAction(
                     AmbientActionName.SET_AMBIENT_MODE_ENABLED) as
        SetAmbientModeEnabledAction;
    assertFalse(action.enabled);

    personalizationStore.expectAction(
        AmbientActionName.SET_AMBIENT_MODE_ENABLED);
    toggleRow.$.toggle.click();
    action = await personalizationStore.waitForAction(
                 AmbientActionName.SET_AMBIENT_MODE_ENABLED) as
        SetAmbientModeEnabledAction;
    assertTrue(action.enabled);
  });

  test('has correct animation theme on load', async () => {
    personalizationStore.expectAction(AmbientActionName.SET_ANIMATION_THEME);
    ambientSubpageElement = initElement(AmbientSubpage);

    await ambientProvider.whenCalled('setAmbientObserver');
    ambientProvider.updateAmbientObserver();

    const action =
        await personalizationStore.waitForAction(
            AmbientActionName.SET_ANIMATION_THEME) as SetAnimationThemeAction;
    assertEquals(AnimationTheme.kSlideshow, action.animationTheme);
  });

  test(
      'sets animation theme when animation theme item is clicked', async () => {
        ambientSubpageElement = await displayMainSettings(
            TopicSource.kArtGallery, TemperatureUnit.kFahrenheit,
            /*ambientModeEnabled=*/ true);

        const animationThemeList =
            ambientSubpageElement.shadowRoot!.querySelector(
                'animation-theme-list');
        assertTrue(!!animationThemeList);
        const animationThemeItems =
            animationThemeList!.shadowRoot!.querySelectorAll(
                'animation-theme-item:not([hidden])');
        assertEquals(3, animationThemeItems!.length);
        const slideshow = animationThemeItems[0] as AnimationThemeItem;
        const feelTheBreeze = animationThemeItems[1] as AnimationThemeItem;
        assertEquals(AnimationTheme.kSlideshow, slideshow.animationTheme);
        assertEquals(
            AnimationTheme.kFeelTheBreeze, feelTheBreeze.animationTheme);

        assertFalse(feelTheBreeze.checked);
        assertTrue(slideshow.checked);

        personalizationStore.expectAction(
            AmbientActionName.SET_ANIMATION_THEME);
        feelTheBreeze!.click();
        let action = await personalizationStore.waitForAction(
                         AmbientActionName.SET_ANIMATION_THEME) as
            SetAnimationThemeAction;
        assertEquals(AnimationTheme.kFeelTheBreeze, action.animationTheme);

        personalizationStore.expectAction(
            AmbientActionName.SET_ANIMATION_THEME);
        slideshow!.click();
        action = await personalizationStore.waitForAction(
                     AmbientActionName.SET_ANIMATION_THEME) as
            SetAnimationThemeAction;
        assertEquals(AnimationTheme.kSlideshow, action.animationTheme);
      });

  test('has correct topic sources on load', async () => {
    personalizationStore.expectAction(AmbientActionName.SET_TOPIC_SOURCE);
    ambientSubpageElement = initElement(AmbientSubpage);

    await ambientProvider.whenCalled('setAmbientObserver');
    ambientProvider.updateAmbientObserver();

    const action =
        await personalizationStore.waitForAction(
            AmbientActionName.SET_TOPIC_SOURCE) as SetTopicSourceAction;
    assertEquals(TopicSource.kArtGallery, action.topicSource);
  });

  test('sets topic source when topic source item clicked', async () => {
    ambientSubpageElement = await displayMainSettings(
        TopicSource.kArtGallery, TemperatureUnit.kFahrenheit,
        /*ambientModeEnabled=*/ true);

    const topicSourceList =
        ambientSubpageElement.shadowRoot!.querySelector('topic-source-list');
    assertTrue(!!topicSourceList);
    const topicSourceItems =
        topicSourceList!.shadowRoot!.querySelectorAll('topic-source-item');
    assertEquals(2, topicSourceItems!.length);
    const googlePhotos = topicSourceItems[0] as TopicSourceItem;
    const art = topicSourceItems[1] as TopicSourceItem;
    assertEquals(TopicSource.kGooglePhotos, googlePhotos.topicSource);
    assertEquals(TopicSource.kArtGallery, art.topicSource);

    assertFalse(googlePhotos.checked);
    assertTrue(art.checked);

    personalizationStore.expectAction(AmbientActionName.SET_TOPIC_SOURCE);
    googlePhotos!.click();
    let action =
        await personalizationStore.waitForAction(
            AmbientActionName.SET_TOPIC_SOURCE) as SetTopicSourceAction;
    assertEquals(TopicSource.kGooglePhotos, action.topicSource);

    personalizationStore.expectAction(AmbientActionName.SET_TOPIC_SOURCE);
    art!.click();
    action = await personalizationStore.waitForAction(
                 AmbientActionName.SET_TOPIC_SOURCE) as SetTopicSourceAction;
    assertEquals(TopicSource.kArtGallery, action.topicSource);
  });

  test('has correct temperature unit on load', async () => {
    personalizationStore.expectAction(AmbientActionName.SET_TEMPERATURE_UNIT);
    ambientSubpageElement = initElement(AmbientSubpage);

    await ambientProvider.whenCalled('setAmbientObserver');
    ambientProvider.updateAmbientObserver();

    const action =
        await personalizationStore.waitForAction(
            AmbientActionName.SET_TEMPERATURE_UNIT) as SetTemperatureUnitAction;
    assertEquals(TemperatureUnit.kFahrenheit, action.temperatureUnit);
  });

  test('sets temperature unit when temperature unit item clicked', async () => {
    ambientSubpageElement = await displayMainSettings(
        TopicSource.kArtGallery, TemperatureUnit.kFahrenheit,
        /*ambientModeEnabled=*/ true);

    const weatherUnit =
        ambientSubpageElement.shadowRoot!.querySelector('ambient-weather-unit');
    assertTrue(!!weatherUnit);

    const temperatureUnitItems =
        weatherUnit!.shadowRoot!.querySelectorAll<CrRadioButtonElement>(
            'cr-radio-button');
    assertEquals(2, temperatureUnitItems!.length);

    const [fahrenheitUnitButton, celsiusUnitButton] = temperatureUnitItems;

    assertTrue(
        fahrenheitUnitButton!.checked, 'fahrenheit button starts checked');

    personalizationStore.expectAction(AmbientActionName.SET_TEMPERATURE_UNIT);
    celsiusUnitButton!.click();
    assertTrue(celsiusUnitButton!.checked);
    let action =
        await personalizationStore.waitForAction(
            AmbientActionName.SET_TEMPERATURE_UNIT) as SetTemperatureUnitAction;
    assertEquals(TemperatureUnit.kCelsius, action.temperatureUnit);

    personalizationStore.expectAction(AmbientActionName.SET_TEMPERATURE_UNIT);
    fahrenheitUnitButton!.click();
    assertTrue(fahrenheitUnitButton!.checked);
    action =
        await personalizationStore.waitForAction(
            AmbientActionName.SET_TEMPERATURE_UNIT) as SetTemperatureUnitAction;
    assertEquals(TemperatureUnit.kFahrenheit, action.temperatureUnit);
  });

  test('has main settings visible with path ambient', async () => {
    ambientSubpageElement =
        initElement(AmbientSubpage, {path: Paths.Ambient, queryParams: {}});
    await waitAfterNextRender(ambientSubpageElement);

    const mainSettings =
        ambientSubpageElement.shadowRoot!.querySelector<HTMLElement>(
            '#mainSettings');
    assertTrue(!!mainSettings);
    assertFalse(mainSettings.hidden);

    const albumsSubpage =
        ambientSubpageElement.shadowRoot!.querySelector('albums-subpage');
    assertFalse(!!albumsSubpage);
  });

  test('has albums subpage visible with path ambient albums', async () => {
    ambientSubpageElement = initElement(AmbientSubpage, {
      path: Paths.AmbientAlbums,
      queryParams: {topicSource: TopicSource.kArtGallery}
    });
    personalizationStore.data.ambient.ambientModeEnabled = true;
    personalizationStore.notifyObservers();
    await waitAfterNextRender(ambientSubpageElement);

    const mainSettings =
        ambientSubpageElement.shadowRoot!.querySelector<HTMLElement>(
            '#mainSettings');
    assertFalse(!!mainSettings);

    const albumsSubpage =
        ambientSubpageElement.shadowRoot!.querySelector('albums-subpage');
    assertTrue(!!albumsSubpage);
    assertFalse(albumsSubpage.hidden);
  });

  test(
      'loading albums subpage redirects to ambient subpage if disabled',
      async () => {
        const reloadCalledPromise = new Promise<void>((resolve) => {
          PersonalizationRouter.reloadAtAmbient = resolve;
        });
        initElement(AlbumsSubpage, {
          path: Paths.AmbientAlbums,
          disabled: true,
        });

        await reloadCalledPromise;
      });

  test('has spinner when no albums on albums subpage', async () => {
    ambientSubpageElement = initElement(AmbientSubpage, {
      path: Paths.AmbientAlbums,
      queryParams: {topicSource: TopicSource.kGooglePhotos}
    });
    personalizationStore.data.ambient.ambientModeEnabled = true;
    personalizationStore.notifyObservers();
    await waitAfterNextRender(ambientSubpageElement);

    const albumsSubpage =
        ambientSubpageElement.shadowRoot!.querySelector('albums-subpage');
    assertTrue(!!albumsSubpage);
    assertFalse(albumsSubpage.hidden);
    await waitAfterNextRender(albumsSubpage);

    let spinner = albumsSubpage.shadowRoot!.querySelector('paper-spinner-lite');
    assertTrue(!!spinner);
    assertTrue(spinner.active);

    personalizationStore.data.ambient.albums = ambientProvider.albums;
    personalizationStore.data.ambient.topicSource = TopicSource.kGooglePhotos;
    personalizationStore.data.ambient.temperatureUnit =
        TemperatureUnit.kFahrenheit;
    personalizationStore.notifyObservers();
    await waitAfterNextRender(albumsSubpage);

    spinner = albumsSubpage.shadowRoot!.querySelector('paper-spinner-lite');
    assertTrue(!!spinner);
    assertEquals(getComputedStyle(spinner).display, 'none');
  });

  test('has correct albums on Google Photos albums subpage', async () => {
    ambientSubpageElement = initElement(AmbientSubpage, {
      path: Paths.AmbientAlbums,
      queryParams: {topicSource: TopicSource.kGooglePhotos}
    });
    personalizationStore.data.ambient.ambientModeEnabled = true;
    personalizationStore.data.ambient.albums = ambientProvider.albums;
    personalizationStore.notifyObservers();
    await waitAfterNextRender(ambientSubpageElement);

    const albumsSubpage =
        ambientSubpageElement.shadowRoot!.querySelector('albums-subpage');
    assertTrue(!!albumsSubpage);
    assertFalse(albumsSubpage.hidden);
    await waitAfterNextRender(albumsSubpage);

    const albumList = albumsSubpage.shadowRoot!.querySelector('album-list');
    assertTrue(!!albumList);

    const albums = albumList.shadowRoot!.querySelectorAll<WallpaperGridItem>(
        'wallpaper-grid-item:not([hidden])');
    assertEquals(1, albums.length);
  });

  test('has correct albums on Art albums subpage', async () => {
    ambientSubpageElement = initElement(AmbientSubpage, {
      path: Paths.AmbientAlbums,
      queryParams: {topicSource: TopicSource.kArtGallery}
    });
    personalizationStore.data.ambient.ambientModeEnabled = true;
    personalizationStore.data.ambient.albums = ambientProvider.albums;
    personalizationStore.notifyObservers();
    await waitAfterNextRender(ambientSubpageElement);

    const albumsSubpage =
        ambientSubpageElement.shadowRoot!.querySelector('albums-subpage');
    assertTrue(!!albumsSubpage);
    assertFalse(albumsSubpage.hidden);
    await waitAfterNextRender(albumsSubpage);

    const albumList = albumsSubpage.shadowRoot!.querySelector('album-list');
    assertTrue(!!albumList);

    const albums = albumList.shadowRoot!.querySelectorAll<WallpaperGridItem>(
        'wallpaper-grid-item:not([hidden])');
    assertEquals(3, albums.length);
    assertTrue(!!albums[0]);
    assertTrue(!!albums[1]);
    assertTrue(!!albums[2]);
  });

  test('toggle album selection by clicking', async () => {
    personalizationStore.setReducersEnabled(true);
    personalizationStore.expectAction(AmbientActionName.SET_ALBUMS);
    ambientSubpageElement = initElement(AmbientSubpage, {
      path: Paths.AmbientAlbums,
      queryParams: {topicSource: TopicSource.kArtGallery}
    });

    await ambientProvider.whenCalled('setAmbientObserver');
    ambientProvider.updateAmbientObserver();

    const action = await personalizationStore.waitForAction(
                       AmbientActionName.SET_ALBUMS) as SetAlbumsAction;
    assertEquals(4, action.albums.length, 'action.albums.length');

    const albumsSubpage =
        ambientSubpageElement.shadowRoot!.querySelector('albums-subpage');
    assertTrue(!!albumsSubpage, '!!albumsSubpage');
    assertFalse(albumsSubpage.hidden, 'albumsSubpage.hidden');
    await waitAfterNextRender(albumsSubpage);

    const albumList = albumsSubpage.shadowRoot!.querySelector('album-list');
    assertTrue(!!albumList, '!!albumList');

    const albums = albumList.shadowRoot!.querySelectorAll<WallpaperGridItem>(
        'wallpaper-grid-item:not([hidden])');
    assertEquals(3, albums.length);
    assertTrue(!!albums[0]);
    assertTrue(!!albums[1]);
    assertTrue(!!albums[2]);
    assertFalse(albums[0].selected);
    assertFalse(albums[1].selected);
    assertTrue(albums[2].selected);
    let selectedAlbums = getSelectedAlbums(
        personalizationStore.data.ambient.albums,
        personalizationStore.data.ambient.topicSource);
    assertEquals(1, selectedAlbums!.length);
    assertEquals('2', selectedAlbums[0]!.title);

    personalizationStore.expectAction(AmbientActionName.SET_ALBUM_SELECTED);
    albums[1].click();
    assertTrue(albums[1].selected);
    await personalizationStore.waitForAction(
        AmbientActionName.SET_ALBUM_SELECTED);
    selectedAlbums = getSelectedAlbums(
        personalizationStore.data.ambient.albums,
        personalizationStore.data.ambient.topicSource);
    assertEquals(2, selectedAlbums!.length);
    assertEquals('1', selectedAlbums[0]!.title);
    assertEquals('2', selectedAlbums[1]!.title);
  });

  test('not deselect last art album', async () => {
    personalizationStore.setReducersEnabled(true);
    personalizationStore.expectAction(AmbientActionName.SET_ALBUMS);
    ambientSubpageElement = initElement(AmbientSubpage, {
      path: Paths.AmbientAlbums,
      queryParams: {topicSource: TopicSource.kArtGallery}
    });

    await ambientProvider.whenCalled('setAmbientObserver');
    ambientProvider.updateAmbientObserver();

    const action = await personalizationStore.waitForAction(
                       AmbientActionName.SET_ALBUMS) as SetAlbumsAction;
    assertEquals(4, action.albums.length);

    const albumsSubpage =
        ambientSubpageElement.shadowRoot!.querySelector('albums-subpage');
    assertTrue(!!albumsSubpage);
    assertFalse(albumsSubpage.hidden);
    await waitAfterNextRender(albumsSubpage);

    const albumList = albumsSubpage.shadowRoot!.querySelector('album-list');
    assertTrue(!!albumList);

    const albums = albumList.shadowRoot!.querySelectorAll<WallpaperGridItem>(
        'wallpaper-grid-item:not([hidden])');
    assertEquals(3, albums.length);
    assertTrue(!!albums[0]);
    assertTrue(!!albums[1]);
    assertTrue(!!albums[2]);
    assertFalse(albums[0].selected);
    assertFalse(albums[1].selected);
    assertTrue(albums[2].selected);

    // Click the last art album item image will not toggle the check and will
    // show a dialog.
    albums[2].click();
    assertTrue(albums[2].selected);

    const artAlbumDialog =
        albumsSubpage.shadowRoot!.querySelector('art-album-dialog');
    assertTrue(!!artAlbumDialog);
    await waitAfterNextRender(artAlbumDialog);
    assertTrue(artAlbumDialog.$.dialog.open);
  });

  test('has correct album preview information', async () => {
    personalizationStore.setReducersEnabled(true);
    personalizationStore.expectAction(AmbientActionName.SET_ALBUMS);

    ambientSubpageElement = await displayMainSettings(
        TopicSource.kArtGallery, TemperatureUnit.kFahrenheit,
        /*ambientModeEnabled=*/ true);

    await ambientProvider.whenCalled('setAmbientObserver');
    ambientProvider.updateAmbientObserver();

    const action = await personalizationStore.waitForAction(
                       AmbientActionName.SET_ALBUMS) as SetAlbumsAction;
    assertEquals(4, action.albums.length);
    const ambientPreview =
        ambientSubpageElement.shadowRoot!.querySelector('ambient-preview');
    assertTrue(!!ambientPreview);

    const previewImage =
        ambientPreview.shadowRoot!.querySelector<HTMLImageElement>(
            '.preview-image');
    assertTrue(!!previewImage);
    assertTrue(previewImage.src.includes('test_url2'));

    const previewAlbumTitle =
        ambientPreview.shadowRoot!.getElementById('albumTitle');
    assertTrue(!!previewAlbumTitle);
    assertEquals('2', previewAlbumTitle.innerText.replace(/\s/g, ''));
  });

  test('displays zero state when ambient mode is disabled', async () => {
    ambientSubpageElement = await displayMainSettings(
        TopicSource.kArtGallery, TemperatureUnit.kFahrenheit,
        /*ambientModeEnabled=*/ false);

    // Preview image should be absent.
    assertEquals(
        ambientSubpageElement.shadowRoot!.querySelector('ambient-preview'),
        null);

    // Topic source list should be absent.
    assertEquals(
        ambientSubpageElement.shadowRoot!.querySelector('topic-source-list'),
        null);

    // Weather unit should be absent.
    assertEquals(
        ambientSubpageElement.shadowRoot!.querySelector('ambient-weather-unit'),
        null);

    // Zero state should be present.
    const zeroState =
        ambientSubpageElement.shadowRoot!.querySelector('ambient-zero-state');
    assertTrue(!!zeroState);
  });
}


text:
package net.sourceforge.mayfly.evaluation.command;

import net.sourceforge.mayfly.datastore.ColumnNames;
import net.sourceforge.mayfly.datastore.DataStore;
import net.sourceforge.mayfly.datastore.Index;
import net.sourceforge.mayfly.datastore.TableReference;

public class CreateIndex extends Command {

    private final UnresolvedTableReference table;
    private final String indexName;
    private final ColumnNames columns;
    private final boolean unique;

    public CreateIndex(UnresolvedTableReference table,
        String indexName, ColumnNames columns, boolean unique) {
        this.table = table;
        this.indexName = indexName;
        this.columns = columns;
        this.unique = unique;
    }

    @Override
    public UpdateStore update(DataStore store, String currentSchema) {
        DataStore newStore = addIndex(store, currentSchema);
        return new UpdateStore(newStore, 0);
    }

    private DataStore addIndex(DataStore store, String currentSchema) {
        Index index = new Index(indexName, columns, unique);
        TableReference reference = table.resolve(store, currentSchema, null);
        index.checkExistingRows(store, reference);
        return store.addIndex(reference, index);
    }

}


text:
"""The pypollmanage package"""

def plugme(app_config, options):
    return dict(appid='pypollmanage', global_helpers=False)


text:
<?php

namespace MVNerds\CoreBundle\Model;

use MVNerds\CoreBundle\Model\om\BaseTournamentPrizePeer;

/**
 * Skeleton subclass for performing query and update operations on the 'tournament_prize' table.
 *
 *
 *
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 *
 * @package    propel.generator.src.MVNerds.CoreBundle.Model
 */
class TournamentPrizePeer extends BaseTournamentPrizePeer {

} // TournamentPrizePeer


text:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import 'normalize.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

const rootEl = document.getElementById('root');

if (rootEl) {
  ReactDOM.render(<App />, rootEl);
  registerServiceWorker();
}


text:
<?php
defined('C5_EXECUTE') or die("Access Denied.");

$pagetypes = PageType::getList();
$types = array();
foreach($pagetypes as $pt) {
	$types[$pt->getPageTypeID()] = $pt->getPageTypeDisplayName();
}

?>

<input type="hidden" name="tab[]" value="posting" />

		<?=t('Enable New Topics')?>

				<?=$form->radio('enablePostingFromGathering', 0, $enablePostingFromGathering)?>
				<?=t('No, posting is disabled.')?>

				<?=$form->radio('enablePostingFromGathering', 1, $enablePostingFromGathering)?>
				<?=t('Yes, this gathering can be posted to the front-end.')?>

		<?=t('Create pages using')?>

			<?=$form->select('ptID', $types, $ptID)?>


text:
using System.Reflection;
using System.Resources;

[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: NeutralResourcesLanguage("en-us")]
[assembly: AssemblyCompany("Microsoft Corporation.")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyProduct("Microsoft ASP.NET Core")]


text:
title: Ember 1.1.2 Released
author: Peter Wagenet
tags: Releases, Recent Posts
---

Unfortunately, there was a second regression in 1.1 that didn't get
caught in time to make it into 1.1.1. On that account 1.1.2 is out now
to correct that issue. For more information about the problem see
[Issue #3637](https://github.com/emberjs/ember.js/issues/3637).

We recommend that everyone using 1.1.0 and 1.1.1 upgrade at their
nearest convenience. Head on over to [emberjs.com/builds](/builds)
to download. Our apologies for the inconvenience.

### Ember 1.2 Beta 2

While we were at it, we also released the second 1.2 beta which includes
a couple of bug fixes. 1.2.0-beta.2 is also available at
[emberjs.com/builds](/builds).


text:
<?php

/**
 * @covers Sanitizer::validateEmail
 * @todo all test methods in this class should be refactored and...
 *    use a single test method and a single data provider...
 */
class SanitizerValidateEmailTest extends PHPUnit_Framework_TestCase {

	private function checkEmail( $addr, $expected = true, $msg = '' ) {
		if ( $msg == '' ) {
			$msg = "Testing $addr";
		}

		$this->assertEquals(
			$expected,
			Sanitizer::validateEmail( $addr ),
			$msg
		);
	}

	private function valid( $addr, $msg = '' ) {
		$this->checkEmail( $addr, true, $msg );
	}

	private function invalid( $addr, $msg = '' ) {
		$this->checkEmail( $addr, false, $msg );
	}

	public function testEmailWellKnownUserAtHostDotTldAreValid() {
		$this->valid( 'user@example.com' );
		$this->valid( 'user@example.museum' );
	}

	public function testEmailWithUpperCaseCharactersAreValid() {
		$this->valid( 'USER@example.com' );
		$this->valid( 'user@EXAMPLE.COM' );
		$this->valid( 'user@Example.com' );
		$this->valid( 'USER@eXAMPLE.com' );
	}

	public function testEmailWithAPlusInUserName() {
		$this->valid( 'user+sub@example.com' );
		$this->valid( 'user+@example.com' );
	}

	public function testEmailDoesNotNeedATopLevelDomain() {
		$this->valid( "user@localhost" );
		$this->valid( "FooBar@localdomain" );
		$this->valid( "nobody@mycompany" );
	}

	public function testEmailWithWhiteSpacesBeforeOrAfterAreInvalids() {
		$this->invalid( " user@host.com" );
		$this->invalid( "user@host.com " );
		$this->invalid( "\tuser@host.com" );
		$this->invalid( "user@host.com\t" );
	}

	public function testEmailWithWhiteSpacesAreInvalids() {
		$this->invalid( "User user@host" );
		$this->invalid( "first last@mycompany" );
		$this->invalid( "firstlast@my company" );
	}

	/**
	 * bug 26948 : comma were matched by an incorrect regexp range
	 */
	public function testEmailWithCommasAreInvalids() {
		$this->invalid( "user,foo@example.org" );
		$this->invalid( "userfoo@ex,ample.org" );
	}

	public function testEmailWithHyphens() {
		$this->valid( "user-foo@example.org" );
		$this->valid( "userfoo@ex-ample.org" );
	}

	public function testEmailDomainCanNotBeginWithDot() {
		$this->invalid( "user@." );
		$this->invalid( "user@.localdomain" );
		$this->invalid( "user@localdomain." );
		$this->valid( "user.@localdomain" );
		$this->valid( ".@localdomain" );
		$this->invalid( ".@a............" );
	}

	public function testEmailWithFunnyCharacters() {
		$this->valid( "\$user!ex{this}@123.com" );
	}

	public function testEmailTopLevelDomainCanBeNumerical() {
		$this->valid( "user@example.1234" );
	}

	public function testEmailWithoutAtSignIsInvalid() {
		$this->invalid( 'useràexample.com' );
	}

	public function testEmailWithOneCharacterDomainIsValid() {
		$this->valid( 'user@a' );
	}
}


text:
/**********************************************************
  @author mail@markus-falk.com
  @description sets css min-height of given elements to the highest calculated value
***********************************************************/

;(function($) {

  $.fn.equalheight = function() {

    var heights = 0;

    this.each(function() {

      // cache object height
      var obj_height = $(this).height();

      // save it if it is higher than before
      if(heights < obj_height) {
        heights = obj_height;
      }
    });

    // set height of given elements to calculated value
    this.css('min-height', heights);

    // preserve chainability
    return this;
  };

})(jQuery);


text:
// This package main implements the executable QingYuan Mesos executor.
package main


text:
namespace net {
class URLRequestContextGetter;
}  // namespace net

namespace syncer {

class CancelationSignal;
class HttpPostProviderFactory;

class NetworkResources {
 public:
  virtual ~NetworkResources() {}

  virtual std::unique_ptr<HttpPostProviderFactory> GetHttpPostProviderFactory(
      const scoped_refptr<net::URLRequestContextGetter>&
          baseline_context_getter,
      const NetworkTimeUpdateCallback& network_time_update_callback,
      CancelationSignal* cancelation_signal) = 0;
};

}  // namespace syncer

#endif  // COMPONENTS_SYNC_ENGINE_NET_NETWORK_RESOURCES_H_


text:
package org.metasyntactic.automata.compiler.python.scanner.delimiters;

public class RightParenthesisDelimiterToken extends DelimiterToken {
  public static final RightParenthesisDelimiterToken instance = new RightParenthesisDelimiterToken();

  private RightParenthesisDelimiterToken() {
    super(")");
  }
}


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>
BasicComboPopup.InvocationMouseHandler (Java Platform SE 6)
</TITLE>

<META NAME="date" CONTENT="2007-03-19">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      概述
      软件包
    类
      使用
      树
      已过时
      索引
      帮助

JavaTM Platform
Standard Ed. 6

 上一个类
 下一个类

  框架
 无框架

  所有类

  摘要: 嵌套 | 字段 | 构造方法 | 方法

详细信息: 字段 | 构造方法 | 方法

javax.swing.plaf.basic

类 BasicComboPopup.InvocationMouseHandler

java.lang.Object
  java.awt.event.MouseAdapter
      javax.swing.plaf.basic.BasicComboPopup.InvocationMouseHandler

所有已实现的接口:
MouseListener, MouseMotionListener, MouseWheelListener, EventListener

正在封闭类:
BasicComboPopup

protected class BasicComboPopup.InvocationMouseHandler
extends MouseAdapter

要在组合框(非 其弹出菜单)上注册的侦听器,该侦听器处理影响弹出菜单状态的鼠标事件。此侦听器的主要用途在于显示和隐藏弹出菜单。此侦听器也用于单击并拖动(click-and-drag)场景:如果拖动过程中在列表上释放鼠标,此侦听器将设置选择。

警告:建议不要 创建此类的子类。如果一定要创建子类,则确保调用每个方法的超类方法。

另请参见:
BasicComboPopup.createMouseListener()

构造方法摘要

protected
BasicComboPopup.InvocationMouseHandler()

方法摘要

 void
mousePressed(MouseEvent e)

          响应组合框上的鼠标按下事件。

 void
mouseReleased(MouseEvent e)

          响应用户终止从组合框开始的单击或拖动操作。

从类 java.awt.event.MouseAdapter 继承的方法

mouseClicked, mouseDragged, mouseEntered, mouseExited, mouseMoved, mouseWheelMoved

从类 java.lang.Object 继承的方法

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

构造方法详细信息

BasicComboPopup.InvocationMouseHandler

protected BasicComboPopup.InvocationMouseHandler()

方法详细信息

mousePressed

public void mousePressed(MouseEvent e)

响应组合框上的鼠标按下事件。

指定者:
接口 MouseListener 中的 mousePressed
覆盖:
类 MouseAdapter 中的 mousePressed

参数:
e - 要处理的鼠标按下事件

mouseReleased

public void mouseReleased(MouseEvent e)

响应用户终止从组合框开始的单击或拖动操作。

指定者:
接口 MouseListener 中的 mouseReleased
覆盖:
类 MouseAdapter 中的 mouseReleased

参数:
e - 要处理的鼠标释放事件

      概述
      软件包
    类
      使用
      树
      已过时
      索引
      帮助

JavaTM Platform
Standard Ed. 6

 上一个类
 下一个类

  框架
 无框架

  所有类

  摘要: 嵌套 | 字段 | 构造方法 | 方法

详细信息: 字段 | 构造方法 | 方法

提交错误或意见
有关更多的 API 参考资料和开发人员文档,请参阅 Java SE 开发人员文档。该文档包含更详细的、面向开发人员的描述,以及总体概述、术语定义、使用技巧和工作代码示例。
版权所有 2007 Sun Microsystems, Inc. 保留所有权利。 请遵守许可证条款。另请参阅文档重新分发政策。


text:
package haskell.data.enumerator.ex;

import haskell.data.enumerator.IterateeState;
import haskell.data.enumerator.Step;
import java.nio.CharBuffer;

/**
 * This class corresponds to the {@code peek} function on page 47.
 * @author hemantka
 */
public class PeekStep implements Step<CharBuffer,Character> {
    private char c;
    private IterateeState state = IterateeState.CONTINUE;
    private String msg;

    @Override
    public String getErrorMessage() {
        return msg;
    }

    @Override
    public Character getResult() {
        return c;
    }

    @Override
    public IterateeState getState() {
        return state;
    }

    @Override
    public void readBuffer(CharBuffer cb) {
        if (cb.hasRemaining()) {
            cb.mark();
            c = cb.get();
            cb.reset();
            this.state = IterateeState.YIELD;
        }

    }

    @Override
    public void reset() {
        this.state = IterateeState.CONTINUE;
        this.c = '\0';
    }

}


text:
import baseComponent from '../helpers/baseComponent'
import classNames from '../helpers/classNames'

baseComponent({
    relations: {
        '../accordion-group/index': {
            type: 'parent',
        },
    },
    properties: {
        prefixCls: {
            type: String,
            value: 'wux-accordion',
        },
        key: {
            type: String,
            value: '',
        },
        thumb: {
            type: String,
            value: '',
        },
        title: {
            type: String,
            value: '',
        },
        content: {
            type: String,
            value: '',
        },
        disabled: {
            type: Boolean,
            value: false,
        },
        showArrow: {
            type: Boolean,
            value: true,
        },
    },
    data: {
        current: false,
        index: '0',
    },
    computed: {
        classes: ['prefixCls, current, disabled', function(prefixCls, current, disabled) {
            const wrap = classNames(prefixCls, {
                [`${prefixCls}--current`]: current,
                [`${prefixCls}--disabled`]: disabled,
            })
            const hd = `${prefixCls}__hd`
            const thumb = `${prefixCls}__thumb`
            const title = `${prefixCls}__title`
            const arrow = `${prefixCls}__arrow`
            const bd = `${prefixCls}__bd`
            const content = `${prefixCls}__content`

            return {
                wrap,
                hd,
                thumb,
                title,
                arrow,
                bd,
                content,
            }
        }],
    },
    methods: {
        changeCurrent(current, index) {
            this.setData({
                current,
                index,
            })
        },
        onTap() {
            const { index, disabled } = this.data
            const parent = this.getRelationNodes('../accordion-group/index')[0]

            if (disabled || !parent) return

            parent.onClickItem(index)
        },
    },
})


text:
package com.facebook.buck.event.listener;

import static org.junit.Assert.assertEquals;

import com.facebook.buck.core.model.BuildId;
import com.facebook.buck.core.model.BuildTargetFactory;
import com.facebook.buck.event.ActionGraphEvent;
import com.facebook.buck.util.Ansi;
import com.google.common.collect.ImmutableMap;
import java.util.Optional;
import java.util.function.Function;
import org.junit.Before;
import org.junit.Test;

public class CommonThreadStateRendererTest {

  private Ansi ansi;
  private Function<Long, String> timeToString;
  private ActionGraphEvent fakeEvent;

  @Before
  public void setUp() {
    ansi = new Ansi(false);
    timeToString = Object::toString;
    fakeEvent = ActionGraphEvent.started();
    fakeEvent.configure(0, 0, 0, 0, new BuildId());
  }

  @Test
  public void rendersShortStatusWithCorrectColor() {
    CommonThreadStateRenderer renderer =
        new CommonThreadStateRenderer(
            new Ansi(false), Object::toString, 0, 80, ImmutableMap.of(), Optional.empty());

    assertEquals(
        ansi.asSubtleText("[:]"),
        renderer.renderShortStatus(
            true, false, CommonThreadStateRenderer.WARNING_THRESHOLD_MS - 1));

    assertEquals(
        ansi.asWarningText("[:]"),
        renderer.renderShortStatus(true, false, CommonThreadStateRenderer.WARNING_THRESHOLD_MS));
    assertEquals(
        ansi.asSubtleText("[:]"),
        renderer.renderShortStatus(true, false, CommonThreadStateRenderer.ERROR_THRESHOLD_MS));
  }

  @Test
  public void rendersShortStatusWithAnimation() {
    CommonThreadStateRenderer renderer =
        new CommonThreadStateRenderer(
            new Ansi(false), Object::toString, 0, 80, ImmutableMap.of(), Optional.empty());

    assertEquals(
        ansi.asSubtleText("[:]"),
        renderer.renderShortStatus(
            true, false, CommonThreadStateRenderer.WARNING_THRESHOLD_MS - 1));

    renderer =
        new CommonThreadStateRenderer(
            new Ansi(false),
            Object::toString,
            CommonThreadStateRenderer.ANIMATION_DURATION,
            80,
            ImmutableMap.of(),
            Optional.empty());

    assertEquals(
        ansi.asSubtleText("[']"),
        renderer.renderShortStatus(
            true, false, CommonThreadStateRenderer.WARNING_THRESHOLD_MS - 1));

    renderer =
        new CommonThreadStateRenderer(
            new Ansi(false),
            Object::toString,
            CommonThreadStateRenderer.ANIMATION_DURATION * 2,
            80,
            ImmutableMap.of(),
            Optional.empty());

    assertEquals(
        ansi.asSubtleText("[:]"),
        renderer.renderShortStatus(
            true, false, CommonThreadStateRenderer.WARNING_THRESHOLD_MS - 1));

    renderer =
        new CommonThreadStateRenderer(
            new Ansi(false),
            Object::toString,
            CommonThreadStateRenderer.ANIMATION_DURATION * 3,
            80,
            ImmutableMap.of(),
            Optional.empty());

    assertEquals(
        ansi.asSubtleText("[.]"),
        renderer.renderShortStatus(
            true, false, CommonThreadStateRenderer.WARNING_THRESHOLD_MS - 1));
  }

  @Test
  public void rendersLineCorrectLength() {
    CommonThreadStateRenderer renderer =
        new CommonThreadStateRenderer(
            new Ansi(false), Object::toString, 0, 100, ImmutableMap.of(), Optional.empty());

    assertEquals(
        ansi.asSubtleText("     - //some:target... 5000 (running some step[0])"),
        renderer.renderLine(
            Optional.of(BuildTargetFactory.newInstance("some:target")),
            Optional.of(fakeEvent),
            Optional.of(fakeEvent),
            Optional.of("some step"),
            Optional.empty(),
            5000));

    renderer =
        new CommonThreadStateRenderer(
            new Ansi(false), Object::toString, 0, 19, ImmutableMap.of(), Optional.empty());

    assertEquals(
        ansi.asSubtleText("     - //so... 5000"),
        renderer.renderLine(
            Optional.of(BuildTargetFactory.newInstance("some:target")),
            Optional.of(fakeEvent),
            Optional.of(fakeEvent),
            Optional.empty(),
            Optional.empty(),
            5000));

    renderer =
        new CommonThreadStateRenderer(
            new Ansi(false), Object::toString, 0, 49, ImmutableMap.of(), Optional.empty());

    assertEquals(
        ansi.asSubtleText("     - //some:target... 5000 (running som... [0])"),
        renderer.renderLine(
            Optional.of(BuildTargetFactory.newInstance("some:target")),
            Optional.of(fakeEvent),
            Optional.of(fakeEvent),
            Optional.of("some step"),
            Optional.empty(),
            5000));

    renderer =
        new CommonThreadStateRenderer(
            new Ansi(false), Object::toString, 0, 84, ImmutableMap.of(), Optional.empty());

    assertEquals(
        ansi.asSubtleText("     - //some:target... 5000 (some placeholder)"),
        renderer.renderLine(
            Optional.of(BuildTargetFactory.newInstance("some:target")),
            Optional.of(fakeEvent),
            Optional.of(fakeEvent),
            Optional.empty(),
            Optional.of("some placeholder"),
            5000));

    renderer =
        new CommonThreadStateRenderer(
            new Ansi(false), Object::toString, 0, 44, ImmutableMap.of(), Optional.of("[[]]"));

    assertEquals(
        ansi.asSubtleText("[[]] - //some:target... 5000 (some plac... )"),
        renderer.renderLine(
            Optional.of(BuildTargetFactory.newInstance("some:target")),
            Optional.of(fakeEvent),
            Optional.of(fakeEvent),
            Optional.empty(),
            Optional.of("some placeholder"),
            5000));
  }
}


text:
class Viehicle():

    def __init__(self, x, y):
        self.acceleration = PVector(0, 0)
        self.velocity = PVector(0, 0)
        self.location = PVector(x, y)
        self.r = 8.0
        self.maxspeed = 5
        self.maxforce = 0.1
        self.d = 25

    def update(self):
        self.velocity.add(self.acceleration)
        self.velocity.limit(self.maxspeed)
        self.location.add(self.velocity)
        self.acceleration.mult(0)

    def applyForce(self, force):
        self.acceleration.add(force)

    def seek(self, target):
        desired = PVector.sub(target, self.location)
        # Check Boundaries
        if self.location.x < self.d:
            desired = PVector(self.maxspeed, self.velocity.y)
        elif self.location.x > width - self.d:
            desired = PVector(-self.maxspeed, self.velocity.y)
        if self.location.y < self.d:
            desired = PVector(self.velocity.x, self.maxspeed)
        elif self.location.y > height - self.d:
            desired = PVector(self.velocity.x, -self.maxspeed)
        desired.normalize()
        desired.mult(self.maxspeed)
        steer = PVector.sub(desired, self.velocity)
        steer.limit(self.maxforce)
        self.applyForce(steer)

    def display(self):
        theta = self.velocity.heading() + PI/2
        fill(color(98, 199, 119))
        stroke(1)
        strokeWeight(1)
        with pushMatrix():
            translate(self.location.x, self.location.y)
            rotate(theta)
            with beginShape():
                vertex(0, -self.r*2)
                vertex(-self.r, self.r*2)
                vertex(self.r, self.r*2)