text:
import m5
from m5.objects import *
from m5.defines import buildEnv
from m5.util import addToPath
import os, optparse, sys
addToPath('../common')
addToPath('../ruby')
addToPath('../topologies')

import Options
import Ruby

# Get paths we might need.  It's expected this file is in m5/configs/example.
config_path = os.path.dirname(os.path.abspath(__file__))
config_root = os.path.dirname(config_path)

parser = optparse.OptionParser()
Options.addCommonOptions(parser)

parser.add_option("--maxloads", metavar="N", default=0,
                  help="Stop after N loads")
parser.add_option("--progress", type="int", default=1000,
                  metavar="NLOADS",
                  help="Progress message interval "
                  "[default: %default]")
parser.add_option("--num-dmas", type="int", default=0, help="# of dma testers")
parser.add_option("--functional", type="int", default=0,
                  help="percentage of accesses that should be functional")
parser.add_option("--suppress-func-warnings", action="store_true",
                  help="suppress warnings when functional accesses fail")

#
# Add the ruby specific and protocol specific options
#
Ruby.define_options(parser)

execfile(os.path.join(config_root, "common", "Options.py"))

(options, args) = parser.parse_args()

#
# Set the default cache size and associativity to be very small to encourage
# races between requests and writebacks.
#
options.l1d_size="256B"
options.l1i_size="256B"
options.l2_size="512B"
options.l3_size="1kB"
options.l1d_assoc=2
options.l1i_assoc=2
options.l2_assoc=2
options.l3_assoc=2

if args:
     print "Error: script doesn't take any positional arguments"
     sys.exit(1)

block_size = 64

if options.num_cpus > block_size:
     print "Error: Number of testers %d limited to %d because of false sharing" \
           % (options.num_cpus, block_size)
     sys.exit(1)

#
# Currently ruby does not support atomic or uncacheable accesses
#
cpus = [ MemTest(atomic = False,
                 max_loads = options.maxloads,
                 issue_dmas = False,
                 percent_functional = options.functional,
                 percent_uncacheable = 0,
                 progress_interval = options.progress,
                 suppress_func_warnings = options.suppress_func_warnings) \
         for i in xrange(options.num_cpus) ]

system = System(cpu = cpus,
                funcmem = SimpleMemory(in_addr_map = False),
                funcbus = IOXBar(),
                clk_domain = SrcClockDomain(clock = options.sys_clock),
                mem_ranges = [AddrRange(options.mem_size)])

if options.num_dmas > 0:
    dmas = [ MemTest(atomic = False,
                     max_loads = options.maxloads,
                     issue_dmas = True,
                     percent_functional = 0,
                     percent_uncacheable = 0,
                     progress_interval = options.progress,
                     suppress_func_warnings =
                                        not options.suppress_func_warnings) \
             for i in xrange(options.num_dmas) ]
    system.dma_devices = dmas
else:
    dmas = []

dma_ports = []
for (i, dma) in enumerate(dmas):
    dma_ports.append(dma.test)
Ruby.create_system(options, False, system, dma_ports = dma_ports)

# Create a top-level voltage domain and clock domain
system.voltage_domain = VoltageDomain(voltage = options.sys_voltage)
system.clk_domain = SrcClockDomain(clock = options.sys_clock,
                                   voltage_domain = system.voltage_domain)
# Create a seperate clock domain for Ruby
system.ruby.clk_domain = SrcClockDomain(clock = options.ruby_clock,
                                        voltage_domain = system.voltage_domain)

#
# The tester is most effective when randomization is turned on and
# artifical delay is randomly inserted on messages
#
system.ruby.randomization = True

assert(len(cpus) == len(system.ruby._cpu_ports))

for (i, cpu) in enumerate(cpus):
    #
    # Tie the cpu memtester ports to the correct system ports
    #
    cpu.test = system.ruby._cpu_ports[i].slave
    cpu.functional = system.funcbus.slave

    #
    # Since the memtester is incredibly bursty, increase the deadlock
    # threshold to 5 million cycles
    #
    system.ruby._cpu_ports[i].deadlock_threshold = 5000000

for (i, dma) in enumerate(dmas):
    #
    # Tie the dma memtester ports to the correct functional port
    # Note that the test port has already been connected to the dma_sequencer
    #
    dma.functional = system.funcbus.slave

# connect reference memory to funcbus
system.funcbus.master = system.funcmem.port

# -----------------------
# run simulation
# -----------------------

root = Root( full_system = False, system = system )
root.system.mem_mode = 'timing'

# Not much point in this being higher than the L1 latency
m5.ticks.setGlobalFrequency('1ns')

# instantiate configuration
m5.instantiate()

# simulate until program terminates
exit_event = m5.simulate(options.abs_max_tick)

print 'Exiting @ tick', m5.curTick(), 'because', exit_event.getCause()


text:
package tomdrever.timetable.android.views;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.GridView;

public class ExpandableGridView extends GridView {
    public ExpandableGridView(Context context) {
        super(context);
    }

    public ExpandableGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ExpandableGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int heightSpec;

        if (getLayoutParams().height == LayoutParams.WRAP_CONTENT) {
            // Remove 2 leftmost bits
            heightSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        } else {
            heightSpec = heightMeasureSpec;
        }

        super.onMeasure(widthMeasureSpec, heightSpec);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
	$image = get_field('header_image');
	$headline = get_field('header_headline');
	$sub = get_field('header_sub');

	// We need at least a headline OR an image to display this section
	if ( !$headline && !$image ) return;
?>

<?php if ( $image ) : ?>
<div class="hero hero-image wow fadeIn" style="background-image: url(<?php echo $image ?>);">
<?php else: ?>

<?php endif; ?>

			<?php if ( $headline ) : ?>

<?php echo $headline; ?>

				<?php if ( $sub ) : ?>

<?php echo $sub; ?>

				<?php endif; ?>

			<?php endif ?>


text:
<?php

// Copyright (C) 2015-2017 Jacob Barkdull
// This file is part of HashOver.
//
// HashOver is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// HashOver 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with HashOver.  If not, see <http://www.gnu.org/licenses/>.

// Display source code
if (basename ($_SERVER['PHP_SELF']) === basename (__FILE__)) {
	if (isset ($_GET['source'])) {
		header ('Content-type: text/plain; charset=UTF-8');
		exit (file_get_contents (basename (__FILE__)));
	} else {
		exit ('<b>HashOver</b>: This is a class file.');
	}
}

class HashOver
{
	public $usage = array ();
	public $statistics;
	public $misc;
	public $setup;
	public $readComments;
	public $locale;
	public $commentParser;
	public $markdown;
	public $cookies;
	public $commentCount;
	public $popularList = array ();
	public $rawComments = array ();
	public $comments = array ();
	public $html;
	public $templater;

	public function __construct ($mode = 'php', $context = 'normal')
	{
		// Store usage context information
		$this->usage['mode'] = $mode;
		$this->usage['context'] = $context;

		// Instantiate and start statistics
		$this->statistics = new HashOver\Statistics ($mode);
		$this->statistics->executionStart ();

		// Instantiate general setup class
		$this->setup = new HashOver\Setup ($this->usage);

		// Instantiate class of miscellaneous functions
		$this->misc = new HashOver\Misc ($mode);
	}

	public function getCommentCount ($locale_key = 'showing-comments')
	{
		// Shorter variables
		$primary_count = $this->readComments->primaryCount;
		$total_count = $this->readComments->totalCount;

		// Subtract deleted comment counts
		if ($this->setup->countIncludesDeleted === false) {
			$primary_count -= $this->readComments->primaryDeletedCount;
			$total_count -= $this->readComments->totalDeletedCount;
		}

		// Decide which locale to use; Exclude "Showing" in API usages
		$locale_key = ($this->usage['context'] === 'api') ? 'count-link' : $locale_key;

		// Decide if comment count is pluralized
		$prime_plural = ($primary_count !== 2) ? 1 : 0;

		// Get appropriate locale
		$showing_comments_locale = $this->locale->get ($locale_key);
		$showing_comments = $showing_comments_locale[$prime_plural];

		// Whether to show reply count separately
		if ($this->setup->showsReplyCount === true) {
			// If so, inject top level comment count into count locale string
			$comment_count = sprintf ($showing_comments, $primary_count - 1);

			// Check if there are any replies
			if ($total_count !== $primary_count) {
				// If so, decide if reply count is pluralized
				$count_diff = $total_count - $primary_count;
				$reply_plural = ($count_diff !== 1) ? 1 : 0;

				// Get appropriate locale
				$reply_locale = $this->locale->text['count-replies'][$reply_plural];

				// Inject total comment count into reply count locale string
				$reply_count = sprintf ($reply_locale, $total_count - 1);

				// And append reply count
				$comment_count .= ' (' . $reply_count . ')';
			}

			// And return count with separate reply count
			return $comment_count;
		}

		// Otherwise inject total comment count into count locale string
		return sprintf ($showing_comments, $total_count - 1);
	}

	// Begin initialization work
	public function initiate ()
	{
		// Instantiate class for reading comments
		$this->readComments = new HashOver\ReadComments ($this->setup);

		// Where to stop reading comments
		if ($this->usage['mode'] === 'javascript'
		    and $this->setup->collapsesComments !== false
		    and $this->setup->popularityLimit <= 0
		    and $this->setup->usesAJAX !== false)
		{
			// Use collapse limit when collapsing and AJAX is enabled
			$end = $this->setup->collapseLimit;
		} else {
			// Otherwise read all comments
			$end = null;
		}

		// TODO: Fix structure when using starting point
		$this->rawComments = $this->readComments->read (0, $end);

		// Instantiate locales class
		$this->locale = new HashOver\Locale ($this->setup);

		// Instantiate cookies class
		$this->cookies = new HashOver\Cookies ($this->setup);

		// Instantiate login class
		$this->login = new HashOver\Login ($this->setup);

		// Instantiate comment parser class
		$this->commentParser = new HashOver\CommentParser ($this->setup);

		// Generate comment count
		$this->commentCount = $this->getCommentCount ();

		// Instantiate markdown class
		$this->markdown = new HashOver\Markdown ();
	}

	// Get reply array from comments via key
	protected function &getRepliesLevel (&$level, $level_count, &$key_parts)
	{
		for ($i = 1; $i < $level_count; $i++) {
			if (!isset ($level)) {
				break;
			}

			$level =& $level['replies'][$key_parts[$i] - 1];
		}

		return $level;
	}

