text:
"""
This module contains tests for L{twisted.internet.task.Cooperator} and
related functionality.
"""

from __future__ import division, absolute_import

from twisted.internet import reactor, defer, task
from twisted.trial import unittest

class FakeDelayedCall(object):
    """
    Fake delayed call which lets us simulate the scheduler.
    """
    def __init__(self, func):
        """
        A function to run, later.
        """
        self.func = func
        self.cancelled = False

    def cancel(self):
        """
        Don't run my function later.
        """
        self.cancelled = True

class FakeScheduler(object):
    """
    A fake scheduler for testing against.
    """
    def __init__(self):
        """
        Create a fake scheduler with a list of work to do.
        """
        self.work = []

    def __call__(self, thunk):
        """
        Schedule a unit of work to be done later.
        """
        unit = FakeDelayedCall(thunk)
        self.work.append(unit)
        return unit

    def pump(self):
        """
        Do all of the work that is currently available to be done.
        """
        work, self.work = self.work, []
        for unit in work:
            if not unit.cancelled:
                unit.func()

class TestCooperator(unittest.TestCase):
    RESULT = 'done'

    def ebIter(self, err):
        err.trap(task.SchedulerStopped)
        return self.RESULT

    def cbIter(self, ign):
        self.fail()

    def testStoppedRejectsNewTasks(self):
        """
        Test that Cooperators refuse new tasks when they have been stopped.
        """
        def testwith(stuff):
            c = task.Cooperator()
            c.stop()
            d = c.coiterate(iter(()), stuff)
            d.addCallback(self.cbIter)
            d.addErrback(self.ebIter)
            return d.addCallback(lambda result:
                                 self.assertEqual(result, self.RESULT))
        return testwith(None).addCallback(lambda ign: testwith(defer.Deferred()))

    def testStopRunning(self):
        """
        Test that a running iterator will not run to completion when the
        cooperator is stopped.
        """
        c = task.Cooperator()
        def myiter():
            for myiter.value in range(3):
                yield myiter.value
        myiter.value = -1
        d = c.coiterate(myiter())
        d.addCallback(self.cbIter)
        d.addErrback(self.ebIter)
        c.stop()
        def doasserts(result):
            self.assertEqual(result, self.RESULT)
            self.assertEqual(myiter.value, -1)
        d.addCallback(doasserts)
        return d

    def testStopOutstanding(self):
        """
        An iterator run with L{Cooperator.coiterate} paused on a L{Deferred}
        yielded by that iterator will fire its own L{Deferred} (the one
        returned by C{coiterate}) when L{Cooperator.stop} is called.
        """
        testControlD = defer.Deferred()
        outstandingD = defer.Deferred()
        def myiter():
            reactor.callLater(0, testControlD.callback, None)
            yield outstandingD
            self.fail()
        c = task.Cooperator()
        d = c.coiterate(myiter())
        def stopAndGo(ign):
            c.stop()
            outstandingD.callback('arglebargle')

        testControlD.addCallback(stopAndGo)
        d.addCallback(self.cbIter)
        d.addErrback(self.ebIter)

        return d.addCallback(
            lambda result: self.assertEqual(result, self.RESULT))

    def testUnexpectedError(self):
        c = task.Cooperator()
        def myiter():
            if 0:
                yield None
            else:
                raise RuntimeError()
        d = c.coiterate(myiter())
        return self.assertFailure(d, RuntimeError)

    def testUnexpectedErrorActuallyLater(self):
        def myiter():
            D = defer.Deferred()
            reactor.callLater(0, D.errback, RuntimeError())
            yield D

        c = task.Cooperator()
        d = c.coiterate(myiter())
        return self.assertFailure(d, RuntimeError)

    def testUnexpectedErrorNotActuallyLater(self):
        def myiter():
            yield defer.fail(RuntimeError())

        c = task.Cooperator()
        d = c.coiterate(myiter())
        return self.assertFailure(d, RuntimeError)

    def testCooperation(self):
        L = []
        def myiter(things):
            for th in things:
                L.append(th)
                yield None

        groupsOfThings = ['abc', (1, 2, 3), 'def', (4, 5, 6)]

        c = task.Cooperator()
        tasks = []
        for stuff in groupsOfThings:
            tasks.append(c.coiterate(myiter(stuff)))

        return defer.DeferredList(tasks).addCallback(
            lambda ign: self.assertEqual(tuple(L), sum(zip(*groupsOfThings), ())))

    def testResourceExhaustion(self):
        output = []
        def myiter():
            for i in range(100):
                output.append(i)
                if i == 9:
                    _TPF.stopped = True
                yield i

        class _TPF:
            stopped = False
            def __call__(self):
                return self.stopped

        c = task.Cooperator(terminationPredicateFactory=_TPF)
        c.coiterate(myiter()).addErrback(self.ebIter)
        c._delayedCall.cancel()
        # testing a private method because only the test case will ever care
        # about this, so we have to carefully clean up after ourselves.
        c._tick()
        c.stop()
        self.failUnless(_TPF.stopped)
        self.assertEqual(output, list(range(10)))

    def testCallbackReCoiterate(self):
        """
        If a callback to a deferred returned by coiterate calls coiterate on
        the same Cooperator, we should make sure to only do the minimal amount
        of scheduling work.  (This test was added to demonstrate a specific bug
        that was found while writing the scheduler.)
        """
        calls = []

        class FakeCall:
            def __init__(self, func):
                self.func = func

            def __repr__(self):
                return '<FakeCall %r>' % (self.func,)

        def sched(f):
            self.failIf(calls, repr(calls))
            calls.append(FakeCall(f))
            return calls[-1]

        c = task.Cooperator(scheduler=sched, terminationPredicateFactory=lambda: lambda: True)
        d = c.coiterate(iter(()))

        done = []
        def anotherTask(ign):
            c.coiterate(iter(())).addBoth(done.append)

        d.addCallback(anotherTask)

        work = 0
        while not done:
            work += 1
            while calls:
                calls.pop(0).func()
                work += 1
            if work > 50:
                self.fail("Cooperator took too long")

    def test_removingLastTaskStopsScheduledCall(self):
        """
        If the last task in a Cooperator is removed, the scheduled call for
        the next tick is cancelled, since it is no longer necessary.

        This behavior is useful for tests that want to assert they have left
        no reactor state behind when they're done.
        """
        calls = [None]
        def sched(f):
            calls[0] = FakeDelayedCall(f)
            return calls[0]
        coop = task.Cooperator(scheduler=sched)

        # Add two task; this should schedule the tick:
        task1 = coop.cooperate(iter([1, 2]))
        task2 = coop.cooperate(iter([1, 2]))
        self.assertEqual(calls[0].func, coop._tick)

        # Remove first task; scheduled call should still be going:
        task1.stop()
        self.assertEqual(calls[0].cancelled, False)
        self.assertEqual(coop._delayedCall, calls[0])

        # Remove second task; scheduled call should be cancelled:
        task2.stop()
        self.assertEqual(calls[0].cancelled, True)
        self.assertEqual(coop._delayedCall, None)

        # Add another task; scheduled call will be recreated:
        coop.cooperate(iter([1, 2]))
        self.assertEqual(calls[0].cancelled, False)
        self.assertEqual(coop._delayedCall, calls[0])

    def test_runningWhenStarted(self):
        """
        L{Cooperator.running} reports C{True} if the L{Cooperator}
        was started on creation.
        """
        c = task.Cooperator()
        self.assertTrue(c.running)

    def test_runningWhenNotStarted(self):
        """
        L{Cooperator.running} reports C{False} if the L{Cooperator}
        has not been started.
        """
        c = task.Cooperator(started=False)
        self.assertFalse(c.running)

    def test_runningWhenRunning(self):
        """
        L{Cooperator.running} reports C{True} when the L{Cooperator}
        is running.
        """
        c = task.Cooperator(started=False)
        c.start()
        self.addCleanup(c.stop)
        self.assertTrue(c.running)

    def test_runningWhenStopped(self):
        """
        L{Cooperator.running} reports C{False} after the L{Cooperator}
        has been stopped.
        """
        c = task.Cooperator(started=False)
        c.start()
        c.stop()
        self.assertFalse(c.running)

class UnhandledException(Exception):
    """
    An exception that should go unhandled.
    """

class AliasTests(unittest.TestCase):
    """
    Integration test to verify that the global singleton aliases do what
    they're supposed to.
    """

    def test_cooperate(self):
        """
        L{twisted.internet.task.cooperate} ought to run the generator that it is
        """
        d = defer.Deferred()
        def doit():
            yield 1
            yield 2
            yield 3
            d.callback("yay")
        it = doit()
        theTask = task.cooperate(it)
        self.assertIn(theTask, task._theCooperator._tasks)
        return d

