text:
WORKDIR=work

usage()
{
	echo "Usage: tests.sh [-w workdir]"
	exit 1
}

# Allow the user to specify an alternate work directory.
while getopts "w:" option; do
	case $option in
		w)
			WORKDIR=$OPTARG
			;;
		*)
			echo
			usage
			;;
	esac
done
shift $((OPTIND - 1))
if [ $# -ne 0 ]; then
	usage
fi

CONFLICTS=$WORKDIR/conflicts
OLD=$WORKDIR/old
NEW=$WORKDIR/current
TEST=$WORKDIR/test

# The various states of the comparison of a file between two trees.
states="equal first second difftype difflinks difffiles"

build_trees()
{
	local i j k

	rm -rf $OLD $NEW $TEST $CONFLICTS
	mkdir -p $OLD/etc $NEW/etc $TEST/etc

	# For an given file, there are three different pair-wise
	# relations between the three threes (old, new, and test): old
	# vs new, old vs test, and new vs test.  Each of these
	# relations takes on one of six different states from the
	# 'compare()' function in etcupdate: equal, onlyfirst,
	# onlysecond, difftype, difflinks, difffiles.  In addition,
	# there are special considerations for considering cases such
	# as a file merge that results in conflicts versus one that
	# does not, special treatment of directories, etc.  The tests
	# below attempt to enumerate the three dimensional test matrix
	# by having the path name use the three different tree states
	# for the parent directories.
	#
	# Note that if the old and new files are identical (so first
	# compare is "equal"), then the second and third comparisons
	# will be the same.
	#
	# Note also that etcupdate only cares about files that are
	# present in at least one of the old or new trees.  Thus, none
	# of the '*/second/second' cases are relevant.

	for i in $states; do
		for j in $states; do
			for k in $states; do
				mkdir -p $OLD/$i/$j/$k $NEW/$i/$j/$k \
				    $TEST/$i/$j/$k
			done
		done
	done

	# /equal/equal/equal: Everything is equal.  Nothing should happen.
	for i in $OLD $NEW $TEST; do
		mkfifo $i/equal/equal/equal/fifo
		echo "foo" > $i/equal/equal/equal/file
		mkdir $i/equal/equal/equal/dir
		ln -s "bar" $i/equal/equal/equal/link
	done

	# /equal/first/first: The file is missing from the test
	# directory.  Nothing should happen.
	for i in $OLD $NEW; do
		mkfifo $i/equal/first/first/fifo
		echo "foo" > $i/equal/first/first/file
		mkdir $i/equal/first/first/dir
		ln -s "bar" $i/equal/first/first/link
	done

	# /equal/difftype/difftype: The local file is a different
	# type.  Nothing should happen.
	for i in $OLD $NEW; do
		mkfifo $i/equal/difftype/difftype/fifo
		mkdir $i/equal/difftype/difftype/fromdir
	done
	echo "bar" > $TEST/equal/difftype/difftype/fifo
	ln -s "test" $TEST/equal/difftype/difftype/fromdir

	# /equal/difflinks/difflinks: The local file is a modified
	# link. Nothing should happen.
	for i in $OLD $NEW; do
		ln -s "foo" $i/equal/difflinks/difflinks/link
	done
	ln -s "bar" $TEST/equal/difflinks/difflinks/link

	# /equal/difffiles/difffiles: The local file is a modified
	# file.  Nothing should happen.
	for i in $OLD $NEW; do
		echo "foo" > $i/equal/difffiles/difffiles/file
	done
	echo "bar" > $TEST/equal/difffiles/difffiles/file

	# /first/equal/second: Remove unmodified files.  The files
	# should all be removed.
	for i in $OLD $TEST; do
		mkfifo $i/first/equal/second/fifo
		echo "foo" > $i/first/equal/second/file
		mkdir $i/first/equal/second/emptydir
		ln -s "bar" $i/first/equal/second/link
		mkdir $i/first/equal/second/fulldir
		echo "foo" > $i/first/equal/second/fulldir/file
	done

	# /first/equal/*: Cannot occur.  If the file is missing from
	# new, then new vs test will always be 'second'.

	# /first/first/equal: Removed files are already removed.
	# Nothing should happen.
	mkfifo $OLD/first/first/equal/fifo
	echo "foo" > $OLD/first/first/equal/file
	mkdir $OLD/first/first/equal/dir
	ln -s "bar" $OLD/first/first/equal/link

	# /first/first/*: Cannot occur.  The files are missing from
	# both new and test.

	# /first/second/*: Cannot happen, if the file is in old for
	# old vs new, it cannot be missing for old vs test.

	# /first/difftype/second: File with different local type
	# removed.  Should generate a warning.
	mkfifo $OLD/first/difftype/second/fifo
	mkdir $TEST/first/difftype/second/fifo

	# /first/difftype/*: Cannot happen since the file is missing
	# from new but present in test.

	# /first/difflinks/second: Modified link removed.  Should
	# generate a warning.
	ln -s "old link" $OLD/first/difflinks/second/link
	ln -s "test link" $TEST/first/difflinks/second/link

	# /first/difflinks/*: Cannot happen since the file is missing
	# from new but present in test.

	# /first/difffiles/second: Modified file removed.  Should
	# generate a warning.
	echo "foo" > $OLD/first/difffiles/second/file
	echo "bar" > $TEST/first/difffiles/second/file

	# /first/difffiles/*: Cannot happen since the file is missing
	# from new but present in test.

	# /second/equal/first: Added a new file that isn't present in
	# test.  The empty directory should be ignored.
	echo "bar" > $NEW/second/equal/first/file
	mkfifo $NEW/second/equal/first/fifo
	ln -s "new" $NEW/second/equal/first/link
	mkdir $NEW/second/equal/first/emptydir
	mkdir $NEW/second/equal/first/fulldir
	echo "foo" > $NEW/second/equal/first/fulldir/file

	# /second/equal/*: Cannot happen since the file is missing
	# from test but present in new.

	# /second/first/*: Cannot happen since the file is missing
	# from old.

	# /second/second/equal: Newly added file is already present in
	# the test directory and identical to the new file.  Nothing
	# should happen.
	for i in $NEW $TEST; do
		mkfifo $i/second/second/equal/fifo
		echo "foo" > $i/second/second/equal/file
		mkdir $i/second/second/equal/dir
		ln -s "bar" $i/second/second/equal/link
	done

	# /second/second/first: Cannot happen.  The file is in dest in
	# the second test, so it can't be missing from the third test.

	# /second/second/second: Cannot happen.  The file is in new in
	# the first test, so it can't be missing from the third test.

	# /second/second/difftype: Newly added file conflicts with
	# existing file in test tree of a different type.  Should
	# generate a warning.
	mkdir $NEW/second/second/difftype/dir
	mkfifo $TEST/second/second/difftype/dir

	# /second/second/difflinks: Newly added link conflicts with
	# existing link in test tree.  Should generate a warning.
	ln -s "new link" $NEW/second/second/difflinks/link
	ln -s "test link" $TEST/second/second/difflinks/link

	# /second/second/difffiles: Newly added file conflicts with
	# existing file in test tree.  Should generate a warning.
	echo "new" > $NEW/second/second/difffiles/file
	echo "test" > $TEST/second/second/difffiles/file

	# /second/difftype/*: Cannot happen since the file is missing
	# from old.

	# /second/difflinks/*: Cannot happen since the file is missing
	# from old.

	# /second/difffiles/*: Cannot happen since the file is missing
	# from old.

	# /difftype/equal/difftype: Unmodified file has changed type.
	# File should be updated to the new file.  In the 'todir' case
	# the directory won't actually be created because it is empty.
	for i in $OLD $TEST; do
		echo "foo" > $i/difftype/equal/difftype/file
		mkdir $i/difftype/equal/difftype/fromdir
		ln -s "old" $i/difftype/equal/difftype/todir
	done
	ln -s "test" $NEW/difftype/equal/difftype/file
	mkfifo $NEW/difftype/equal/difftype/fromdir
	mkdir $NEW/difftype/equal/difftype/todir

	# /difftype/equal/*: Cannot happen.  Since the old file is a
	# difftype from the new file and the test file is identical to
	# the old file, the test file must be a difftype from the new
	# file.

	# /difftype/first/first: A removed file has changed type.
	# This should generate a warning.
	mkfifo $OLD/difftype/first/first/fifo
	mkdir $NEW/difftype/first/first/fifo

	# /difftype/first/*: Cannot happen.  Since the new file exists
	# and the dest file is missing, the last test must be 'first'.

	# /difftype/second/*: Cannot happen.  The old file exists in
	# the first test, so it cannot be missing in the second test.

	# /difftype/difftype/equal: A file has changed type, but the
	# file in the test directory already matches the new file.  Do
	# nothing.
	echo "foo" > $OLD/difftype/difftype/equal/fifo
	mkfifo $OLD/difftype/difftype/equal/file
	for i in $NEW $TEST; do
		mkfifo $i/difftype/difftype/equal/fifo
		echo "bar" > $i/difftype/difftype/equal/file
	done

	# /difftype/difftype/first: Cannot happen.  The dest file
	# exists in the second test.

	# /difftype/difftype/second: Cannot happen.  The new file
	# exists in the first test.

	# /difftype/difftype/difftype: All three files (old, new, and
	# test) are different types from each other.  This should
	# generate a warning.
	mkfifo $OLD/difftype/difftype/difftype/one
	mkdir $NEW/difftype/difftype/difftype/one
	echo "foo" > $TEST/difftype/difftype/difftype/one
	mkdir $OLD/difftype/difftype/difftype/two
	echo "baz" > $NEW/difftype/difftype/difftype/two
	ln -s "bar" $TEST/difftype/difftype/difftype/two

	# /difftype/difftype/difflinks: A file has changed from a
	# non-link to a link in both the new and test trees, but the
	# target of the new and test links differ.  This should
	# generate a new link conflict.
	mkfifo $OLD/difftype/difftype/difflinks/link
	ln -s "new" $NEW/difftype/difftype/difflinks/link
	ln -s "test" $TEST/difftype/difftype/difflinks/link

	# /difftype/difftype/difffile: A file has changed from a
	# non-regular file to a regular file in both the new and test
	# trees, but the contents in the new and test files differ.
	# This should generate a new file conflict.
	ln -s "old" $OLD/difftype/difftype/difffiles/file
	echo "foo" > $NEW/difftype/difftype/difffiles/file
	echo "bar" > $TEST/difftype/difftype/difffiles/file

	# /difflinks/equal/difflinks: An unmodified symlink has
	# changed.  The link should be updated.
	for i in $OLD $TEST; do
		ln -s "old" $i/difflinks/equal/difflinks/link
	done
	ln -s "new" $NEW/difflinks/equal/difflinks/link

	# /difflinks/equal/*: Cannot happen.  Since old is identical
	# to test, the third test must be 'difflinks'.

	# /difflinks/first/first: A modified link is missing in the
	# test tree.  This should generate a warning.
	ln -s "old" $OLD/difflinks/first/first/link
	ln -s "new" $NEW/difflinks/first/first/link

	# /difflinks/first/*: Cannot happen.  Since the test file is
	# missing in the second test, it must be missing in the third
	# test.

	# /difflinks/second/*: Cannot happen.  The old link is present
	# in the first test, so it cannot be missing in the second
	# test.

	# /difflinks/difftype/difftype: An updated link has been
	# changed to a different file type in the test tree.  This
	# should generate a warning.
	ln -s "old" $OLD/difflinks/difftype/difftype/link
	ln -s "new" $NEW/difflinks/difftype/difftype/link
	echo "test" > $TEST/difflinks/difftype/difftype/link

	# /difflinks/difftype/*: Cannot happen.  The old and new files
	# are both links and the test file is not a link, so the third
	# test must be 'difftype'.

	# /difflinks/difflinks/equal: An updated link has already been
	# updated to the new target in the test tree.  Nothing should
	# happen.
	ln -s "old" $OLD/difflinks/difflinks/equal/link
	for i in $NEW $TEST; do
		ln -s "new" $i/difflinks/difflinks/equal/link
	done

	# /difflinks/difflinks/difflinks: An updated link has been
	# modified in the test tree and doesn't match either the old
	# or new links.  This should generate a warning.
	ln -s "old" $OLD/difflinks/difflinks/difflinks/link
	ln -s "new" $NEW/difflinks/difflinks/difflinks/link
	ln -s "test" $TEST/difflinks/difflinks/difflinks/link

	# /difflinks/difflinks/*: Cannot happen.  All three files are
	# links from the first two tests, so the third test can only
	# be 'equal' or 'difflink'.

	# /difflinks/difffiles/*: Cannot happen.  The old file is a
	# link in the first test, so it cannot be a regular file in
	# the second.

	# /difffiles/equal/difffiles: An unmodified file has been
	# changed in new tree.  The file should be updated to the new
	# version.
	for i in $OLD $TEST; do
		echo "foo" > $i/difffiles/equal/difffiles/file
	done
	echo "bar" > $NEW/difffiles/equal/difffiles/file

	# /difffiles/equal/*: Cannot happen.  Since the old file is
	# identical to the test file, the third test must be
	# 'difffiles'.

	# /difffiles/first/first: A removed file has been changed in
	# the new tree.  This should generate a warning.
	echo "foo" > $OLD/difffiles/first/first/file
	echo "bar" > $NEW/difffiles/first/first/file

	# /difffiles/first/*: Cannot happen.  The new file is a
	# regular file from the first test and the test file is
	# missing in the second test, so the third test must be
	# 'first'.

	# /difffiles/second/*: Cannot happen.  The old file is present
	# in the first test, so it must be present in the second test.

	# /difffiles/difftype/difftype: An updated regular file has
	# been changed to a different file type in the test tree.
	# This should generate a warning.
	echo "old" > $OLD/difffiles/difftype/difftype/file
	echo "new" > $NEW/difffiles/difftype/difftype/file
	mkfifo $TEST/difffiles/difftype/difftype/file

	# /difffiles/difftype/*: Cannot happen.  The new file is known
	# to be a regular file from the first test, and the test file
	# is known to exist as a different file type from the second
	# test.  The third test must be 'difftype'.

	# /difffiles/difflink/*: Cannot happen.  The old file is known
	# to be a regular file from the first test, so it cannot be a
	# link in the second test.

	# /difffiles/difffiles/equal: An updated regular file has
	# already been updated to match the new file in the test tree.
	# Nothing should happen.
	echo "foo" > $OLD/difffiles/difffiles/equal/file
	for i in $NEW $TEST; do
		echo "bar" > $i/difffiles/difffiles/equal/file
	done

	# /difffiles/difffiles/difffiles: A modified regular file was
	# updated in the new tree.  The changes should be merged into
	# to the new file if possible.  If the merge fails, a conflict
	# should be generated.
	cat > $OLD/difffiles/difffiles/difffiles/simple <<EOF
this is an old line

EOF
	cat > $NEW/difffiles/difffiles/difffiles/simple <<EOF
this is a new line

EOF
	cat > $TEST/difffiles/difffiles/difffiles/simple <<EOF
this is an old line

this is a local line
EOF
	cat > $OLD/difffiles/difffiles/difffiles/conflict <<EOF
this is an old file
EOF
	cat > $NEW/difffiles/difffiles/difffiles/conflict <<EOF
this is a new file
EOF
	cat > $TEST/difffiles/difffiles/difffiles/conflict <<EOF
this is a test file
EOF

	# /difffiles/difffiles/*: Cannot happen.  From the first three
	# tests, all three files are regular files.  The test file can
	# either be identical to the new file ('equal') or not
	# ('difffiles').

	## Tests for adding directories
	mkdir -p $OLD/adddir $NEW/adddir $TEST/adddir

	# /adddir/conflict: Add a new file in a directory that already
	# exists as a file.  This should generate two warnings.
	mkdir $NEW/adddir/conflict
	touch $NEW/adddir/conflict/newfile
	touch $TEST/adddir/conflict

	# /adddir/partial: Add a new file in a directory.  The
	# directory already exists in the test tree and contains a
	# different local file.  The new file from the new tree should
	# be added.
	for i in $NEW $TEST; do
		mkdir $i/adddir/partial
	done
	echo "foo" > $NEW/adddir/partial/file
	mkfifo $TEST/adddir/partial/fifo

	## Tests for removing directories
	mkdir -p $OLD/rmdir $NEW/rmdir $TEST/rmdir

	# /rmdir/extra: Do not remove a directory with an extra local file.
	# This should generate a warning.
	for i in $OLD $TEST; do
		mkdir $i/rmdir/extra
	done
	echo "foo" > $TEST/rmdir/extra/localfile.txt

	# /rmdir/conflict: Do not remove a directory with a conflicted
	# remove file.  This should generate a warning.
	for i in $OLD $TEST; do
		mkdir $i/rmdir/conflict
	done
	mkfifo $OLD/rmdir/conflict/difftype
	mkdir $TEST/rmdir/conflict/difftype

	# /rmdir/partial: Remove a complete hierarchy when part of the
	# tree has already been removed locally.
	for i in $OLD $TEST; do
		mkdir -p $i/rmdir/partial/subdir
		mkfifo $i/rmdir/partial/subdir/fifo
	done
	echo "foo" > $OLD/rmdir/partial/subdir/file

	## Tests for converting files to directories and vice versa
	for i in $OLD $NEW $TEST; do
		for j in already old fromdir todir; do
			mkdir -p $i/dirchange/$j
		done
	done

	# /dirchange/already/fromdir: Convert a directory tree to a
	# file without conflicts where the test tree already has the
	# new file.  Nothing should happen.
	mkdir $OLD/dirchange/already/fromdir
	echo "blah" > $OLD/dirchange/already/fromdir/somefile
	for i in $NEW $TEST; do
		echo "bar" > $i/dirchange/already/fromdir
	done

	# /dirchange/already/todir: Convert an unmodified file to a
	# directory tree where the test tree already has the new
	# tree.  Nothing should happen.
	echo "baz" > $OLD/dirchange/already/todir
	for i in $NEW $TEST; do
		mkdir $i/dirchange/already/todir
		echo "blah" > $i/dirchange/already/todir/somefile
	done

	# /dirchange/old/fromdir: Convert a directory tree to a file.
	# The old files are unmodified and should be changed to the new tree.
	for i in $OLD $TEST; do
		mkdir $i/dirchange/old/fromdir
		echo "blah" > $i/dirchange/old/fromdir/somefile
	done
	echo "bar" > $NEW/dirchange/old/fromdir

	# /dirchange/old/todir: Convert a file to a directory tree.
	# The old file is unmodified and should be changed to the new
	# tree.
	for i in $OLD $TEST; do
		echo "foo" > $i/dirchange/old/todir
	done
	mkdir $NEW/dirchange/old/todir
	echo "bar" > $NEW/dirchange/old/todir/file

	# /dirchange/fromdir/extradir: Convert a directory tree to a
	# file.  The test tree includes an extra file in the directory
	# that is not present in the old tree.  This should generate a
	# warning.
	for i in $OLD $TEST; do
		mkdir $i/dirchange/fromdir/extradir
		echo "foo" > $i/dirchange/fromdir/extradir/file
	done
	mkfifo $TEST/dirchange/fromdir/extradir/fifo
	ln -s "bar" $NEW/dirchange/fromdir/extradir

	# /dirchange/fromdir/conflict: Convert a directory tree to a
	# file.  The test tree includes a local change that generates
	# a warning and prevents the removal of the directory.
	for i in $OLD $TEST; do
		mkdir $i/dirchange/fromdir/conflict
	done
	echo "foo" > $OLD/dirchange/fromdir/conflict/somefile
	echo "bar" > $TEST/dirchange/fromdir/conflict/somefile
	mkfifo $NEW/dirchange/fromdir/conflict

	# /dirchange/todir/difffile: Convert a file to a directory
	# tree.  The test tree has a locally modified version of the
	# file so that the conversion fails with a warning.
	echo "foo" > $OLD/dirchange/todir/difffile
	mkdir $NEW/dirchange/todir/difffile
	echo "baz" > $NEW/dirchange/todir/difffile/file
	echo "bar" > $TEST/dirchange/todir/difffile

	# /dirchange/todir/difftype: Similar to the previous test, but
	# the conflict is due to a change in the file type.
	echo "foo" > $OLD/dirchange/todir/difftype
	mkdir $NEW/dirchange/todir/difftype
	echo "baz" > $NEW/dirchange/todir/difftype/file
	mkfifo $TEST/dirchange/todir/difftype

	## Tests for post-install actions

	# - Adding /etc/master.passwd should cause pwd_mkdb to be run
	echo "foo:*:16000:100::0:0:& user:/home/foo:/bin/tcsh" > \
	    $NEW/etc/master.passwd

	# - Verify that updating an unmodified /etc/login.conf builds
	# /etc/login.conf.db.
	cat > $OLD/etc/login.conf <<EOF
default:\\
	:passwd_format=md5:
EOF
	cat > $NEW/etc/login.conf <<EOF
default:\\
	:passwd_format=md5:\\
	:copyright=/etc/COPYRIGHT
EOF
	cp $OLD/etc/login.conf $TEST/etc/login.conf

	# - Verify that a merge without conflicts to /etc/mail/aliases
	# will trigger a newaliases run request.
	mkdir -p $OLD/etc/mail $NEW/etc/mail $TEST/etc/mail
	cat > $OLD/etc/mail/aliases <<EOF
# root: me@my.domain

# Basic system aliases -- these MUST be present
MAILER-DAEMON: postmaster
postmaster: root
EOF
	cat > $NEW/etc/mail/aliases <<EOF
# root: me@my.domain

# Basic system aliases -- these MUST be present
MAILER-DAEMON: postmaster
postmaster: root

# General redirections for pseudo accounts
_dhcp:  root
_pflogd: root
EOF
	cat > $TEST/etc/mail/aliases <<EOF
root: someone@example.com

# Basic system aliases -- these MUST be present
MAILER-DAEMON: postmaster
postmaster: root
EOF
}

# $1 - relative path to file that should be missing from TEST
missing()
{
	if [ -e $TEST/$1 -o -L $TEST/$1 ]; then
		echo "File $1 should be missing"
	fi
}

# $1 - relative path to file that should be present in TEST
present()
{
	if ! [ -e $TEST/$1 -o -L $TEST/$1 ]; then
		echo "File $1 should be present"
	fi
}

# $1 - relative path to file that should be a fifo in TEST
fifo()
{
	if ! [ -p $TEST/$1 ]; then
		echo "File $1 should be a FIFO"
	fi
}

# $1 - relative path to file that should be a directory in TEST
dir()
{
	if ! [ -d $TEST/$1 ]; then
		echo "File $1 should be a directory"
	fi
}

# $1 - relative path to file that should be a symlink in TEST
# $2 - optional value of the link
link()
{
	local val

	if ! [ -L $TEST/$1 ]; then
		echo "File $1 should be a link"
	elif [ $# -gt 1 ]; then
		val=`readlink $TEST/$1`
		if [ "$val" != "$2" ]; then
			echo "Link $1 should link to \"$2\""
		fi
	fi
}

# $1 - relative path to regular file that should be present in TEST
# $2 - optional string that should match file contents
# $3 - optional MD5 of the flie contents, overrides $2 if present
file()
{
	local contents sum

	if ! [ -f $TEST/$1 ]; then
		echo "File $1 should be a regular file"
	elif [ $# -eq 2 ]; then
		contents=`cat $TEST/$1`
		if [ "$contents" != "$2" ]; then
			echo "File $1 has wrong contents"
		fi
	elif [ $# -eq 3 ]; then
		sum=`md5 -q $TEST/$1`
		if [ "$sum" != "$3" ]; then
			echo "File $1 has wrong contents"
		fi
	fi
}

# $1 - relative path to a regular file that should have a conflict
# $2 - optional MD5 of the conflict file contents
conflict()
{
	local sum

	if ! [ -f $CONFLICTS/$1 ]; then
		echo "File $1 missing conflict"
	elif [ $# -gt 1 ]; then
		sum=`md5 -q $CONFLICTS/$1`
		if [ "$sum" != "$2" ]; then
			echo "Conflict $1 has wrong contents"
		fi
	fi
}

check_trees()
{

	echo "Checking tree for correct results:"

	## /equal/equal/equal:
	fifo /equal/equal/equal/fifo
	file /equal/equal/equal/file "foo"
	dir /equal/equal/equal/dir
	link /equal/equal/equal/link "bar"

	## /equal/first/first:
	missing /equal/first/first/fifo
	missing /equal/first/first/file
	missing /equal/first/first/dir
	missing /equal/first/first/link

	## /equal/difftype/difftype:
	file /equal/difftype/difftype/fifo "bar"
	link /equal/difftype/difftype/fromdir "test"

	## /equal/difflinks/difflinks:
	link /equal/difflinks/difflinks/link "bar"

	## /equal/difffiles/difffiles:
	file /equal/difffiles/difffiles/file "bar"

	## /first/equal/second:
	missing /first/equal/second/fifo
	missing /first/equal/second/file
	missing /first/equal/second/emptydir
	missing /first/equal/second/link
	missing /first/equal/second/fulldir

	## /first/first/equal:
	missing /first/first/equal/fifo
	missing /first/first/equal/file
	missing /first/first/equal/dir
	missing /first/first/equal/link

	## /first/difftype/second:
	present /first/difftype/second/fifo

	## /first/difflinks/second:
	link /first/difflinks/second/link "test link"

	## /first/difffiles/second:
	file /first/difffiles/second/file "bar"

	## /second/equal/first:
	file /second/equal/first/file "bar"
	fifo /second/equal/first/fifo
	link /second/equal/first/link "new"
	missing /second/equal/first/emptydir
	file /second/equal/first/fulldir/file "foo"

	## /second/second/equal:
	fifo /second/second/equal/fifo
	file /second/second/equal/file "foo"
	dir /second/second/equal/dir
	link /second/second/equal/link "bar"

	## /second/second/difftype:
	fifo /second/second/difftype/dir

	## /second/second/difflinks:
	link /second/second/difflinks/link "test link"

	## /second/second/difffiles:
	file /second/second/difffiles/file "test"
	conflict /second/second/difffiles/file 4f2ee8620a251fd53f06bb6112eb6ffa

	## /difftype/equal/difftype:
	link /difftype/equal/difftype/file "test"
	fifo /difftype/equal/difftype/fromdir
	missing /difftype/equal/difftype/todir

	## /difftype/first/first:
	missing /difftype/first/first/fifo

	## /difftype/difftype/equal:
	fifo /difftype/difftype/equal/fifo
	file /difftype/difftype/equal/file "bar"

	## /difftype/difftype/difftype:
	file /difftype/difftype/difftype/one "foo"
	link /difftype/difftype/difftype/two "bar"

	## /difftype/difftype/difflinks:
	link /difftype/difftype/difflinks/link "test"

	## /difftype/difftype/difffile:
	conflict /difftype/difftype/difffiles/file \
	    117f2bcd1f6491f6044e79e5a57a9229

	## /difflinks/equal/difflinks:
	link /difflinks/equal/difflinks/link "new"

	## /difflinks/first/first:
	missing /difflinks/first/first/link

	## /difflinks/difftype/difftype:
	file /difflinks/difftype/difftype/link "test"

	## /difflinks/difflinks/equal:
	link /difflinks/difflinks/equal/link "new"

	## /difflinks/difflinks/difflinks:
	link /difflinks/difflinks/difflinks/link "test"

	## /difffiles/equal/difffiles:
	file /difffiles/equal/difffiles/file "bar"

	## /difffiles/first/first:
	missing /difffiles/first/first/file

	## /difffiles/difftype/difftype:
	fifo /difffiles/difftype/difftype/file

	## /difffiles/difffiles/equal:
	file /difffiles/difffiles/equal/file "bar"

	## /difffiles/difffiles/difffiles:
	file /difffiles/difffiles/difffiles/simple "" \
	    cabc7e5e80b0946d79edd555e9648486
	file /difffiles/difffiles/difffiles/conflict "this is a test file"
	conflict /difffiles/difffiles/difffiles/conflict \
	    8261cfdd89280c4a6c26e4ac86541fe9

	## /adddir/conflict:
	file /adddir/conflict

	## /adddir/partial:
	file /adddir/partial/file "foo"
	fifo /adddir/partial/fifo

	## /rmdir/extra:
	dir /rmdir/extra
	file /rmdir/extra/localfile.txt "foo"

	## /rmdir/conflict:
	dir /rmdir/conflict/difftype
	present /rmdir/conflict

	## /rmdir/partial:
	missing /rmdir/partial

	## /dirchange/already/fromdir:
	file /dirchange/already/fromdir "bar"

	## /dirchange/already/todir:
	file /dirchange/already/todir/somefile "blah"

	## /dirchange/old/fromdir:
	file /dirchange/old/fromdir "bar"

	## /dirchange/old/todir
	file /dirchange/old/todir/file "bar"

	## /dirchange/fromdir/extradir:
	missing /dirchange/fromdir/extradir/file
	fifo /dirchange/fromdir/extradir/fifo

	## /dirchange/fromdir/conflict:
	file /dirchange/fromdir/conflict/somefile "bar"

	## /dirchange/todir/difffile:
	file /dirchange/todir/difffile "bar"

	## /dirchange/todir/difftype:
	fifo /dirchange/todir/difftype

	## Tests for post-install actions
	file /etc/master.passwd
	file /etc/passwd
	file /etc/pwd.db
	file /etc/spwd.db
	file /etc/login.conf "" 7774a0f9a3a372c7c109c32fd31c4b6b
	file /etc/login.conf.db
	file /etc/mail/aliases "" 7d598f89ec040ab56af54011bdb83337
}

if [ `id -u` -ne 0 ]; then
	echo "must be root"
fi

if [ -r /etc/etcupdate.conf ]; then
	echo "WARNING: /etc/etcupdate.conf settings may break some tests."
fi

build_trees

etcupdate -nr -d $WORKDIR -D $TEST > $WORKDIR/testn.out

cat > $WORKDIR/correct.out <<EOF
  D /dirchange/fromdir/extradir/file
  D /dirchange/old/fromdir/somefile
  D /first/equal/second/fifo
  D /first/equal/second/file
  D /first/equal/second/fulldir/file
  D /first/equal/second/link
  D /rmdir/partial/subdir/fifo
  D /rmdir/partial/subdir
  D /rmdir/partial
  D /first/equal/second/fulldir
  D /first/equal/second/emptydir
  C /difffiles/difffiles/difffiles/conflict
  M /difffiles/difffiles/difffiles/simple
  U /difffiles/equal/difffiles/file
  U /difflinks/equal/difflinks/link
  C /difftype/difftype/difffiles/file
  U /difftype/equal/difftype/file
  U /difftype/equal/difftype/fromdir
  D /difftype/equal/difftype/todir
  U /dirchange/old/fromdir
  U /dirchange/old/todir
  U /etc/login.conf
  M /etc/mail/aliases
  A /adddir/partial/file
  A /dirchange/old/todir/file
  A /etc/master.passwd
  A /second/equal/first/fifo
  A /second/equal/first/file
  A /second/equal/first/fulldir/file
  A /second/equal/first/link
  C /second/second/difffiles/file
Warnings:
  Modified regular file remains: /dirchange/fromdir/conflict/somefile
  Modified regular file remains: /first/difffiles/second/file
  Modified symbolic link remains: /first/difflinks/second/link
  Modified directory remains: /first/difftype/second/fifo
  Modified directory remains: /rmdir/conflict/difftype
  Non-empty directory remains: /rmdir/extra
  Non-empty directory remains: /rmdir/conflict
  Modified mismatch: /difffiles/difftype/difftype/file (regular file vs fifo file)
  Removed file changed: /difffiles/first/first/file
  Modified link changed: /difflinks/difflinks/difflinks/link ("old" became "new")
  Modified mismatch: /difflinks/difftype/difftype/link (symbolic link vs regular file)
  Removed link changed: /difflinks/first/first/link ("old" became "new")
  New link conflict: /difftype/difftype/difflinks/link ("new" vs "test")
  Modified regular file changed: /difftype/difftype/difftype/one (fifo file became directory)
  Modified symbolic link changed: /difftype/difftype/difftype/two (directory became regular file)
  Remove mismatch: /difftype/first/first/fifo (fifo file became directory)
  Modified directory changed: /dirchange/fromdir/conflict (directory became fifo file)
  Modified directory changed: /dirchange/fromdir/extradir (directory became symbolic link)
  Modified regular file changed: /dirchange/todir/difffile (regular file became directory)
  Modified fifo file changed: /dirchange/todir/difftype (regular file became directory)
  New file mismatch: /adddir/conflict (directory vs regular file)
  Directory mismatch: $TEST/adddir/conflict (regular file)
  Directory mismatch: $TEST/dirchange/todir/difffile (regular file)
  Directory mismatch: $TEST/dirchange/todir/difftype (fifo file)
  New link conflict: /second/second/difflinks/link ("new link" vs "test link")
  New file mismatch: /second/second/difftype/dir (directory vs fifo file)
  Needs update: /etc/mail/aliases.db (requires manual update via newaliases(1))
EOF

echo "Differences for -n:"
diff -u -L "correct" $WORKDIR/correct.out -L "test" $WORKDIR/testn.out

etcupdate -r -d $WORKDIR -D $TEST > $WORKDIR/test.out

echo "Differences for real:"
diff -u -L "correct" $WORKDIR/correct.out -L "test" $WORKDIR/test.out

check_trees


text:
Copyright 2008-2016 João Cardoso
Sushi is distributed under the terms of the GNU General Public License (or the Lesser GPL).
This file is part of Sushi.

Sushi is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Sushi is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Sushi. If not, see <http://www.gnu.org/licenses/>.
--]]

local CallHandler = SushiCallHandler
local Group = MakeSushi(2, 'Frame', 'Group', nil, nil, CallHandler)
if not Group then
	return
end

--[[ Constructor ]]--

function Group:OnCreate()
	self:SetScript('OnSizeChanged', self.CheckLimit)
	self:SetScript('OnHide', self.ReleaseChildren)
	self:SetScript('OnShow', self.UpdateChildren)
	self.children = {}
	self.layout = {}
end

function Group:OnAcquire()
	CallHandler.OnAcquire(self)
	self:SetOrientation('VERTICAL')
	self:SetResizing('VERTICAL')
	self:SetSize(200, 200)
end

function Group:OnRelease()
	self:ReleaseChildren()
	self:SetCall('UpdateChildren', nil)
	CallHandler.OnRelease(self)
end

--[[ Children Management ]]--

function Group:SetChildren (method)
	self:SetCall('UpdateChildren', method)
	self:UpdateChildren()
end

function Group:UpdateChildren()
	if self:CanLayout() then
		self:ReleaseChildren()
		self:FireCall('UpdateChildren')
		self:FireCall('OnUpdate')
		self:Layout()
	end
end

function Group:ReleaseChildren()
	for child in self:IterateChildren() do
		if child.Release then
			child.top, child.bottom, child.left, child.right = nil
			child:Release()
		end
	end

	wipe(self.children)
	wipe(self.layout)
end

function Group:IterateChildren()
	return pairs(self.children)
end

--[[ Child Creation ]]--

function Group:CreateChild (name)
	local class = _G['Sushi' .. name]
	if not class then
		error('Sushi class "' .. name .. '" was not found.')
	end

	local child = class(self)
	if child.SetCall then
		child:SetCall('OnUpdate', self.OnChildUpdate)
		child:SetCall('OnInput', self.OnChildInput)
	end

	return self:BindChild(child)
end

function Group:BindChild (child)
	if not self.children[child] then
		self.children[child] = true
		tinsert(self.layout, child)
		child:SetParent(self)
	end
	return child
end

function Group:AddBreak ()
	tinsert(self.layout, 1)
end

--[[ Children Events ]]--

function Group:OnChildUpdate ()
	local parent = self:GetParent()
	if parent and parent.UpdateChildren then
		parent:UpdateChildren()
	end
end

function Group:OnChildInput (...)
	local parent = self:GetParent()
	if parent and parent.FireCall then
		parent:FireCall('OnInput', self, ...)
	end
end

--[[ Orientation ]]--

function Group:SetOrientation (orient)
	self.horizontal = orient == 'HORIZONTAL'
	self.orient = orient
	self:UpdateLayout()
end

function Group:GetOrientation ()
	return self.orient
end

function Group:Orient (a, b)
	if self.horizontal then
		return a,b
	end
	return b,a
end

--[[ Resizing ]]--

function Group:SetResizing (resize)
	self.resize = resize
	self:UpdateLayout()
end

function Group:GetResizing ()
	return self.resize
end

function Group:CheckLimit()
	if self.limit ~= self:GetLimit() then
		self:UpdateLayout()
	elseif self:CanLayout() then
		for child in self:IterateChildren() do
			if child.FireCall then
				child:FireCall('OnParentResize')
			end
		end
	end
end

function Group:GetLimit ()
	return self.resize ~= self.orient and self:Orient(self:GetSize())
end

--[[ Layout ]]--

function Group:UpdateLayout ()
	if self:CanLayout() then
		self:Layout()
	end
end

function Group:Layout ()
	local x, y = 0, 0
	local line = 0

	local function breakLine()
		y = y + line
		line, x = 0, 0
	end

	self.limit = self:GetLimit()
	for i, child in ipairs(self.layout) do
		if child ~= 1 then
			local top, left = child.top or 0, child.left or 0
			local bottom, right = child.bottom or 0, child.right or 0
			local width, height = child:GetSize()

			width, height = self:Orient(width + left + right, height + top + bottom)
			top, left = self:Orient(top, left)

			if self.limit and (x + width) > self.limit then
	 			breakLine()
	 		end

			self:LayoutChild(child, self:Orient(x + left, y + top))
			line = max(line, height)
			x = x + width
		else
			breakLine()
		end
	end

	x, y = self:Orient(x, y + line)
	if self.resize == 'HORIZONTAL' then
		self:SetWidth(x)
	elseif self.resize == 'VERTICAL' then
		self:SetHeight(y)
	end
end

function Group:LayoutChild (child, x, y)
	child:SetPoint('TOPLEFT', x, - y)
end

function Group:CanLayout ()
	return self:GetCall('UpdateChildren') and self:IsVisible()
end

--[[ Aliases ]]--

Group.Create = Group.CreateChild
Group.Update = Group.UpdateChildren

Group.SetContent = Group.SetChildren
Group.SetResize = Group.SetResizing

Group.CreateBreak = Group.AddBreak
Group.LineBreak = Group.AddBreak
Group.Break = Group.AddBreak

Group.AppendChild = Group.BindChild
Group.AddChild = Group.BindChild
Group.Append = Group.BindChild
Group.Add = Group.BindChild
Group.Bind = Group.BindChild

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using Moonshine.Data.Interfaces;
using Moonshine.Data.Interfaces.Results;

namespace Moonshine.Data.Common.Results
{
    public class ListGetDataOperationResult<T> : IGetDataOperationResult<T> where T : IBaseObject
    {
        public ListGetDataOperationResult(List<T> result)
        {
            Success = true;
            Result = result;
        }

        public ListGetDataOperationResult(Exception exception)
        {
            Exception = exception;
        }

        public bool Success { get; private set; }
        public Exception Exception { get; private set; }
        public List<T> Result { get; private set; }
    }
}


text:
App.SinglePostRoute = Em.Route.extend({
  templateName: '_single_post',

  model: function(params) {
    return this.store.findQuery('post', {
      blog_name: params.blog_name,
      id: params.post_ident
    });
  }
});


text:
from pudzu.charts import *
from statistics import mean
from colorsys import rgb_to_hls, hls_to_rgb

flags = pd.read_csv("datasets/countries.csv").filter_rows("organisations >> un").update_columns(country=lambda s: s.split("|")[0]).set_index("country").flag

W,H = 80, 40

bg = "#BBBBBBFF"

ratios = {}
actual_ratios = {}
for c,f in flags.items():
    flag = Image.from_url_with_cache(f)
    ar = flag.width / flag.height + 0.000001
    ratios.setdefault(round(ar, 1), set()).add(c)
    actual_ratios.setdefault(ar, set()).add(c)

df = pd.DataFrame([len(ratios.get(ar/10, [])) for ar in range(1, 26)], index=range(1, 26))

def clabel(c,r,v, x, y):
    countries = sorted(ratios.get(df.index[r]/10, []), reverse=True)
    flagimgs = [Rectangle((W,H),None).place(Image.from_url_with_cache(flags[c]).to_rgba().resize_fixed_aspect(width=W-2, height=H-2).pad(1, bg)) for c in countries]
    bar = Image.from_column(flagimgs) if flagimgs else None
    return bar

chart = bar_chart(df, W, H*87, spacing=5,
                  ymax=87, grid_interval=5, colors=[bg],
                  clabels={ BarChartLabelPosition.INSIDE : clabel },
                  rlabels = lambda v: str(df.index[v]/10),
                  xlabel=Image.from_text("flag aspect ratio (rounded to nearest 0.1)", sans(36, bold=False), padding=20),
                  label_font=sans(24),
)

title = Image.from_text("Flags of the world by aspect ratio".upper(), verdana(92, bold=True), padding=(0,0,0,2))
subtitle = Image.from_text("195 UN member and observer states, based on flag images on Wikipedia", verdana(60, italics=True), padding=(0,0,0,20))
img = Image.from_column([title, subtitle, chart], bg="white", padding=5).pad(10, "white")
img.place(Image.from_text("/u/Udzu", sans(24), fg="grey", bg="white", padding=5).pad((1,1,0,0), "grey"), align=1, padding=5, copy=False)
img.save("output/flagsaspect.png")


text:
Matches the specified regex against the segment.

```csharp
public Match Match(Regex regex)
```

| parameter | description |
| --- | --- |
| regex | The regex to match. |

## Return Value

The result of calling `regex.Match` on the segment.

## See Also

* struct [StringSegment](../StringSegment.md)
* namespace [Faithlife.Utility](../../Faithlife.Utility.md)

<!-- DO NOT EDIT: generated by xmldocmd for Faithlife.Utility.dll -->


text:
package fi.kela.kanta.exceptions;

public class PurkuException extends Exception {

    private static final long serialVersionUID = 412351L;

    public PurkuException() {
        super();
    }

    public PurkuException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }

    public PurkuException(String message, Throwable cause) {
        super(message, cause);
    }

    public PurkuException(String message) {
        super(message);
    }

    public PurkuException(Throwable cause) {
        super(cause);
    }
}


text:
using CsvEditSharp.ViewModels;
using System.Windows;

namespace CsvEditSharp.Views
{
    /// <summary>
    /// CsvConfigFileSettingDialog.xaml の相互作用ロジック
    /// </summary>
    public partial class GenerateConfigDialog : Window
    {
        public GenerateConfigDialog()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = true;
        }
    }
}


text:
import {convertObjectWithTemplates, processResponse} from '../utils'

function httpPutFactory (url, body = {}) {
  function httpPut ({http, path, resolveArg}) {
    return processResponse(http.put(resolveArg.value(url), convertObjectWithTemplates(body, resolveArg)), path)
  }

  return httpPut
}

export default httpPutFactory


text:
exports.up = knex => knex.schema
    .createTable('categories', (table) => {
        table.increments('id').primary()
        table.string('name')
    })

exports.down = knex => knex.schema.dropTable('categories')


text:
#ifndef ANDROID_AUDIO_RESAMPLER_SINC_H
#define ANDROID_AUDIO_RESAMPLER_SINC_H

#include <stdint.h>
#include <sys/types.h>
#include <android/log.h>

#include <media/AudioResampler.h>

namespace android {

typedef const int32_t * (*readCoefficientsFn)(bool upDownSample);
typedef int32_t (*readResampleFirNumCoeffFn)();
typedef int32_t (*readResampleFirLerpIntBitsFn)();

// ----------------------------------------------------------------------------

class AudioResamplerSinc : public AudioResampler {
public:
    AudioResamplerSinc(int inChannelCount, int32_t sampleRate,
            src_quality quality = HIGH_QUALITY);

    virtual ~AudioResamplerSinc();

    virtual size_t resample(int32_t* out, size_t outFrameCount,
            AudioBufferProvider* provider);
private:
    void init();

    virtual void setVolume(float left, float right);

    template<int CHANNELS>
    size_t resample(int32_t* out, size_t outFrameCount,
            AudioBufferProvider* provider);

    template<int CHANNELS>
    inline void filterCoefficient(
            int32_t* out, uint32_t phase, const int16_t *samples, uint32_t vRL);

    template<int CHANNELS>
    inline void interpolate(
            int32_t& l, int32_t& r,
            const int32_t* coefs, size_t offset,
            int32_t lerp, const int16_t* samples);

    template<int CHANNELS>
    inline void read(int16_t*& impulse, uint32_t& phaseFraction,
            const int16_t* in, size_t inputIndex);

    int16_t *mState;
    int16_t *mImpulse;
    int16_t *mRingFull;
    int32_t mVolumeSIMD[2];

    const int32_t * mFirCoefs;
    static const uint32_t mFirCoefsDown[];
    static const uint32_t mFirCoefsUp[];

    // ----------------------------------------------------------------------------
    static const int32_t RESAMPLE_FIR_NUM_COEF       = 8;
    static const int32_t RESAMPLE_FIR_LERP_INT_BITS  = 7;

    struct Constants {
        int coefsBits;
        int cShift;
        uint32_t cMask;
        int pShift;
        uint32_t pMask;
        // number of zero-crossing on each side
        unsigned int halfNumCoefs;
    };

    static Constants highQualityConstants;
    static Constants veryHighQualityConstants;
    const Constants *mConstants;    // points to appropriate set of coefficient parameters

    static void init_routine();
};

// ----------------------------------------------------------------------------
} // namespace android

#endif /*ANDROID_AUDIO_RESAMPLER_SINC_H*/


text:
import os
from configurations.values import Value, ListValue, DictValue, URLValue

class JurisdictionConfig(object):
    ###############################
    # These settings are required #
    ###############################

    OCD_CITY_COUNCIL_NAME = Value('Toronto City Council')
    CITY_COUNCIL_NAME = Value('Toronto City Council')
    OCD_JURISDICTION_ID = Value('ocd-jurisdiction/country:ca/csd:3520005/legislature')
    LEGISLATIVE_SESSIONS = ListValue(None) # the last one in this list should be the current legislative session
    CITY_NAME = Value('Toronto')
    CITY_NAME_SHORT = Value(None)

    # TODO: Yuck.
    # See: https://github.com/jazzband/django-configurations/issues/149
    @classmethod
    def setup(cls):
        default_city_short = cls.CITY_NAME_SHORT.value
        super().setup()
        if default_city_short == cls.CITY_NAME_SHORT:
            cls.CITY_NAME_SHORT = cls.CITY_NAME

    city_vocab = {
        'MUNICIPAL_DISTRICT': 'Ward',
        'SOURCE': 'City of Toronto',
        'COUNCIL_MEMBER': 'Councillor',
        'COUNCIL_MEMBERS': 'Councillors',
        'EVENTS': 'Meetings',
    }

    BOUNDARY_API_BASE_URL = Value('http://represent.opennorth.ca')

    # TODO: Keep track of this issue
    # Ref: https://github.com/jazzband/django-configurations/issues/151
    CITY_VOCAB = DictValue(city_vocab)

    APP_NAME = 'toronto'

    #########################
    # The rest are optional #
    #########################

    # this is for populating meta tags
    if os.environ.get('HEROKU_APP_NAME') :
        # Available when labs feature has been turned on: `heroku labs:enable runtime-dyno-metadata`
        # See: https://devcenter.heroku.com/articles/dyno-metadata
        HEROKU_URL = 'https://{}.herokuapp.com'.format(os.environ['HEROKU_APP_NAME'])
    else :
        HEROKU_URL = None

    SITE_URL = URLValue(HEROKU_URL or 'https://chicago.councilmatic.org')

    SITE_META = {
        'site_name' : 'Toronto Councilmatic',
        'site_desc' : 'City Council, demystified. Keep tabs on Toronto legislation, councillors, & meetings.',
        'site_author' : 'Civic Tech Toronto',
        'twitter_site': '@councilmatic',
        'twitter_creator': '@CivicTechTO',
    }

    LEGISTAR_URL = 'https://chicago.legistar.com/Legislation.aspx'

    # this is for the boundaries of municipal districts, to add
    # shapes to posts & ultimately display a map with the council
    # member listing. the boundary set should be the relevant
    # slug from the ocd api's boundary service
    # available boundary sets here: http://ocd.datamade.us/boundary-sets/
    BOUNDARY_SET = Value('toronto-wards')

    # this is for configuring a map of council districts using data from the posts
    # set MAP_CONFIG = None to hide map
    map_config = {
        'center': [43.7245,-79.3882],
        'zoom': 10,
        'color': "#54afe8",
        'highlight_color': "#C00000",
    }

    MAP_CONFIG = DictValue(map_config)

    FOOTER_CREDITS = [
        {
            'name':     'Civic Tech Toronto',
            'url':      'http://civictech.ca/',
            'image':    'civictechto-logo.png',
        },
        {
            'name':     'DataMade',
            'url':      'http://datamade.us/',
            'image':    'datamade-logo.png',
        },
        {
            'name':     'Sunlight Foundation',
            'url':      'http://sunlightfoundation.org/',
            'image':    'sunlight-logo.png',
        },
    ]

    # this is the default text in search bars
    SEARCH_PLACEHOLDER_TEXT = "police, zoning, O2015-7825, etc."

    # these should live in APP_NAME/static/
    IMAGES = {
        'logo': 'images/metro-toronto-logo.png',
    }
    # you can generate icons from the logo at http://www.favicomatic.com/
    # & put them in APP_NAME/static/images/icons/

    # THE FOLLOWING ARE VOCAB SETTINGS RELEVANT TO DATA MODELS, LOGIC
    # (this is diff from VOCAB above, which is all for the front end)

    # this is the name of the meetings where the entire city council meets
    # as stored in legistar
    CITY_COUNCIL_MEETING_NAME = 'City Council'

    COMMITTEE_CHAIR_TITLES = ListValue(['Chair', 'Vice Chair'])

    # this is for convenience, & used to populate a table
    # describing legislation types on the about page template
    LEGISLATION_TYPE_DESCRIPTIONS = [
        {
            'name': 'Action Items',
            'search_term': 'Action',
            'fa_icon': 'check-square-o',
            'html_desc': True,
            'desc': "Generally, these items are seeking some kind of direction or resolution from Council or Committee. Usually there are proposed recommendations which Council or Committee can adopt or amend by vote.",

        },
        {
            'name': 'Information Reports',
            'search_term': 'Information',
            'fa_icon': 'pie-chart',
            'html_desc': True,
            'desc': "A City official's report that advises and informs without recommending.
A vote is required to dispose of the item (normally, a motion to receive).",

        },
        {
            'name': 'Presentations',
            'search_term': 'Presentation',
            'fa_icon': 'bullhorn',
            'html_desc': True,
            'desc': "Normally a verbal update, a ceremonial presentation or presentations to the committee without a covering report, such as slide presentations or playing of videos.
A vote is required to dispose of the item (normally, a motion to receive).",

        },
    ]

    # these keys should match committee slugs
    # Source: http://www1.toronto.ca/wps/portal/contentonly?vgnextoid=762b6804e1f22410VgnVCM10000071d60f89RCRD&vgnextchannel=9632acb640c21410VgnVCM10000071d60f89RCRD
    COMMITTEE_DESCRIPTIONS = {
            "community-development-and-recreation-committee": "Social inclusion and undertaking work to strengthen services to communities and neighbourhoods.",
            "economic-development-committee": "Monitors and makes recommendations to strengthen Toronto's economy and investment climate.",
            "government-management-committee": "Government assets and resources; monitors and makes recommendations on the administrative operations of the City.",
            "licensing-and-standards-committee": "Consumer safety and protection; monitors and makes recommendations on the licensing of business and the enforcement of property standards.",
            "parks-and-environment-committee": "Monitors, makes recommendations and undertakes work to ensure the sustainability of Toronto's natural environment.",
            "planning-and-growth-management-committee": "Urban form and work related to good city planning; monitors and makes recommendations on the planning, growth and development of the City.",
            "public-works-and-infrastructure-committee": "Delivers and maintains Toronto's infrastructure; monitors and makes recommendations on Toronto's infrastructure needs and services.Urban form and work related to good city planning; monitors and makes recommendations on the planning, growth and development of the City.",
            "executive-committee": "Monitors and makes recommendations on Council's strategic policy and priorities, governance policy and structure, financial planning and budgeting, fiscal policy including revenue and tax policies, intergovernmental and international relations, Council and its operations, and human resources and labour relations.",
            "affordable-housing-committee": "Affordable housing policies, acquiring land for affordable housing, providing funding and financing, development fee and charge waivers and property tax reductions or waivers for affordable housing projects. Proposes legislation and advocates to the provincial and federal governments. In charge of strategic planning for Toronto Community Housing, and measuring the effectiveness of Affordable Housing Office projects.",
            "budget-committee": "Includes, but is not limited to, coordinating the preparation of the capital and operating estimates, and making recommendations on the capital and operating budgets.",
            "employee-and-labour-relations-committee": "Reviews corporate human resource policy issues related to achieving and maintaining excellence in the public service and issues that affect the workforce. Responsibilities include compensation, performance management, training and development, recruitment, retention, retirement, labour relations, human rights, equity goals, wellness, and health and safety strategic policy direction on collective bargaining.",
            "audit-committee": "Considers and recommends to Council the appointment of external auditors for the City and the Auditor General's office; the annual external audits of the financial statements of the City, its agencies and the Auditor General's office; the Auditor General's reports, audit plan and accomplishments.",
            "board-of-health": "Ensures that Toronto Public Health delivers programs and services in response to local needs; determines and sets public health policy and advises City Council on a broad range of health issues; recommendations with city-wide or financial implications are forwarded to City Council for final approval.",
            "civic-appointments-committee": "Considers and recommends to Council the citizens to appoint to agencies.",
            "striking-committee": "Recommends councillor appointments to fill the positions of the boards outlined above, as well many other boards, agencies and advisory committees; makes recommendations to Council on the meeting schedule for Council and Council Committees.",
    }

    ABOUT_BLURBS = {
            "COMMITTEES" : "
Most meaningful legislative activity happens in committee meetings, where committee members debate proposed legislation. These meetings are open to the public. Unlike City Council meetings, committee meetings allow for public presentations.
Find out how »
\

Each committee has a Chair. Along with the City Clerk, the Chair shapes the committee meeting agenda (and thus, the legislation to be considered).
\

Committee jurisdiction, memberships, and appointments all require City Council approval.
",
        "EVENTS":       "
There are two types of meetings: committee meetings and full city council meetings.
\

Most of the time, meaningful legislative debate happens in committee meetings, which at scheduled at regular intervals depending on the committee.
\

Meetings of the entire City Council generally occur once a month at City Hall.
\

All committee and City Council meetings are open to the public.
",
        "COUNCIL_MEMBERS": ""

    }

    # notable positions that aren't district representatives, e.g. mayor & city clerk
    # keys should match person slugs
    EXTRA_TITLES = {
        'mendoza-susana-a': 'City Clerk',
        'emanuel-rahm': 'Mayor',
    }

    TOPIC_HIERARCHY = [
        {
            'name': 'Citywide matters',
            'children': [
                {
                    'name': 'Municipal Code',
                    'children': [],
                },
                {
                    'name': 'City Business',
                    'children': [   {'name': 'Getting and Giving Land'},
                                    {'name': 'Intergovernmental Agreement'},
                                    {'name': 'Lease Agreement'},
                                    {'name': 'Vacation of Public Street'},],
                },
                {
                    'name': 'Finances',
                    'children': [ {'name': 'Bonds'} ],
                },
                {
                    'name': 'Appointment',
                    'children': [],
                },
                {
                    'name': 'Oath of Office',
                    'children': [],
                },
                {
                    'name': 'Airports',
                    'children': [],
                },
                {
                    'name': 'Special Funds',
                    'children': [   {'name': 'Open Space Impact Funds'} ],
                },
                {
                    'name': 'Inspector General',
                    'children': [],
                },
                {
                    'name': 'Council Matters',
                    'children': [   {'name': 'Call for Action'},
                                    {'name': 'Transfer of Committee Funds'},
                                    {'name': 'Correction of City Council Journal'},
                                    {'name': 'Next Meeting'},],
                },
            ]

        },
        {
            'name': 'Ward matters',
            'children': [
                {
                    'name': 'Business Permits and Privileges',
                    'children': [   {'name': 'Grant of privilege in public way'},
                                    {'name': 'Awnings'},
                                    {'name': 'Sign permits'},
                                    {'name': 'Physical barrier exemption'},
                                    {'name': 'Canopy'}],
                },
                {
                    'name': 'Residents',
                    'children': [   {'name': 'Handicapped Parking Permit'},
                                    {'name': 'Residential permit parking'},
                                    {'name': 'Condo Refuse Claim'},
                                    {'name': 'Senior citizen sewer refund'},],
                },
                {
                    'name': 'Land Use',
                    'children': [   {'name': 'Zoning Reclassification'},
                                    {'name': 'Liquor and Package Store Restrictions'},],
                },
                {
                    'name': 'Parking',
                    'children': [   {'name': 'Loading/Standing/Tow Zone'},
                                    {'name': 'Parking Restriction'},],
                },
                {
                    'name': 'Economic Development',
                    'children': [   {'name': 'Special Service Area'},
                                    {'name': 'Tax Incentives'},
                                    {'name': 'Tax Increment Financing'},],
                },
                {
                    'name': 'Traffic',
                    'children': [   {'name': 'Traffic signs and signals'},
                                    {'name': 'Vehicle Weight Limitation'},],
                },
                {
                    'name': 'Churches and Non-Profits',
                    'children': [   {'name': 'Tag Day Permits'} ],
                },
                {
                    'name': 'Redevelopment Agreement',
                    'children': [],
                },
            ],
        },
        {
            'name': 'Individual matters',
            'children': [
                {
                    'name': 'Small Claims',
                    'children': [   {'name': 'Damage to vehicle claim'},
                                    {'name': 'Damage to property claim'},
                                    {'name': 'Settlement of Claims'},
                                    {'name': 'Excessive water rate claim'},],
                },
                {
                    'name': 'Honorifics',
                    'children': [   {'name': 'Honorific Resolution'},
                                    {'name': 'Honorary street'},],
                },
            ],
        }
    ]


text:
from django.db import models
from cms.models.fields import PlaceholderField
from managers import ChunkManager

class Chunk(models.Model):
    name = models.CharField(max_length=200)
    tags = models.CharField(max_length=200)
    code = PlaceholderField('chunk_placeholder', related_name="chunks")
    priority = models.IntegerField()

    objects = ChunkManager()

    def __unicode__(self):
        return "Tags: %s. Priority: %s" % (self.tags, self.priority)

    def has_tag(self, tag):
        tags = [string.strip() for string in str(self.tags).split(",")]
        return tag in tags

# Create your models here.


text:
Set a fixed width for Atom's Tree View (file browser).

This package is for anyone who is annoyed by the Tree View width being reset and can't set the Tree View width themselves using the provided stylesheet (`~/.atom/styles.less`).

# Requirements

* [Atom](https://atom.io/) text editor
* [npm](https://docs.npmjs.com/cli/install)

## Installation

1. Download .zip
2. Unzip and move to `~/.atom/packages/`

## Usage

1. Open Atom and go to `Settings` -> `Packages`
2. Look for "fixed-tree-view" and enable it
3. Click "Settings" next to the package's name
4. Enter width (in pixels) for the Tree View
5. Go to `View` -> `Reload` in the menu to apply the setting.


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using GameCloud.Database.Attributes;
using MongoDB.Bson;
using MongoDB.Driver;

namespace GameCloud.Database.Adapters
{
    /// <summary>
    /// Provide an adapter for MongoDBA collection.
    /// </summary>
    /// <typeparam name="TEntity">Indicating the document type.</typeparam>
    public class CollectionAdapter<TEntity> : ICollectionAdapter<TEntity>
        where TEntity : EntityBase
    {
        private readonly IMongoCollection<TEntity> collection;
        private readonly string collectionName;
        private readonly DatabaseContext context;

        /// <summary>
        /// Initializes a new instance of the <see cref="CollectionAdapter{TEntity}" /> class.
        /// </summary>
        /// <param name="context">Indicating the database context.</param>
        /// <param name="collectionName">Indicating the database collection</param>
        public CollectionAdapter(DatabaseContext context, string collectionName)
        {
            this.context = context;
            this.collectionName = collectionName;
            this.collection = this.context.Database.GetCollection<TEntity>(this.collectionName, this.context.Settings.CollectionSettings);
        }

        public CollectionAdapter(DatabaseContext context)
            : this(context, typeof(TEntity).GetCustomAttribute<CollectionNameAttribute>().CollectionName)
        {
        }

        IMongoCollection<TEntity> ICollectionAdapter<TEntity>.Collection
        {
            get
            {
                return this.collection;
            }
        }

        Task<long> ICollectionAdapter<TEntity>.CountAsync(
            Expression<Func<TEntity, bool>> filter,
            CountOptions options,
            CancellationToken token)
        {
            if (filter == null)
            {
                return this.collection.CountAsync(new BsonDocument(), options, token);
            }

            return this.collection.CountAsync(filter, options, token);
        }

        async Task ICollectionAdapter<TEntity>.DeleteAsync(
            Expression<Func<TEntity, bool>> filter,
            CancellationToken token)
        {
            var result = await this.collection.DeleteOneAsync(filter, token);
            //// todo: check the delete result.
        }

        async Task<IReadOnlyList<TEntity>> ICollectionAdapter<TEntity>.GetListAsync(
            Expression<Func<TEntity, bool>> filter,
            FindOptions options,
            CancellationToken token)
        {
            return await this.collection.Find(filter, options).ToListAsync(token);
        }

        Task<TEntity> ICollectionAdapter<TEntity>.GetSingleAsync(
            Expression<Func<TEntity, bool>> filter,
            CancellationToken token)
        {
            return this.collection.Find(filter, null).FirstOrDefaultAsync(token);
        }

        async Task<TEntity> ICollectionAdapter<TEntity>.InsertAsync(
            TEntity entity,
            InsertOneOptions options,
            CancellationToken token)
        {
            await this.collection.InsertOneAsync(entity, options, token);

            // todo: need retrieve the entity from server side?
            return entity;
        }

        async Task<IReadOnlyList<TEntity>> ICollectionAdapter<TEntity>.InsertManyAsync(
            IReadOnlyList<TEntity> entities,
            InsertManyOptions options,
            CancellationToken token)
        {
            await this.collection.InsertManyAsync(entities, options, token);

            return entities;
        }

        async Task<TEntity> ICollectionAdapter<TEntity>.ReplaceOneAsync(
            TEntity entity,
            UpdateOptions options,
            CancellationToken token)
        {
            var replaceResult = await this.collection.ReplaceOneAsync(
                e => e.Id == entity.Id,
                entity,
                options,
                token);

            // todo: add some check logic here.
            // todo: reterive the entity from server side??
            return entity;
        }

        Task<UpdateResult> ICollectionAdapter<TEntity>.UpdateOneAsync(
            TEntity entity,
            FilterDefinition<TEntity> filter,
            UpdateDefinition<TEntity> update,
            UpdateOptions options,
            CancellationToken token)
        {
            return this.collection.UpdateOneAsync(filter, update, options, token);
        }

        async Task<string> ICollectionAdapter<TEntity>.CreateIndexIfNotExistAsync(
            IndexKeysDefinition<TEntity> keys,
            CreateIndexOptions options,
            CancellationToken token)
        {
            using (var cursor = await this.collection.Indexes.ListAsync(token))
            {
                var indexes = await cursor.ToListAsync(token);
                var index = indexes.FirstOrDefault(i => i["name"] == options.Name);
                if (index == null)
                {
                    return await this.collection.Indexes.CreateOneAsync(keys, options, token);
                }
            }

            return null;
        }
    }
}


text:
package ces;
import java.util.Scanner;

public class semana3ArrayIguais {

	public static void main(String[] args) {
		// Instancia um objeto do tipo Scanner que serve
		// para ler dados a partir do teclado.
		Scanner keyboard = new Scanner(System.in);

		//cria o primeiro array de compara��o
		int primeiro[] = new int[10];
		//cria o segundo array de compara��o
		int segundo[] = new int[10];

		for (int i = 0; i < 10; i++) {
			System.out.print("Digite o "+(i+1)+"� numero do Primeiro Array: ");
			int value = keyboard.nextInt();
			primeiro[i] = value;
		}

		for (int i = 0; i < 10; i++) {
			System.out.print("Digite o "+(i+1)+"� numero do Segundo Array: ");
			int value = keyboard.nextInt();
			segundo[i] = value;
		}

		boolean verifica = true;
		for (int i = 0; i < 10; i++) {
			//Verifica se as posi��es guardam o mesmo valor entre os arrays
			if (primeiro[i] != segundo[i]) {
				verifica = false;
			}
		}

		if(!verifica)
				System.out.println("ARRAYS S�O DIFERENTES");
			else
				System.out.println("ARRAYS S�O IGUAIS");

		System.out.println("\n");
		for (int i = 0; i < 10; i++) {

			System.out.print(primeiro[i] + " | ");
		}

		System.out.println("\n");
		for (int i = 0; i < 10; i++) {

			System.out.print(segundo[i] + " | ");
		}

		keyboard.close();

	}
}


text:
Conjugate Gradients
===================

.. automodule:: climin.cg

.. autoclass:: climin.cg.ConjugateGradient
   :members: __init__

.. autoclass:: climin.cg.NonlinearConjugateGradient
   :members: __init__


text:
/*
 * Do not modify this file. This file is generated from the inspector-2015-08-18.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.Inspector.Model
{
    ///
    /// This data type is used as the request parameter in the ListApplications action.
    ///
    public partial class ApplicationsFilter
    {
        private List<string> _applicationNamePatterns = new List<string>();

        ///
        /// Gets and sets the property ApplicationNamePatterns.
        /// <para>
        /// For a record to match a filter, an explicit value or a string containing a wildcard
        /// specified for this data type property must match the value of the applicationName
        /// property of the Application data type.
        /// </para>
        ///
        public List<string> ApplicationNamePatterns
        {
            get { return this._applicationNamePatterns; }
            set { this._applicationNamePatterns = value; }
        }

        // Check to see if ApplicationNamePatterns property is set
        internal bool IsSetApplicationNamePatterns()
        {
            return this._applicationNamePatterns != null && this._applicationNamePatterns.Count > 0;
        }

    }
}


text:
import { takeLatest, call, put } from 'redux-saga/effects';
import axios from 'axios';
import {
    UPDATE_JOB_REQUEST,
    UPDATE_JOB_RECEIVE,
    UPDATE_JOB_FAILURE,
} from '../actiontypes';

function doUpdateJob(updatedJob) {
    return axios.post('/ukelonn/api/job/update', updatedJob);
}

function* requestReceiveUpdateJobSaga(action) {
    try {
        const response = yield call(doUpdateJob, action.payload);
        const jobs = (response.headers['content-type'] == 'application/json') ? response.data : [];
        yield put(UPDATE_JOB_RECEIVE(jobs));
    } catch (error) {
        yield put(UPDATE_JOB_FAILURE(error));
    }
}

export default function* updateJobSaga() {
    yield takeLatest(UPDATE_JOB_REQUEST, requestReceiveUpdateJobSaga);
}


text: .\XrmContext.exe


text:
from dev.regularized_evolution.search_space.evolution_search_space import SSFZoph17
# from deep_architect.contrib.enas.search_space.enas_search_space import SSFEnasnet
import dev.regularized_evolution.search_space.dnn as css_dnn
import deep_architect.modules as mo

class SSF0(mo.SearchSpaceFactory):

    def __init__(self, num_classes):
        mo.SearchSpaceFactory.__init__(
            self, lambda: css_dnn.dnn_net(num_classes))

name_to_search_space_factory_fn = {
    'zoph_sp1': lambda num_classes: SSFZoph17('sp1', num_classes),
    'zoph_sp2': lambda num_classes: SSFZoph17('sp2', num_classes),
    'zoph_sp3': lambda num_classes: SSFZoph17('sp3', num_classes),
    # 'enas': lambda num_classes: SSFEnasnet(num_classes, 12, 36),
    # 'enas_noshare': lambda num_classes: SSFEnasnet(num_classes, 12, 36, False),
    'dnn': SSF0
}


text:
<?php

/*
	Form Definition

	Tabledefinition

	Datatypes:
	- INTEGER (Forces the input to Int)
	- DOUBLE
	- CURRENCY (Formats the values to currency notation)
	- VARCHAR (no format check, maxlength: 255)
	- TEXT (no format check)
	- DATE (Dateformat, automatic conversion to timestamps)

	Formtype:
	- TEXT (Textfield)
	- TEXTAREA (Textarea)
	- PASSWORD (Password textfield, input is not shown when edited)
	- SELECT (Select option field)
	- RADIO
	- CHECKBOX
	- CHECKBOXARRAY
	- FILE

	VALUE:
	- Wert oder Array

	Hint:
	The ID field of the database table is not part of the datafield definition.
	The ID field must be always auto incement (int or bigint).

*/

$form["title"]    = "Web Folder";
$form["description"]  = "";
$form["name"]    = "web_folder";
$form["action"]   = "web_folder_edit.php";
$form["db_table"]  = "web_folder";
$form["db_table_idx"] = "web_folder_id";
$form["db_history"]  = "yes";
$form["tab_default"] = "folder";
$form["list_default"] = "web_folder_list.php";
$form["auth"]   = 'yes'; // yes / no

$form["auth_preset"]["userid"]  = 0; // 0 = id of the user, > 0 id must match with id of current user
$form["auth_preset"]["groupid"] = 0; // 0 = default groupid of the user, > 0 id must match with groupid of current user
$form["auth_preset"]["perm_user"] = 'riud'; //r = read, i = insert, u = update, d = delete
$form["auth_preset"]["perm_group"] = 'riud'; //r = read, i = insert, u = update, d = delete
$form["auth_preset"]["perm_other"] = ''; //r = read, i = insert, u = update, d = delete

$form["tabs"]['folder'] = array (
	'title'  => "Folder",
	'width'  => 100,
	'template'  => "templates/web_folder_edit.htm",
	'fields'  => array (
		//#################################
		// Begin Datatable fields
		//#################################
		'server_id' => array (
			'datatype' => 'INTEGER',
			'formtype' => 'SELECT',
			'default' => '',
			'datasource' => array (  'type' => 'SQL',
				'querystring' => 'SELECT server_id,server_name FROM server WHERE mirror_server_id = 0 AND {AUTHSQL} ORDER BY server_name',
				'keyfield'=> 'server_id',
				'valuefield'=> 'server_name'
			),
			'value'  => ''
		),
		'parent_domain_id' => array (
			'datatype' => 'INTEGER',
			'formtype' => 'SELECT',
			'default' => '',
			'datasource' => array (  'type' => 'SQL',
				'querystring' => "SELECT web_domain.domain_id, CONCAT(web_domain.domain, ' :: ', server.server_name) AS parent_domain FROM web_domain, server WHERE (web_domain.type = 'vhost' OR web_domain.type = 'vhostsubdomain') AND web_domain.server_id = server.server_id AND {AUTHSQL::web_domain} ORDER BY web_domain.domain",
				'keyfield'=> 'domain_id',
				'valuefield'=> 'parent_domain'
			),
			'value'  => ''
		),
		'path' => array (
			'datatype' => 'VARCHAR',
			'formtype' => 'TEXT',
			'validators' => array (  0 => array ( 'type' => 'REGEX',
					'regex' => '/^[\w\.\-\_\/]{0,255}$/',
					'errmsg'=> 'path_error_regex'),
			),
			'default' => '/',
			'value'  => '',
			'width'  => '30',
			'maxlength' => '255'
		),
		'active' => array (
			'datatype' => 'VARCHAR',
			'formtype' => 'CHECKBOX',
			'default' => 'y',
			'value'  => array(0 => 'n', 1 => 'y')
		),
		//#################################
		// ENDE Datatable fields
		//#################################
	)
);

?>


text:
module minerva.controls.usercontrol.measure.tapins {
    export function preOverride (input: IInput, state: IState, output: core.measure.IOutput, tree: control.ControlUpdaterTree, availableSize: Size): boolean {
        var tb = state.totalBorder;
        Thickness.copyTo(input.padding, tb);
        Thickness.add(tb, input.borderThickness);
        Thickness.shrinkSize(tb, state.availableSize);
        return true;
    }
}


text:
"""Test the runtime usage of `numpy.typing`."""

from __future__ import annotations

import sys
from typing import get_type_hints, Union, Tuple, NamedTuple, get_args, get_origin

import pytest
import numpy as np
import numpy.typing as npt

class TypeTup(NamedTuple):
    typ: type
    args: Tuple[type, ...]
    origin: None | type

if sys.version_info >= (3, 9):
    NDArrayTup = TypeTup(npt.NDArray, npt.NDArray.__args__, np.ndarray)
else:
    NDArrayTup = TypeTup(npt.NDArray, (), None)

TYPES = {
    "ArrayLike": TypeTup(npt.ArrayLike, npt.ArrayLike.__args__, Union),
    "DTypeLike": TypeTup(npt.DTypeLike, npt.DTypeLike.__args__, Union),
    "NBitBase": TypeTup(npt.NBitBase, (), None),
    "NDArray": NDArrayTup,
}

@pytest.mark.parametrize("name,tup", TYPES.items(), ids=TYPES.keys())
def test_get_args(name: type, tup: TypeTup) -> None:
    """Test `typing.get_args`."""
    typ, ref = tup.typ, tup.args
    out = get_args(typ)
    assert out == ref

@pytest.mark.parametrize("name,tup", TYPES.items(), ids=TYPES.keys())
def test_get_origin(name: type, tup: TypeTup) -> None:
    """Test `typing.get_origin`."""
    typ, ref = tup.typ, tup.origin
    out = get_origin(typ)
    assert out == ref

@pytest.mark.parametrize("name,tup", TYPES.items(), ids=TYPES.keys())
def test_get_type_hints(name: type, tup: TypeTup) -> None:
    """Test `typing.get_type_hints`."""
    typ = tup.typ

    # Explicitly set `__annotations__` in order to circumvent the
    # stringification performed by `from __future__ import annotations`
    def func(a): pass
    func.__annotations__ = {"a": typ, "return": None}

    out = get_type_hints(func)
    ref = {"a": typ, "return": type(None)}
    assert out == ref

@pytest.mark.parametrize("name,tup", TYPES.items(), ids=TYPES.keys())
def test_get_type_hints_str(name: type, tup: TypeTup) -> None:
    """Test `typing.get_type_hints` with string-representation of types."""
    typ_str, typ = f"npt.{name}", tup.typ

    # Explicitly set `__annotations__` in order to circumvent the
    # stringification performed by `from __future__ import annotations`
    def func(a): pass
    func.__annotations__ = {"a": typ_str, "return": None}

    out = get_type_hints(func)
    ref = {"a": typ, "return": type(None)}
    assert out == ref

def test_keys() -> None:
    """Test that ``TYPES.keys()`` and ``numpy.typing.__all__`` are synced."""
    keys = TYPES.keys()
    ref = set(npt.__all__)
    assert keys == ref


text:
package com.google.android.apps.common.testing.ui.testapp;

import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.assertThat;
import static com.google.android.apps.common.testing.ui.testapp.LongListMatchers.withItemContent;
import static com.google.android.apps.common.testing.ui.testapp.LongListMatchers.withItemSize;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;

import com.google.android.apps.common.testing.ui.testapp.LongListActivity;

import android.content.Intent;
import android.test.ActivityUnitTestCase;

/**
 * UnitTests for LongListMatchers matcher factory.
 */
public final class LongListMatchersTest extends ActivityUnitTestCase<LongListActivity> {

  public LongListMatchersTest() {
    super(LongListActivity.class);
  }

  @Override
  public void setUp() throws Exception {
    super.setUp();
    startActivity(new Intent(getInstrumentation().getTargetContext(), LongListActivity.class),
        null, null);
  }

  public void testWithContent() {
    assertThat(getActivity().makeItem(54), withItemContent("item: 54"));
    assertThat(getActivity().makeItem(54), withItemContent(endsWith("54")));
    assertFalse(withItemContent("hello world").matches(getActivity().makeItem(54)));
  }

  @SuppressWarnings("unchecked")
  public void testWithItemSize() {
    assertThat(getActivity().makeItem(54), withItemSize(8));
    assertThat(getActivity().makeItem(54), withItemSize(anyOf(equalTo(8), equalTo(7))));
    assertFalse(withItemSize(7).matches(getActivity().makeItem(54)));
  }
}


text:
<?php

class Fooman_GoogleAnalyticsPlus_Helper_Data extends Mage_Core_Helper_Abstract
{

    const XML_PATH_GOOGLEANALYTICSPLUS_SETTINGS = 'google/analyticsplus/';

    /**
     * Return store config value for key
     *
     * @param   string $key
     * @return  string
     */
    public function getGoogleanalyticsplusStoreConfig ($key, $flag=false)
    {
        $path = self::XML_PATH_GOOGLEANALYTICSPLUS_SETTINGS . $key;
        if ($flag) {
            return Mage::getStoreConfigFlag($path);
        } else {
            return Mage::getStoreConfig($path);
        }
    }

    public function convert($order, $dataMethod, $item=null)
    {
        $basecur = $order->getBaseCurrency();
        if($basecur) {
            return sprintf("%01.4f", Mage::app()->getStore()->roundPrice(
                $basecur->convert(
                    (is_null($item))?$order->$dataMethod():$item->$dataMethod(),
                    Mage::helper('googleanalyticsplus')->getGoogleanalyticsplusStoreConfig('convertcurrency')
                ))
            );
        } else {
            //unable to load base currency return zero
            return '0.0000';
            //return (is_null($item))?$order->$dataMethod():$item->$dataMethod();
        }
    }

}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Aster trinervius subsp. ovatus (Franch. & Sav.) Kitam.

### Remarks
null


text:
package io.crate.expression.scalar.timestamp;

import static io.crate.testing.Asserts.exactlyInstanceOf;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import io.crate.expression.scalar.ScalarTestCase;
import io.crate.expression.symbol.Literal;
import io.crate.metadata.SystemClock;

public class CurrentTimestampFunctionTest extends ScalarTestCase {

    private static final long EXPECTED_TIMESTAMP = 1422294644581L;

    @Before
    public void prepare() {
        SystemClock.setCurrentMillisFixedUTC(EXPECTED_TIMESTAMP);
    }

    @After
    public void cleanUp() {
        SystemClock.setCurrentMillisSystemUTC();
    }

    @Test
    public void timestampIsCreatedCorrectly() {
        assertEvaluate("current_timestamp", EXPECTED_TIMESTAMP);
    }

    @Test
    public void precisionOfZeroDropsAllFractionsOfSeconds() {
        assertEvaluate("current_timestamp(0)", EXPECTED_TIMESTAMP - (EXPECTED_TIMESTAMP % 1000));
    }

    @Test
    public void precisionOfOneDropsLastTwoDigitsOfFractionsOfSecond() {
        assertEvaluate("current_timestamp(1)", EXPECTED_TIMESTAMP - (EXPECTED_TIMESTAMP % 100));
    }

    @Test
    public void precisionOfTwoDropsLastDigitOfFractionsOfSecond() {
        assertEvaluate("current_timestamp(2)", EXPECTED_TIMESTAMP - (EXPECTED_TIMESTAMP % 10));
    }

    @Test
    public void precisionOfThreeKeepsAllFractionsOfSeconds() {
        assertEvaluate("current_timestamp(3)", EXPECTED_TIMESTAMP);
    }

    @Test
    public void precisionLargerThan3RaisesException() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Precision must be between 0 and 3");
        assertEvaluateNull("current_timestamp(4)");
    }

    @Test
    public void test_calls_within_statement_are_idempotent() {
        assertEvaluate("current_timestamp(3) = current_timestamp(3)", true);
    }

    @Test
    public void integerIsNormalizedToLiteral() {
        assertNormalize("current_timestamp(1)", exactlyInstanceOf(Literal.class));
    }
}


text:
package uk.nhs.hdn.dbs.response.parsing.parsers;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import uk.nhs.hdn.common.parsers.parseResultUsers.ParseResultUser;
import uk.nhs.hdn.dbs.response.ResponseBody;

public final class ResponseBodyParseResultUser implements ParseResultUser<ResponseBody>
{
	@NotNull
	public final ResponseBody[] responseBodies;

	private int lineIndex;

	public ResponseBodyParseResultUser(final int numberOfResponseRecords)
	{
		responseBodies = new ResponseBody[numberOfResponseRecords];
		lineIndex = 0;
	}

	@Override
	public void use(@Nullable final ResponseBody value)
	{
		responseBodies[lineIndex] = value;
		lineIndex++;
	}
}


text:
using Cake.Common.Tools.DotNetCore.Pack;

namespace Cake.Common.Tests.Fixtures.Tools.DotNetCore.Pack
{
    internal sealed class DotNetCorePackFixture : DotNetCoreFixture<DotNetCorePackSettings>
    {
        public string Project { get; set; }

        protected override void RunTool()
        {
            var tool = new DotNetCorePacker(FileSystem, Environment, ProcessRunner, Globber);
            tool.Pack(Project, Settings);
        }
    }
}


text:
* http://www.w3.org/TR/2000/NOTE-SOAP-20000508/

* http://www.w3.org/TR/wsdl

## Current status

Durden can generate a not too bad WSDL from specially cooked erlang modules.
It also can handle SOAP/1.2-bound requests.

## Nearest future

Soap transports:
* HTTP-POST
* SOAP/1.1
* HTTP-GET

Support of indirect reference loops in the types declarations (currently parse transformation hangs when analysing a types like "A references B references A again")

Human readable documentation page (alike to that one generated when you visit .Net's ASMX page with no parameters)

## How it wokrs

Durden analyses the source of the module supposed to become a Web-service via parse-transform.

The specs of the functions enlisted in 'soap_actions' attribute are analysed.

All the mentioned types are gathered recursively.

The type info is then used as the return value of a generated function Module:'#durden.get_wsd#'/0.

Besides the latter, 'cowboy_http_handler' behaviour is implemented: init/3 callback just asks Cowboy to upgrade the protocol into 'durden_cowboy_http_soap'.

## Example

(https://github.com/RGafiyatullin/durden_examples)

The following module:

-module(soap_test_service).
-compile({parse_transform, durden_pt}).

-include_lib("durden/include/predefined_types.hrl").

-soap_target_ns("http://rgafiyatullin.github.com/test-service").
-soap_service_name("TestService").

-soap_actions(['GetUserByID'/1]).

-type phone_numbers() :: [ string() ].

-record('User', {
	'ID' :: uuid(),
	'Name' :: string(),
	'YearOfBirth' :: integer(),
	'Phones' :: phone_numbers()
	}).

-spec 'GetUserByID'( ID :: uuid() ) -> #'User'{}.
'GetUserByID'( ID ) ->
	#'User'{
		'ID' = ID,
		'Name' = "Test User",
		'YearOfBirth' = 1988,
		'Phones' = ["+375005550000", "+375115550000"]
	}.

produces WSDL below:
(alternatively can be viewed at https://gist.github.com/3364435)

<?xml version="1.0"?>
<wsdl:definitions xmlns:ms="http://microsoft.com/wsdl/types/" xmlns:mstm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://rgafiyatullin.github.com/test-service" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:s0="http://rgafiyatullin.github.com/test-service/s0" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" targetNamespace="http://rgafiyatullin.github.com/test-service">
  <wsdl:types>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://rgafiyatullin.github.com/test-service/s0">
      <xs:element name="GetUserByIDResponse">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="GetUserByIDResult" type="s0:User" minOccurs="1" maxOccurs="1"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="GetUserByID">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="ID" type="xs:guid" minOccurs="1" maxOccurs="1"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:complexType name="User">
        <xs:sequence>
          <xs:element name="ID" type="xs:guid" minOccurs="1" maxOccurs="1"/>
          <xs:element name="Name" type="xs:string" minOccurs="1" maxOccurs="1"/>
          <xs:element name="YearOfBirth" type="xs:int" minOccurs="1" maxOccurs="1"/>
          <xs:element name="Phones" type="s0:phone_numbers" minOccurs="1" maxOccurs="1"/>
        </xs:sequence>
      </xs:complexType>
      <xs:complexType name="phone_numbers">
        <xs:sequence>
          <xs:element minOccurs="0" maxOccurs="unbounded" name="string" type="xs:string"/>
        </xs:sequence>
      </xs:complexType>
    </xs:schema>
  </wsdl:types>
  <wsdl:message name="GetUserByIDSoapIn">
    <wsdl:part name="parameters" element="s0:GetUserByID"/>
  </wsdl:message>
  <wsdl:message name="GetUserByIDSoapOut">
    <wsdl:part name="parameters" element="s0:GetUserByIDResponse"/>
  </wsdl:message>
  <wsdl:portType name="TestServiceSoap">
    <wsdl:operation name="GetUserByID">
      <wsdl:input message="tns:GetUserByIDSoapIn"/>
      <wsdl:output message="tns:GetUserByIDSoapOut"/>
    </wsdl:operation>
  </wsdl:portType>
  <wsdl:portType name="TestServiceSoap12">
    <wsdl:operation name="GetUserByID">
      <wsdl:input message="tns:GetUserByIDSoapIn"/>
      <wsdl:output message="tns:GetUserByIDSoapOut"/>
    </wsdl:operation>
  </wsdl:portType>
  <wsdl:binding name="TestServiceSoap" type="tns:TestServiceSoap">
    <soap:binding transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="GetUserByID">
      <soap:operation soapAction="http://rgafiyatullin.github.com/test-service/GetUserByID" style="document"/>
      <wsdl:input>
        <soap:body use="literal"/>
      </wsdl:input>
      <wsdl:output>
        <soap:body use="literal"/>
      </wsdl:output>
    </wsdl:operation>
  </wsdl:binding>
  <wsdl:binding name="TestServiceSoap12" type="tns:TestServiceSoap12">
    <soap12:binding transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="GetUserByID">
      <soap12:operation soapAction="http://rgafiyatullin.github.com/test-service/GetUserByID" style="document"/>
      <wsdl:input>
        <soap12:body use="literal"/>
      </wsdl:input>
      <wsdl:output>
        <soap12:body use="literal"/>
      </wsdl:output>
    </wsdl:operation>
  </wsdl:binding>
  <wsdl:service name="TestService">
    <wsdl:port name="TestServiceSoap" binding="tns:TestServiceSoap">
      <soap:address location="http://localhost:8080/test/service.asmx"/>
    </wsdl:port>
    <wsdl:port name="TestServiceSoap12" binding="tns:TestServiceSoap12">
      <soap12:address location="http://localhost:8080/test/service.asmx"/>
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>


text:
	#include "afxtempl.h"
#endif

#include "BCGExCheckList.h"

/////////////////////////////////////////////////////////////////////////////
// CBCGCustomizePage dialog

class CBCGToolbarButton;
class CBCGToolBarImages;
class CBCGToolBar;

class CBCGCustomizePage : public CPropertyPage
{
	DECLARE_DYNCREATE(CBCGCustomizePage)

// Construction
public:
	CBCGCustomizePage();
	~CBCGCustomizePage();

// Operations:
	void SetUserCategory (LPCTSTR lpszCategory);
	void SetAllCategory (LPCTSTR lpszCategory);
	void OnChangeSelButton (CBCGToolbarButton* pButton);

protected:

// Dialog Data
	//{{AFX_DATA(CBCGCustomizePage)
	enum { IDD = IDD_BCGBARRES_PROPPAGE1 };
	CListBox	m_wndCategory;
	CButtonsTextList	m_wndTools;
	CString	m_strButtonDescription;
	//}}AFX_DATA

// Overrides
	// ClassWizard generate virtual function overrides
	//{{AFX_VIRTUAL(CBCGCustomizePage)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	// Generated message map functions
	//{{AFX_MSG(CBCGCustomizePage)
	afx_msg void OnSelchangeUserTools();
	virtual BOOL OnInitDialog();
	afx_msg void OnSelchangeCategory();
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()

// Attributes:
protected:

	CBCGToolbarButton*	m_pSelButton;
	CString				m_strUserCategory;
	CString				m_strAllCategory;
};

/////////////////////////////////////////////////////////////////////////////
// CBCGToolbarsPage dialog

class CBCGToolbarsPage : public CPropertyPage
{
	DECLARE_DYNCREATE(CBCGToolbarsPage)

// Construction
public:
	CBCGToolbarsPage(CFrameWnd* pParentFrame = NULL);
	~CBCGToolbarsPage();

// Dialog Data
	//{{AFX_DATA(CBCGToolbarsPage)
	enum { IDD = IDD_BCGBARRES_PROPPAGE2 };
	CButton	m_wndTextLabels;
	CButton	m_bntRenameToolbar;
	CButton	m_btnNewToolbar;
	CButton	m_btnDelete;
	CButton	m_btnReset;
	CBCGExCheckList	m_wndToobarList;
	BOOL	m_bTextLabels;
	//}}AFX_DATA

// Operations:
public:
	void ShowToolBar (CBCGToolBar* pToolBar, BOOL bShow);
	void EnableUserDefinedToolbars (BOOL bEnable)
	{
		m_bUserDefinedToolbars = bEnable;
	}

protected:
// Overrides
	// ClassWizard generate virtual function overrides
	//{{AFX_VIRTUAL(CBCGToolbarsPage)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam);
	//}}AFX_VIRTUAL

// Implementation
protected:
	// Generated message map functions
	//{{AFX_MSG(CBCGToolbarsPage)
	virtual BOOL OnInitDialog();
	afx_msg void OnSelchangeToolbarList();
	afx_msg void OnDblclkToolbarList();
	afx_msg void OnReset();
	afx_msg void OnResetAll();
	afx_msg void OnDeleteToolbar();
	afx_msg void OnNewToolbar();
	afx_msg void OnRenameToolbar();
	afx_msg void OnBcgbarresTextLabels();
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()

	CBCGToolBar*	m_pSelectedToolbar;
	BOOL			m_bUserDefinedToolbars;
	CFrameWnd*		m_pParentFrame;
};

#endif // BCG_NO_CUSTOMIZATION

#endif // __CBCGTOOLBARCUSTOMIZEPAGES_H__


text:
package org.spash.narrow;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.spash.TestHelper.ALLOWABLE_DELTA;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.spash.Translation;
import org.spash.Vector2f;
import org.spash.narrow.LineRectOverlapper;
import org.spash.shape.Line;
import org.spash.shape.Rect;

public class LineRectOverlapperTest {
    /** square root of 2 */
    private static final float SQRT_2 = (float)Math.sqrt(2);

    LineRectOverlapper overlapper;

    @Before
    public void before() {
        overlapper = new LineRectOverlapper();
    }

    @After
    public void after() {
        overlapper = null;
    }

    @Test
    public void GetMinTranslation_RectAndLineAreDisjoint_ReturnsNull() {
        Rect rect = new Rect(0, 0, 10, 10);
        Line line = new Line(0, 10, 20, 10);

        assertNull(overlapper.getMinTranslation(line, rect));
    }

    @Test
    public void GetMinTranslation_VerticalTranslation() {
        Rect rect = new Rect(0, 0, 10, 10);
        Line line = new Line(-5, -2, 5, -2);

        assertEquals(new Translation(new Vector2f(0, 1), 3f), overlapper.getMinTranslation(line, rect));
    }

    @Test
    public void GetMinTranslation_HorizontalTranslation() {
        Rect rect = new Rect(0, 0, 10, 10);
        Line line = new Line(4, -10, 4, 10);

        assertEquals(new Translation(new Vector2f(-1, 0), 1f), overlapper.getMinTranslation(line, rect));
    }

    @Test
    public void GetMinTranslation_LineNormalTranslation() {
        Rect rect = new Rect(4, 4, 10, 10);
        Line line = new Line(1, -1, -1, 1);

        Translation actual = overlapper.getMinTranslation(line, rect);
        assertEquals("translation.direction.x is wrong", SQRT_2 / 2, actual.getDirection().getX(), ALLOWABLE_DELTA);
        assertEquals("translation.direction.y is wrong", SQRT_2 / 2, actual.getDirection().getY(), ALLOWABLE_DELTA);
        assertEquals("translation.distance is wrong", SQRT_2, actual.getDistance(), ALLOWABLE_DELTA);
    }

    @Test
    public void GetMinTranslation_RectAndLineTouchVerticallyButDontOverlap_ReturnsNull() {
        Rect rect = new Rect(0, 0, 10, 10);
        Line line = new Line(-10, 5, 10, 5);

        assertNull(overlapper.getMinTranslation(line, rect));
    }

    @Test
    public void GetMinTranslation_RectAndLineTouchHorizontallyButDontOverlap_ReturnsNull() {
        Rect rect = new Rect(0, 0, 10, 10);
        Line line = new Line(5, -10, 5, 10);

        assertNull(overlapper.getMinTranslation(line, rect));
    }

    @Test
    public void GetMinTranslation_RectAndLineTouchAtCornerButDontOverlap_ReturnsNull() {
        Rect rect = new Rect(-5, 5, 10, 10);
        Line line = new Line(-2, -2, 2, 2);

        assertNull(overlapper.getMinTranslation(line, rect));
    }
}


text:
using Newtonsoft.Json;

namespace Nest
{
	public interface IIndicesResponse : IResponse
	{
		bool Acknowledged { get; }
		ShardsMetaData ShardsHit { get; }
	}

	[JsonObject]
	public abstract class IndicesResponseBase : ResponseBase, IIndicesResponse
	{
		[JsonProperty(PropertyName = "acknowledged")]
		public bool Acknowledged { get; private set; }

		[JsonProperty(PropertyName = "_shards")]
		public ShardsMetaData ShardsHit { get; private set; }
	}
}