	// Parse primary comments
	public function parsePrimary ($start = 0)
	{
		// Initial comments array
		$this->comments['comments'] = array ();

		// If no comments were found, setup a default message comment
		if ($this->readComments->totalCount <= 1) {
			$this->comments['comments'][] = array (
				'title' => $this->locale->text['be-first-name'],
				'avatar' => $this->setup->httpImages . '/first-comment.' . $this->setup->imageFormat,
				'permalink' => 'c1',
				'notice' => $this->locale->text['be-first-note'],
				'notice-class' => 'hashover-first'
			);

			return;
		}

		// Last existing comment date for sorting deleted comments
		$last_date = 0;

		// Allowed comment count
		$allowed_count = 0;

		// Where to stop reading comments
		if ($this->usage['mode'] === 'javascript'
		    and $this->setup->collapsesComments !== false
		    and $this->setup->usesAJAX !== false)
		{
			// Use collapse limit when collapsing and AJAX is enabled
			$end = $this->setup->collapseLimit;
		} else {
			// Otherwise read all comments
			$end = null;
		}

		// Run all comments through parser
		foreach ($this->rawComments as $key => $comment) {
			$key_parts = explode ('-', $key);
			$indentions = count ($key_parts);
			$status = 'approved';

			if ($this->setup->popularityLimit > 0) {
				$popularity = 0;

				// Add number of likes to popularity value
				if (!empty ($comment['likes'])) {
					$popularity += $comment['likes'];
				}

				// Subtract number of dislikes to popularity value
				if ($this->setup->allowsDislikes === true) {
					if (!empty ($comment['dislikes'])) {
						$popularity -= $comment['dislikes'];
					}
				}

				// Add comment to popular comments list if popular enough
				if ($popularity >= $this->setup->popularityThreshold) {
					$this->popularList[] = array (
						'popularity' => $popularity,
						'key' => $key,
						'parts' => $key_parts
					);
				}
			}

			// Stop parsing after end point
			if ($end !== null and $allowed_count >= $end) {
				continue;
			}

			if ($indentions > 1 and $this->setup->streamDepth > 0) {
				$level =& $this->comments['comments'][$key_parts[0] - 1];

				if ($this->setup->replyMode === 'stream'
				    and $indentions > $this->setup->streamDepth)
				{
					$level =& $this->getRepliesLevel ($level, $this->setup->streamDepth, $key_parts);
					$level =& $level['replies'][];
				} else {
					$level =& $this->getRepliesLevel ($level, $indentions, $key_parts);
				}
			} else {
				$level =& $this->comments['comments'][];
			}

			// Set status to what's stored in the comment
			if (!empty ($comment['status'])) {
				$status = $comment['status'];
			}

			switch ($status) {
				// Parse as pending notice, viewable and editable by owner and admin
				case 'pending': {
					$parsed = $this->commentParser->parse ($comment, $key, $key_parts, false);

					if (!isset ($parsed['user-owned'])) {
						$level = $this->commentParser->notice ('pending', $key, $last_date);
						break;
					}

					$last_date = $parsed['sort-date'];
					$level = $parsed;

					break;
				}

				// Parse as deletion notice, viewable and editable by admin
				case 'deleted': {
					if ($this->login->userIsAdmin === true) {
						$level = $this->commentParser->parse ($comment, $key, $key_parts, false);
						$last_date = $level['sort-date'];
					} else {
						$level = $this->commentParser->notice ('deleted', $key, $last_date);
					}

					break;
				}

				// Parse as deletion notice, non-existent comment
				case 'missing': {
					$level = $this->commentParser->notice ('deleted', $key, $last_date);
					break;
				}

				// Parse as an unknown/error notice
				case 'read-error': {
					$level = $this->commentParser->notice ('error', $key, $last_date);
					break;
				}

				// Otherwise parse comment normally
				default: {
					$comment['status'] = 'approved';
					$level = $this->commentParser->parse ($comment, $key, $key_parts);
					$last_date = $level['sort-date'];

					break;
				}
			}

			$allowed_count++;
		}

		// Reset array keys
		$this->comments['comments'] = array_values ($this->comments['comments']);
	}

	// Parse popular comments
	public function parsePopular ()
	{
		// Initial popular comments array
		$this->comments['popularComments'] = array ();

		// If no comments or popularity limit is 0, return void
		if ($this->readComments->totalCount <= 1
		    or $this->setup->popularityLimit <= 0)
		{
			return;
		}

		// Sort popular comments
		usort ($this->popularList, function ($a, $b) {
			return ($b['popularity'] > $a['popularity']);
		});

		// Calculate how many popular comments will be shown
		$limit = $this->setup->popularityLimit;
		$count = min ($limit, count ($this->popularList));

		// Read, parse, and add popular comments to output
		for ($i = 0; $i < $count; $i++) {
			$item =& $this->popularList[$i];
			$comment = $this->readComments->data->read ($item['key']);
			$parsed = $this->commentParser->parse ($comment, $item['key'], $item['parts'], true);
			$this->comments['popularComments'][$i] = $parsed;
		}
	}

	// Do final initialization work
	public function finalize ()
	{
		// Expire various temporary cookies
		$this->cookies->clear ();

		// Various comment count numbers
		$commentCounts = array (
			'show-count' => $this->commentCount,
			'primary' => $this->readComments->primaryCount,
			'total' => $this->readComments->totalCount,
		);

		// Instantiate HTML output class
		$this->html = new HashOver\HTMLOutput (
			$this->setup,
			$commentCounts
		);

		// Instantiate comment theme templater class
		$this->templater = new HashOver\Templater (
			$this->usage['mode'],
			$this->setup
		);
	}

	// Display all comments as HTML
	public function displayComments ()
	{
		// Instantiate PHP mode class
		$phpmode = new HashOver\PHPMode (
			$this->setup,
			$this->html,
			$this->comments
		);

		// Run popular comments through parser
		if (!empty ($this->comments['popularComments'])) {
			foreach ($this->comments['popularComments'] as $comment) {
				$this->html->popularComments .= $phpmode->parseComment ($comment, null, true) . PHP_EOL;
			}
		}

		// Run primary comments through parser
		if (!empty ($this->comments['comments'])) {
			foreach ($this->comments['comments'] as $comment) {
				$this->html->comments .= $phpmode->parseComment ($comment, null) . PHP_EOL;
			}
		}

		// Start HTML output with initial HTML
		$html  = $this->html->initialHTML ($this->popularList);

		// End statistics and add them as code comment
		$html .= $this->statistics->executionEnd ();

		// Return final HTML
		return $html;
	}
}


text:
package net.njcull.collections;

import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Objects;
import java.util.function.Function;

/**
 * Builder for the {@link ImmutableSortedArrayPropertyMap} class.
 *
 * @param <K> the type of keys maintained by the resulting map
 * @param <V> the type of mapped values
 * @author run2000
 * @version 1/09/2017.
 */
public final class ImmutableSortedArrayPropertyMapBuilder<K,V> {
    private java.util.function.Function<? super V, ? extends K> m_KeySupplier;
    private Comparator<? super K> m_KeyComparator;
    private Object[] m_Values = EMPTY_ELEMENTS;
    private int m_Size = 0;

    private static final Object[] EMPTY_ELEMENTS = new Object[0];
    @SuppressWarnings("unchecked")
    private static final Comparator<Comparable> naturalOrder = Comparator.nullsFirst(Comparator.<Comparable>naturalOrder());

    /**
     * Create a new builder instance that builds a new immutable sorted
     * property map.
     *
     * @param <K> the key type of the map
     * @param <V> the value type of the map
     * @return a new builder for building a new map
     */
    public static <K,V> ImmutableSortedArrayPropertyMapBuilder<K,V> newMap() {
        ImmutableSortedArrayPropertyMapBuilder<K,V> builder = new ImmutableSortedArrayPropertyMapBuilder<>();
        return builder;
    }

    /**
     * Create a new builder instance that builds a new immutable sorted
     * property map, using the given function to provide the keys.
     *
     * @param <K> the key type of the map
     * @param <V> the value type of the map
     * @param supplier the key supplier
     * @return a new builder for building a new map
     */
    public static <K,V> ImmutableSortedArrayPropertyMapBuilder<K,V> newMapWithKeys(Function<? super V, ? extends K> supplier) {
        ImmutableSortedArrayPropertyMapBuilder<K,V> builder = new ImmutableSortedArrayPropertyMapBuilder<>();
        return builder.byKeyMethod(supplier);
    }

    /**
     * Create a new builder instance that builds a new immutable sorted
     * property map, using the given function to provide the keys, and the
     * given comparator to sort the keys within the map.
     *
     * @param <K> the key type of the map
     * @param <V> the value type of the map
     * @param supplier the key supplier
     * @param keyCmp the key comparator
     * @return a new builder for building a new map
     */
    public static <K,V> ImmutableSortedArrayPropertyMapBuilder<K,V> newMapWithKeysComparing(Function<? super V, ? extends K> supplier, Comparator<? super K> keyCmp) {
        ImmutableSortedArrayPropertyMapBuilder<K,V> builder = new ImmutableSortedArrayPropertyMapBuilder<>();
        return builder.byKeyMethod(supplier).byComparingKeys(keyCmp);
    }

    /**
     * Create a new builder instance for constructing a new immutable
     * sorted array property map.
     */
    public ImmutableSortedArrayPropertyMapBuilder() {
    }

    /**
     * Use the supplied function to provide the keys in the resulting map.
     *
     * @param supplier the function to provide the key for each value
     * @return this builder, for chaining purposes
     */
    public ImmutableSortedArrayPropertyMapBuilder<K,V> byKeyMethod(Function<? super V, ? extends K> supplier) {
        this.m_KeySupplier = supplier;
        return this;
    }

    /**
     * Use the supplied comparator to sort the keys in the resulting map.
     *
     * @param cmp the comparator for sorting the keys in the map
     * @return this builder, for chaining purposes
     */
    public ImmutableSortedArrayPropertyMapBuilder<K,V> byComparingKeys(Comparator<? super K> cmp) {
        this.m_KeyComparator = cmp;
        return this;
    }

    /**
     * Sort the keys for the resulting map using the keys' natural order.
     *
     * @return this builder, for chaining purposes
     */
    public ImmutableSortedArrayPropertyMapBuilder<K,V> byNaturalKeyOrder() {
        this.m_KeyComparator = null;
        return this;
    }

    /**
     * All the values from the supplied iterable will be added to the
     * resulting map.
     *
     * @param it the iterable containing values to be added
     * @return this builder, for chaining purposes
     */
    public ImmutableSortedArrayPropertyMapBuilder<K,V> with(Iterable<? extends V> it) {
        int count = 0;

        for(Iterator<? extends V> iIt = it.iterator(); iIt.hasNext(); count++) {
            if((count % 8) == 0) {
                ensureCapacity(8);
            }
            V value = iIt.next();
            m_Values[m_Size++] = value;
        }

        return this;
    }

    /**
     * All the values from the supplied collection will be added to the
     * resulting map.
     *
     * @param coll the collection containing values to be added
     * @return this builder, for chaining purposes
     */
    @SuppressWarnings("unchecked")
    public ImmutableSortedArrayPropertyMapBuilder<K,V> with(Collection<? extends V> coll) {
        int size = coll.size();
        ensureCapacity(size);

        for(V entry : coll) {
            m_Values[m_Size++] = entry;
        }

        return this;
    }

    /**
     * Add the given value to the resulting map.
     *
     * @param val the value to be added
     * @return this builder, for chaining purposes
     */
    public ImmutableSortedArrayPropertyMapBuilder<K,V> with(V val) {
        ensureCapacity(1);
        m_Values[m_Size++] = val;
        return this;
    }