class RunStateTests(unittest.TestCase):
    """
    Tests to verify the behavior of L{CooperativeTask.pause},
    L{CooperativeTask.resume}, L{CooperativeTask.stop}, exhausting the
    underlying iterator, and their interactions with each other.
    """

    def setUp(self):
        """
        Create a cooperator with a fake scheduler and a termination predicate
        that ensures only one unit of work will take place per tick.
        """
        self._doDeferNext = False
        self._doStopNext = False
        self._doDieNext = False
        self.work = []
        self.scheduler = FakeScheduler()
        self.cooperator = task.Cooperator(
            scheduler=self.scheduler,
            # Always stop after one iteration of work (return a function which
            # returns a function which always returns True)
            terminationPredicateFactory=lambda: lambda: True)
        self.task = self.cooperator.cooperate(self.worker())
        self.cooperator.start()

    def worker(self):
        """
        This is a sample generator which yields Deferreds when we are testing
        deferral and an ascending integer count otherwise.
        """
        i = 0
        while True:
            i += 1
            if self._doDeferNext:
                self._doDeferNext = False
                d = defer.Deferred()
                self.work.append(d)
                yield d
            elif self._doStopNext:
                return
            elif self._doDieNext:
                raise UnhandledException()
            else:
                self.work.append(i)
                yield i

    def tearDown(self):
        """
        Drop references to interesting parts of the fixture to allow Deferred
        errors to be noticed when things start failing.
        """
        del self.task
        del self.scheduler

    def deferNext(self):
        """
        Defer the next result from my worker iterator.
        """
        self._doDeferNext = True

    def stopNext(self):
        """
        Make the next result from my worker iterator be completion (raising
        StopIteration).
        """
        self._doStopNext = True

    def dieNext(self):
        """
        Make the next result from my worker iterator be raising an
        L{UnhandledException}.
        """
        def ignoreUnhandled(failure):
            failure.trap(UnhandledException)
            return None
        self._doDieNext = True

    def test_pauseResume(self):
        """
        Cooperators should stop running their tasks when they're paused, and
        start again when they're resumed.
        """
        # first, sanity check
        self.scheduler.pump()
        self.assertEqual(self.work, [1])
        self.scheduler.pump()
        self.assertEqual(self.work, [1, 2])

        # OK, now for real
        self.task.pause()
        self.scheduler.pump()
        self.assertEqual(self.work, [1, 2])
        self.task.resume()
        # Resuming itself shoult not do any work
        self.assertEqual(self.work, [1, 2])
        self.scheduler.pump()
        # But when the scheduler rolls around again...
        self.assertEqual(self.work, [1, 2, 3])

    def test_resumeNotPaused(self):
        """
        L{CooperativeTask.resume} should raise a L{TaskNotPaused} exception if
        it was not paused; e.g. if L{CooperativeTask.pause} was not invoked
        more times than L{CooperativeTask.resume} on that object.
        """
        self.assertRaises(task.NotPaused, self.task.resume)
        self.task.pause()
        self.task.resume()
        self.assertRaises(task.NotPaused, self.task.resume)

    def test_pauseTwice(self):
        """
        Pauses on tasks should behave like a stack. If a task is paused twice,
        it needs to be resumed twice.
        """
        # pause once
        self.task.pause()
        self.scheduler.pump()
        self.assertEqual(self.work, [])
        # pause twice
        self.task.pause()
        self.scheduler.pump()
        self.assertEqual(self.work, [])
        # resume once (it shouldn't)
        self.task.resume()
        self.scheduler.pump()
        self.assertEqual(self.work, [])
        # resume twice (now it should go)
        self.task.resume()
        self.scheduler.pump()
        self.assertEqual(self.work, [1])

    def test_pauseWhileDeferred(self):
        """
        C{pause()}ing a task while it is waiting on an outstanding
        L{defer.Deferred} should put the task into a state where the
        outstanding L{defer.Deferred} must be called back I{and} the task is
        C{resume}d before it will continue processing.
        """
        self.deferNext()
        self.scheduler.pump()
        self.assertEqual(len(self.work), 1)
        self.failUnless(isinstance(self.work[0], defer.Deferred))
        self.scheduler.pump()
        self.assertEqual(len(self.work), 1)
        self.task.pause()
        self.scheduler.pump()
        self.assertEqual(len(self.work), 1)
        self.task.resume()
        self.scheduler.pump()
        self.assertEqual(len(self.work), 1)
        self.work[0].callback("STUFF!")
        self.scheduler.pump()
        self.assertEqual(len(self.work), 2)
        self.assertEqual(self.work[1], 2)

    def test_whenDone(self):
        """
        L{CooperativeTask.whenDone} returns a Deferred which fires when the
        Cooperator's iterator is exhausted.  It returns a new Deferred each
        time it is called; callbacks added to other invocations will not modify
        the value that subsequent invocations will fire with.
        """

        deferred1 = self.task.whenDone()
        deferred2 = self.task.whenDone()
        results1 = []
        results2 = []
        final1 = []
        final2 = []

        def callbackOne(result):
            results1.append(result)
            return 1

        def callbackTwo(result):
            results2.append(result)
            return 2

        deferred1.addCallback(callbackOne)
        deferred2.addCallback(callbackTwo)

        deferred1.addCallback(final1.append)
        deferred2.addCallback(final2.append)

        # exhaust the task iterator
        # callbacks fire
        self.stopNext()
        self.scheduler.pump()

        self.assertEqual(len(results1), 1)
        self.assertEqual(len(results2), 1)

        self.assertIdentical(results1[0], self.task._iterator)
        self.assertIdentical(results2[0], self.task._iterator)

        self.assertEqual(final1, [1])
        self.assertEqual(final2, [2])

    def test_whenDoneError(self):
        """
        L{CooperativeTask.whenDone} returns a L{defer.Deferred} that will fail
        when the iterable's C{next} method raises an exception, with that
        exception.
        """
        deferred1 = self.task.whenDone()
        results = []
        deferred1.addErrback(results.append)
        self.dieNext()
        self.scheduler.pump()
        self.assertEqual(len(results), 1)
        self.assertEqual(results[0].check(UnhandledException), UnhandledException)

    def test_whenDoneStop(self):
        """
        L{CooperativeTask.whenDone} returns a L{defer.Deferred} that fails with
        L{TaskStopped} when the C{stop} method is called on that
        L{CooperativeTask}.
        """
        deferred1 = self.task.whenDone()
        errors = []
        deferred1.addErrback(errors.append)
        self.task.stop()
        self.assertEqual(len(errors), 1)
        self.assertEqual(errors[0].check(task.TaskStopped), task.TaskStopped)

    def test_whenDoneAlreadyDone(self):
        """
        L{CooperativeTask.whenDone} will return a L{defer.Deferred} that will
        succeed immediately if its iterator has already completed.
        """
        self.stopNext()
        self.scheduler.pump()
        results = []
        self.task.whenDone().addCallback(results.append)
        self.assertEqual(results, [self.task._iterator])

    def test_stopStops(self):
        """
        C{stop()}ping a task should cause it to be removed from the run just as
        C{pause()}ing, with the distinction that C{resume()} will raise a
        L{TaskStopped} exception.
        """
        self.task.stop()
        self.scheduler.pump()
        self.assertEqual(len(self.work), 0)
        self.assertRaises(task.TaskStopped, self.task.stop)
        self.assertRaises(task.TaskStopped, self.task.pause)
        # Sanity check - it's still not scheduled, is it?
        self.scheduler.pump()
        self.assertEqual(self.work, [])

    def test_pauseStopResume(self):
        """
        C{resume()}ing a paused, stopped task should be a no-op; it should not
        raise an exception, because it's paused, but neither should it actually
        do more work from the task.
        """
        self.task.pause()
        self.task.stop()
        self.task.resume()
        self.scheduler.pump()
        self.assertEqual(self.work, [])

    def test_stopDeferred(self):
        """
        As a corrolary of the interaction of C{pause()} and C{unpause()},
        C{stop()}ping a task which is waiting on a L{Deferred} should cause the
        task to gracefully shut down, meaning that it should not be unpaused
        when the deferred fires.
        """
        self.deferNext()
        self.scheduler.pump()
        d = self.work.pop()
        self.assertEqual(self.task._pauseCount, 1)
        results = []
        d.addBoth(results.append)
        self.scheduler.pump()
        self.task.stop()
        self.scheduler.pump()
        d.callback(7)
        self.scheduler.pump()
        # Let's make sure that Deferred doesn't come out fried with an
        # unhandled error that will be logged.  The value is None, rather than
        # our test value, 7, because this Deferred is returned to and consumed
        # by the cooperator code.  Its callback therefore has no contract.
        self.assertEqual(results, [None])
        # But more importantly, no further work should have happened.
        self.assertEqual(self.work, [])

    def test_stopExhausted(self):
        """
        C{stop()}ping a L{CooperativeTask} whose iterator has been exhausted
        should raise L{TaskDone}.
        """
        self.stopNext()
        self.scheduler.pump()
        self.assertRaises(task.TaskDone, self.task.stop)

    def test_stopErrored(self):
        """
        C{stop()}ping a L{CooperativeTask} whose iterator has encountered an
        error should raise L{TaskFailed}.
        """
        self.dieNext()
        self.scheduler.pump()
        self.assertRaises(task.TaskFailed, self.task.stop)

    def test_stopCooperatorReentrancy(self):
        """
        If a callback of a L{Deferred} from L{CooperativeTask.whenDone} calls
        C{Cooperator.stop} on its L{CooperativeTask._cooperator}, the
        L{Cooperator} will stop, but the L{CooperativeTask} whose callback is
        calling C{stop} should already be considered 'stopped' by the time the
        callback is running, and therefore removed from the
        L{CoooperativeTask}.
        """
        callbackPhases = []
        def stopit(result):
            callbackPhases.append(result)
            self.cooperator.stop()
            # "done" here is a sanity check to make sure that we get all the
            # way through the callback; i.e. stop() shouldn't be raising an
            # exception due to the stopped-ness of our main task.
            callbackPhases.append("done")
        self.task.whenDone().addCallback(stopit)
        self.stopNext()
        self.scheduler.pump()
        self.assertEqual(callbackPhases, [self.task._iterator, "done"])


text:
import { BackgroundpageWindow } from './sharedTypes';

declare const window: BackgroundpageWindow;