    /**
     * Add the given values to the resulting map.
     *
     * @param v1 the first value to be added
     * @param v2 the second value to be added
     * @return this builder, for chaining purposes
     */
    public ImmutableSortedArrayPropertyMapBuilder<K,V> with(V v1, V v2) {
        ensureCapacity(2);
        m_Values[m_Size++] = v1;
        m_Values[m_Size++] = v2;
        return this;
    }

    /**
     * Add the given values to the resulting map.
     *
     * @param v1 the first value to be added
     * @param v2 the second value to be added
     * @param v3 the third value to be added
     * @return this builder, for chaining purposes
     */
    public ImmutableSortedArrayPropertyMapBuilder<K,V> with(V v1, V v2, V v3) {
        ensureCapacity(3);
        m_Values[m_Size++] = v1;
        m_Values[m_Size++] = v2;
        m_Values[m_Size++] = v3;
        return this;
    }

    /**
     * Add the given values to the resulting map.
     *
     * @param v1 the first value to be added
     * @param v2 the second value to be added
     * @param v3 the third value to be added
     * @param v4 the fourth value to be added
     * @return this builder, for chaining purposes
     */
    public ImmutableSortedArrayPropertyMapBuilder<K,V> with(V v1, V v2, V v3, V v4) {
        ensureCapacity(4);
        m_Values[m_Size++] = v1;
        m_Values[m_Size++] = v2;
        m_Values[m_Size++] = v3;
        m_Values[m_Size++] = v4;
        return this;
    }

    /**
     * Add the given values to the resulting map.
     *
     * @param values the values to be added
     * @return this builder, for chaining purposes
     */
    @SafeVarargs
    public final ImmutableSortedArrayPropertyMapBuilder<K,V> with(V... values) {
        int len = values.length;
        ensureCapacity(len);
        System.arraycopy(values, 0, m_Values, m_Size, len);
        m_Size += len;
        return this;
    }

    /**
     * For the stream combiner, merge the entries from the supplied builder
     * to this builder.
     *

     * Note that we make no assumptions about the key, the key extractor,
     * or the comparator, on the incoming builder.
     *
     * @param entries the builder containing the entries to be merged into
     * this builder
     * @return this builder containing the merged items
     */
    public ImmutableSortedArrayPropertyMapBuilder<K,V> merge(ImmutableSortedArrayPropertyMapBuilder<?, ? extends V> entries) {
        int len = entries.m_Size;
        ensureCapacity(len);
        System.arraycopy(entries.m_Values, 0, m_Values, m_Size, len);
        m_Size += len;
        return this;
    }

    private void ensureCapacity(int capacity) {
        if(m_Values.length - m_Size < capacity) {
            int newLength = m_Size + capacity;
            // round up to divisible by 8
            newLength += (8 - (newLength % 8)) % 8;
            m_Values = Arrays.copyOf(m_Values, newLength);
        }
    }

    /**
     * Returns the number of entries in this builder.
     *
     * @return the number of entries in this builder
     */
    public int size() {
        return m_Size;
    }

    /**
     * Build the immutable map. Validates all keys and values added, including
     * sorting the keys and values, and checking for duplicate keys and values
     * as necessary.
     *

     * Repeated calls to a builder containing a non-zero number of entries
     * will return distinct map instances.
     *
     * @return an ImmutableSortedArrayPropertyMap containing the elements in
     * the builder
     * @throws IllegalStateException there was a duplicate key or value
     * specified in the builder
     */
    @SuppressWarnings("unchecked")
    public ImmutableSortedArrayPropertyMap<K,V> build() {
        if(m_Size == 0) {
            return ImmutableSortedArrayPropertyMap.<K,V>emptyMap();
        }

        Function<? super V, ? extends K> keySupplier = m_KeySupplier;
        Comparator<? super K> keyComparator = m_KeyComparator;
        Comparator nullsKeyComparator = (keyComparator == null) ? naturalOrder : Comparator.nullsFirst(keyComparator);

        Integer[] sortedKeys = new Integer[m_Size];
        Object[] values = Arrays.copyOf(m_Values, m_Size);

        for(int i = 0; i < m_Size; i++) {
            Integer iVal = i;
            sortedKeys[i] = iVal;
        }

        // Sort keys by index, insert sorted values into result array
        ArrayComparator<? extends K, ? super V> arrayComparator = new ArrayComparator<>(values, keySupplier, nullsKeyComparator);
        Arrays.sort(sortedKeys, 0, m_Size, arrayComparator);

        Object[] elements = new Object[m_Size];
        for(int i = 0; i < sortedKeys.length; i++) {
            elements[i] = m_Values[sortedKeys[i]];
        }

        Object prev = keySupplier.apply((V)elements[0]);
        for (int i = 1; i < m_Size; i++) {
            Object o = keySupplier.apply((V)elements[i]);
            int cmp = nullsKeyComparator.compare(o, prev);
            if(cmp == 0) {
                throw new IllegalStateException("duplicate key " + o);
            }
            prev = o;
        }

        return new ImmutableSortedArrayPropertyMap<>(elements, keyComparator, keySupplier);
    }

    /**
     * Reset this builder to its initial state.
     *
     * @return this builder, for chaining purposes
     */
    public ImmutableSortedArrayPropertyMapBuilder<K,V> clear() {
        m_Values = EMPTY_ELEMENTS;
        m_KeyComparator = null;
        m_KeySupplier = null;
        m_Size = 0;
        return this;
    }

    /**
     * Comparator for creating sorted indexes into the key array.
     */
    private static final class ArrayComparator <K,V> implements Comparator<Integer> {
        private final Object[] m_Values;
        private final Function<V, K> m_Supplier;
        private final Comparator<K> m_Delegate;

        public ArrayComparator(Object[] values, Function<V, K> supplier, Comparator<K> delegate) {
            this.m_Values = Objects.requireNonNull(values, "values cannot be null");
            this.m_Supplier = Objects.requireNonNull(supplier, "key supplier cannot be null");
            this.m_Delegate = Objects.requireNonNull(delegate, "delegate cannot be null");
        }

        @SuppressWarnings("unchecked")
        @Override
        public int compare(Integer o1, Integer o2) {
            return m_Delegate.compare(m_Supplier.apply((V)m_Values[o1]), m_Supplier.apply((V)m_Values[o2]));
        }
    }
}


text:
from src.stash import EqualityMixin

class PullRequest(EqualityMixin):
    def __init__(self, pull_request_id, from_branch, to_branch, title, link, project_key, repo_name):
        self.pull_request_id = pull_request_id
        self.from_branch = from_branch
        self.to_branch = to_branch
        self.title = title
        self.link = link
        self.project_key = project_key
        self.repo_name = repo_name

    @classmethod
    def from_json(cls, json):
        pull_request = cls(json['id'],
                           json['fromRef']['displayId'],
                           json['toRef']['displayId'],
                           json['title'],
                           json['links']['self'][0]['href'],
                           json['fromRef']['repository']['project']['key'],
                           json['fromRef']['repository']['name'])
        return pull_request

    def __str__(self):
        return unicode(self).encode('utf-8')

    def __unicode__(self):
        return u'{} #{}: {} → {}'.format(self.repo_name, self.pull_request_id, self.from_branch, self.to_branch)


text:
.. diffusion-maps documentation master file, created by
   sphinx-quickstart on Sat May 20 12:03:02 2017.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to diffusion-maps's documentation!
==========================================

.. toctree::
   :maxdepth: 2
   :caption: Contents:

   modules

.. automodule:: diffusion_maps

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
<footer>

	<span>{{ site.version }}</span>

</footer>


text:
/**
 * Lightbox and gallery combined.
 */

(function($) {

  /**
   * ----------
   * Lightbox-function - Display the lightbox with overlay
   * ----------
   */
  $.fn.lBGlightbox = function(params) {
	//get window (inner) height and width
    var windowHeight = window.innerHeight || $(window).height(), // make it work on ipad & android
        windowWidth  = window.innerWidth  || $(window).width(),
		imgTitle = $(this).attr('title'),
		// extend
		options = $.extend({
		  'fade': false
		}, params),
		fading = options.fade;

	//Remove lightbox and overlay if it's already exists
	$('#lBG-overlay, #lBG-lightbox').remove();

    // Display the overlay (fade or not?)
	if(fading) {
		$('

')
		.css('opacity', '0')
		.animate({'opacity' : '0.9'})
		.appendTo('body');
	} else {
		$('

')
		.css('opacity', '0.9')
		.appendTo('body');
	}

    // Create the lightbox container and hide it
    $('

')
    .hide()
    .appendTo('body');

    // Display the image on load
    $('')
    .attr('src', $(this).attr('src'))
    .css({
      'max-height': windowHeight,
      'max-width':  windowWidth
    })
    .load(function() { //Load image when it's ready
      $('#lBG-lightbox') // center image and fade it in
        .css({  //center image
          'top':  (windowHeight - $('#lBG-lightbox').height()) / 2,
          'left': (windowWidth  - $('#lBG-lightbox').width())  / 2
        })
        .fadeIn('slow');

		$('#lBG-overlay').css('background-image', 'none'); //remove loading image

    })
    .appendTo('#lBG-lightbox');

	if(imgTitle) {
	  // Display the title of the image
	  $('

')
      .hide()
	  .appendTo('#lBG-lightbox');

      $('

')
      .appendTo('#lBG-title-wrapper')
      document.getElementById("lBG-title").innerHTML = imgTitle;
	}

	//show extra info on hover
	$('#lBG-lightbox').hover(function() {
		$('#lBG-arrow-left, #lBG-arrow-right')
		.css('opacity', '0.5');

		$('#lBG-title-wrapper')
		.animate({width:'toggle'},300)
    },
	function() {
		$('#lBG-arrow-left, #lBG-arrow-right')
		.css('opacity', '0');

		$('#lBG-title-wrapper')
		.animate({width:'toggle'},300)
	});

    // Remove it all on click (overlay and image).
    $('#lBG-overlay, #lBG-lightbox').click(function() {
      $('#lBG-overlay, #lBG-lightbox')
	  .fadeOut('slow', function() {
		$(this).remove();
		});
    });

	// Remove it all by pressing the escape key
	$(document).keydown(function(e) {

	  if(e.keyCode == 27) {
		$('#lBG-overlay, #lBG-lightbox')
	    .fadeOut('slow', function() {
		  $(this).remove();
		});
	  }
	});

	return this;

  };

  /**
   * ----------
   * Gallery-function - Display pictures in a gallery
   * ----------
   */
  $.fn.lBGgallery = function(params) {

	// Initializing variables
	var liItems = $(this).children(), //all li elements (child to ul)
	imgItems = liItems.children(), //all img elements (child to li)
	imgCount = liItems.size(), //number of li elements and also the number of images in this case
	options = $.extend({ // extend
      'width': 200,
      'height': 200
    }, params),
	imgWidth = options.width,
	imgHeight = options.height;

	// Set the width and the height of the images
	imgItems.css({
	  'width': imgWidth + 'px',
	  'height': imgHeight + 'px'
	});

	// Load gallery item on click
	imgItems.click(function() {
	  //save the index of the clicked item
	  var imgId = $(this).parent().index();

	  //load the selected image
	  loadImg($(this), imgId);
	});

	/**
	 * Display the selected image
	 */
	function loadImg(img, imgId) {
	    //show image with the lightbox-plug
	    img.lBGlightbox();

	    //create/show navigation
	    createNavitagion(imgId);
	}

	/**
	 * Create the navigation arrows
	 */
	function createNavitagion(imgId) {
	  var prevImg,
	    nextImg,
		navHeight = 50,
		navMiddle = ($('#lBG-lightbox').height() - navHeight) / 2;

	  //create left nav-arrow only if imgId is not 0
	  if(imgId !== 0) {
		//prev image
		prevImg = $(liItems).eq(imgId - 1).children();

		//create left nav-arrow
		$('

')
          .appendTo('#lBG-lightbox')
          .css({left: '0px', top: navMiddle})
          .click(function() { //load prev image on click
            loadImg(prevImg, imgId - 1);
          });

		$('

')
          .appendTo('#lBG-arrow-left');

	  } else {
		//last image
		prevImg = $(liItems).eq(imgCount-1).children();

		//create left nav-arrow
		$('

')
          .appendTo('#lBG-lightbox')
          .css({left: '0px', top: navMiddle})
          .click(function() { //load prev image on click
            loadImg(prevImg, imgCount-1);
          });

		$('

')
          .appendTo('#lBG-arrow-left');
	  }

	  //create right nav-arrow
	  if(imgId+1 < imgCount) {
		//next image
		nextImg = $(liItems).eq(imgId + 1).children();

		//create right nav-arrow
		$('

')
          .appendTo('#lBG-lightbox')
          .css({right: '0px', top: navMiddle})
          .click(function() { //load next image on click
            loadImg(nextImg, imgId + 1);
          });

		$('

')
          .appendTo('#lBG-arrow-right');
	  } else {
		//next image
		nextImg = $(liItems).eq(0).children();

		//create right nav-arrow
		$('

')
          .appendTo('#lBG-lightbox')
          .css({right: '0px', top: navMiddle})
          .click(function() { //load next image on click
            loadImg(nextImg, 0);
          });

		$('

')
          .appendTo('#lBG-arrow-right');
	  }

	}

	return this;

  };

})(jQuery);


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('courses', '0008_auto_20210320_2252'),
    ]

    operations = [
        migrations.RenameField(
            model_name='course',
            old_name='easyCI',
            new_name='easyCI_url',
        ),
    ]


text:
body { padding-top: 70px; }
#menu .navbar-brand {
  background-image: url("../img/logo.svg");
  background-repeat: no-repeat;
  background-position: 4px center;
  background-size: auto 90%;
  padding: 8px 0 8px 40px;
  height: 50px;
  color: #eee;
}
#menu .navbar-brand>span {
  text-align: center;
  text-transform: uppercase;
  line-height: 34px;
}
#menu .navbar-brand>span>span {
  display: block;
  line-height: 10px;
  font-size: 10px;
}
#menu .navbar-brand>span>.focus {
  line-height: 24px;
  font-family: serif;
  font-size: 24px;
}
#home .navbar-brand {
  background-image: url("../img/logo2.svg");
  background-repeat: no-repeat;
  background-position: center;
  background-size: auto 90%;
  padding: 8px 0 8px 40px;
  height: 200px;
}
@media (min-width:992px){
#home {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    height: 30%;
    margin: auto;
}
#resumen p{
    font-size: 15px;font-size: 1.5rem;-webkit-column-count:3;/* Chrome, Safari, Opera */-moz-column-count: 3;/* Firefox */column-count: 3;
}
}
#resumen p {
    font-size: 15px;font-size: 1.5rem;
}
/*.searchform #search_q{width: 80%;height:20px;padding: 5px;float: left;border: 0;background: #eee;border-radius: 3px 0 0 3px;box-shadow: 0 1px 1px rgba(0,0,0,.4) inset;box-sizing: initial;-webkit-box-sizing: initial;font: 16px arial,sans-serif;}*/
.searchform #search_q:focus {
    outline: 0;
    background: #fff;
    box-shadow: 0 0 2px rgba(0,0,0,.8) inset;}
/*#search_q:-webkit-input-placeholder, input:-moz-placeholder,input:-ms-input-placeholder {
    color: #999;
    font-weight: normal;
    font-style: italic;
    box-sizing: initial;*/
}
.searchform #search_submit {
    /*width: 12%;*/
    color: #fff;
    background: #438cdb;
    /*height: 30px;*/
    }
/*.searchform select {
    height: 25px;
    background: rgba(38,114,224,0.5);
}
.searchform #search_submit, select {
    position: relative;
    border: 0;
    cursor: pointer;
    font-size:15px;
    border-radius: 0 3px 3px 0;
    text-shadow: 0 -1px 0 rgba(0, 0 ,0, .3);}*/
.searchform #search_submit:hover, .searchform select:hover{color: #fff;background: #2672e0;}
.searchform #search_submit:active,.searchform #search_submit:focus{background: #2672e0;}
.searchform #search_submit:before { /* flecha */content: '';position: absolute;border-width: 8px 8px 8px 0;border-style: solid solid solid none;border-color: transparent #438cdb transparent;top: 8px;left: -5px;}
.searchform #search_submit:hover:before{border-right-color: #2672e0;}
.searchform #search_submit:focus:before{border-right-color: #2672e0;}

.reciente p {max-height: 6rem;overflow: hidden;}.reciente p:after {content:'...';position: absolute;top: 6.5rem;right: 15px;}.reciente {border-width: medium; border: 1px solid rgba(150,150,150,0.3137254901960784); padding: 20px 25px 30px; border-radius: 2px; box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);}
/*.form-compacto .input-group .form-control {
width: initial;
}
.form-compacto select
{width: 100%;}*/
textarea.form-control{
    min-height:100px;
}

.searchform #search_submit:disabled { background: rgba(38,114,224,0.5); cursor: not-allowed;}

.separator { padding-right:5px;padding-left:5px; }
.section-box hr {margin-top: 0;margin-bottom: 5px;border: 0;border-top: 1px solid rgb(199, 199, 199);}

.oculto {
  border-color: #a94442;
  background-color: #f2dede;
}
.error {
  border-color: #a94442;
}
.valid {
  border-color: #3c763d;
}

.warning {
  border-color: yellow;
}
tags-input[name="biblioteca_tegbundle_teg[keyWords]"].error > div > div {
  border-color: #a94442;
  -webkit-box-shadow: 0 0 0 0 rgb(169, 68, 66);
  -moz-box-shadow: 0 0 0 0 rgb(169, 68, 66);
    box-shadow: 0 0 0 0 rgb(169, 68, 66);
}
tags-input[name="biblioteca_tegbundle_teg[keyWords]"].valid > div > div {
  border-color: #3c763d;
  -webkit-box-shadow: 0 0 0 0 rgb(60, 118, 61);
  -moz-box-shadow: 0 0 0 0 rgb(60, 118, 61);
    box-shadow: 0 0 0 0 rgb(60, 118, 61);
}
tags-input[name="biblioteca_tegbundle_teg[keyWords]"].defaultTags > div > div {
  -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
    box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
}
tags-input[name="biblioteca_tegbundle_teg[keyWords]"] > div > div {
  color: #555;
  background-color: #fff;
  background-image: none;
  border: 1px solid #ccc;
  border-radius: 4px;

}
.drop-box {
    background: #F8F8F8;
    border: 5px dashed #DDD;
    width: 200px;
    height: 65px;
    text-align: center;
    padding-top: 25px;
    margin: 10px;
}
.dragover {
    border: 5px dashed blue;
}


text:
package org.bluecabin.textoo;

import android.text.Html;
import android.text.Spanned;
import android.text.util.Linkify;

import java.util.regex.Pattern;

/**
 * Base configurator for java.lang.String
 */
public abstract class StringConfigurator extends Configurator<String>
        implements TextLinkify<Spanned, SpannedConfigurator> {
    protected StringConfigurator(TextooContext textooContext) {
        super(textooContext);
    }

    // Re-declare abstract methods with generic return type to enable scala implementations

    @Override
    public abstract String apply();

    @Override
    public abstract SpannedConfigurator linkifyEmailAddresses();

    @Override
    public abstract SpannedConfigurator linkifyMapAddresses();

    @Override
    public abstract SpannedConfigurator linkifyPhoneNumbers();

    @Override
    public abstract SpannedConfigurator linkifyWebUrls();

    @Override
    public abstract SpannedConfigurator linkifyAll();

    @Override
    public abstract SpannedConfigurator linkify(Pattern pattern, String scheme);

    @Override
    public abstract SpannedConfigurator linkify(Pattern p, String scheme, Linkify.MatchFilter matchFilter,
                                                Linkify.TransformFilter transformFilter);

    /**
     * See android.text.Html.fromHtml(java.lang.String)
     *
     */
    public abstract SpannedConfigurator parseHtml();

    /**
     * See android.text.Html#fromHtml(java.lang.String, android.text.Html.ImageGetter, android.text.Html.TagHandler)
     *
     */
    public abstract SpannedConfigurator parseHtml(Html.ImageGetter imageGetter,
                                                  Html.TagHandler tagHandler);

}


text:
package antlr;

/* ANTLR Translator Generator
 * Project led by Terence Parr at http://www.jGuru.com
 * Software rights: http://www.antlr.org/license.html
 *
 * $Id: //depot/code/org.antlr/release/antlr-2.7.5/antlr/Grammar.java#1 $
 */

import java.util.Hashtable;
import java.util.Enumeration;
import java.io.IOException;

import antlr.collections.impl.BitSet;
import antlr.collections.impl.Vector;

/**A Grammar holds a set of rules (which are stored
 * in a symbol table).  Most of the time a grammar
 * needs a code generator and an LLkAnalyzer too.
 */
public abstract class Grammar {
    protected Tool antlrTool;
    protected CodeGenerator generator;
    protected LLkGrammarAnalyzer theLLkAnalyzer;
    protected Hashtable symbols;
    protected boolean buildAST = false;
    protected boolean analyzerDebug = false;
    protected boolean interactive = false;
    protected String superClass = null;

    /** The token manager associated with the grammar, if any.
     // The token manager is responsible for maintaining the set of valid tokens, and
     // is conceptually shared between the lexer and parser.  This may be either a
     // LexerGrammar or a ImportVocabTokenManager.
     */
    protected TokenManager tokenManager;

    /** The name of the export vocabulary...used to generate the output
     *  token types interchange file.
     */
    protected String exportVocab = null;

    /** The name of the import vocabulary.  "Initial conditions"
     */
    protected String importVocab = null;

    // Mapping from String keys to Token option values
    protected Hashtable options;
    // Vector of RuleSymbol entries
    protected Vector rules;