export namespace Info {
	export function init() {
		if (typeof location === 'undefined' || typeof location.host === 'undefined') {
			// Running in node
			window.log = () => { };
			window.logAsync = () => { };
			window.info = () => { };
			window.infoAsync = () => { };
			window.testLog = console.log.bind(console);
			window.Promise = Promise;
		} else {
			// Running in the browser
			window.log = console.log.bind(console);
			window.logAsync = async (...args: any[]) => {
				console.log.apply(console, await Promise.all(args));
			}
			if (window.location && window.location.hash && window.location.hash.indexOf('noBackgroundInfo')) {
				window.info = () => { };
				window.infoAsync = () => { };
			} else {
				window.info = console.log.bind(console);
				window.infoAsync = async (...args: any[]) => {
					console.log.apply(console, await Promise.all(args));
				}
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package spark;

/**
 * Created by Per Wendel on 2014-05-10.
 */
@FunctionalInterface
public interface ExceptionHandler {

    /**
     * Invoked when an exception that is mapped to this handler occurs during routing
     *
     * @param exception The exception that was thrown during routing
     * @param request   The request object providing information about the HTTP request
     * @param response  The response object providing functionality for modifying the response
     */
    void handle(Exception exception, Request request, Response response);
}


text:
<?php namespace SolarPhase\Http\Controllers\Admin\Website;

use SolarPhase\Http\Requests;
use SolarPhase\Http\Controllers\Admin\Controller;
use SolarPhase\Website\Link;

use Illuminate\Http\Request;

class LinkController extends Controller {

	public function __construct()
	{
		parent::__construct();

		$this->setTitle(trans_choice('model.website_links', 2));
		view()->share('route', 'admin.website.link');
		view()->share('model_class', 'SolarPhase\Website\Link');
	}

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{
		return view('admin.website.link.index')
			->withModels(Link::orderBy('order', 'desc')->get());
	}

	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create()
	{
		return view('admin.website.link.form')
			->withModel(new Link)
			->withParents($this->getParentLinkList());
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store(Request $request)
	{
		$link = new Link;
		$this->fillModel($link, $request);
		$this->resultMessage('created', $link, $link->save());

		return redirect()->route('admin.website.link.index');
	}

	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		return null;
	}

	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		return view('admin.website.link.form')
			->withModel(Link::findOrFail($id))
			->withParents($this->getParentLinkList($id));
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update(Request $request, $id)
	{
		$link = Link::findOrFail($id);
		$this->fillModel($link, $request);
		$this->resultMessage('saved', $link, $link->save());

		return redirect()->route('admin.website.link.index');
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		$link = Link::findOrFail($id);
		$this->resultMessage('deleted', $link, $link->delete());

		return redirect()->route('admin.website.link.index');
	}

	/**
	 * Fills the link model with the input values of the request.
	 *
	 * @param Link $model
	 * @param Request $request
	 */
	protected function fillModel(Link $link, Request $request)
	{
		$link->title = $request->input('title');
		$link->uri = $request->input('uri');
		$link->order = $request->input('order');
		$link->enabled = $request->input('enabled') === 'yes';

		$parent_id = $request->input('parent_id');
		if ($parent_id)
		{
			$parent = Link::findOrFail($parent_id);
			$link->parent()->associate($parent);
		}
		else
		{
			$link->parent_id = null;
		}
	}

	/**
	 * Returns an array of parent links in a list format that can be used in a
	 * HTML select box.
	 *
	 * @return array
	 */
	protected function getParentLinkList($id = null)
	{
		$parents = Link::onlyParents();
		if ($id != null)
		{
			$parents = $parents->whereNotIn('id', [$id]);
		}

		$parents = ['' => ''] + $parents->lists('title', 'id');

		return $parents;
	}

}


text:
#include "config.h"
#include "core/dom/NodeRenderingTraversal.h"

#include "core/dom/PseudoElement.h"
#include "core/dom/shadow/ComposedShadowTreeWalker.h"

namespace WebCore {

namespace NodeRenderingTraversal {

void ParentDetails::didTraverseInsertionPoint(InsertionPoint* insertionPoint)
{
    if (!m_insertionPoint) {
        m_insertionPoint = insertionPoint;
        m_resetStyleInheritance  = m_resetStyleInheritance || insertionPoint->resetStyleInheritance();
    }
}

void ParentDetails::didTraverseShadowRoot(const ShadowRoot* root)
{
    m_resetStyleInheritance  = m_resetStyleInheritance || root->resetStyleInheritance();
}

ContainerNode* parent(const Node* node, ParentDetails* details)
{
    // FIXME: Once everything lazy attaches we should assert that we don't need a distribution recalc here.
    ComposedShadowTreeWalker walker(node, ComposedShadowTreeWalker::CrossUpperBoundary, ComposedShadowTreeWalker::CanStartFromShadowBoundary);
    ContainerNode* found = toContainerNode(walker.traverseParent(walker.get(), details));
    return details->outOfComposition() ? 0 : found;
}

Node* nextSibling(const Node* node)
{
    ComposedShadowTreeWalker walker(node);
    if (node->isBeforePseudoElement()) {
        walker.parent();
        walker.firstChild();
    } else
        walker.nextSibling();

    if (walker.get() || node->isAfterPseudoElement())
        return walker.get();

    Node* parent = walker.traverseParent(node);
    if (parent && parent->isElementNode())
        return toElement(parent)->pseudoElement(AFTER);

    return 0;
}

Node* previousSibling(const Node* node)
{
    ComposedShadowTreeWalker walker(node);
    if (node->isAfterPseudoElement()) {
        walker.parent();
        walker.lastChild();
    } else
        walker.previousSibling();

    if (walker.get() || node->isBeforePseudoElement())
        return walker.get();

    Node* parent = walker.traverseParent(node);
    if (parent && parent->isElementNode())
        return toElement(parent)->pseudoElement(BEFORE);

    return 0;
}

Node* nextInScope(const Node* node)
{
    ComposedShadowTreeWalker walker = ComposedShadowTreeWalker(node, ComposedShadowTreeWalker::DoNotCrossUpperBoundary);
    walker.next();
    return walker.get();
}

Node* previousInScope(const Node* node)
{
    ComposedShadowTreeWalker walker = ComposedShadowTreeWalker(node, ComposedShadowTreeWalker::DoNotCrossUpperBoundary);
    walker.previous();
    return walker.get();
}

Node* parentInScope(const Node* node)
{
    ComposedShadowTreeWalker walker = ComposedShadowTreeWalker(node, ComposedShadowTreeWalker::DoNotCrossUpperBoundary);
    walker.parent();
    return walker.get();
}

Node* lastChildInScope(const Node* node)
{
    ComposedShadowTreeWalker walker = ComposedShadowTreeWalker(node, ComposedShadowTreeWalker::DoNotCrossUpperBoundary);
    walker.lastChild();
    return walker.get();
}

}

} // namespace


text:
package com.cameronstanley.javatetris.network.messages;

public class LoginRequest {

	private String username;
	private String password;

	public LoginRequest() {

	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}


text:
"""Tests for misc module."""

from tensorflow.python.autograph.utils import misc
from tensorflow.python.eager import def_function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import test_util
from tensorflow.python.framework.constant_op import constant
from tensorflow.python.ops.variables import Variable
from tensorflow.python.platform import test

class MiscTest(test.TestCase):

  @test_util.run_deprecated_v1
  def test_alias_single_tensor(self):
    a = constant(1)

    new_a = misc.alias_tensors(a)
    self.assertFalse(new_a is a)
    with self.cached_session() as sess:
      self.assertEqual(1, self.evaluate(new_a))

  @test_util.run_deprecated_v1
  def test_alias_tensors(self):
    a = constant(1)
    v = Variable(2)
    s = 'a'
    l = [1, 2, 3]

    new_a, new_v, new_s, new_l = misc.alias_tensors(a, v, s, l)

    self.assertFalse(new_a is a)
    self.assertTrue(new_v is v)
    self.assertTrue(new_s is s)
    self.assertTrue(new_l is l)
    with self.cached_session() as sess:
      self.assertEqual(1, self.evaluate(new_a))

  def test_get_range_len(self):
    get_range_as_graph = def_function.function(misc.get_range_len)
    test_range = [(i, constant_op.constant(i)) for i in range(-3, 3)]
    results = []
    for i, ti in test_range:
      for j, tj in test_range:
        for k, tk in test_range:
          if k == 0:
            continue
          results.append(((i, j, k), get_range_as_graph(ti, tj, tk)))

    for (i, j, k), result_tensor in results:
      self.assertEqual(
          len(list(range(i, j, k))), self.evaluate(result_tensor))

if __name__ == '__main__':
  test.main()


text:
package sh.isaac.misc.exporters.rf2.files;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang3.ArrayUtils;

/**
 *
 * @author Dan Armbrust
 */
public class RF2FileFetcher
{
	ConcurrentHashMap<String, RF2File> openFiles = new ConcurrentHashMap<>();
	private final File rootFolder;
	private final String namespace;
	private final String versionDate;

	public RF2FileFetcher(File rootFolder, String namespace, String versionDate)
	{
		this.rootFolder = rootFolder;
		this.namespace = namespace;
		this.versionDate = versionDate;
	}

	/**
	 * Just write the provided text to a text file.
	 * @param fileName
	 * @param content
	 * @throws IOException
	 */
	public void writeTextFile(String fileName, String content) throws IOException
	{
		Path temp = rootFolder.toPath().resolve(fileName);
		temp.getParent().toFile().mkdirs();
		Files.writeString(temp, content, StandardCharsets.UTF_8, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
	}

	public int getOpenFileCount()
	{
		return openFiles.size();
	}

	public void closeAll() throws IOException
	{
		for (RF2File file : openFiles.values())
		{
			file.close();
		}
	}

	/**
	 * Gets the cached file, or creates as necessary, one of these standard type files.  Cannot be used for {@link StandardFiles#CustomRefset}
	 * or {@link StandardFiles#CustomTextFile}
	 * @param releaseType
	 * @param fileKey
	 * @return the file, if the fileKey is known or creatable from {@link StandardFiles} (the key being the name of the enum value)
	 */
	public RF2File getFile(RF2ReleaseType releaseType, String fileKey)
	{
		return openFiles.computeIfAbsent((releaseType.name() + fileKey), keyAgain ->
		{
			StandardFiles sf = StandardFiles.parse(fileKey);
			if (sf != null)
			{
				try
				{
					switch (sf)
					{
						case Association:
						case AttributeValue:
						case DescriptionType:
						case ExtendedMap:
						case ModuleDependency:
						case RefsetDescriptor:
						case Simple:
						case SimpleMap:
							return new DERFile(rootFolder, sf.subfolder, String.valueOf(sf.additionalColTypes) + "Refset", Optional.of(fileKey), Optional.empty(),
									releaseType, namespace, versionDate, sf.getAllColNames());
						case Concept:
						case Identifier:
						case OWLExpression:
						case StatedRelationship:
						case Relationship:
							return new SCTFile(rootFolder, sf.name(), releaseType, Optional.empty(), namespace, versionDate, sf.getAllColNames());
						case CustomRefset:
							throw new RuntimeException("Call getCustomRefsetFile");
						case CustomTextFile:
							throw new RuntimeException("Call getDescriptionFile or getTextDefinitionFile");
						default :
							throw new RuntimeException("oops");
					}
				}
				catch (IOException e)
				{
					throw new RuntimeException(e);
				}
			}
			return null;
		});
	}

	private DERFile createRefsetFile(String subfolder, RF2ReleaseType releaseType, String fileKey, Optional<String> languageCode, char[] additionalColTypes, String[] additionalColNames) throws IOException
	{
		if (additionalColNames.length != additionalColTypes.length)
		{
			throw new RuntimeException("oops");
		}
		return new DERFile(rootFolder, subfolder, String.valueOf(additionalColTypes) + "Refset", Optional.of(fileKey), languageCode, releaseType, namespace, versionDate,
				ArrayUtils.addAll(StandardFiles.CustomRefset.getAllColNames(), additionalColNames));
	}

	/**
	 * After the initial create, you get get it again by calling {@link #getFile(RF2ReleaseType, String)} with the refsetName as the fileKey
	 * This method supports {@link StandardFiles#CustomRefset}
	 * @param releaseType
	 * @param refsetName
	 * @param additionalColTypes
	 * @param additionalColNames
	 * @return the custom refset file, newly created, if the refsetName / releaseType hasn't been previously requested.
	 */
	public RF2File getCustomRefsetFile(RF2ReleaseType releaseType, String refsetName, char[] additionalColTypes, String[] additionalColNames)
	{
		return openFiles.computeIfAbsent((releaseType.name() + refsetName), keyAgain ->
		{
			try
			{
				return createRefsetFile("Content", releaseType, refsetName, Optional.empty(), additionalColTypes, additionalColNames);
			}
			catch (IOException e)
			{
				throw new RuntimeException(e);
			}
		});
	}

	public RF2File getLanguageFile(RF2ReleaseType releaseType, String languageCode)
	{
		return openFiles.computeIfAbsent((releaseType.name() + "Language-" + languageCode), keyAgain ->
		{
			try
			{
				return createRefsetFile("Language", releaseType, "Language", Optional.of(languageCode), new char[] {'c'}, new String[] {"acceptabilityId"});
			}
			catch (IOException e)
			{
				throw new RuntimeException(e);
			}
		});
	}

	/**
	 * supports {@link StandardFiles#CustomTextFile}
	 * @param releaseType
	 * @param languageCode
	 * @return
	 */
	public RF2File getDescriptionFile(RF2ReleaseType releaseType, String languageCode)
	{
		return getTextFile(releaseType, "Description", languageCode);
	}

	/**
	 * supports {@link StandardFiles#CustomTextFile}
	 * @param releaseType
	 * @param languageCode
	 * @return
	 */
	public RF2File getTextDefinitionFile(RF2ReleaseType releaseType, String languageCode)
	{
		return getTextFile(releaseType, "TextDefinition", languageCode);
	}

	private RF2File getTextFile(RF2ReleaseType releaseType, String fileType, String languageCode)
	{
		return openFiles.computeIfAbsent((releaseType.name() + fileType + "-" + languageCode), keyAgain ->
		{
			try
			{
				return new SCTFile(rootFolder, fileType, releaseType, Optional.of(languageCode), namespace, versionDate,
						StandardFiles.CustomTextFile.getAllColNames());
			}
			catch (IOException e)
			{
				throw new RuntimeException(e);
			}
		});
	}

	public RF2File getLogFile(RF2ReleaseType releaseType, String fileName)
	{
		return openFiles.computeIfAbsent((releaseType == null ? "root" : releaseType.name() + fileName), keyAgain ->
		{
			try
			{
				return new LogFile(rootFolder, releaseType, fileName);
			}
			catch (IOException e)
			{
				throw new RuntimeException(e);
			}
		});
	}

	@Override
	public String toString()
	{
		return "FileFetcher namespace: " + namespace + ", rootFolder: " + rootFolder.getAbsolutePath() + ", versionDate: " + versionDate;
	}
}


text:
package com.aspectran.core.support.i18n.locale;

import com.aspectran.core.activity.Translet;

import java.util.Locale;
import java.util.TimeZone;

/**
 * {@link LocaleResolver} implementation
 * that always returns a fixed default locale and optionally time zone.
 * Default is the current JVM's default locale.
 *
 *
Note: Does not support {@code setLocale(Context)}, as the fixed
 * locale and time zone cannot be changed.
 *
 *
Created: 2016. 9. 5.

 */
public class FixedLocaleResolver extends AbstractLocaleResolver {

    /**
     * Create a default FixedLocaleResolver, exposing a configured default
     * locale (or the JVM's default locale as fallback).
     *
     * @see #setDefaultLocale
     * @see #setDefaultTimeZone
     */
    public FixedLocaleResolver() {
        setDefaultLocale(Locale.getDefault());
    }

    /**
     * Create a FixedLocaleResolver that exposes the given locale.
     * @param locale the locale to expose
     */
    public FixedLocaleResolver(Locale locale) {
        setDefaultLocale(locale);
    }

    /**
     * Create a FixedLocaleResolver that exposes the given locale and time zone.
     * @param locale the locale to expose
     * @param timeZone the time zone to expose
     */
    public FixedLocaleResolver(Locale locale, TimeZone timeZone) {
        setDefaultLocale(locale);
        setDefaultTimeZone(timeZone);
    }

    @Override
    public Locale resolveLocale(Translet translet) {
        Locale locale = getDefaultLocale();
        if (locale == null) {
            locale = Locale.getDefault();
        }
        translet.getRequestAdapter().setLocale(locale);
        return locale;
    }

    @Override
    public TimeZone resolveTimeZone(Translet translet) {
        TimeZone timeZone = getDefaultTimeZone();
        if (timeZone == null) {
            timeZone = TimeZone.getDefault();
        }
        translet.getRequestAdapter().setTimeZone(timeZone);
        return timeZone;
    }

    @Override
    public void setLocale(Translet translet, Locale locale) {
        throw new UnsupportedOperationException("Cannot change fixed locale - use a different locale resolution strategy");
    }

    @Override
    public void setTimeZone(Translet translet, TimeZone timeZone) {
        throw new UnsupportedOperationException("Cannot change fixed locale - use a different locale resolution strategy");
    }

}


text:
package com.clinicpatientqueueexample.messaging;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.inject.Inject;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Topic;

import static com.clinicpatientqueueexample.messaging.MessageSenderBean.CALL_IN_JMS_DESTINATION;

@MessageDriven(activationConfig = {
        @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = CALL_IN_JMS_DESTINATION),
        @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),
        @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge") })
public class CallInMessageReceiverBean extends AbstractMessageReceiverBean implements MessageListener {

    @Inject
    private CallInBroadcaster callInBroadcaster;

    @Override
    public void onMessage(Message receivedMessage) {
        broadcastReceivedMessage(callInBroadcaster, receivedMessage);
    }

}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE90_LDAP_Injection__w32_char_listen_socket_52b.c
Label Definition File: CWE90_LDAP_Injection__w32.label.xml
Template File: sources-sink-52b.tmpl.c
*/
/*
 * @description
 * CWE: 90 LDAP Injection
 * BadSource: listen_socket Read data using a listen socket (server side)
 * GoodSource: Use a fixed string
 * Sink:
 *    BadSink : data concatenated into LDAP search, which could result in LDAP Injection
 * Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files
 *
 * */

#include "std_testcase.h"

#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif

#define TCP_PORT 27015
#define LISTEN_BACKLOG 5

#include <Winldap.h>

#pragma comment(lib, "wldap32")

/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */

#ifndef OMITBAD

/* bad function declaration */
void CWE90_LDAP_Injection__w32_char_listen_socket_52c_badSink(char * data);

void CWE90_LDAP_Injection__w32_char_listen_socket_52b_badSink(char * data)
{
    CWE90_LDAP_Injection__w32_char_listen_socket_52c_badSink(data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* good function declaration */
void CWE90_LDAP_Injection__w32_char_listen_socket_52c_goodG2BSink(char * data);

/* goodG2B uses the GoodSource with the BadSink */
void CWE90_LDAP_Injection__w32_char_listen_socket_52b_goodG2BSink(char * data)
{
    CWE90_LDAP_Injection__w32_char_listen_socket_52c_goodG2BSink(data);
}

#endif /* OMITGOOD */


text:
package com.projecttango.experiments.nativearealearning;

import android.app.Activity;

// Interfaces between native C++ code and Java code.
public class TangoJNINative {
  static {
    System.loadLibrary("area_description_jni_example");
  }

  // Initialize the Tango Service, this function starts the communication
  // between the application and Tango Service.
  // The activity object is used for checking if the API version is outdated.
  public static native int initialize(Activity activity);

  // Setup the configuration file of the Tango Service. We are also setting up
  // the auto-recovery option from here.
  public static native int setupConfig(boolean isAreaLearningEnabled,
                                       boolean isLoadingADF);

  // Connect the onPoseAvailable callback.
  public static native int connectCallbacks();

  // Connect to the Tango Service.
  // This function will start the Tango Service pipeline, in this case, it will
  // start Motion Tracking.
  public static native int connect();

  // Disconnect from the Tango Service, release all the resources that the app is
  // holding from the Tango Service.
  public static native void disconnect();

  // Release/reset all resources that are allocated from the native code.
  public static native void freeContent();

  // Allocate OpenGL resources for rendering.
  public static native void initGlContent();

  // Setup the view port width and height.
  public static native void setupGraphics(int width, int height);

  // Main render loop.
  public static native void render();

  // Set the render camera's viewing angle:
  //   first person, third person, or top down.
  public static native void setCamera(int cameraIndex);

  // Explicitly reset motion tracking and restart the pipeline.
  // Note that this will cause motion tracking to re-initialize.
  public static native void resetMotionTracking();

  // Get the latest pose string from our application for display in our debug UI.
  public static native String getStartServiceTDeviceString();

  // Get the latest pose string from our application for display in our debug UI.
  public static native String getAdfTDeviceString();

  // Get the latest pose string from our application for display in our debug UI.
  public static native String getAdfTStartServiceString();

  // Get the latest event string from our application for display in our debug UI.
  public static native String getEventString();

  // Get the TangoCore version from our application for display in our debug UI.
  public static native String getVersionNumber();

  // Pass touch events to the native layer.
  public static native void onTouchEvent(int touchCount, int event0,
                                         float x0, float y0, float x1, float y1);

  // Get the loaded ADF's UUID.
  public static native String getLoadedADFUUIDString();

  // Save ADF in learning mode.
  public static native String saveAdf();

  // Query metadata from an exsiting ADF using the key.
  public static native String getAdfMetadataValue(String uuid, String key);

  // Assign a key value of a specific ADF's metadata.
  public static native void setAdfMetadataValue(String uuid, String key, String value);

  // Query all ADF file's UUID, the string includes all UUIDs saperated by comma.
  public static native String getAllAdfUuids();

  // Delete a ADF from Tango space.
  public static native void deleteAdf(String uuid);
}


text:
from django import forms
from core.models import Entry

class Alert(forms.Form):
    entry = forms.ModelChoiceField(queryset=Entry.objects.all())
    subject = forms.CharField(max_length=100)
    message = forms.CharField(widget=forms.Textarea(attrs={'cols': '65', 'rows': '6'}))
    email = forms.BooleanField(required=False, label='Send Subscribers E-Mail')


text:
module MongoidAddressModels
  class Engine < ::Rails::Engine

    initializer 'mongoid_address_models.autoload', :before => :set_autoload_paths do |app|
      model_path = File.expand_path("../../../app/models", __FILE__)
      app.config.eager_load_paths << model_path
    end
  end
end


text:
/**
 * Controller for Library Pane Create Modal.
 */

angular
  .module('dataCollectorApp.home')
  .controller('CreateModalInstanceController', function ($scope, $modalInstance, $translate, api, pipelineType) {
    angular.extend($scope, {
      common: {
        errors: []
      },
      selectedSource: '',
      selectedProcessors: {},
      selectedTargets: {},
      newConfig : {
        name: '',
        description: '',
        pipelineType: pipelineType !== undefined ? pipelineType: 'DATA_COLLECTOR'
      },

      save : function () {
        if($scope.newConfig.name) {
          api.pipelineAgent.createNewPipelineConfig(
            $scope.newConfig.name,
            $scope.newConfig.description,
            $scope.newConfig.pipelineType
          ).then(
            function(res) {
              $modalInstance.close(res.data);
            },
            function(res) {
              $scope.common.errors = [res.data];
            }
          );
        } else {
          $translate('home.library.nameRequiredValidation').then(function(translation) {
            $scope.common.errors = [translation];
          });
        }
      },
      cancel : function () {
        $modalInstance.dismiss('cancel');
      }
    });

  });


text:
/*
This question is from https://leetcode.com/problems/palindrome-number/
Difficulty: easy

Determine whether an integer is a palindrome. Do this without extra space.

Time Complexity: O()
*/

// Without extra space
public class Solution{
	public boolean isPalindrome(int x){
		if(x < 0) return false;
		int tmp = x;
		int palindrome = 0;
		while(tmp > 0){
			palindrome = palindrome * 10 + tmp%10;
			tmp = tmp/10;
		}
		return palindrome == x;
	}

}

// With extra space
public class Solution {
    public boolean isPalindrome(int x) {
        if(x < 0) return false;
        char[] palindrome = Integer.toString(x).toCharArray();
        for(int i = 0; i < palindrome.length/2; i++){
        	if(palindrome[i] != palindrome[palindrome.length - 1 - i])
        		return false;
        }
        return true;
    }
}

/*
Some hints:
Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer",
you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.
*/


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#pragma once
#include "AmbientSound.generated.h"

/** A sound actor that can be placed in a level */
UCLASS(AutoExpandCategories=Audio, ClassGroup=Sounds, MinimalAPI, hideCategories(Collision, Input, Game), showCategories=("Input|MouseInput", "Input|TouchInput", "Game|Damage"), ComponentWrapperClass)
class AAmbientSound : public AActor
{
	GENERATED_UCLASS_BODY()

private_subobject:
	/** Audio component that handles sound playing */
	DEPRECATED_FORGAME(4.6, "AudioComponent should not be accessed directly, please use GetAudioComponent() function instead. AudioComponent will soon be private and your code will not compile.")
	UPROPERTY(Category = Sound, VisibleAnywhere, BlueprintReadOnly, meta = (ExposeFunctionCategories = "Sound,Audio,Audio|Components|Audio", AllowPrivateAccess = "true"))
	class UAudioComponent* AudioComponent;
public:

	ENGINE_API FString GetInternalSoundCueName();

	// Begin AActor interface.
#if WITH_EDITOR
	virtual void CheckForErrors() override;
	virtual bool GetReferencedContentObjects( TArray<UObject*>& Objects ) const override;
#endif
	virtual void PostRegisterAllComponents() override;
	// End AActor interface.

	// BEGIN DEPRECATED (use component functions now in level script)
	UFUNCTION(BlueprintCallable, Category="Audio", meta=(DeprecatedFunction))
	void FadeIn(float FadeInDuration, float FadeVolumeLevel = 1.f);
	UFUNCTION(BlueprintCallable, Category="Audio", meta=(DeprecatedFunction))
	void FadeOut(float FadeOutDuration, float FadeVolumeLevel);
	UFUNCTION(BlueprintCallable, Category="Audio", meta=(DeprecatedFunction))
	void AdjustVolume(float AdjustVolumeDuration, float AdjustVolumeLevel);
	UFUNCTION(BlueprintCallable, Category="Audio", meta=(DeprecatedFunction))
	void Play(float StartTime = 0.f);
	UFUNCTION(BlueprintCallable, Category="Audio", meta=(DeprecatedFunction))
	void Stop();
	// END DEPRECATED

public:
	/** Returns AudioComponent subobject **/
	ENGINE_API class UAudioComponent* GetAudioComponent() const;
};


text:
package com.sequenceiq.mock.swagger.model;

import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.*;

/**
 * Arguments passed to the remove hosts from cluster api, every host passed in has the roles in it deleted and the host is removed from the cluster, but is still managed by CM.  If deleteHosts is set to true hosts are also deleted from CM.
 */
@ApiModel(description = "Arguments passed to the remove hosts from cluster api, every host passed in has the roles in it deleted and the host is removed from the cluster, but is still managed by CM.  If deleteHosts is set to true hosts are also deleted from CM.")
@Validated
@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2021-12-10T21:24:30.629+01:00")

public class ApiHostsToRemoveArgs   {
  @JsonProperty("hostsToRemove")
  @Valid
  private List<String> hostsToRemove = null;

  @JsonProperty("deleteHosts")
  private Boolean deleteHosts = null;

  public ApiHostsToRemoveArgs hostsToRemove(List<String> hostsToRemove) {
    this.hostsToRemove = hostsToRemove;
    return this;
  }

  public ApiHostsToRemoveArgs addHostsToRemoveItem(String hostsToRemoveItem) {
    if (this.hostsToRemove == null) {
      this.hostsToRemove = new ArrayList<>();
    }
    this.hostsToRemove.add(hostsToRemoveItem);
    return this;
  }

  /**
   *
   * @return hostsToRemove
  **/
  @ApiModelProperty(value = "")

  public List<String> getHostsToRemove() {
    return hostsToRemove;
  }

  public void setHostsToRemove(List<String> hostsToRemove) {
    this.hostsToRemove = hostsToRemove;
  }

  public ApiHostsToRemoveArgs deleteHosts(Boolean deleteHosts) {
    this.deleteHosts = deleteHosts;
    return this;
  }

  /**
   *
   * @return deleteHosts
  **/
  @ApiModelProperty(required = true, value = "")
  @NotNull

  public Boolean isDeleteHosts() {
    return deleteHosts;
  }

  public void setDeleteHosts(Boolean deleteHosts) {
    this.deleteHosts = deleteHosts;
  }

  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    ApiHostsToRemoveArgs apiHostsToRemoveArgs = (ApiHostsToRemoveArgs) o;
    return Objects.equals(this.hostsToRemove, apiHostsToRemoveArgs.hostsToRemove) &&
        Objects.equals(this.deleteHosts, apiHostsToRemoveArgs.deleteHosts);
  }

  @Override
  public int hashCode() {
    return Objects.hash(hostsToRemove, deleteHosts);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class ApiHostsToRemoveArgs {\n");

    sb.append("    hostsToRemove: ").append(toIndentedString(hostsToRemove)).append("\n");
    sb.append("    deleteHosts: ").append(toIndentedString(deleteHosts)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
    Course Constraints

    Main Page

    Course Page

    Logout

<form ng-submit="saveConstraints()" >

                Course Code

                    <select ng-model="crs"  ng-options="c.CODE for c in courses | orderBy: 'CODE'"
                            ng-change="selectCourse(crs)" >
                        <option value="">Select Course</option>
                    </select>

Clash

Same/Different Day

Consecutiveness

Precedence

                    Add course and select the type of the constraint. (Not for courses in the same curriculum or taught by the same instructor)

                <input type="button" ng-click="addClashConst()" value="Add" style=" margin-left: 20px; " />

                            <select ng-model="clash.course"   ng-options="c.CODE for c in constCourses | orderBy: 'CODE'"
                                    style=" margin-left: 10px; margin-right: 10px; " >
                                <option value="">Select Course</option>
                            </select>

                            <select ng-model="clash.type" style=" margin-left: 10px; margin-right: 10px; " >
                                <option value="soft">Soft</option>
                                <option value="hard">Hard</option>
                            </select>

                            Remove

                    Add course that should / shouldn't be scheduled at the same day with the current course

                <input type="button" ng-click="addDayConst()" value="Add" style=" margin-left: 20px; "  />

                            <select ng-model="dayConst.course"
                                    ng-options="c.CODE for c in constCourses | orderBy: 'CODE'"
                                    style=" margin-left: 10px; margin-right: 10px; " >
                                <option value="">Select Course</option>
                            </select>

                            <select ng-model="dayConst.type" style=" margin-left: 10px; margin-right: 10px; " >
                                <option value="sameday">Same Day</option>
                                <option value="differentday">Different Day</option>
                            </select>

                            Remove

                    Add course that should be scheduled just before or just after the current course.

                <input type="button" ng-click="addConsecutiveConst()" value="Add" style=" margin-left: 20px; "  />

                            <select ng-model="consecutive.course"
                                    ng-options="c.CODE for c in constCourses | orderBy: 'CODE'"
                                    style=" margin-left: 10px; margin-right: 10px; " >
                                <option value="">Select Course</option>
                            </select>

                            Remove

                    Add course which should be scheduled later than the current course. (Current course precedes)

                <input type="button" ng-click="addPrecedenceConst()" value="Add" style=" margin-left: 20px; "  />

                            <select ng-model="precedence.course"
                                     ng-options="c.CODE for c in constCourses | orderBy: 'CODE'"
                                    style=" margin-left: 10px; margin-right: 10px; " >
                                <option value="">Select Course</option>
                            </select>

                            Remove

        Saved Succesfully

        You will lose your data if course is changed without saving

    <input type="submit" ng-show="isUpdater()"  value="Save Changes" id="recordButton" style=" position: absolute; bottom: 10px; left: 50%; margin-left: -140px; " />

</form>


text:
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" >

	<persistence-unit name="teste" transaction-type="RESOURCE_LOCAL">
		<provider>org.hibernante.jpa.HibernatePersistenceProvider</provider>
		<properties>
			<property name="javax.persistence.jdbc.driver" value="org.mysql.jdbc.Driver"/>
			<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/teste"/>
			<property name="java.persistence.jdbc.user" value="root"/>
			<property name="java.persistence.jdbc.password" value=""/>

			<property name="hibernate.hbm2ddl.auto" value="update"/>
			<property name="hibernate.show.sql" value="true"/>
			<property name="hibernate.format_sql" value="false"/>
			<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLInnoDBDialect"/>

		</properties>
	</persistence-unit>
</persistence>


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Seis</logradouro><bairro>Grajaú</bairro><cidade>Divinópolis</cidade><uf>MG</uf><cep>35502339</cep></feed>


text:
CircularProgress
================

Props
-----

| Name | Type | Default | Description |
|:-----|:-----|:--------|:------------|
| className | string |  | The CSS class name of the root element. |
| mode | enum: 'determinate'
 'indeterminate'
 | 'indeterminate' | The mode of show your progress, indeterminate for when there is no value for progress. |
| size | number | 40 | The size of the circle. |
| value | number |  | The value of progress, only works in determinate mode. |

Any other properties supplied will be spread to the root element.


text:
{% load i18n %}

<form {% if form_id %}id="{{ form_id }}"{% endif %} class="form-{{ style|default:"stacked" }} {{ class }}" method="{{ method|default:"post" }}"
    {% if action %}action="{{ action }}"{% endif %}
    {% if includes_files %}enctype="multipart/form-data"{% endif %}>

    {% if not method == "get" %}{% csrf_token %}{% endif %}
    {% include 'oscar/dashboard/partials/form_fields.html' %}

        <button class="btn btn-primary" type="submit" data-loading-text="{% trans 'Saving...' %}">{% trans "Save" %}</button>
        {% trans "or" %} {% trans "cancel" %}.

</form>


text:
**babel-eslint** allows you to lint **ALL** valid Babel code with the fantastic
[ESLint](https://github.com/eslint/eslint).

`babel-eslint` is successfully linting [babel core](https://github.com/babel/babel/blob/master/.eslintrc) and many other projects.

> If there is an issue, first check if it can be reproduced with the regular parser or with the latest versions of `eslint` and `babel-eslint`!

For questions and support please visit the [`#linting`](https://babeljs.slack.com/messages/linting/) babel slack channel (sign up [here](https://babel-slack.herokuapp.com))!

## Known Issues
Flow:
- `no-undef` for global flow types: `ReactElement`, `ReactClass` [#130](https://github.com/babel/babel-eslint/issues/130#issuecomment-111215076)
  - Workaround: define types as globals in `.eslintrc` or define types and import them `import type ReactElement from './types'`
- `no-unused-vars/no-undef` with Flow declarations (`declare module A {}`) [#132](https://github.com/babel/babel-eslint/issues/132#issuecomment-112815926)

Modules/strict mode
- `no-unused-vars: [2, {vars: local}]` [#136](https://github.com/babel/babel-eslint/issues/136)

Please check out [eslint-plugin-react](https://github.com/yannickcr/eslint-plugin-react) for React/JSX issues
- `no-unused-vars` with jsx

Please check out [eslint-plugin-babel](https://github.com/babel/eslint-plugin-babel) for other issues such as:
- `generator-star` with async/await functions [#78](https://github.com/babel/babel-eslint/issues/78)
- `object-shorthand` with spread operator [#131](https://github.com/babel/babel-eslint/issues/131)

## How does it work?

ESLint allows custom parsers. This is great but some of the syntax nodes that Babel supports
aren't supported by ESLint. When using this plugin, ESLint is monkeypatched and your code is
transformed into code that ESLint can understand. All location info such as line numbers,
columns is also retained so you can track down errors with ease.

## Usage

### Install

```sh
$ npm install -g eslint babel-eslint
```

### Setup

**.eslintrc**

```json
{
  "parser": "babel-eslint",
  "rules": {
    "strict": 0
  }
}
```

Check out the [ESLint docs](http://eslint.org/docs/rules/) for all possible rules.

### Run

```sh
$ eslint your-files-here
```

[travis-url]: https://travis-ci.org/babel/babel-eslint
[travis-image]: https://travis-ci.org/babel/babel-eslint.svg?branch=master


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Agaricus endochordus Berk. & Broome

### Remarks
null


text:
package com.aimbrain.sdk.server;

import com.aimbrain.sdk.models.FaceCompareModel;
import com.aimbrain.sdk.models.FaceEnrollModel;
import com.android.volley.VolleyError;

import org.json.JSONException;
import org.json.JSONObject;

public abstract class FaceCompareCallback {

    public abstract void success(FaceCompareModel response);

    public abstract void failure(VolleyError error);

}


text:
<?php

class MockSearch extends SearchEngine {
	public static $id;
	public static $title;
	public static $text;

	public function __construct( $db ) {
	}

	public function update( $id, $title, $text ) {
		self::$id = $id;
		self::$title = $title;
		self::$text = $text;
	}
}

/**
 * @group Search
 */
class SearchUpdateTest extends MediaWikiTestCase {
	static $searchType;

	function update( $text, $title = 'Test', $id = 1 ) {
		$u = new SearchUpdate( $id, $title, $text );
		$u->doUpdate();
		return array( MockSearch::$title, MockSearch::$text );
	}

	function updateText( $text ) {
		list( , $resultText ) = $this->update( $text );
		$resultText = trim( $resultText ); // abstract from some implementation details
		return $resultText;
	}

	function setUp() {
		global $wgSearchType;

		self::$searchType  = $wgSearchType;
		$wgSearchType = 'MockSearch';
	}

	function tearDown() {
		global $wgSearchType;

		$wgSearchType = self::$searchType;
	}

	function testUpdateText() {
		$this->assertEquals(
			'test',
			$this->updateText( '
TeSt
' ),
			'HTML stripped, text lowercased'
		);

		$this->assertEquals(
			'foo bar boz quux',
			$this->updateText( <<<EOT

foo

bar

boz
quux

EOT
			), 'Stripping HTML tables' );

		$this->assertEquals(
			'a b',
			$this->updateText( 'a > b' ),
			'Handle unclosed tags'
		);

		$text = str_pad( "foo <barbarbar \n", 10000, 'x' );

		$this->assertNotEquals(
			'',
			$this->updateText( $text ),
			'Bug 18609'
		);
	}

	function testBug32712() {
		$text = "text "http://example.com" text";
		$result = $this->updateText( $text );
		$processed = preg_replace( '/Q/u', 'Q', $result );
		$this->assertTrue(
			$processed != '',
			'Link surrounded by unicode quotes should not fail UTF-8 validation'
		);
	}
}


text:
import React from 'react'

import FormButton from 'src/collections/Form/FormButton'
import Button from 'src/elements/Button/Button'
import * as common from 'test/specs/commonTests'

describe('FormButton', () => {
  common.isConformant(FormButton, {
    ignoredTypingsProps: ['label'],
  })
  common.labelImplementsHtmlForProp(FormButton)

  it('renders a FormField with a Button control', () => {
    shallow(<FormButton />)
      .find('FormField')
      .should.have.prop('control', Button)
  })
})


text:
package de.openpizza.android.activitys.shopOverview;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import de.openpizza.android.R;

public class ShopOverviewActivity extends FragmentActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_shop_overview);

		if (savedInstanceState == null) {
			Fragment shopListFragment = new ShopOverviewFragment();
			getSupportFragmentManager().beginTransaction()
					.add(R.id.container, shopListFragment).commit();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.shop_overview, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}

class City {
	String name;
	String id;

	public City(String id, String name) {
		this.id = id;
		this.name = name;
	}

	@Override
	public String toString() {
		return name;
	}
}


text:
Order Pizza

Handcrafted with fresh ingredients and baked in a woodburning oven. Our pizzas are so tasty and authentic you'll shout, "Mamma Mia!"

{{product.name}}

{{product.description}}


text:
<?php

namespace Kadeke\WebsiteBundle\Entity\Pages\Search;

use Doctrine\ORM\Mapping as ORM;
use Kunstmaan\NodeSearchBundle\Entity\AbstractSearchPage;

/**
 * @ORM\Entity()
 * @ORM\Table(name="kd_search_page")
 */
class SearchPage extends AbstractSearchPage
{
    /*
     * return string
     */
    public function getDefaultView()
    {
        return "KadekeWebsiteBundle:Pages\Search\SearchPage:view.html.twig";
    }

}


text:
<?php
/**
 * @author springer
 */

namespace Proj\BussinesTrip\Controller;

use Proj\BussinesTrip\Component\Dialog\EditTripDialog;
use Proj\BussinesTrip\Component\Dialog\EditExpenseDialog;
use Proj\BussinesTrip\Component\Dialog\EditTripPointDialog;
use Proj\BussinesTrip\Component\Dialog\EditTripUserDialog;
use Proj\BussinesTrip\Component\Form\EditTripUserForm;
use Proj\BussinesTrip\Component\Form\EditTripForm;
use Proj\BussinesTrip\Component\Form\TripGridFilterForm;
use Proj\BussinesTrip\Component\Form\TripGridUserForm;
use Proj\BussinesTrip\Component\Grid\ExpenseGrid;
use Proj\BussinesTrip\Component\Grid\TripGrid;
use Proj\BussinesTrip\Component\Grid\TripPointGrid;
use Proj\BussinesTrip\Component\Grid\TripUserGrid;
use Proj\BussinesTrip\Entity\Trip;
use Proj\BussinesTrip\Entity\TripUser;
use /** @noinspection PhpUnusedAliasInspection */
    Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use /** @noinspection PhpUnusedAliasInspection */
    Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Proj\Base\Controller\BaseController;

/**
 * @Route("trip", name="_trip")
 * @Template()
 */
class TripController extends BaseController {

    const TRIP_DETAIL      = '/trip/detail';
    const TRIP_DETAIL_DATA = '/trip/detailData';

    const EDIT_FORM           = '/trip/editForm';
    const EDIT_TRIP_USER_FORM = '/trip/editTripUserForm';
    const GRID_DATA           = '/trip/grid';

    /**
     * @Route("/index")
     * @Template()
     */
    public function indexAction() {

        $user = $this->getSelfUser();
        $formatter = $this->getFormater();
        $dialog = EditTripDialog::create($formatter);
        $grid = new TripGrid($this->getLangTranslator(), $this->getDoctrine());
        $grid->setFilter(TripGridFilterForm::create($formatter, $grid, $this->getDoctrine(), $this->getRequestNil()));
        return ['grid' => $grid, 'dialog' => $dialog, 'user' =>$user];
    }

    /**
     * @Route("/detail")
     * @Template()
     */
    public function tripDetailAction() {
        $formatter = $this->getFormater();
        $doctrine = $this->getDoctrine();
        $tr = $this->getLangTranslator();
        $id = $this->getRequestNil()->getParam(Trip::COLUMN_ID);
        $trip = $this->getDoctrine()->getRepository('ProjBussinesTripBundle:Trip')->find($id);
        return [
            'trip'         => $trip,
            'formatter'    => $this->getFormater(),
            'tripUserGrid' => new TripUserGrid($tr, $doctrine, $trip),
            'expenseGrid'  => new ExpenseGrid($tr, $doctrine, $trip),
            'tripPointGrid'  => new TripPointGrid($tr, $doctrine, $trip),
            'editTripUserDialog' => EditTripUserDialog::create($formatter, $id),
            'editExpenseDialog' => EditExpenseDialog::create($formatter, $id),
            'editTripPointDialog' => EditTripPointDialog::create($formatter, $id),
        ];
    }

    /**
     * @Route("/detailData")
     */
    public function tripDetailGridAction() {
        $id = $this->getRequestNil()->getParam(Trip::COLUMN_ID);
        $trip = $this->getDoctrine()->getRepository('ProjBussinesTripBundle:Trip')->find($id);

        $paramList = new \GenericClass();
        $paramList->selfUser = $this->getSelfUser();
        $paramList->formatter = $this->getFormater();
        $paramList->translator = $this->getLangTranslator();
        $paramList->trip = $trip;

        TripUserGrid::renderDataDoctrine($this->getDoctrine(), $this->getRequestNil(), $paramList);
    }

    /**
     * @Route ("/editForm")
     * @Template()
     */
    public function editFormAction() {
        $id = $this->getRequestNil()->getParam(Trip::COLUMN_ID);
        $trip = new Trip();
        if ($id > 0) {
            $trip = $this->getDoctrine()->getRepository('ProjBussinesTripBundle:Trip')->find($id);
        }
        $trip = $trip ?: new Trip();
        $form = EditTripForm::create($this->getFormater(), $this->getRequestNil(), $this->getDoctrine(), $trip, $this->getSelfUser());
        return ['form' => $form];
    }

    /**
     * @Route ("/editTripUserForm")
     * @Template()
     */
    public function editTripUserFormAction() {
        $id = $this->getRequestNil()->getParam(TripUser::COLUMN_ID);
        $tripId = $this->getRequestNil()->getParam(EditTripUserForm::INPUT_TRIP);
        $tripUser = new TripUser();
        $trip = $this->getDoctrine()->getRepository('ProjBussinesTripBundle:Trip')->find($tripId);
        if ($id > 0) {
            $tripUser = $this->getDoctrine()->getRepository('ProjBussinesTripBundle:TripUser')->find($id);
        }
        $tripUser->setTrip($trip);
        $form = EditTripUserForm::create($this->getFormater(), $this->getRequestNil(), $this->getDoctrine(), $tripUser, $this->getSelfUser());
        return ['form' => $form];
    }

    /**
     * @Route("/grid")
     */
    public function gridAction() {
        $paramList = new \GenericClass();
        $paramList->selfUser = $this->getSelfUser();
        $paramList->formatter = $this->getFormater();
        $paramList->translator = $this->getLangTranslator();
        TripGrid::renderDataDoctrine($this->getDoctrine(), $this->getRequestNil(), $paramList);
    }

}


text:
package Image::ExifTool::ITC;

use strict;
use vars qw($VERSION);
use Image::ExifTool qw(:DataAccess :Utils);

$VERSION = '1.02';

sub ProcessITC($$);

# tags used in ITC files
%Image::ExifTool::ITC::Main = (
    NOTES => 'This information is found in iTunes Cover Flow data files.',
    itch => { SubDirectory => { TagTable => 'Image::ExifTool::ITC::Header' } },
    item => { SubDirectory => { TagTable => 'Image::ExifTool::ITC::Item' } },
    data => {
        Name => 'ImageData',
        Notes => 'embedded JPEG or PNG image, depending on ImageType',
    },
);

# ITC header information
%Image::ExifTool::ITC::Header = (
    PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
    GROUPS => { 2 => 'Image' },
    0x10 => {
        Name => 'DataType',
        Format => 'undef[4]',
        PrintConv => { artw => 'Artwork' },
    },
);

# ITC item information
%Image::ExifTool::ITC::Item = (
    PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
    GROUPS => { 2 => 'Image' },
    FORMAT => 'int32u',
    FIRST_ENTRY => 0,
    0 => {
        Name => 'LibraryID',
        Format => 'undef[8]',
        ValueConv => 'uc unpack "H*", $val',
    },
    2 => {
        Name => 'TrackID',
        Format => 'undef[8]',
        ValueConv => 'uc unpack "H*", $val',
    },
    4 => {
        Name => 'DataLocation',
        Format => 'undef[4]',
        PrintConv => {
            down => 'Downloaded Separately',
            locl => 'Local Music File',
        },
    },
    5 => {
        Name => 'ImageType',
        Format => 'undef[4]',
        ValueConv => { # (not PrintConv because the unconverted JPEG value is nasty)
            'PNGf' => 'PNG',
            "\0\0\0\x0d" => 'JPEG',
        },
    },
    7 => 'ImageWidth',
    8 => 'ImageHeight',
);

#------------------------------------------------------------------------------
# Process an iTunes Cover Flow (ITC) file
# Inputs: 0) ExifTool object reference, 1) Directory information reference
# Returns: 1 on success, 0 if this wasn't a valid ITC file
sub ProcessITC($$)
{
    my ($et, $dirInfo) = @_;
    my $raf = $$dirInfo{RAF};
    my $rtnVal = 0;
    my ($buff, $err, $pos, $tagTablePtr, %dirInfo);

    # loop through all blocks in this image
    for (;;) {
        # read the block header
        my $n = $raf->Read($buff, 8);
        unless ($n == 8) {
            # no error if we reached the EOF normally
            undef $err unless $n;
            last;
        }
        my ($size, $tag) = unpack('Na4', $buff);
        if ($rtnVal) {
            last unless $size >= 8 and $size < 0x80000000;
        } else {
            # check to be sure this is a valid ITC image
            # (first block must be 'itch')
            last unless $tag eq 'itch';
            last unless $size >= 0x1c and $size < 0x10000;
            $et->SetFileType();
            SetByteOrder('MM');
            $rtnVal = 1;    # this is an ITC file
            $err = 1;       # format error unless we read to EOF
        }
        if ($tag eq 'itch') {
            $pos = $raf->Tell();
            $size -= 8; # size of remaining data in block
            $raf->Read($buff,$size) == $size or last;
            # extract header information
            %dirInfo = (
                DirName => 'ITC Header',
                DataPt  => \$buff,
                DataPos => $pos,
            );
            my $tagTablePtr = GetTagTable('Image::ExifTool::ITC::Header');
            $et->ProcessDirectory(\%dirInfo, $tagTablePtr);
        } elsif ($tag eq 'item') {
            # don't want to read the entire item data (includes image)
            $size > 12 or last;
            $raf->Read($buff, 4) == 4 or last;
            my $len = unpack('N', $buff);
            $len >= 0xd0 and $len <= $size or last;
            $size -= $len;  # size of data after item header
            $len -= 12;     # length of remaining item header
            # read in 4-byte blocks until we find the null terminator
            # (this is just a guess about how to parse this variable-length part)
            while ($len >= 4) {
                $raf->Read($buff, 4) == 4 or last;
                $len -= 4;
                last if $buff eq "\0\0\0\0";
            }
            last if $len < 4;
            $pos = $raf->Tell();
            $raf->Read($buff, $len) == $len or last;
            unless ($len >= 0xb4 and substr($buff, 0xb0, 4) eq 'data') {
                $et->Warn('Parsing error. Please submit this ITC file for testing');
                last;
            }
            %dirInfo = (
                DirName => 'ITC Item',
                DataPt  => \$buff,
                DataPos => $pos,
            );
            $tagTablePtr = GetTagTable('Image::ExifTool::ITC::Item');
            $et->ProcessDirectory(\%dirInfo, $tagTablePtr);
            # extract embedded image
            $pos += $len;
            if ($size > 0) {
                $tagTablePtr = GetTagTable('Image::ExifTool::ITC::Main');
                my $tagInfo = $et->GetTagInfo($tagTablePtr, 'data');
                my $image = $et->ExtractBinary($pos, $size, $$tagInfo{Name});
                $et->FoundTag($tagInfo, \$image);
                # skip the rest of the block if necessary
                $raf->Seek($pos+$size, 0) or last
            } elsif ($size < 0) {
                last;
            }
        } else {
            $et->VPrint(0, "Unknown $tag block ($size bytes)\n");
            $raf->Seek($size-8, 1) or last;
        }
    }
    $err and $et->Warn('ITC file format error');
    return $rtnVal;
}

1;  # end

__END__

=head1 NAME

Image::ExifTool::ITC - Read iTunes Cover Flow meta information

=head1 SYNOPSIS

This module is used by Image::ExifTool

=head1 DESCRIPTION

This module contains the routines required by Image::ExifTool to read meta
information (including artwork images) from iTunes Cover Flow files.

=head1 AUTHOR

Copyright 2003-2022, Phil Harvey (philharvey66 at gmail.com)

This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

=head1 REFERENCES

=over 4

=item L<http://www.waldoland.com/dev/Articles/ITCFileFormat.aspx>

=item L<http://www.falsecognate.org/2007/01/deciphering_the_itunes_itc_fil/>

=back

=head1 SEE ALSO

L<Image::ExifTool::TagNames/ITC Tags>,
L<Image::ExifTool(3pm)|Image::ExifTool>

=cut


text:
Changelog
=========

0.9.7
-----

- Support for Lambda environment variables

0.9.6
-----

- Do not silence exception if Kinesis payload is not a json object

0.9.5
-----

- Support for delivery streams filters and mappers

0.9.0
-----

- Better debugging of processing errors

0.8.9
-----

- Add error annotations to events that failed to be processed

0.8.6
-----

- Bugfix in error handling logic.

0.8.5
-----

- Better error handling.

0.7.7
-----

- Support for multiple delivery streams for input, error, and output(s)

0.7.6
-----

- Support for one-to-many mappers

0.7.5
-----

- Users can also specify input/output/error streams by name instead of as
  references to another layer outputs.

0.6.8
-----

- Set environment variables for the humilis environment/layer/stage

0.4.0
-----

- Major bugfix: permission to put records in delivery streams

0.3.0
-----

- Major bugfix: give permission to write state to DynamodDB

0.2.0
-----

- Package becomes a generic map-multiplex-map processor (germangh)

0.1.1
-----

- Cleanup package data (bubenkoff)

0.1.0
-----

- Major refactoring to simplify and clean the code (germangh)

0.0.1
-----

- Initial release (bubenkoff)


text:
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit
{
    using System;
    using GreenPipes;
    using PipeConfigurators;

    public static class LatestExtensions
    {
        /// <summary>
        /// Adds a latest value filter to the pipe
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="configurator"></param>
        /// <param name="configure"></param>
        public static void UseLatest<T>(this IPipeConfigurator<T> configurator, Action<ILatestConfigurator<T>> configure = null)
            where T : class, PipeContext
        {
            if (configurator == null)
                throw new ArgumentNullException(nameof(configurator));

            var pipeBuilderConfigurator = new LatestPipeSpecification<T>();

            configure?.Invoke(pipeBuilderConfigurator);

            configurator.AddPipeSpecification(pipeBuilderConfigurator);
        }
    }
}


text:
<!-- REQUIRED JS SCRIPTS -->

<!-- jQuery 2.1.4 -->
<script src="/bootstrap/js/jquery.js"></script>
<!-- Bootstrap 3.3.5 -->
<script src="bootstrap/js/bootstrap.min.js"></script>
<!-- AdminLTE App -->
<script src="js/app.min.js"></script>

<script type="text/javascript" src="https://cdn.datatables.net/t/dt/dt-1.10.11/datatables.min.js"></script>

<script src="summernote/summernote.js"></script>

<!-- Optionally, you can add Slimscroll and FastClick plugins.
     Both of these plugins are recommended to enhance the
     user experience. Slimscroll is required when using the
     fixed layout. -->

<!-- stuff for newsfeed-->
<script type="text/javascript">
$(function() {
  $('#summernote').summernote();
});
function savePost(){
  var markupStr = $('#summernote').summernote('code');
  console.log(markupStr);
  document.getElementById('postbody').value = markupStr;
  var element = document.getElementById("postbody");
  element.form.submit();
}
function destroyPost(){
  $('#summernote').summernote('destroy');
}

//Stuff for tasks
jQuery(document).ready(function($) {
    $(".clickable-row").click(function() {
        window.document.location = $(this).data("id");
    });
});

//Stuff for tasks
$(document).ready(function() {
    $('#tasksTable').DataTable();
} );
</script>


text:
author: slowe
categories: Explanation
comments: true
date: 2013-12-20T09:00:00Z
slug: reducing-the-friction-training-a-spam-filter
tags:
- Automation
- macOS
- Personal
- Productivity
- Messaging
title: 'Reducing the Friction: Training a Spam Filter'
url: /2013/12/20/reducing-the-friction-training-a-spam-filter/
wordpress_id: 3391
---

I'm back with another "Reducing the Friction" blog post, this time to talk about training an e-mail spam filter. As you may recall if you read one of the earlier posts (may I suggest [this one][1] and [this one][2]?), I use the phrase "reducing the friction" to talk about streamlining and simplifying commonly-performed tasks so as to allow you to improve your own personal efficiency and/or adopt more efficient habits or workflows.

I recently moved my e-mail services off Google and onto [Fastmail](http://www.fastmail.fm/). (I described the reasons why I made this move in [this post][3].) Fastmail has been _great_---I find their e-mail service to be much faster than what I was seeing with Google. The one drawback, though, has been an increase in spam. Not a huge increase, mind you, but enough to notice. Fastmail recommends that you help train your personal spam filter by moving messages into a folder you designate, and then telling their systems to consider everything in that folder to be spam. While that's not hard, it's also not very streamlined, so I took up the task of making it even easier and faster.

(Note that, as a Mac user, most of my tips focus on Mac applications. If you're a user of another platform, I do apologize---but I can only speak about what I use myself.)

To help make this easier, I came up with a bit of AppleScript:

``` applescript
-- This script moves messages to a spam training folder
-- Set some default values to be used later in the script; not all values may be used
property destMailbox : "Spam Training"
property destAccount : "example.com"

-- Handler called when running script from script menu
on run
    tell application "Mail"
        set theSelectedMessages to selection
        if ((count of theSelectedMessages) < 1) then
            beep
            return
        end if
        repeat with theMessage in theSelectedMessages
            if (read status of theMessage) is false then
                set read status of theMessage to true
            end if
            move theMessage to mailbox destMailbox of account destAccount
        end repeat
    end tell
end run
```

You can download this script [from GitHub][gist-1], if that's helpful.

To make this work on your system, all you need to do is just change the two `property` declarations at the top. Set them to the correct values for your system.

As you can tell by the comments in the code, this script was designed to be run from within Apple's Mail app itself. To make that easy, I use a fantastic tool called [FastScripts](http://www.red-sweater.com/fastscripts/) (_highly recommended!_). Using FastScripts, I can easily designate an application-specific shortcut key (I use Ctrl-Cmd-S) to invoke the script from within Apple Mail. Boom! Just like that, you now have a super-easy way to both help speed up processing your e-mail as well as helping train your personal spam filter. (Note: if you are also a FastMail customer, refer to the FastMail help screens while logged in to get more details on marking a folder for spam learning.)

I hope this helps someone out there!

[1]: {{< relref "2013-06-21-reducing-the-friction-processing-e-mail.md" >}}
[2]: {{< relref "2013-07-19-reducing-the-friction-processing-e-mail-part-2.md" >}}
[3]: {{< relref "2013-12-04-divorcing-google.md" >}}
[gist-1]: https://gist.github.com/scottslowe/7990921


text:
export function invariant(
  condition: boolean,
  message?: string,
): asserts condition {
  if (!condition) {
    throw new Error(
      message != null ? message : 'Unexpected invariant triggered.',
    );
  }
}


text:
All notable changes to this project will be documented in this file.

## [Unreleased]

## [2.0.0] - 2020-03-05

This is major rewrite of the way the gem works. This version introduces many
breaking changes. Please review the README.


text:
require 'spec_helper'

#Check the AWS directory

describe file('/var/lib/jenkins/.aws') do
    it { should exist }
    it { should be_directory }
    it { should be_owned_by 'jenkins' }
end

describe file('/var/lib/jenkins/.aws/config') do
    it { should exist }
    it { should be_file }
    it { should be_owned_by 'jenkins' }
    its(:content) { should match /output\s+=\s+json/ }
end

describe file('/var/lib/jenkins/.aws/credentials') do
    it { should exist }
    it { should be_file }
    it { should be_owned_by 'jenkins' }
    its(:content) { should match /aws_access_key_id\s+=\s+yourAccessKeyIdHere/ }
end

#Check the Jenkins service
describe service('jenkins') do
    it { should be_running }
end

#Check the Jenkins user
describe user('jenkins') do
    it { should belong_to_group 'jenkins' }
    it { should belong_to_group 'docker' }
    it { should have_home_directory '/var/lib/jenkins' }
    it { should have_login_shell '/bin/bash' }
end

#Check the Jenkins cli
describe file('/var/lib/jenkins/jenkins-cli.jar') do
    it { should exist }
end

#Check Jenkins version
describe file('/var/lib/jenkins/jenkins.install.InstallUtil.lastExecVersion') do
    its(:content) { should match /2\.100/ }
end


text:
package spacequota

import (
	"github.com/cloudfoundry/cli/cf/api/space_quotas"
	"github.com/cloudfoundry/cli/cf/command_metadata"
	"github.com/cloudfoundry/cli/cf/configuration/core_config"
	"github.com/cloudfoundry/cli/cf/errors"
	"github.com/cloudfoundry/cli/cf/requirements"
	"github.com/cloudfoundry/cli/cf/terminal"
	"github.com/codegangsta/cli"

	. "github.com/cloudfoundry/cli/cf/i18n"
)

type DeleteSpaceQuota struct {
	ui             terminal.UI
	config         core_config.Reader
	spaceQuotaRepo space_quotas.SpaceQuotaRepository
}

func NewDeleteSpaceQuota(ui terminal.UI, config core_config.Reader, spaceQuotaRepo space_quotas.SpaceQuotaRepository) DeleteSpaceQuota {
	return DeleteSpaceQuota{
		ui:             ui,
		config:         config,
		spaceQuotaRepo: spaceQuotaRepo,
	}
}
func (cmd DeleteSpaceQuota) Metadata() command_metadata.CommandMetadata {
	return command_metadata.CommandMetadata{
		Name:        "delete-space-quota",
		Description: T("Delete a space quota definition and unassign the space quota from all spaces"),
		Usage:       T("CF_NAME delete-space-quota SPACE-QUOTA-NAME"),
		Flags: []cli.Flag{
			cli.BoolFlag{Name: "f", Usage: T("Force delete (do not prompt for confirmation)")},
		},
	}
}

func (cmd DeleteSpaceQuota) GetRequirements(requirementsFactory requirements.Factory, context *cli.Context) ([]requirements.Requirement, error) {
	if len(context.Args()) != 1 {
		cmd.ui.FailWithUsage(context)
	}

	return []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
	}, nil
}

func (cmd DeleteSpaceQuota) Run(context *cli.Context) {
	quotaName := context.Args()[0]

	if !context.Bool("f") {
		response := cmd.ui.ConfirmDelete("quota", quotaName)
		if !response {
			return
		}
	}

	cmd.ui.Say(T("Deleting space quota {{.QuotaName}} as {{.Username}}...", map[string]interface{}{
		"QuotaName": terminal.EntityNameColor(quotaName),
		"Username":  terminal.EntityNameColor(cmd.config.Username()),
	}))

	quota, apiErr := cmd.spaceQuotaRepo.FindByName(quotaName)
	switch (apiErr).(type) {
	case nil: // no error
	case *errors.ModelNotFoundError:
		cmd.ui.Ok()
		cmd.ui.Warn(T("Quota {{.QuotaName}} does not exist", map[string]interface{}{"QuotaName": quotaName}))
		return
	default:
		cmd.ui.Failed(apiErr.Error())
	}

	apiErr = cmd.spaceQuotaRepo.Delete(quota.Guid)
	if apiErr != nil {
		cmd.ui.Failed(apiErr.Error())
	}

	cmd.ui.Ok()
}