    protected Token preambleAction = new CommonToken(Token.INVALID_TYPE, "");
    protected String className = null;
    protected String fileName = null;
    protected Token classMemberAction = new CommonToken(Token.INVALID_TYPE, "");
    protected boolean hasSyntacticPredicate = false;
    protected boolean hasUserErrorHandling = false;

    // max lookahead that can be attempted for this parser.
    protected int maxk = 1;

    // options
    protected boolean traceRules = false;
    protected boolean debuggingOutput = false;
    protected boolean defaultErrorHandler = true;

    protected String comment = null; // javadoc comment

    public Grammar(String className_, Tool tool_, String superClass) {
        className = className_;
        antlrTool = tool_;
        symbols = new Hashtable();
        options = new Hashtable();
        rules = new Vector(100);
        this.superClass = superClass;
    }

    /** Define a rule */
    public void define(RuleSymbol rs) {
        rules.appendElement(rs);
        // add the symbol to the rules hash table
        symbols.put(rs.getId(), rs);
    }

    /** Top-level call to generate the code for this grammar */
    public abstract void generate() throws IOException;

    protected String getClassName() {
        return className;
    }

    /* Does this grammar have a default error handler? */
    public boolean getDefaultErrorHandler() {
        return defaultErrorHandler;
    }

    public String getFilename() {
        return fileName;
    }

    /** Get an integer option.  Given the name of the option find its
     * associated integer value.  If the associated value is not an integer or
     * is not in the table, then throw an exception of type NumberFormatException.
     * @param key The name of the option
     * @return The value associated with the key.
     */
    public int getIntegerOption(String key) throws NumberFormatException {
        Token t = (Token)options.get(key);
        if (t == null || t.getType() != ANTLRTokenTypes.INT) {
            throw new NumberFormatException();
        }
        else {
            return Integer.parseInt(t.getText());
        }
    }

    /** Get an option.  Given the name of the option find its associated value.
     * @param key The name of the option
     * @return The value associated with the key, or null if the key has not been set.
     */
    public Token getOption(String key) {
        return (Token)options.get(key);
    }

    // Get name of class from which generated parser/lexer inherits
    protected abstract String getSuperClass();

    public GrammarSymbol getSymbol(String s) {
        return (GrammarSymbol)symbols.get(s);
    }

    public Enumeration getSymbols() {
        return symbols.elements();
    }

    /** Check the existence of an option in the table
     * @param key The name of the option
     * @return true if the option is in the table
     */
    public boolean hasOption(String key) {
        return options.containsKey(key);
    }

    /** Is a rule symbol defined? (not used for tokens) */
    public boolean isDefined(String s) {
        return symbols.containsKey(s);
    }

    /**Process command line arguments.  Implemented in subclasses */
    public abstract void processArguments(String[] args);

    public void setCodeGenerator(CodeGenerator gen) {
        generator = gen;
    }

    public void setFilename(String s) {
        fileName = s;
    }

    public void setGrammarAnalyzer(LLkGrammarAnalyzer a) {
        theLLkAnalyzer = a;
    }

    /** Set a generic option.
     * This associates a generic option key with a Token value.
     * No validation is performed by this method, although users of the value
     * (code generation and/or analysis) may require certain formats.
     * The value is stored as a token so that the location of an error
     * can be reported.
     * @param key The name of the option.
     * @param value The value to associate with the key.
     * @return true if the option was a valid generic grammar option, false o/w
     */
    public boolean setOption(String key, Token value) {
        options.put(key, value);
        String s = value.getText();
        int i;
        if (key.equals("k")) {
            try {
                maxk = getIntegerOption("k");
				if ( maxk<=0 ) {
					antlrTool.error("option 'k' must be greater than 0 (was " +
									value.getText() + ")",
									getFilename(),
									value.getLine(),
									value.getColumn());
					maxk = 1;
				}
            }
            catch (NumberFormatException e) {
                antlrTool.error("option 'k' must be an integer (was " + value.getText() + ")", getFilename(), value.getLine(), value.getColumn());
            }
            return true;
        }
        if (key.equals("codeGenMakeSwitchThreshold")) {
            try {
                i = getIntegerOption("codeGenMakeSwitchThreshold");
            }
            catch (NumberFormatException e) {
                antlrTool.error("option 'codeGenMakeSwitchThreshold' must be an integer", getFilename(), value.getLine(), value.getColumn());
            }
            return true;
        }
        if (key.equals("codeGenBitsetTestThreshold")) {
            try {
                i = getIntegerOption("codeGenBitsetTestThreshold");
            }
            catch (NumberFormatException e) {
                antlrTool.error("option 'codeGenBitsetTestThreshold' must be an integer", getFilename(), value.getLine(), value.getColumn());
            }
            return true;
        }
        if (key.equals("defaultErrorHandler")) {
            if (s.equals("true")) {
                defaultErrorHandler = true;
            }
            else if (s.equals("false")) {
                defaultErrorHandler = false;
            }
            else {
                antlrTool.error("Value for defaultErrorHandler must be true or false", getFilename(), value.getLine(), value.getColumn());
            }
            return true;
        }
        if (key.equals("analyzerDebug")) {
            if (s.equals("true")) {
                analyzerDebug = true;
            }
            else if (s.equals("false")) {
                analyzerDebug = false;
            }
            else {
                antlrTool.error("option 'analyzerDebug' must be true or false", getFilename(), value.getLine(), value.getColumn());
            }
            return true;
        }
        if (key.equals("codeGenDebug")) {
            if (s.equals("true")) {
                analyzerDebug = true;
            }
            else if (s.equals("false")) {
                analyzerDebug = false;
            }
            else {
                antlrTool.error("option 'codeGenDebug' must be true or false", getFilename(), value.getLine(), value.getColumn());
            }
            return true;
        }
        if (key.equals("classHeaderSuffix")) {
            return true;
        }
        if (key.equals("classHeaderPrefix")) {
            return true;
        }
        if (key.equals("namespaceAntlr")) {
            return true;
        }
        if (key.equals("namespaceStd")) {
            return true;
        }
        if (key.equals("genHashLines")) {
            return true;
        }
        if (key.equals("noConstructors")) {
            return true;
        }
        return false;
    }

    public void setTokenManager(TokenManager tokenManager_) {
        tokenManager = tokenManager_;
    }

    /** Print out the grammar without actions */
    public String toString() {
        StringBuffer buf = new StringBuffer(20000);
        Enumeration ids = rules.elements();
        while (ids.hasMoreElements()) {
            RuleSymbol rs = (RuleSymbol)ids.nextElement();
            if (!rs.id.equals("mnextToken")) {
                buf.append(rs.getBlock().toString());
                buf.append("\n\n");
            }
        }
        return buf.toString();
    }

}


text:
package main

// create collections if not exist and ensure indexes

const USERS = "users"
const LOGINATTEMPTS = "loginattempts"
const ACCOUNTS = "accounts"
const ADMINGROUPS = "admingroups"
const CATEGORIES = "categories"
const STATUSES = "status"
const ADMINS = "admins"

func init() {

	db := getMongoDBInstance()
	defer db.Session.Close()

	c := db.C(USERS)
	c.EnsureIndex(UserUniqueIndex)
	c.EnsureIndex(UserIndex)

	c = db.C(LOGINATTEMPTS)
	c.EnsureIndex(LoginAttemptsIndex)

	c = db.C(ACCOUNTS)
	c.EnsureIndex(AccountIndex)

	c = db.C(ADMINGROUPS)
	c.EnsureIndex(AdminGroupIndex)

	c = db.C(CATEGORIES)
	c.EnsureIndex(CategoryIndex)

	c = db.C(STATUSES)
	c.EnsureIndex(StatusesIndex)

	c = db.C(ADMINS)
	c.EnsureIndex(AdminsIndex)

}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cc.congyi.persistence.mybatis.DealerMapper" >
  <resultMap id="BaseResultMap" type="cc.congyi.model.Dealer" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="login_name" property="loginName" jdbcType="VARCHAR" />
    <result column="login_pwd" property="loginPwd" jdbcType="VARCHAR" />
    <result column="organization_name" property="organizationName" jdbcType="VARCHAR" />
    <result column="integral" property="integral" jdbcType="INTEGER" />
    <result column="state" property="state" jdbcType="INTEGER" />
    <result column="create_time" property="createTime" jdbcType="VARCHAR" />
    <result column="last_edit_time" property="lastEditTime" jdbcType="VARCHAR" />
    <result column="is_delete" property="isDelete" jdbcType="CHAR" />
  </resultMap>
  <sql id="Base_Column_List" >
    id, login_name, login_pwd, organization_name, integral, state, create_time, last_edit_time,
    is_delete
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select
    <include refid="Base_Column_List" />
    from dealer
    where id = #{id,jdbcType=INTEGER}
  </select>
  <!-- -->
  <select id="queryDealerListByConditionWithPage" resultMap="BaseResultMap" parameterType="map" >
    select
    <include refid="Base_Column_List" />
    from dealer
    <include refid="whereCondition" />
    order by create_time desc
    <if test="offset != null and limit != null">
      LIMIT #{offset,jdbcType=INTEGER}, #{limit,jdbcType=INTEGER}
    </if>
  </select>
  <!-- -->
  <select id="queryDealerCountByCondition" resultType="java.lang.Integer" parameterType="map" >
    select count(id)
    from dealer
    <include refid="whereCondition" />
  </select>
  <sql id="whereCondition">
    <where>
      <if test="loginName != null" >
        and login_name = #{loginName,jdbcType=VARCHAR}
      </if>
      <if test="organizationName != null" >
        and organization_name = #{organizationName,jdbcType=VARCHAR}
      </if>
      <if test="integral != null" >
        and integral = #{integral,jdbcType=INTEGER}
      </if>
      <if test="state != null" >
        and state = #{state,jdbcType=INTEGER}
      </if>
      <if test="createTime != null" >
        and create_time = #{createTime,jdbcType=VARCHAR}
      </if>
      <if test="isDelete != null" >
        and is_delete = #{isDelete,jdbcType=CHAR}
      </if>
    </where>
  </sql>
  <insert id="insert" parameterType="cc.congyi.model.Dealer" >
    <selectKey resultType="java.lang.Integer" keyProperty="id" order="AFTER" >
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into dealer (login_name, login_pwd, organization_name,
      integral, state, create_time,
      last_edit_time, is_delete)
    values (#{loginName,jdbcType=VARCHAR}, #{loginPwd,jdbcType=VARCHAR}, #{organizationName,jdbcType=VARCHAR},
      #{integral,jdbcType=INTEGER}, #{state,jdbcType=INTEGER}, #{createTime,jdbcType=VARCHAR},
      #{lastEditTime,jdbcType=VARCHAR}, #{isDelete,jdbcType=CHAR})
  </insert>
  <insert id="insertSelective" parameterType="cc.congyi.model.Dealer" >
    <selectKey resultType="java.lang.Integer" keyProperty="id" order="AFTER" >
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into dealer
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="loginName != null" >
        login_name,
      </if>
      <if test="loginPwd != null" >
        login_pwd,
      </if>
      <if test="organizationName != null" >
        organization_name,
      </if>
      <if test="integral != null" >
        integral,
      </if>
      <if test="state != null" >
        state,
      </if>
      <if test="createTime != null" >
        create_time,
      </if>
      <if test="lastEditTime != null" >
        last_edit_time,
      </if>
      <if test="isDelete != null" >
        is_delete,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="loginName != null" >
        #{loginName,jdbcType=VARCHAR},
      </if>
      <if test="loginPwd != null" >
        #{loginPwd,jdbcType=VARCHAR},
      </if>
      <if test="organizationName != null" >
        #{organizationName,jdbcType=VARCHAR},
      </if>
      <if test="integral != null" >
        #{integral,jdbcType=INTEGER},
      </if>
      <if test="state != null" >
        #{state,jdbcType=INTEGER},
      </if>
      <if test="createTime != null" >
        #{createTime,jdbcType=VARCHAR},
      </if>
      <if test="lastEditTime != null" >
        #{lastEditTime,jdbcType=VARCHAR},
      </if>
      <if test="isDelete != null" >
        #{isDelete,jdbcType=CHAR},
      </if>
    </trim>
  </insert>
  <update id="updateIntegralByDealerId" parameterType="map">
    update dealer
    <set >
      <choose>
        <when test="operator == 'plus'">
          integral = integral + #{integralNum,jdbcType=INTEGER},
        </when>
        <when test="operator == 'minus'">
          integral = integral - #{integralNum,jdbcType=INTEGER},
        </when>
      </choose>
        last_edit_time = now(),
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="cc.congyi.model.Dealer" >
    update dealer
    <set >
      <if test="loginName != null" >
        login_name = #{loginName,jdbcType=VARCHAR},
      </if>
      <if test="loginPwd != null" >
        login_pwd = #{loginPwd,jdbcType=VARCHAR},
      </if>
      <if test="organizationName != null" >
        organization_name = #{organizationName,jdbcType=VARCHAR},
      </if>
      <if test="integral != null" >
        integral = #{integral,jdbcType=INTEGER},
      </if>
      <if test="state != null" >
        state = #{state,jdbcType=INTEGER},
      </if>
      <if test="createTime != null" >
        create_time = #{createTime,jdbcType=VARCHAR},
      </if>
      <if test="lastEditTime != null" >
        last_edit_time = #{lastEditTime,jdbcType=VARCHAR},
      </if>
      <if test="isDelete != null" >
        is_delete = #{isDelete,jdbcType=CHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="cc.congyi.model.Dealer" >
    update dealer
    set login_name = #{loginName,jdbcType=VARCHAR},
      login_pwd = #{loginPwd,jdbcType=VARCHAR},
      organization_name = #{organizationName,jdbcType=VARCHAR},
      integral = #{integral,jdbcType=INTEGER},
      state = #{state,jdbcType=INTEGER},
      create_time = #{createTime,jdbcType=VARCHAR},
      last_edit_time = #{lastEditTime,jdbcType=VARCHAR},
      is_delete = #{isDelete,jdbcType=CHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>


text:
//============================================================================
// Copyright 5AM Solutions, Inc
// Copyright Ekagra Software Technologies Ltd.
// Copyright Guidewire Architecture
// Copyright The Ohio State University Research Foundation
// Copyright SAIC
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/iso21090/LICENSE.txt for details.
//============================================================================

package gov.nih.nci.iso21090.grid.ser;

import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.namespace.QName;

import org.apache.axis.Constants;
import org.apache.axis.encoding.SerializationContext;
import org.apache.axis.encoding.Serializer;
import org.apache.axis.wsdl.fromJava.Types;
import org.w3c.dom.Element;
import org.xml.sax.Attributes;

/**
 * JAXB based serializer.
 *
 * @author gax
 */
public class JaxbSerializer implements Serializer {

    private static final long serialVersionUID = -3204978709399586948L;

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings({ "PMD.PreserveStackTrace", "PMD.AvoidPrintStackTrace" })
    public void serialize(QName name, Attributes attributes, Object value, SerializationContext context)
            throws IOException {
        try {
            JAXBContext jaxbContext = JaxbContextManager.getContextForPackage(value.getClass().getPackage().getName());
            Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
            // marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.marshal(value, new Filter(context));
        } catch (Exception e) {
            e.printStackTrace();
            IOException ioe = new IOException(e.getMessage());
            ioe.initCause(e);
            throw ioe;
        }
    }

    /**
     * {@inheritDoc}
     */
    public String getMechanismType() {
        return Constants.AXIS_SAX;
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings({ "unchecked", "PMD.SignatureDeclareThrowsException" })
    public Element writeSchema(final Class javaType, final Types types) throws Exception {
        return null;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromAlpha="100"
    android:toAlpha="0"
    android:duration="500">

</alpha>


text:
          search
          <input type="text" #searchTerm materialize="autocomplete" [materializeParams]="keywords" (keyup.enter)="getUsersByKeyword(searchTerm.value)"
            id="autocomplete-input" class="autocomplete">
          search volunteers

        <form materialize>
          Titles

            <input type="checkbox" class="filled-in" id="{{title.name}}" />
            {{title.name}}

          Skills

            <input type="checkbox" class="filled-in" id="{{skill.name}}" />
            {{skill.name}}

        </form>

{{users?.length}} volunteers found

        mood

            {{user.firstName + ' ' + user.lastName}}

            {{user.state + ', ' + user.country}}

            Joined "TODO (add date to model)"

Title

Skills

 1}">
            chevron_left

            {{page}}

          <li (click)="setPage(pager.currentPage + 1)" [ngClass]="{disabled:pager.currentPage === pager.totalPages, 'waves-effect': pager.currentPage < pager.totalPages}">
            chevron_right


text:
<?php

use Threema\MsgApi\Connection;
use Threema\MsgApi\ConnectionSettings;

//include_project
require_once 'bootstrap.php';

//define your connection settings
$settings = new ConnectionSettings(
	'*YOUR_GATEWAY_THREEMA_ID',
	'YOUR_GATEWAY_THREEMA_ID_SECRET'
);

//public key store file
//best practice: create a publickeystore
//$publicKeyStore = new Threema\MsgApi\PublicKeyStores\PhpFile('keystore.php');
$publicKeyStore = null;

//create a connection
$connector = new Connection($settings, $publicKeyStore);

$senderPrivateKey = "MY_PUBLIC_KEY_IN_BIN";

$e2eHelper = new \Threema\MsgApi\Helpers\E2EHelper($senderPrivateKey,$connector);
$result = $e2eHelper->sendTextMessage("TEST1234", "This is an end-to-end encrypted message");

if(true === $result->isSuccess()) {
	echo 'Message ID: '.$result->getMessageId() . "\n";
}
else {
	echo 'Error: '.$result->getErrorMessage() . "\n";
}


text:
class RmOldPetsfromAdoptionApp < ActiveRecord::Migration[4.2]
  def change
    remove_column :adoption_apps, :prior_pets
    remove_column :adoption_apps, :vet_name
    remove_column :adoption_apps, :vet_phone
    add_column :adoption_apps, :vet_info, :text
  end

end


text:
namespace Easings {
namespace Quart {
		float easeIn(float t,float b , float c, float d);
		float easeOut(float t,float b , float c, float d);
		float easeInOut(float t,float b , float c, float d);
};
};

#endif


text:
using System;
using System.Linq;

namespace _03.Safe_Manipulation
{
    class Program
    {
        static void Main()
        {
            string[] input = Console.ReadLine().Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
            string[] command = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            while (command[0] != "END")
            {
                switch (command[0])
                {
                    case "Distinct":
                        input = input.Distinct().ToArray();
                        break;
                    case "Reverse":
                        Array.Reverse(input);
                        break;
                    case "Replace":
                        string newWord = command[2];
                        int index = int.Parse(command[1]);
                        if (index >= input.Length || index < 0)
                        {
                            Console.WriteLine("Invalid input!");
                        }
                        else
                        {
                            input[index] = newWord;
                        }
                        break;
                    default:
                        Console.WriteLine("Invalid input!");
                        break;
                }
                command = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            }
            Console.WriteLine(String.Join(", ", input));
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--L
   Copyright Ekagra Software Technologies Ltd.
   Copyright SAIC, SAIC-Frederick

   Distributed under the OSI-approved BSD 3-Clause License.
   See http://ncip.github.com/common-security-module/LICENSE.txt for details.
L-->

<file
  name="nih/nci/security/upt/actions/LogoutAction.java"
  last-modified="0"
  file="/home/csmuser/nih/nci/security/upt/actions/LogoutAction.java"
>
  <violation
    line="142"
    source="IfStmtsMustUseBraces"
    severity="Medium"
    type="pmd"
    message="Avoid using if statements without curly braces"
    severity-level="2"
    popup-message="Avoid using if statements without curly braces"
  />
  <violation
    line="147"
    source="IfStmtsMustUseBraces"
    severity="Medium"
    type="pmd"
    message="Avoid using if statements without curly braces"
    severity-level="2"
    popup-message="Avoid using if statements without curly braces"
  />
  <violation
    line="162"
    source="UnusedPrivateMethod"
    severity="Medium"
    type="pmd"
    message="Avoid unused private methods such as 'getUPTContextName()'."
    severity-level="2"
    popup-message="Avoid unused private methods such as 'getUPTContextName()'."
  />
  <type type='pmd' number='3' suppressed='0'/>
</file>


text:
package loggregator_trafficcontroller
/*
* File Generated by enaml generator
* !!! Please do not edit this file !!!
*/
type Doppler struct {

	/*OutgoingPort - Descr: Port for outgoing doppler messages Default: 8081
*/
	OutgoingPort interface{} `yaml:"outgoing_port,omitempty"`

}


text:
package com.fulcrumgenomics.coord

import com.fulcrumgenomics.coord.LocatableOrderingTest._
import com.fulcrumgenomics.fasta.{SequenceDictionary, SequenceMetadata}
import com.fulcrumgenomics.testing.UnitSpec
import htsjdk.samtools.util.{Interval, Locatable}

/** Companion object for [[LocatableOrderingTest]]. */
object LocatableOrderingTest {

  /** The reference sequence name for chromosome 1. */
  private val Chr1: String = "chr1"

  /** The reference sequence name for chromosome 2. */
  private val Chr2: String = "chr2"

  /** The sequence dictionary for the ordering. */
  private val Dict: SequenceDictionary = SequenceDictionary(SequenceMetadata(Chr1), SequenceMetadata(Chr2))

  /** The ordering of the given <Dict>. */
  private val Ordering: Ordering[Locatable] = LocatableOrdering(Dict)
}

/** Unit tests for [[LocatableOrdering]]. */
class LocatableOrderingTest extends UnitSpec {

  "LocatableOrdering" should "know when two locatables are equivalent" in {
    val interval1 = new Interval(Chr1, 1, 1)
    val interval2 = new Interval(Chr1, 1, 1)
    Ordering.compare(interval1, interval2) shouldBe 0
  }

  it should "know when one Locatable is more 'left' than another Locatable on the same contig" in {
    val interval1 = new Interval(Chr1, 1, 1)
    val interval2 = new Interval(Chr1, 2, 2)
    Ordering.compare(interval1, interval2) should be < 0
  }

  it should "know when one Locatable is more 'right' than another Locatable on the same contig" in {
    val interval1 = new Interval(Chr1, 2, 2)
    val interval2 = new Interval(Chr1, 1, 2)
    Ordering.compare(interval1, interval2) should be > 0
  }

  it should "know when one Locatable is more 'left' than another Locatable on a further 'right' contig" in {
    val interval1 = new Interval(Chr1, 1, 1)
    val interval2 = new Interval(Chr2, 1, 1)
    Ordering.compare(interval1, interval2) should be < 0
  }

  it should "know when one Locatable is more 'right' than another Locatable on a further 'left' contig" in {
    val interval1 = new Interval(Chr2, 1, 1)
    val interval2 = new Interval(Chr1, 1, 1)
    Ordering.compare(interval1, interval2) should be > 0
  }

  it should "raise an exception when any of the locatables are aligned to contigs that don't exist" in {
    val interval1 = new Interval(Chr1, 1, 1)
    val interval2 = new Interval("ChrDoesNotExist", 1, 1)
    a[NoSuchElementException] shouldBe thrownBy { Ordering.compare(interval1, interval2) }
  }

  it should "order genomic locatables first by contig, then start, then end" in {
    val intervals = Seq(
      new Interval(Chr2, 2, 5),
      new Interval(Chr2, 2, 9),
      new Interval(Chr1, 2, 5),
      new Interval(Chr1, 2, 5),
      new Interval(Chr1, 4, 5)
    )
    val expected  = Seq(
      new Interval(Chr1, 2, 5),
      new Interval(Chr1, 2, 5),
      new Interval(Chr1, 4, 5),
      new Interval(Chr2, 2, 5),
      new Interval(Chr2, 2, 9)
    )
    intervals.min(Ordering) shouldBe new Interval(Chr1, 2, 5)
    intervals.max(Ordering) shouldBe new Interval(Chr2, 2, 9)
    intervals.sorted(Ordering) should contain theSameElementsInOrderAs expected
  }
}


text:
'use strict';

var validRegExp = require('../../valid-reg-exp');

module.exports = function (string) {
	validRegExp(this);
	return String(string).search(this);
};


text:
<?php

namespace KevRou\Bundle\SiteBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class KevRouSiteBundle extends Bundle
{
	public function getParent()
    {
        return 'FOSUserBundle';
    }
}


text:
import logging

from pkg_resources import iter_entry_points
from pyramid.config import Configurator

from amnesia.security.policy import cookie_security_policy
from amnesia.traversal import AmnesiaResourceURL
from amnesia.resources import get_root
from amnesia.modules.folder import Folder
from amnesia.modules.folder import FolderEntity
from amnesia.modules.document import Document
from amnesia.modules.document import DocumentEntity
from amnesia.modules.event import Event
from amnesia.modules.event import EventEntity
from amnesia.modules.file import File
from amnesia.modules.file import FileEntity

log = logging.getLogger(__name__)  # pylint: disable=C0103

def include_pyramid_addons(config):
    config.include('pyramid_chameleon')
    config.include('pyramid_tm')
    config.include('pyramid_mailer')

def include_security_policy(config):
    policy = cookie_security_policy(config.registry.settings)
    config.set_security_policy(policy)

def include_session(config):
    config.include('pyramid_beaker')

#    session_package = settings.pop('session.package', None)
#
#    if session_package == 'nacl':
#        config.include('pyramid_nacl_session')
#    elif session_package == 'beaker':
#        session_type = settings.get('session.type')
#        if session_type == 'ext:sqla':
#            # FIXME: don't use it yet, there are <idle in transaction>
#            # issues
#            from pyramid_beaker import session_factory_from_settings
#            config.include('amnesia.db')
#            settings['session.bind'] = registry['engine']
#            settings['session.table'] = registry['metadata'].tables['_sessions']
#            factory = session_factory_from_settings(settings)
#            config.set_session_factory(factory)
#        else:
#            config.include('pyramid_beaker')

def include_security(config):
    config.set_default_csrf_options(require_csrf=True)

def include_entry_points(config):
    for entry_point in iter_entry_points(group='amnesiacms.pkgs'):
        plugin = entry_point.load()
        plugin.includeme(config)

def include_config_directives(config):
    config.add_directive(
        'cms_register_frontend_asset',
        'amnesia.lib.configurator.cms_register_frontend_asset'
    )

    config.add_directive(
        'cms_add_entity_resource',
        'amnesia.lib.configurator.cms_add_entity_resource'
    )

    config.add_directive(
        'cms_add_resource_path',
        'amnesia.lib.configurator.cms_add_resource_path'
    )

def include_request_methods(config):
    config.add_request_method(
        'amnesia.lib.configurator.cms_get_resource',
        'cms_get_resource'
    )

def include_cms_modules(config):
    config.include('amnesia.modules.folder')
    config.include('amnesia.modules.document')
    config.include('amnesia.modules.event')
    config.include('amnesia.modules.file')
    config.include('amnesia.modules.account')
    config.include('amnesia.modules.tag')
    config.include('amnesia.modules.state')
    config.include('amnesia.modules.search')
    config.include('amnesia.modules.content.views')

def include_entity_resource_mapping(config):
    config.cms_add_entity_resource(Folder, FolderEntity)
    config.cms_add_entity_resource(Document, DocumentEntity)
    config.cms_add_entity_resource(Event, EventEntity)
    config.cms_add_entity_resource(File, FileEntity)

def include_amnesia(config):
    config.include(include_config_directives)
    config.include(include_request_methods)
    config.include(include_pyramid_addons)
    config.include(include_session)
    #config.include(include_security)

    config.include('amnesia.widgets')
    config.include('amnesia.subscribers')
    config.include('amnesia.renderers')
    config.include('amnesia.db')
    config.include('amnesia.events')

    config.include(include_cms_modules)
    config.include(include_entity_resource_mapping)
    config.include(include_security_policy)

    config.include('amnesia.views')

    config.add_resource_url_adapter(AmnesiaResourceURL)

    config.include(include_entry_points)

    config.add_static_view(name='static', path='amnesia:static/')

    #config.scan()
    #config.add_renderer('.html', 'pyramid_chameleon.zpt.renderer_factory')
    config.add_renderer('.xml', 'pyramid_chameleon.zpt.renderer_factory')

def includeme(config):
    config.include(include_amnesia)

def main(global_config, **settings):
    """
    This function returns a Pyramid WSGI application.
    """

    config = Configurator(settings=settings, root_factory=get_root)
    config.include(include_amnesia)

    return config.make_wsgi_app()


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

<title>com.google.gwt.file.client</title>
<meta name="date" content="2012-10-02">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package com.google.gwt.file.client

Class Summary

Class
Description

Blob

This class represents raw data.

File

This interface describes a single file in a FileList and exposes its name.

FileError

ErrorCode representation class.

FileList

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
"""Tests for Organization Admin views.
"""

__authors__ = [
    '"Madhusudan.C.S" <madhusudancs@gmail.com>',
  ]

import datetime
import httplib

from google.appengine.api import users

from soc.logic.models.org_admin import logic as org_admin_logic
from soc.logic.models.organization import logic as org_logic
from soc.logic.models.program import logic as program_logic
from soc.logic.models.sponsor import logic as sponsor_logic
from soc.logic.models.timeline import logic as timeline_logic
from soc.logic.models.user import logic as user_logic

from tests.test_utils import DjangoTestCase

class OrgAdminTestNonexistent(DjangoTestCase):
  """Tests related to the org admin view.

  With non-existent sponsor, program, organization and org admin.
  """

  def setUp(self):
    """Set up required for the view tests.
    """
    # define link_ids of the entities that form the scope path for the
    # org admin entity related views.
    self.sponsor_link_id = 'nonexistent_sponsor'
    self.program_link_id = 'nonexistent_program'
    self.org_link_id = 'nonexistent_org'

    # construct the scope path from the link_id definitions
    self.scope_path = '/'.join([self.sponsor_link_id, self.program_link_id,
                                self.org_link_id])
    self.link_id = 'nonexistent_link_id'

  def testCreateOrgAdmin(self):
    """Test that the "create org admin" page is redirected to its gsoc page.
    """
    url = '/org_admin/create'
    response = self.client.get(url)
    self.assertEqual(response.status_code, httplib.FOUND)
    actual_redirected_location = response.get('location', None)
    # Test that the request has been redirected
    expected_redirected_location ='http://testserver/gsoc' + url
    self.assertEqual(actual_redirected_location, expected_redirected_location)

  def testCreateOrgAdminWithScopePath(self):
    """Test that create org admin page with non-existent scope path is
    not found.
    """
    url = '/org_admin/create/' + self.scope_path
    response = self.client.get(url)
    self.assertEqual(response.status_code, httplib.FOUND)
    actual_redirected_location = response.get('location', None)
    # Test that the request has been redirected
    expected_redirected_location ='http://testserver/gsoc' + url
    self.assertEqual(actual_redirected_location, expected_redirected_location)

  def testCreateOrgAdminWithScopePathAndLinkId(self):
    """Test that the create org admin page is redirected to its gsoc page.

    If a scope path and a link id are specified in the URL.
    """
    url = '/org_admin/create/' + self.scope_path + '/' + self.link_id
    response = self.client.get(url)
    self.assertEqual(response.status_code, httplib.FOUND)
    actual_redirected_location = response.get('location', None)
    # Test that the request has been redirected
    expected_redirected_location ='http://testserver/gsoc' + url
    self.assertEqual(actual_redirected_location, expected_redirected_location)

  def testEditOrgAdmin(self):
    """Test that the edit org admin page is redirected to its gsoc page.

    If a non-existent scope path and a non-existent link id
    are specified in the URL.
    """
    url = '/org_admin/edit/' + self.scope_path + '/' + self.link_id
    response = self.client.get(url)
    self.assertEqual(response.status_code, httplib.FOUND)
    actual_redirected_location = response.get('location', None)
    # Test that the request has been redirected
    expected_redirected_location ='http://testserver/gsoc' + url
    self.assertEqual(actual_redirected_location, expected_redirected_location)

  def testDeleteOrgAdmin(self):
    """Test that the delete org admin page is redirected to its gsoc page.

    If a non-existent scope path and a non-existent link id
    are specified in the URL.
    """
    url = '/org_admin/delete/' + self.scope_path + '/' + self.link_id
    response = self.client.get(url)
    self.assertEqual(response.status_code, httplib.FOUND)
    actual_redirected_location = response.get('location', None)
    # Test that the request has been redirected
    expected_redirected_location ='http://testserver/gsoc' + url
    self.assertEqual(actual_redirected_location, expected_redirected_location)

  def testListOrgAdmins(self):
    """Test that the list org admins page is redirected to its gsoc page.
    """
    url = '/org_admin/list'
    response = self.client.get(url)
    self.assertEqual(response.status_code, httplib.FOUND)
    actual_redirected_location = response.get('location', None)
    # Test that the request has been redirected
    expected_redirected_location ='http://testserver/gsoc' + url
    self.assertEqual(actual_redirected_location, expected_redirected_location)

  def testShowOrgAdmin(self):
    """Test that the show org admin page is redirected to its gsoc page.

    If a non-existent scope path and a non-existent link id
    are specified in the link.
    """
    url = '/org_admin/show/' + self.scope_path + '/' + self.link_id
    response = self.client.get(url)
    self.assertEqual(response.status_code, httplib.FOUND)
    actual_redirected_location = response.get('location', None)
    # Test that the request has been redirected
    expected_redirected_location ='http://testserver/gsoc' + url
    self.assertEqual(actual_redirected_location, expected_redirected_location)

  def testAdminOrgAdmin(self):
    """Test that the admin org_admin page is redirected to its gsoc page.

    If a non-existent scope path and a non-existent link id
    are specified in the link.
    """
    url = '/org_admin/admin/' + self.scope_path + '/' + self.link_id
    response = self.client.get(url)
    self.assertEqual(response.status_code, httplib.FOUND)
    actual_redirected_location = response.get('location', None)
    # Test that the request has been redirected
    expected_redirected_location ='http://testserver/gsoc' + url
    self.assertEqual(actual_redirected_location, expected_redirected_location)

  def testManageOrgAdmin(self):
    """Test that the manage org admin page redirected to its gsoc page.

    If a non-existent scope path and a non-existent link id
    are specified in the link.
    """
    url = '/org_admin/manage/' + self.scope_path + '/' + self.link_id
    response = self.client.get(url)
    self.assertEqual(response.status_code, httplib.FOUND)
    actual_redirected_location = response.get('location', None)
    # Test that the request has been redirected
    expected_redirected_location ='http://testserver/gsoc' + url
    self.assertEqual(actual_redirected_location, expected_redirected_location)

class OrgAdminTestExistent(DjangoTestCase):
  """Tests related to the org admin view.

  With existent sponsor, program and org admin.
  """

  def setUp(self):
    """Set up required for the view tests.
    """

    # Create a user for sponsor
    email = "a_sponsor@example.com"
    account = users.User(email=email)
    link_id = 'a_sponsor_user'
    name = 'A Sponsor User'
    sponsor_user_properties = {
        'account': account,
        'link_id': link_id,
        'name': name,
        }
    self.sponsor_user = user_logic.updateOrCreateFromFields(
        sponsor_user_properties)

    # Create sponsor role for a_sponsor_user
    link_id = 'a_sponsor'
    name = link_id
    phone = '01234567'
    contact_postalcode = 'A postalcode'
    description = 'A description'
    contact_country = 'United States'
    short_name = 'AS'
    contact_city = 'A city'
    home_page = 'http://www.asponsor.com'
    email = 'email@asponsor.com'
    sponsor_properties = {
        'link_id': link_id,
        'name': name,
        'short_name': short_name,
        'founder': self.sponsor_user,
        'phone': phone,
        'description': description,
        'contact_country': contact_country,
        'contact_city': contact_city,
        'contact_street': 'A Street',
        'contact_postalcode': contact_postalcode,
        'home_page': home_page,
        'email': email,
        }
    self.sponsor = sponsor_logic.updateOrCreateFromFields(sponsor_properties)

    # Create a timeline for a program
    timeline_properties = {
        'link_id': 'a_program',
        'scope_path': 'a_sponsor',
        'scope': self.sponsor,
          }
    self.timeline = timeline_logic.updateOrCreateFromFields(
      timeline_properties)

    # Create a program for a_sponsor
    program_properties = {
        'link_id': 'a_program',
        'scope': self.sponsor,
        'scope_path': self.sponsor.key().id_or_name(),
        'name': 'A Program 2010',
        'short_name': 'AP2010',
        'group_label': 'AP',
        'description': 'This is the program for AP2010.',
        'apps_tasks_limit': 42,
        'slots': 42,
        'timeline': self.timeline,
        'status': 'visible',
        }
    self.program = program_logic.updateOrCreateFromFields(program_properties)

    # Create another user for org admin who is also the founder of the org
    email = 'an_org_admin@example.com'
    account = users.User(email=email)
    link_id = 'an_org_admin_user'
    name = 'An Org Admin User'
    org_admin_user_properties = {
        'account': account,
        'link_id': link_id,
        'name': name,
        }
    self.org_admin_user = user_logic.updateOrCreateFromFields(
        org_admin_user_properties)

    # create an org for the program
    org_properties = {
        'link_id': 'an_org',
        'scope': self.program,
        'scope_path': self.program.key().id_or_name(),
        'name': 'An Organization',
        'short_name': 'An Org' ,
        'founder': self.org_admin_user,
        'home_page': 'http://anorg.com',
        'email': 'email@anorg.com',
        'description': 'An Organization Description',
        'contact_street': 'An Organization Street',
        'contact_city': 'An Organization City',
        'contact_country': 'United Kingdom',
        'contact_postalcode': '0123456 AnO',
        'phone': '1-555-BANANA',
        'status': 'active',
        }
    self.org = org_logic.updateOrCreateFromFields(org_properties)

    # Create an org admin role for a_user
    org_admin_properties = {
        'link_id': 'an_org_admin',
        'scope_path': self.org.key().id_or_name(),
        'scope': self.org,
        'program': self.program,
        'user' : self.org_admin_user,
        'given_name': 'OrgAdmin',
        'surname': 'Administrator',
        'name_on_documents': 'OrgAdmin Administrator',
        'birth_date': datetime.date(1970, 1, 1),
        'email': 'an_org_admin@example.com',
        'res_street': 'An Org Admin Street',
        'res_city': 'An Org Admin City',
        'res_state': 'An Org Admin State',
        'res_country': 'France',
        'res_postalcode': '12345',
        'phone': '1-555-BANANA',
        'agreed_to_tos': True,
        }
    # create the org_admin_entity
    self.org_admin = org_admin_logic.updateOrCreateFromFields(
      org_admin_properties)
    self.scope_path = self.org_admin.scope_path
    self.link_id = self.org_admin.link_id

  def testCreateOrgAdmin(self):
    """Test that the "create org admin" page is redirected to its gsoc page.
    """
    url = '/org_admin/create'
    response = self.client.get(url)
    self.assertEqual(response.status_code, httplib.FOUND)
    actual_redirected_location = response.get('location', None)
    # Test that the request has been redirected
    expected_redirected_location ='http://testserver/gsoc' + url
    self.assertEqual(actual_redirected_location, expected_redirected_location)

  def testCreateOrgAdminWithScopePath(self):
    """Test that create org admin page with non-existent scope path is
    not found.
    """
    url = '/org_admin/create/' + self.scope_path
    response = self.client.get(url)
    self.assertEqual(response.status_code, httplib.FOUND)
    actual_redirected_location = response.get('location', None)
    # Test that the request has been redirected
    expected_redirected_location ='http://testserver/gsoc' + url
    self.assertEqual(actual_redirected_location, expected_redirected_location)

  def testCreateOrgAdminWithScopePathAndLinkId(self):
    """Test that the create org admin page is redirected to its gsoc page.

    If a scope path and a link id are specified in the URL.
    """
    url = '/org_admin/create/' + self.scope_path + '/' + self.link_id
    response = self.client.get(url)
    self.assertEqual(response.status_code, httplib.FOUND)
    actual_redirected_location = response.get('location', None)
    # Test that the request has been redirected
    expected_redirected_location ='http://testserver/gsoc' + url
    self.assertEqual(actual_redirected_location, expected_redirected_location)

  def testEditOrgAdmin(self):
    """Test that the edit org admin page is redirected to its gsoc page.

    If a non-existent scope path and a non-existent link id
    are specified in the URL.
    """
    url = '/org_admin/edit/' + self.scope_path + '/' + self.link_id
    response = self.client.get(url)
    self.assertEqual(response.status_code, httplib.FOUND)
    actual_redirected_location = response.get('location', None)
    # Test that the request has been redirected
    expected_redirected_location ='http://testserver/gsoc' + url
    self.assertEqual(actual_redirected_location, expected_redirected_location)

  def testDeleteOrgAdmin(self):
    """Test that the delete org admin page is redirected to its gsoc page.

    If a non-existent scope path and a non-existent link id
    are specified in the URL.
    """
    url = '/org_admin/delete/' + self.scope_path + '/' + self.link_id
    response = self.client.get(url)
    self.assertEqual(response.status_code, httplib.FOUND)
    actual_redirected_location = response.get('location', None)
    # Test that the request has been redirected
    expected_redirected_location ='http://testserver/gsoc' + url
    self.assertEqual(actual_redirected_location, expected_redirected_location)

  def testListOrgAdmins(self):
    """Test that the list org admins page is redirected to its gsoc page.
    """
    url = '/org_admin/list'
    response = self.client.get(url)
    self.assertEqual(response.status_code, httplib.FOUND)
    actual_redirected_location = response.get('location', None)
    # Test that the request has been redirected
    expected_redirected_location ='http://testserver/gsoc' + url
    self.assertEqual(actual_redirected_location, expected_redirected_location)

  def testShowOrgAdmin(self):
    """Test that the show org admin page is redirected to its gsoc page.

    If a non-existent scope path and a non-existent link id
    are specified in the link.
    """
    url = '/org_admin/show/' + self.scope_path + '/' + self.link_id
    response = self.client.get(url)
    self.assertEqual(response.status_code, httplib.FOUND)
    actual_redirected_location = response.get('location', None)
    # Test that the request has been redirected
    expected_redirected_location ='http://testserver/gsoc' + url
    self.assertEqual(actual_redirected_location, expected_redirected_location)

  def testAdminOrgAdmin(self):
    """Test that the admin org_admin page is redirected to its gsoc page.

    If a non-existent scope path and a non-existent link id
    are specified in the link.
    """
    url = '/org_admin/admin/' + self.scope_path + '/' + self.link_id
    response = self.client.get(url)
    self.assertEqual(response.status_code, httplib.FOUND)
    actual_redirected_location = response.get('location', None)
    # Test that the request has been redirected
    expected_redirected_location ='http://testserver/gsoc' + url
    self.assertEqual(actual_redirected_location, expected_redirected_location)

  def testManageOrgAdmin(self):
    """Test that the manage org admin page redirected to its gsoc page.

    If a non-existent scope path and a non-existent link id
    are specified in the link.
    """
    url = '/org_admin/manage/' + self.scope_path + '/' + self.link_id
    response = self.client.get(url)
    self.assertEqual(response.status_code, httplib.FOUND)
    actual_redirected_location = response.get('location', None)
    # Test that the request has been redirected
    expected_redirected_location ='http://testserver/gsoc' + url
    self.assertEqual(actual_redirected_location, expected_redirected_location)


text:
Для того, чтобы запустить проект, нужно выполнить 3 простых шага:

1. Скачать этот репозиторий: git clone https://github.com/koroandr/decoupling_habr.git
2. Установить зависимости: npm install
3. Запустить компиляцию и тесты: grunt