text:
<?php

namespace Clearcode\SimpleBusElkBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader;

class ElkBridgeExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $config, ContainerBuilder $container)
    {
        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config/'));
        $loader->load('services.yml');

        $configuration = new Configuration();
        $config        = $this->processConfiguration($configuration, $config);

        $container->setParameter('simple_bus_elk.logstash_namespace', $config['logstash_namespace']);
        $container->setParameter('simple_bus_elk.monolog_channel', $config['monolog_channel']);
        $container->setParameter('simple_bus_elk.middleware', $config['middleware']);

        if ($config['middleware']) {
            $loader->load('logstash.yml');
            $loader->load('middlewares.yml');
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getAlias()
    {
        return 'simple_bus_elk';
    }
}


text:
package de.digitalcollections.iiif.presentation.model.impl.jackson.mixin.v2;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import de.digitalcollections.iiif.presentation.model.impl.v2.LayerImpl;

@JsonDeserialize(as = LayerImpl.class)
public abstract class LayerMixIn extends AbstractIiifResourceMixIn {

}

redpajama_set_name: RedPajamaGithub


text:
<?php
require_once("function/basic.php");
require_once("function/config.php");
echoheader();
?>

Talk v<?php echo $VERSION; ?>

This is a project for safe communications under monitored environment. All you need is a passphrase (key) known by both you and your recipient (i.e. anything both of you knows but others don't know).

No one knows what you're talking even if they get access to your router / your server / your database, because all encryption and decryption happens on your web browser. We do 1M iterations of PBKDF2 - SHA512 of your key, and then, the result as key for AES256-CBC. This is the highest security standard in the industry.

Start Your Secure Communication

<form>
Message to Send:
 <textarea id="m" name="m"></textarea>

Passphrase: <input type="text" id='p' />

Passphrase Hint (Optional): <input type="text" id='phint' />

(Give some hint about the passphrase to the receiver. It will be stored and displayed in plaintext form)

</form>
<button class="btn btn-md btn-primary bu" id="bu">Generate one-time-access Message Link</button> <button class="btn btn-md btn-success bu" id="bu1">Generate unlimited-access Message Link</button>

<?php echofooter();?>


text:
package com.goodworkalan.sheaf;

/**
 * Derived classes implement the address, block, journal formats of an
 * underlying page in a Pack file. The Page interface is a
 * specialized application of an underlying page. It is the strategy participant
 * in the strategy design pattern. Each page has an underlying {@link RawPage}.
 *

 * RawPage contains the basic position and byte buffer page
 * attributes and maintains a set of invalid regions. A Page
 * implementation interprets the raw page as a specific page type.
 *
Frequent Instantiation and Two-Step Initialization

 *

 * When we request a page from the the pager, we give it an implementation of
 * Page that represents the type request. If the raw page exists in
 * the pager and it is associated with the type of page requested, that page is
 * returned. If it is not in the pager, or if the page associated with the raw
 * page is a super class of the page requested, the raw page is associated with
 * the Page implementation given.
 *

 * This means that we create a lot of instances of type Page that
 * are not initialized. They are not initialized because they are not needed.
 * The pager has the right type of Page. They are simply forgotten
 * and left for the garbage collector. For this reason, it is important that
 * implementations of Page have simple default constructors.
 *

 * Page instances are not initialized by their default
 * constructors. They are actually initialized by a call to either
 * {@link #create create} or {@link #load load}.
 *
Circular RawPage and Page Reference

 *

 * The circular reference between Page and RawPage is
 * necessary. RawPage is used as the mutex for changes to the
 * underlying byte buffer as well as to the data members of the
 * Page itself. All the Page implementations use the
 * associated RawPage as the lock object in synchronized blocks as
 * opposed to using synchronized methods on the Page itself.
 *

 * The pager keeps a map by position of the RawPage object an not
 * the Page objects, because the Page associated with
 * a RawPage can change. Specifically, the Page
 * associated with a RawPage can be promoted from a
 * RelocatablePage to a subclass of RelocatablePage
 *
 * @see Sheaf#getPage(long, Class, Page)
 * @see Sheaf#setPage(long, Class, Page, DirtyPageSet)
 */
public class Page {
    /** The underlying raw page. */
    private RawPage rawPage;

    /**
     * Set the underlying raw page.
     *

     * This can only be set by the Sheaf that maintains the
     * RawPage.
     *
     * @param rawPage
     */
    void setRawPage(RawPage rawPage) {
        this.rawPage = rawPage;
    }

    /**
     * Return the underlying raw page associated with this page.
     *
     * @return The raw page.
     */
    public RawPage getRawPage() {
        return rawPage;
    }

    /**
     * Initialize the raw page to the specific interpretation implemented by
     * this page. This method is called from within the Pager when
     * a new raw page is allocated. The specified raw page will subsequently be
     * returned by {@link #getRawPage() getRawPage}.
     *
     * @param dirtyPages
     *            The collection of dirty pages.
     * @see Sheaf#setPage(long, Class, Page, DirtyPageSet)
     */
    public void create(DirtyPageSet dirtyPages) {
    }

    /**
     * Load this specific interpretation from the specified the raw page. This
     * method is called from within the {@link Sheaf#getPage getPage} method of
     * the Pager when a page is loaded from the file. The specified
     * RawPage will be subsequently returned by
     * {@link #getRawPage() getRawPage}.
     *
     * @see Sheaf#getPage(long, Class, Page)
     */
    public void load() {
    }
}


text:
using DotNetNuke.Entities.Modules;

#endregion

namespace DotNetNuke.Modules.Groups
{
    public class GroupsSettingsBase : ModuleSettingsBase
    {
    }
}


text:
package ninja.leaping.permissionsex.sponge.rank;

import ninja.leaping.permissionsex.rank.RankLadder;

public interface RankingService {
    /**
     * Get a ladder by name. This will create a new ladder if none exists yet.
     *
     * @param ladder The name of the ladder to get. Case-insensitive.
     * @return the ladder
     */
    RankLadder getLadder(String ladder);

    /**
     * Return whether or not this ladder is present
     *
     * @param ladder The ladder to check. Case-insensitive
     * @return Whether this ladder is present
     */
    boolean hasLadder(String ladder);
}


text:
"""Simple utility to pull in all the testing functions we're likely to use.
"""

import os

import numpy as np
from distutils.version import LooseVersion

from nose.tools import (assert_true, assert_false, assert_not_equal,
                        assert_raises)
from nose import SkipTest, with_setup

if LooseVersion(np.__version__) >= '1.2':
    from numpy.testing import *
    from numpy.testing.decorators import *
else:
    from numpytesting import *
    from numpytesting.decorators import *

from utils import *
from enthought.traits.api import TraitError

# import Fernando's lightunit for parametric tests
from lightunit import ParametricTestCase, parametric

# import datasets for doctests
filepath = os.path.abspath(__file__)
basedir = os.path.dirname(filepath)

funcfile = os.path.join(basedir, 'data', 'functional.nii')
anatfile = funcfile
template = funcfile
transfm = funcfile

def example_data(infile='functional.nii'):
    """returns path to empty example data files for doc tests
    it will raise an exception if filename is not in the directory"""

    filepath = os.path.abspath(__file__)
    basedir = os.path.dirname(filepath)
    outfile = os.path.join(basedir, 'data', infile)
    if not os.path.exists(outfile):
        raise IOError('%s empty data file does NOT exist'%(outfile))

    return outfile


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

<title>Uses of Interface org.apache.cassandra.net.IAsyncCallback (apache-cassandra API)</title>
<meta name="date" content="2015-05-13">
<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

Next

Frames

No Frames

All Classes

Uses of Interface
org.apache.cassandra.net.IAsyncCallback

Packages that use IAsyncCallback

Package
Description

org.apache.cassandra.net

org.apache.cassandra.service

org.apache.cassandra.service.paxos

Uses of IAsyncCallback in org.apache.cassandra.net

Subinterfaces of IAsyncCallback in org.apache.cassandra.net

Modifier and Type
Interface and Description

interface
IAsyncCallbackWithFailure<T>

Classes in org.apache.cassandra.net that implement IAsyncCallback

Modifier and Type
Class and Description

class
AsyncOneResponse<T>

A callback specialized for returning a value from a single target; that is, this is for messages
 that we only send to one recipient.

Fields in org.apache.cassandra.net declared as IAsyncCallback

Modifier and Type
Field and Description

protected IAsyncCallback
CallbackInfo.callback

Methods in org.apache.cassandra.net with parameters of type IAsyncCallback

Modifier and Type
Method and Description

int
MessagingService.addCallback(IAsyncCallback cb,
           MessageOut<? extends IMutation> message,
           java.net.InetAddress to,
           long timeout,
           ConsistencyLevel consistencyLevel,
           boolean allowHints)

int
MessagingService.addCallback(IAsyncCallback cb,
           MessageOut message,
           java.net.InetAddress to,
           long timeout,
           boolean failureCallback)

void
MessagingService.maybeAddLatency(IAsyncCallback cb,
               java.net.InetAddress address,
               long latency)

Track latency information for the dynamic snitch

int
MessagingService.sendRR(MessageOut message,
      java.net.InetAddress to,
      IAsyncCallback cb)

int
MessagingService.sendRR(MessageOut message,
      java.net.InetAddress to,
      IAsyncCallback cb,
      long timeout,
      boolean failureCallback)

Send a non-mutation message to a given endpoint.

Constructors in org.apache.cassandra.net with parameters of type IAsyncCallback

Constructor and Description

CallbackInfo(java.net.InetAddress target,
            IAsyncCallback callback,
            IVersionedSerializer<?> serializer)

CallbackInfo(java.net.InetAddress target,
            IAsyncCallback callback,
            IVersionedSerializer<?> serializer,
            boolean failureCallback)

Create CallbackInfo without sent message

WriteCallbackInfo(java.net.InetAddress target,
                 IAsyncCallback callback,
                 MessageOut message,
                 IVersionedSerializer<?> serializer,
                 ConsistencyLevel consistencyLevel,
                 boolean allowHints)

Uses of IAsyncCallback in org.apache.cassandra.service

Classes in org.apache.cassandra.service that implement IAsyncCallback

Modifier and Type
Class and Description

class
AbstractWriteResponseHandler

class
AsyncRepairCallback

class
DatacenterSyncWriteResponseHandler

This class blocks for a quorum of responses _in all datacenters_ (CL.EACH_QUORUM).

class
DatacenterWriteResponseHandler

This class blocks for a quorum of responses _in the local datacenter only_ (CL.LOCAL_QUORUM).

class
ReadCallback<TMessage,TResolved>

class
TruncateResponseHandler

class
WriteResponseHandler

Handles blocking writes for ONE, ANY, TWO, THREE, QUORUM, and ALL consistency levels.

Uses of IAsyncCallback in org.apache.cassandra.service.paxos

Classes in org.apache.cassandra.service.paxos that implement IAsyncCallback

Modifier and Type
Class and Description

class
AbstractPaxosCallback<T>

class
PrepareCallback

class
ProposeCallback

ProposeCallback has two modes of operation, controlled by the failFast parameter.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2015 The Apache Software Foundation


text:
<?php

/**
 * @namespace
 */
namespace PopTest\Validator;

use Pop\Loader\Autoloader;
use Pop\Validator\CreditCard;

// Require the library's autoloader.
require_once __DIR__ . '/../../../src/Pop/Loader/Autoloader.php';

// Call the autoloader's bootstrap function.
Autoloader::factory()->splAutoloadRegister();

class CreditCardTest extends \PHPUnit_Framework_TestCase
{

    public function testEvaluateTrue()
    {
        $v = new CreditCard();
        $this->assertTrue($v->evaluate(4111111111111111));
        $this->assertTrue($v->evaluate('4111 1111 1111 1111'));
        $this->assertTrue($v->evaluate('4111-1111-1111-1111'));
        $this->assertFalse($v->evaluate(123456789));
    }

    public function testEvaluateFalse()
    {
        $v = new CreditCard(null, null, false);
        $this->assertFalse($v->evaluate(4111111111111111));
        $this->assertTrue($v->evaluate(123456789));
    }

}


text:
"""
The Mandelbrot set is the set of complex numbers "c" for which the series
"z_(n+1) = z_n * z_n + c" does not diverge, i.e. remains bounded. Thus, a
complex number "c" is a member of the Mandelbrot set if, when starting with
"z_0 = 0" and applying the iteration repeatedly, the absolute value of
"z_n" remains bounded for all "n > 0". Complex numbers can be written as
"a + b*i": "a" is the real component, usually drawn on the x-axis, and "b*i"
is the imaginary component, usually drawn on the y-axis. Most visualizations
of the Mandelbrot set use a color-coding to indicate after how many steps in
the series the numbers outside the set diverge. Images of the Mandelbrot set
exhibit an elaborate and infinitely complicated boundary that reveals
progressively ever-finer recursive detail at increasing magnifications, making
the boundary of the Mandelbrot set a fractal curve.
(description adapted from https://en.wikipedia.org/wiki/Mandelbrot_set )
(see also https://en.wikipedia.org/wiki/Plotting_algorithms_for_the_Mandelbrot_set )
"""

import colorsys

from PIL import Image  # type: ignore

def get_distance(x: float, y: float, max_step: int) -> float:
    """
    Return the relative distance (= step/max_step) after which the complex number
    constituted by this x-y-pair diverges. Members of the Mandelbrot set do not
    diverge so their distance is 1.

    >>> get_distance(0, 0, 50)
    1.0
    >>> get_distance(0.5, 0.5, 50)
    0.061224489795918366
    >>> get_distance(2, 0, 50)
    0.0
    """
    a = x
    b = y
    for step in range(max_step):
        a_new = a * a - b * b + x
        b = 2 * a * b + y
        a = a_new

        # divergence happens for all complex number with an absolute value
        # greater than 4
        if a * a + b * b > 4:
            break
    return step / (max_step - 1)

def get_black_and_white_rgb(distance: float) -> tuple:
    """
    Black&white color-coding that ignores the relative distance. The Mandelbrot
    set is black, everything else is white.

    >>> get_black_and_white_rgb(0)
    (255, 255, 255)
    >>> get_black_and_white_rgb(0.5)
    (255, 255, 255)
    >>> get_black_and_white_rgb(1)
    (0, 0, 0)
    """
    if distance == 1:
        return (0, 0, 0)
    else:
        return (255, 255, 255)

def get_color_coded_rgb(distance: float) -> tuple:
    """
    Color-coding taking the relative distance into account. The Mandelbrot set
    is black.

    >>> get_color_coded_rgb(0)
    (255, 0, 0)
    >>> get_color_coded_rgb(0.5)
    (0, 255, 255)
    >>> get_color_coded_rgb(1)
    (0, 0, 0)
    """
    if distance == 1:
        return (0, 0, 0)
    else:
        return tuple(round(i * 255) for i in colorsys.hsv_to_rgb(distance, 1, 1))

def get_image(
    image_width: int = 800,
    image_height: int = 600,
    figure_center_x: float = -0.6,
    figure_center_y: float = 0,
    figure_width: float = 3.2,
    max_step: int = 50,
    use_distance_color_coding: bool = True,
) -> Image.Image:
    """
    Function to generate the image of the Mandelbrot set. Two types of coordinates
    are used: image-coordinates that refer to the pixels and figure-coordinates
    that refer to the complex numbers inside and outside the Mandelbrot set. The
    figure-coordinates in the arguments of this function determine which section
    of the Mandelbrot set is viewed. The main area of the Mandelbrot set is
    roughly between "-1.5 < x < 0.5" and "-1 < y < 1" in the figure-coordinates.

    Commenting out tests that slow down pytest...
    # 13.35s call     fractals/mandelbrot.py::mandelbrot.get_image
    # >>> get_image().load()[0,0]
    (255, 0, 0)
    # >>> get_image(use_distance_color_coding = False).load()[0,0]
    (255, 255, 255)
    """
    img = Image.new("RGB", (image_width, image_height))
    pixels = img.load()

    # loop through the image-coordinates
    for image_x in range(image_width):
        for image_y in range(image_height):

            # determine the figure-coordinates based on the image-coordinates
            figure_height = figure_width / image_width * image_height
            figure_x = figure_center_x + (image_x / image_width - 0.5) * figure_width
            figure_y = figure_center_y + (image_y / image_height - 0.5) * figure_height

            distance = get_distance(figure_x, figure_y, max_step)

            # color the corresponding pixel based on the selected coloring-function
            if use_distance_color_coding:
                pixels[image_x, image_y] = get_color_coded_rgb(distance)
            else:
                pixels[image_x, image_y] = get_black_and_white_rgb(distance)

    return img

if __name__ == "__main__":
    import doctest

    doctest.testmod()

    # colored version, full figure
    img = get_image()

    # uncomment for colored version, different section, zoomed in
    # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4,
    # figure_width = 0.8)

    # uncomment for black and white version, full figure
    # img = get_image(use_distance_color_coding = False)

    # uncomment to save the image
    # img.save("mandelbrot.png")

    img.show()


text:
(function () {
    "use strict";

    var controlTemplate = null;
    var templateInitPromise = null;

    // This will load and cache the control's template.
    // This happens the first time an instance of the control is created, or when you call Controls.EditTools.cacheControlTemplate
    function loadControlTemplate() {
        if (!templateInitPromise) {
            var controlFragment = document.createElement("div");
            templateInitPromise = WinJS.UI.Fragments.render("controls/edittools/edittools.html", controlFragment).then(function () {
                controlTemplate = new WinJS.Binding.Template(controlFragment.querySelector("#edittools-template"));
                controlTemplate._renderImpl = controlTemplate._compileTemplate({ target: "render" });
            });
        }
        return templateInitPromise;
    }

    var EditTools = WinJS.Class.define(function (element, options) {
        var options = options || {};
        this.element = element || document.createElement("div");
        this.element.winControl = this;
        WinJS.UI.setOptions(this, options);

        this.controlInitialized = false;
        var that = this;
        this.initPromise = loadControlTemplate().then(function () {
            that.element.className = controlTemplate.element.className;
            return controlTemplate.render(options.dataSource, that.element).then(
                function (element) {
                    that._initialize();
                    that.controlInitialized = true;
                });
        });
    }
    , {
        _initialize: function () {
            var that = this;
            var labels = this.element.querySelectorAll(".edit-tools-button-label");
            for (var n = 0; n < labels.length; n++) {
                var label = labels[n];
                if (WinJS.UI.AppBarIcon[label.dataset.label]) {
                    label.textContent = WinJS.UI.AppBarIcon[label.dataset.label];
                }
                else {
                    label.textContent = label.dataset.label;
                }
                label.parentElement.dataset.label = label.dataset.label;
            }

            var buttons = this.getButtons();
            Object.keys(buttons).forEach(function (buttonKey) {
                var button = buttons[buttonKey];
                button.addEventListener("click", function () {
                    that.dispatchEvent("click", {
                        sender: button,
                        label: this.dataset.label
                    });
                });
            });
        },

        ensureInitialized: function () {
            return this.initPromise;
        },

        dispose: function () {
            // TODO: Control clean-up
            this._disposed = true;
        },

        getButtons: function () {
            var buttons = {};
            var buttonElements = this.element.querySelectorAll(".edit-tools-button");
            for (var n = 0; n < buttonElements.length; n++) {
                var buttonElement = buttonElements[n];
                buttons[buttonElement.dataset.label] = buttonElement;
            }
            return buttons;
        }
    },
    {
        cacheControlTemplate: function () {
            return loadControlTemplate();
        },
    });

    WinJS.Namespace.define("Controls", {
        EditTools: EditTools,
    });
})();

WinJS.Class.mix(Controls.EditTools,
    WinJS.Utilities.createEventProperties("click"),
    WinJS.UI.DOMEventMixin);


text:
package com.google.mr4c.metadata;

/**
  * Default implementation of MetadataVistitor.  Default for all visitXXX
  * methods is to call visitMetadataElement (except visitXXXPreIteration
  * methods, which are no-ops)
*/
public class DefaultMetadataVisitor implements MetadataVisitor {

	public void visitMapPreIteration(MetadataMap map) {}

	public void visitMapPostIteration(MetadataMap map) {
		visitMetadataElement(map);
	}

	public void visitListPreIteration(MetadataList list) {}

	public void visitListPostIteration(MetadataList list) {
		visitMetadataElement(list);
	}

	public void visitField(MetadataField field) {
		visitMetadataElement(field);
	}

	public void visitArray(MetadataArray array) {
		visitMetadataElement(array);
	}

	public void visitKey(MetadataKey key) {
		visitMetadataElement(key);
	}

	protected void visitMetadataElement(MetadataElement ele) {}

}


text:
@interface ExampleDRYUIColorDRYUtilViewController()
@property (weak, nonatomic) IBOutlet UITextField *hexTextField;
@property (weak, nonatomic) IBOutlet UIView *coloredView;

@end

@implementation ExampleDRYUIColorDRYUtilViewController {

}

-(void)viewDidLoad {
    [super viewDidLoad];
    _hexTextField.text = @"#113399";
}

- (IBAction)colorize:(id)sender {
    _coloredView.backgroundColor = [UIColor dryColorFromRGBHexString:_hexTextField.text];
}
@end


text:
package mock.contract;

import com.intuit.karate.EventContext;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author pthomas3
 */
public class QueueConsumer {

    private static final Logger logger = LoggerFactory.getLogger(QueueConsumer.class);

    private final Connection connection;
    private final MessageConsumer consumer;
    private final String queueName;
    private final Session session;

    public QueueConsumer(String queueName) {
        this.queueName = queueName;
        this.connection = QueueUtils.getConnection();
        try {
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createQueue(queueName);
            consumer = session.createConsumer(destination);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void listen(java.util.function.Consumer<String> handler) {
        setMessageListener(message -> {
            TextMessage tm = (TextMessage) message;
            try {
                handler.accept(tm.getText());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }

    public void bind(EventContext context) {
        setMessageListener(message -> {
            TextMessage tm = (TextMessage) message;
            try {
                context.signal(tm.getText());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }

    public void setMessageListener(MessageListener ml) {
        try {
            consumer.setMessageListener(ml);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public String waitForNextMessage() {
        try {
            TextMessage tm = (TextMessage) consumer.receive();
            return tm.getText();
        } catch (JMSException e) {
            throw new RuntimeException(e);
        }
    }

    public void purgeMessages() {
        try {
            consumer.setMessageListener(null);
            while (true) {
                Message message = consumer.receive(50);
                if (message == null) {
                    logger.info("*** no more messages to purge: {}", queueName);
                    break;
                }
                logger.info("*** purged message: {} - {}", queueName, message);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void stop() {
        try {
            consumer.close();
            session.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}


text:
<md-toolbar class="header">

  <md-button class="md-raised header-button" ui-sref= "signin" ng-if="!isLoggedIn">Sign In</md-button>
  <md-button class="md-raised header-button" ng-click="logout()" ng-if="isLoggedIn">Log Out</md-button>

</md-toolbar>


text:
namespace zombie {

	ZombiePlayer::ZombiePlayer(std::unique_ptr<Unit> unit)
		: findNewTargetTime_{random(0.f, 3.f)}
		, timeToUpdateAngleDirection_{random()}
		, targetAngle_{unit->getDirection()}
		, unit_{std::move(unit)} {
	}

	void ZombiePlayer::updateInput(double time, double deltaTime) {
		Input input{};

		if (time > findNewTargetTime_) {
			findNewTargetTime_ = random(0.f, 3.f) + static_cast<float>(time);

			target_ = findUninfectedTarget(unit_->getPosition(), unit_->getVisibleObjects());
		}

		if (time > timeToUpdateAngleDirection_) {
			timeToUpdateAngleDirection_ = random() + static_cast<float>(time);

			// Has a target?
			if (false && target_ != nullptr && target_->isEnabled() && !target_->isDead()) {
				auto dir = target_->getPosition() - unit_->getPosition();
				targetAngle_ = std::atan2(dir.y, dir.x);
				forward_ = true;

				auto distSquared = dir.LengthSquared();

				// Target is in range?
				if (auto& weapon = unit_->getWeapon();
					weapon != nullptr && distSquared < weapon->getRange() * weapon->getRange()) {

					// Attack!
					input.shoot = true;
				}
			} else {
				targetAngle_ +=  random(-0.5f, 0.5f) * 2.f * Pi * 2.f * 0.05f;
				forward_ = random() > 0.25f;
			}
		}

		auto diffAngle = calculateDifferenceBetweenAngles(targetAngle_, unit_->getDirection());

		// Turn?
		if (std::abs(diffAngle) > 0.1f) {
			if (diffAngle > 0) {
				input.turnLeft = true;
			} else {
				input.turnRight = true;
			}
		}

		input.forward = forward_;
		unit_->setInput(input);
		unit_->updatePhysics(time, deltaTime);
	}

	void ZombiePlayer::draw(sdl::Graphic& graphic) {
		auto pos = unit_->getPosition();
		graphic.addCircle({pos.x, pos.y}, unit_->getRadius(), sdl::color::html::Firebrick);
		graphic.addCircleOutline({pos.x, pos.y}, unit_->getViewDistance(), 0.04f, sdl::color::html::Firebrick);
        graphic.addLine({pos.x, pos.y}, glm::vec2{pos.x, pos.y} + glm::rotate(glm::vec2{1.f, 0.f}*0.5f, unit_->getDirection()), 0.1f, sdl::color::html::Firebrick);
	}

	PhysicalObject* ZombiePlayer::getPhysicalObject() {
		return unit_.get();
	}

	MovingObject* ZombiePlayer::findUninfectedTarget(Position position, const std::list<MovingObject*>& units) const {
		MovingObject* target = nullptr;
		float distance = 100.f;
		for (auto unit : units) {
			if (!unit->isInfected()) {
				auto tmp = (position - unit->getPosition()).LengthSquared();
				if (tmp < distance) {
					target = unit;
					distance = tmp;
				}
			}
		}
		return target;
	}

}


text:
import { expect } from '@playwright/test';
import { getPage } from '../../../baseTest';

export const SELECTOR_OPEN_STATUS = '#open-status';
export const SELECTOR_TOOLTIP = 'ngb-tooltip-window';

export const expectTooltipToBeOpen = async (message: string) => {
	await getPage().waitForSelector(SELECTOR_TOOLTIP);
	await expect(getPage().locator(SELECTOR_OPEN_STATUS), message).toHaveText('open');
};

export const expectTooltipToBeClosed = async (message: string) => {
	await getPage().waitForSelector(SELECTOR_TOOLTIP, { state: 'detached' });
	await expect(getPage().locator(SELECTOR_OPEN_STATUS), message).toHaveText('closed');
};


text:
class CreateTeachers < ActiveRecord::Migration
  def change
    create_table :teachers do |t|
      t.references :person, index: true, foreign_key: true
      t.boolean :active

      t.timestamps null: false
    end
  end
end


text:
"""
Common test support for pymatgen test scripts.

This single module should provide all the common functionality for pymatgen
tests in a single location, so that test scripts can just import it and work
right away.
"""

import json
import tempfile
import unittest
from pathlib import Path

import numpy.testing as nptu
from monty.dev import requires
from monty.json import MontyDecoder, MSONable
from monty.serialization import loadfn

from pymatgen.core import SETTINGS
from pymatgen.ext.matproj import MPRester

class PymatgenTest(unittest.TestCase):
    """
    Extends unittest.TestCase with functions (taken from numpy.testing.utils)
    that support the comparison of arrays.
    """

    _multiprocess_shared_ = True
    MODULE_DIR = Path(__file__).absolute().parent
    STRUCTURES_DIR = MODULE_DIR / "structures"
    try:
        TEST_FILES_DIR = Path(SETTINGS["PMG_TEST_FILES_DIR"])
    except KeyError:
        import warnings

        warnings.warn(
            "It is recommended that you set the PMG_TEST_FILES_DIR environment variable explicitly. "
            "Now using a fallback location based on relative path from this module."
        )
        TEST_FILES_DIR = MODULE_DIR / ".." / ".." / "test_files"
    """
    Dict for test structures to aid testing.
    """
    TEST_STRUCTURES = {}
    for fn in STRUCTURES_DIR.iterdir():
        TEST_STRUCTURES[fn.name.rsplit(".", 1)[0]] = loadfn(str(fn))

    @classmethod
    def get_structure(cls, name):
        """
        Get a structure from the template directories.

        :param name: Name of a structure.
        :return: Structure
        """
        return cls.TEST_STRUCTURES[name].copy()

    @classmethod
    @requires(SETTINGS.get("PMG_MAPI_KEY"), "PMG_MAPI_KEY needs to be set.")
    def get_mp_structure(cls, mpid):
        """
        Get a structure from MP.

        :param mpid: Materials Project id.
        :return: Structure
        """
        m = MPRester()
        return m.get_structure_by_material_id(mpid)

    @staticmethod
    def assertArrayAlmostEqual(actual, desired, decimal=7, err_msg="", verbose=True):
        """
        Tests if two arrays are almost equal to a tolerance. The CamelCase
        naming is so that it is consistent with standard unittest methods.
        """
        return nptu.assert_almost_equal(actual, desired, decimal, err_msg, verbose)

    @staticmethod
    def assertDictsAlmostEqual(actual, desired, decimal=7, err_msg="", verbose=True):
        """
        Tests if two arrays are almost equal to a tolerance. The CamelCase
        naming is so that it is consistent with standard unittest methods.
        """

        for k, v in actual.items():
            if k not in desired:
                return False
            v2 = desired[k]
            if isinstance(v, dict):
                pass_test = PymatgenTest.assertDictsAlmostEqual(
                    v, v2, decimal=decimal, err_msg=err_msg, verbose=verbose
                )
                if not pass_test:
                    return False
            elif isinstance(v, (list, tuple)):
                pass_test = nptu.assert_almost_equal(v, v2, decimal, err_msg, verbose)
                if not pass_test:
                    return False
            elif isinstance(v, (int, float)):
                PymatgenTest().assertAlmostEqual(v, v2)  # pylint: disable=E1120
            else:
                assert v == v2
        return True

    @staticmethod
    def assertArrayEqual(actual, desired, err_msg="", verbose=True):
        """
        Tests if two arrays are equal. The CamelCase naming is so that it is
         consistent with standard unittest methods.
        """
        return nptu.assert_equal(actual, desired, err_msg=err_msg, verbose=verbose)

    @staticmethod
    def assertStrContentEqual(actual, desired, err_msg="", verbose=True):
        """
        Tests if two strings are equal, ignoring things like trailing spaces,
        etc.
        """
        lines1 = actual.split("\n")
        lines2 = desired.split("\n")
        if len(lines1) != len(lines2):
            return False
        failed = []
        for l1, l2 in zip(lines1, lines2):
            if l1.strip() != l2.strip():
                failed.append(f"{l1} != {l2}")
        return len(failed) == 0

    def serialize_with_pickle(self, objects, protocols=None, test_eq=True):
        """
        Test whether the object(s) can be serialized and deserialized with
        pickle. This method tries to serialize the objects with pickle and the
        protocols specified in input. Then it deserializes the pickle format
        and compares the two objects with the __eq__ operator if
        test_eq == True.

        Args:
            objects: Object or list of objects.
            protocols: List of pickle protocols to test. If protocols is None,
                HIGHEST_PROTOCOL is tested.

        Returns:
            Nested list with the objects deserialized with the specified
            protocols.
        """
        # Use the python version so that we get the traceback in case of errors
        import pickle

        from pymatgen.util.serialization import pmg_pickle_dump, pmg_pickle_load

        # Build a list even when we receive a single object.
        got_single_object = False
        if not isinstance(objects, (list, tuple)):
            got_single_object = True
            objects = [objects]

        if protocols is None:
            protocols = [pickle.HIGHEST_PROTOCOL]

        # This list will contains the object deserialized with the different
        # protocols.
        objects_by_protocol, errors = [], []

        for protocol in protocols:
            # Serialize and deserialize the object.
            mode = "wb"
            fd, tmpfile = tempfile.mkstemp(text="b" not in mode)

            try:
                with open(tmpfile, mode) as fh:
                    pmg_pickle_dump(objects, fh, protocol=protocol)
            except Exception as exc:
                errors.append(f"pickle.dump with protocol {protocol} raised:\n{exc}")
                continue

            try:
                with open(tmpfile, "rb") as fh:
                    new_objects = pmg_pickle_load(fh)
            except Exception as exc:
                errors.append(f"pickle.load with protocol {protocol} raised:\n{exc}")
                continue

            # Test for equality
            if test_eq:
                for old_obj, new_obj in zip(objects, new_objects):
                    self.assertEqual(old_obj, new_obj)

            # Save the deserialized objects and test for equality.
            objects_by_protocol.append(new_objects)

        if errors:
            raise ValueError("\n".join(errors))

        # Return nested list so that client code can perform additional tests.
        if got_single_object:
            return [o[0] for o in objects_by_protocol]
        return objects_by_protocol

    def assertMSONable(self, obj, test_if_subclass=True):
        """
        Tests if obj is MSONable and tries to verify whether the contract is
        fulfilled.

        By default, the method tests whether obj is an instance of MSONable.
        This check can be deactivated by setting test_if_subclass to False.
        """
        if test_if_subclass:
            self.assertIsInstance(obj, MSONable)
        self.assertDictEqual(obj.as_dict(), obj.__class__.from_dict(obj.as_dict()).as_dict())
        json.loads(obj.to_json(), cls=MontyDecoder)


text:
bool NormalizeExtensionResourcePath(const base::FilePath& path,
                                    base::FilePath* result) {
  DCHECK(result);

  if (path.ReferencesParent())
    return false;

  base::FilePath rv;
  for (const auto& path_component : path.GetComponents()) {
    if (path_component != base::FilePath::kCurrentDirectory)
      rv = rv.Append(path_component);
  }

  if (rv.empty())
    return false;

  *result = std::move(rv);
  return true;
}

std::set<base::FilePath> NormalizeExtensionResourcePaths(
    const std::set<base::FilePath>& icons_paths) {
  std::set<base::FilePath> rv;
  for (const auto& icon_path : icons_paths) {
    base::FilePath normalized_path;
    if (NormalizeExtensionResourcePath(icon_path, &normalized_path))
      rv.emplace(std::move(normalized_path));
  }
  return rv;
}


text:
require 'spec_helper'

feature 'Commit Update' do
  let(:lens) do
    Lens.create(
      registered_at: Time.current,
      mfr_id: MFR.find_by(name: 'Leica').id,
      mount_id: Mount.find_by(name: 'Leica L').id,
      name: 'Summitar',
      mm: 50,
      f: 2.0,
      close_up: false,
      note: '荳ク邨槭j'
    )
    LensOnPage.edit
  end

  background do
    lens.name = 'Summicron'
    lens.note = '8 elements'
    lens.confirm
  end

  context 'confirm inputted content' do
    background { lens.update }

    scenario { expect(lens).to have_registered_at }
    scenario { expect(lens).to have_mfr_name }
    scenario { expect(lens).to have_mount_name }
    scenario { expect(lens).to have_name }
    scenario { expect(lens).to have_mm }
    scenario { expect(lens).to have_f }
    scenario { expect(lens).to have_close_up }
    scenario { expect(lens).to have_note }
  end

  context 'cancel inputted content' do
    background { lens.cancel }

    scenario { expect(lens).to have_edit_form }
    scenario { expect(lens).to have_filled_registered_at }
    scenario { expect(lens).to have_filled_mfr_id }
    scenario { expect(lens).to have_filled_mount_id }
    scenario { expect(lens).to have_filled_name }
    scenario { expect(lens).to have_filled_mm }
    scenario { expect(lens).to have_filled_f }
    scenario { expect(lens).to have_filled_close_up }
    scenario { expect(lens).to have_filled_note }
  end

  context 'cancel(by back) inputted content' do
    background { lens.cancel_by_back }

    scenario { expect(lens).to have_edit_form }
    scenario { expect(lens).to have_filled_registered_at }
    scenario { expect(lens).to have_filled_mfr_id }
    scenario { expect(lens).to have_filled_mount_id }
    scenario { expect(lens).to have_filled_name }
    scenario { expect(lens).to have_filled_mm }
    scenario { expect(lens).to have_filled_f }
    scenario { expect(lens).to have_filled_close_up }
    scenario { expect(lens).to have_filled_note }
  end
end


text: Plugin documentation: [doc/index.md](doc/index.md)


text:
	<title>David Basnett's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

David Basnett's panel show appearances

David Basnett has appeared in 3 episodes between 1980-1983.  David Basnett on Wikipedia.

1980

1981

1982

1983

1983-05-12 / Question Time

1980-10-16 / Question Time

1980-02-21 / Question Time


text:
package org.drools.base;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

import org.drools.WorkingMemory;
import org.drools.rule.Declaration;
import org.drools.rule.Rule;
import org.drools.spi.Enabled;
import org.drools.spi.Tuple;

public class EnabledBoolean
    implements
    Enabled,
    Externalizable {

    private static final long   serialVersionUID = 510l;

    public static final Enabled ENABLED_TRUE  = new EnabledBoolean( true );
    public static final Enabled ENABLED_FALSE  = new EnabledBoolean( false );

    private boolean             value;

    public EnabledBoolean() {
    }

    public EnabledBoolean(boolean value) {
        this.value = value;
    }

    public void readExternal(ObjectInput in) throws IOException,
                                            ClassNotFoundException {
        value = in.readBoolean();
    }

    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeBoolean( value );
    }

    public boolean getValue(final Tuple tuple,
                            final Declaration[] declrs,
                            final Rule rule,
                            final WorkingMemory workingMemory) {
        return this.value;
    }

    public String toString() {
        return String.valueOf( this.value );
    }

}


text:
package org.broadinstitute.clio.client

import better.files.File
import com.typesafe.config.Config
import net.ceedubs.ficus.Ficus._
import org.broadinstitute.clio.util.config.{ClioConfig, ConfigReaders}

import scala.concurrent.duration.FiniteDuration

/**
  * Configuration file accessors.
  */
object ClioClientConfig extends ConfigReaders {
  private val config = ClioConfig.load

  private val clientConfig = config.as[Config]("client")

  val responseTimeout: FiniteDuration =
    clientConfig.as[FiniteDuration]("response-timeout")

  val maxRequestRetries: Int =
    clientConfig.as[Int]("max-request-retries")

  val serviceAccountJson: Option[File] =
    clientConfig.getAs[File]("service-account-json")

  object Version {
    val value: String = config.as[String]("client.version")
  }

  object ClioServer {
    private val clioServer = config.as[Config]("server")
    val clioServerHostName: String = clioServer.as[String]("hostname")
    val clioServerPort: Int = clioServer.as[Int]("port")
    val clioServerUseHttps: Boolean = clioServer.as[Boolean]("use-https")
  }
}


text:
#include <linux/oom.h>
#include <linux/mm.h>
#include <linux/err.h>
#include <linux/gfp.h>
#include <linux/sched.h>
#include <linux/swap.h>
#include <linux/timex.h>
#include <linux/jiffies.h>
#include <linux/cpuset.h>
#include <linux/export.h>
#include <linux/notifier.h>
#include <linux/memcontrol.h>
#include <linux/mempolicy.h>
#include <linux/security.h>
#include <linux/ptrace.h>
#include <linux/freezer.h>
#include <linux/ftrace.h>
#include <linux/ratelimit.h>

#define CREATE_TRACE_POINTS
#include <trace/events/oom.h>

int sysctl_panic_on_oom;
int sysctl_oom_kill_allocating_task;
int sysctl_oom_dump_tasks = 1;

DEFINE_MUTEX(oom_lock);

#ifdef CONFIG_NUMA
/**
 * has_intersects_mems_allowed() - check task eligiblity for kill
 * @start: task struct of which task to consider
 * @mask: nodemask passed to page allocator for mempolicy ooms
 *
 * Task eligibility is determined by whether or not a candidate task, @tsk,
 * shares the same mempolicy nodes as current if it is bound by such a policy
 * and whether or not it has the same set of allowed cpuset nodes.
 */
static bool has_intersects_mems_allowed(struct task_struct *start,
					const nodemask_t *mask)
{
	struct task_struct *tsk;
	bool ret = false;

	rcu_read_lock();
	for_each_thread(start, tsk) {
		if (mask) {
			/*
			 * If this is a mempolicy constrained oom, tsk's
			 * cpuset is irrelevant.  Only return true if its
			 * mempolicy intersects current, otherwise it may be
			 * needlessly killed.
			 */
			ret = mempolicy_nodemask_intersects(tsk, mask);
		} else {
			/*
			 * This is not a mempolicy constrained oom, so only
			 * check the mems of tsk's cpuset.
			 */
			ret = cpuset_mems_allowed_intersects(current, tsk);
		}
		if (ret)
			break;
	}
	rcu_read_unlock();

	return ret;
}
#else
static bool has_intersects_mems_allowed(struct task_struct *tsk,
					const nodemask_t *mask)
{
	return true;
}
#endif /* CONFIG_NUMA */

/*
 * The process p may have detached its own ->mm while exiting or through
 * use_mm(), but one or more of its subthreads may still have a valid
 * pointer.  Return p, or any of its subthreads with a valid ->mm, with
 * task_lock() held.
 */
struct task_struct *find_lock_task_mm(struct task_struct *p)
{
	struct task_struct *t;

	rcu_read_lock();

	for_each_thread(p, t) {
		task_lock(t);
		if (likely(t->mm))
			goto found;
		task_unlock(t);
	}
	t = NULL;
found:
	rcu_read_unlock();

	return t;
}

/* return true if the task is not adequate as candidate victim task. */
static bool oom_unkillable_task(struct task_struct *p,
		struct mem_cgroup *memcg, const nodemask_t *nodemask)
{
	if (is_global_init(p))
		return true;
	if (p->flags & PF_KTHREAD)
		return true;

	/* When mem_cgroup_out_of_memory() and p is not member of the group */
	if (memcg && !task_in_mem_cgroup(p, memcg))
		return true;

	/* p may not have freeable memory in nodemask */
	if (!has_intersects_mems_allowed(p, nodemask))
		return true;

	return false;
}

/**
 * oom_badness - heuristic function to determine which candidate task to kill
 * @p: task struct of which task we should calculate
 * @totalpages: total present RAM allowed for page allocation
 *
 * The heuristic for determining which task to kill is made to be as simple and
 * predictable as possible.  The goal is to return the highest value for the
 * task consuming the most memory to avoid subsequent oom failures.
 */
unsigned long oom_badness(struct task_struct *p, struct mem_cgroup *memcg,
			  const nodemask_t *nodemask, unsigned long totalpages)
{
	long points;
	long adj;

	if (oom_unkillable_task(p, memcg, nodemask))
		return 0;

	p = find_lock_task_mm(p);
	if (!p)
		return 0;

	adj = (long)p->signal->oom_score_adj;
	if (adj == OOM_SCORE_ADJ_MIN) {
		task_unlock(p);
		return 0;
	}

	/*
	 * The baseline for the badness score is the proportion of RAM that each
	 * task's rss, pagetable and swap space use.
	 */
	points = get_mm_rss(p->mm) + get_mm_counter(p->mm, MM_SWAPENTS) +
		atomic_long_read(&p->mm->nr_ptes) + mm_nr_pmds(p->mm);
	task_unlock(p);

	/*
	 * Root processes get 3% bonus, just like the __vm_enough_memory()
	 * implementation used by LSMs.
	 */
	if (has_capability_noaudit(p, CAP_SYS_ADMIN))
		points -= (points * 3) / 100;

	/* Normalize to oom_score_adj units */
	adj *= totalpages / 1000;
	points += adj;

	/*
	 * Never return 0 for an eligible task regardless of the root bonus and
	 * oom_score_adj (oom_score_adj can't be OOM_SCORE_ADJ_MIN here).
	 */
	return points > 0 ? points : 1;
}

/*
 * Determine the type of allocation constraint.
 */
#ifdef CONFIG_NUMA
static enum oom_constraint constrained_alloc(struct oom_control *oc,
					     unsigned long *totalpages)
{
	struct zone *zone;
	struct zoneref *z;
	enum zone_type high_zoneidx = gfp_zone(oc->gfp_mask);
	bool cpuset_limited = false;
	int nid;

	/* Default to all available memory */
	*totalpages = totalram_pages + total_swap_pages;

	if (!oc->zonelist)
		return CONSTRAINT_NONE;
	/*
	 * Reach here only when __GFP_NOFAIL is used. So, we should avoid
	 * to kill current.We have to random task kill in this case.
	 * Hopefully, CONSTRAINT_THISNODE...but no way to handle it, now.
	 */
	if (oc->gfp_mask & __GFP_THISNODE)
		return CONSTRAINT_NONE;

	/*
	 * This is not a __GFP_THISNODE allocation, so a truncated nodemask in
	 * the page allocator means a mempolicy is in effect.  Cpuset policy
	 * is enforced in get_page_from_freelist().
	 */
	if (oc->nodemask &&
	    !nodes_subset(node_states[N_MEMORY], *oc->nodemask)) {
		*totalpages = total_swap_pages;
		for_each_node_mask(nid, *oc->nodemask)
			*totalpages += node_spanned_pages(nid);
		return CONSTRAINT_MEMORY_POLICY;
	}

	/* Check this allocation failure is caused by cpuset's wall function */
	for_each_zone_zonelist_nodemask(zone, z, oc->zonelist,
			high_zoneidx, oc->nodemask)
		if (!cpuset_zone_allowed(zone, oc->gfp_mask))
			cpuset_limited = true;

	if (cpuset_limited) {
		*totalpages = total_swap_pages;
		for_each_node_mask(nid, cpuset_current_mems_allowed)
			*totalpages += node_spanned_pages(nid);
		return CONSTRAINT_CPUSET;
	}
	return CONSTRAINT_NONE;
}
#else
static enum oom_constraint constrained_alloc(struct oom_control *oc,
					     unsigned long *totalpages)
{
	*totalpages = totalram_pages + total_swap_pages;
	return CONSTRAINT_NONE;
}
#endif

enum oom_scan_t oom_scan_process_thread(struct oom_control *oc,
			struct task_struct *task, unsigned long totalpages)
{
	if (oom_unkillable_task(task, NULL, oc->nodemask))
		return OOM_SCAN_CONTINUE;

	/*
	 * This task already has access to memory reserves and is being killed.
	 * Don't allow any other task to have access to the reserves.
	 */
	if (test_tsk_thread_flag(task, TIF_MEMDIE)) {
		if (oc->order != -1)
			return OOM_SCAN_ABORT;
	}
	if (!task->mm)
		return OOM_SCAN_CONTINUE;

	/*
	 * If task is allocating a lot of memory and has been marked to be
	 * killed first if it triggers an oom, then select it.
	 */
	if (oom_task_origin(task))
		return OOM_SCAN_SELECT;

	if (task_will_free_mem(task) && oc->order != -1)
		return OOM_SCAN_ABORT;

	return OOM_SCAN_OK;
}

/*
 * Simple selection loop. We chose the process with the highest
 * number of 'points'.  Returns -1 on scan abort.
 */
static struct task_struct *select_bad_process(struct oom_control *oc,
		unsigned int *ppoints, unsigned long totalpages)
{
	struct task_struct *g, *p;
	struct task_struct *chosen = NULL;
	unsigned long chosen_points = 0;

	rcu_read_lock();
	for_each_process_thread(g, p) {
		unsigned int points;

		switch (oom_scan_process_thread(oc, p, totalpages)) {
		case OOM_SCAN_SELECT:
			chosen = p;
			chosen_points = ULONG_MAX;
			/* fall through */
		case OOM_SCAN_CONTINUE:
			continue;
		case OOM_SCAN_ABORT:
			rcu_read_unlock();
			return (struct task_struct *)(-1UL);
		case OOM_SCAN_OK:
			break;
		};
		points = oom_badness(p, NULL, oc->nodemask, totalpages);
		if (!points || points < chosen_points)
			continue;
		/* Prefer thread group leaders for display purposes */
		if (points == chosen_points && thread_group_leader(chosen))
			continue;

		chosen = p;
		chosen_points = points;
	}
	if (chosen)
		get_task_struct(chosen);
	rcu_read_unlock();

	*ppoints = chosen_points * 1000 / totalpages;
	return chosen;
}

/**
 * dump_tasks - dump current memory state of all system tasks
 * @memcg: current's memory controller, if constrained
 * @nodemask: nodemask passed to page allocator for mempolicy ooms
 *
 * Dumps the current memory state of all eligible tasks.  Tasks not in the same
 * memcg, not in the same cpuset, or bound to a disjoint set of mempolicy nodes
 * are not shown.
 * State information includes task's pid, uid, tgid, vm size, rss, nr_ptes,
 * swapents, oom_score_adj value, and name.
 */
static void dump_tasks(struct mem_cgroup *memcg, const nodemask_t *nodemask)
{
	struct task_struct *p;
	struct task_struct *task;

	pr_info("[ pid ]   uid  tgid total_vm      rss nr_ptes nr_pmds swapents oom_score_adj name\n");
	rcu_read_lock();
	for_each_process(p) {
		if (oom_unkillable_task(p, memcg, nodemask))
			continue;

		task = find_lock_task_mm(p);
		if (!task) {
			/*
			 * This is a kthread or all of p's threads have already
			 * detached their mm's.  There's no need to report
			 * them; they can't be oom killed anyway.
			 */
			continue;
		}

		pr_info("[%5d] %5d %5d %8lu %8lu %7ld %7ld %8lu         %5hd %s\n",
			task->pid, from_kuid(&init_user_ns, task_uid(task)),
			task->tgid, task->mm->total_vm, get_mm_rss(task->mm),
			atomic_long_read(&task->mm->nr_ptes),
			mm_nr_pmds(task->mm),
			get_mm_counter(task->mm, MM_SWAPENTS),
			task->signal->oom_score_adj, task->comm);
		task_unlock(task);
	}
	rcu_read_unlock();
}

static void dump_header(struct oom_control *oc, struct task_struct *p,
			struct mem_cgroup *memcg)
{
	task_lock(current);
	pr_warning("%s invoked oom-killer: gfp_mask=0x%x, order=%d, "
		"oom_score_adj=%hd\n",
		current->comm, oc->gfp_mask, oc->order,
		current->signal->oom_score_adj);
	cpuset_print_task_mems_allowed(current);
	task_unlock(current);
	dump_stack();
	if (memcg)
		mem_cgroup_print_oom_info(memcg, p);
	else
		show_mem(SHOW_MEM_FILTER_NODES);
	if (sysctl_oom_dump_tasks)
		dump_tasks(memcg, oc->nodemask);
}

/*
 * Number of OOM victims in flight
 */
static atomic_t oom_victims = ATOMIC_INIT(0);
static DECLARE_WAIT_QUEUE_HEAD(oom_victims_wait);

bool oom_killer_disabled __read_mostly;

/**
 * mark_oom_victim - mark the given task as OOM victim
 * @tsk: task to mark
 *
 * Has to be called with oom_lock held and never after
 * oom has been disabled already.
 */
void mark_oom_victim(struct task_struct *tsk)
{
	WARN_ON(oom_killer_disabled);
	/* OOM killer might race with memcg OOM */
	if (test_and_set_tsk_thread_flag(tsk, TIF_MEMDIE))
		return;
	/*
	 * Make sure that the task is woken up from uninterruptible sleep
	 * if it is frozen because OOM killer wouldn't be able to free
	 * any memory and livelock. freezing_slow_path will tell the freezer
	 * that TIF_MEMDIE tasks should be ignored.
	 */
	__thaw_task(tsk);
	atomic_inc(&oom_victims);
}

/**
 * exit_oom_victim - note the exit of an OOM victim
 */
void exit_oom_victim(void)
{
	clear_thread_flag(TIF_MEMDIE);

	if (!atomic_dec_return(&oom_victims))
		wake_up_all(&oom_victims_wait);
}

/**
 * oom_killer_disable - disable OOM killer
 *
 * Forces all page allocations to fail rather than trigger OOM killer.
 * Will block and wait until all OOM victims are killed.
 *
 * The function cannot be called when there are runnable user tasks because
 * the userspace would see unexpected allocation failures as a result. Any
 * new usage of this function should be consulted with MM people.
 *
 * Returns true if successful and false if the OOM killer cannot be
 * disabled.
 */
bool oom_killer_disable(void)
{
	/*
	 * Make sure to not race with an ongoing OOM killer
	 * and that the current is not the victim.
	 */
	mutex_lock(&oom_lock);
	if (test_thread_flag(TIF_MEMDIE)) {
		mutex_unlock(&oom_lock);
		return false;
	}

	oom_killer_disabled = true;
	mutex_unlock(&oom_lock);

	wait_event(oom_victims_wait, !atomic_read(&oom_victims));

	return true;
}

/**
 * oom_killer_enable - enable OOM killer
 */
void oom_killer_enable(void)
{
	oom_killer_disabled = false;
}

#define K(x) ((x) << (PAGE_SHIFT-10))
/*
 * Must be called while holding a reference to p, which will be released upon
 * returning.
 */
void oom_kill_process(struct oom_control *oc, struct task_struct *p,
		      unsigned int points, unsigned long totalpages,
		      struct mem_cgroup *memcg, const char *message)
{
	struct task_struct *victim = p;
	struct task_struct *child;
	struct task_struct *t;
	struct mm_struct *mm;
	unsigned int victim_points = 0;
	static DEFINE_RATELIMIT_STATE(oom_rs, DEFAULT_RATELIMIT_INTERVAL,
					      DEFAULT_RATELIMIT_BURST);

	/*
	 * If the task is already exiting, don't alarm the sysadmin or kill
	 * its children or threads, just set TIF_MEMDIE so it can die quickly
	 */
	task_lock(p);
	if (p->mm && task_will_free_mem(p)) {
		mark_oom_victim(p);
		task_unlock(p);
		put_task_struct(p);
		return;
	}
	task_unlock(p);

	if (__ratelimit(&oom_rs))
		dump_header(oc, p, memcg);

	task_lock(p);
	pr_err("%s: Kill process %d (%s) score %u or sacrifice child\n",
		message, task_pid_nr(p), p->comm, points);
	task_unlock(p);

	/*
	 * If any of p's children has a different mm and is eligible for kill,
	 * the one with the highest oom_badness() score is sacrificed for its
	 * parent.  This attempts to lose the minimal amount of work done while
	 * still freeing memory.
	 */
	read_lock(&tasklist_lock);
	for_each_thread(p, t) {
		list_for_each_entry(child, &t->children, sibling) {
			unsigned int child_points;

			if (child->mm == p->mm)
				continue;
			/*
			 * oom_badness() returns 0 if the thread is unkillable
			 */
			child_points = oom_badness(child, memcg, oc->nodemask,
								totalpages);
			if (child_points > victim_points) {
				put_task_struct(victim);
				victim = child;
				victim_points = child_points;
				get_task_struct(victim);
			}
		}
	}
	read_unlock(&tasklist_lock);

	p = find_lock_task_mm(victim);
	if (!p) {
		put_task_struct(victim);
		return;
	} else if (victim != p) {
		get_task_struct(p);
		put_task_struct(victim);
		victim = p;
	}

	/* mm cannot safely be dereferenced after task_unlock(victim) */
	mm = victim->mm;
	mark_oom_victim(victim);
	pr_err("Killed process %d (%s) total-vm:%lukB, anon-rss:%lukB, file-rss:%lukB\n",
		task_pid_nr(victim), victim->comm, K(victim->mm->total_vm),
		K(get_mm_counter(victim->mm, MM_ANONPAGES)),
		K(get_mm_counter(victim->mm, MM_FILEPAGES)));
	task_unlock(victim);

	/*
	 * Kill all user processes sharing victim->mm in other thread groups, if
	 * any.  They don't get access to memory reserves, though, to avoid
	 * depletion of all memory.  This prevents mm->mmap_sem livelock when an
	 * oom killed thread cannot exit because it requires the semaphore and
	 * its contended by another thread trying to allocate memory itself.
	 * That thread will now get access to memory reserves since it has a
	 * pending fatal signal.
	 */
	rcu_read_lock();
	for_each_process(p)
		if (p->mm == mm && !same_thread_group(p, victim) &&
		    !(p->flags & PF_KTHREAD)) {
			if (p->signal->oom_score_adj == OOM_SCORE_ADJ_MIN)
				continue;

			task_lock(p);	/* Protect ->comm from prctl() */
			pr_err("Kill process %d (%s) sharing same memory\n",
				task_pid_nr(p), p->comm);
			task_unlock(p);
			do_send_sig_info(SIGKILL, SEND_SIG_FORCED, p, true);
		}
	rcu_read_unlock();

	do_send_sig_info(SIGKILL, SEND_SIG_FORCED, victim, true);
	put_task_struct(victim);
}
#undef K

/*
 * Determines whether the kernel must panic because of the panic_on_oom sysctl.
 */
void check_panic_on_oom(struct oom_control *oc, enum oom_constraint constraint,
			struct mem_cgroup *memcg)
{
	if (likely(!sysctl_panic_on_oom))
		return;
	if (sysctl_panic_on_oom != 2) {
		/*
		 * panic_on_oom == 1 only affects CONSTRAINT_NONE, the kernel
		 * does not panic for cpuset, mempolicy, or memcg allocation
		 * failures.
		 */
		if (constraint != CONSTRAINT_NONE)
			return;
	}
	/* Do not panic for oom kills triggered by sysrq */
	if (oc->order == -1)
		return;
	dump_header(oc, NULL, memcg);
	panic("Out of memory: %s panic_on_oom is enabled\n",
		sysctl_panic_on_oom == 2 ? "compulsory" : "system-wide");
}

static BLOCKING_NOTIFIER_HEAD(oom_notify_list);

int register_oom_notifier(struct notifier_block *nb)
{
	return blocking_notifier_chain_register(&oom_notify_list, nb);
}
EXPORT_SYMBOL_GPL(register_oom_notifier);

int unregister_oom_notifier(struct notifier_block *nb)
{
	return blocking_notifier_chain_unregister(&oom_notify_list, nb);
}
EXPORT_SYMBOL_GPL(unregister_oom_notifier);

/**
 * out_of_memory - kill the "best" process when we run out of memory
 * @oc: pointer to struct oom_control
 *
 * If we run out of memory, we have the choice between either
 * killing a random task (bad), letting the system crash (worse)
 * OR try to be smart about which process to kill. Note that we
 * don't have to be perfect here, we just have to be good.
 */
bool out_of_memory(struct oom_control *oc)
{
	struct task_struct *p;
	unsigned long totalpages;
	unsigned long freed = 0;
	unsigned int uninitialized_var(points);
	enum oom_constraint constraint = CONSTRAINT_NONE;

	if (oom_killer_disabled)
		return false;

	blocking_notifier_call_chain(&oom_notify_list, 0, &freed);
	if (freed > 0)
		/* Got some memory back in the last second. */
		return true;

	/*
	 * If current has a pending SIGKILL or is exiting, then automatically
	 * select it.  The goal is to allow it to allocate so that it may
	 * quickly exit and free its memory.
	 *
	 * But don't select if current has already released its mm and cleared
	 * TIF_MEMDIE flag at exit_mm(), otherwise an OOM livelock may occur.
	 */
	if (current->mm &&
	    (fatal_signal_pending(current) || task_will_free_mem(current))) {
		mark_oom_victim(current);
		return true;
	}

	/*
	 * Check if there were limitations on the allocation (only relevant for
	 * NUMA) that may require different handling.
	 */
	constraint = constrained_alloc(oc, &totalpages);
	if (constraint != CONSTRAINT_MEMORY_POLICY)
		oc->nodemask = NULL;
	check_panic_on_oom(oc, constraint, NULL);

	if (sysctl_oom_kill_allocating_task && current->mm &&
	    !oom_unkillable_task(current, NULL, oc->nodemask) &&
	    current->signal->oom_score_adj != OOM_SCORE_ADJ_MIN) {
		get_task_struct(current);
		oom_kill_process(oc, current, 0, totalpages, NULL,
				 "Out of memory (oom_kill_allocating_task)");
		return true;
	}

	p = select_bad_process(oc, &points, totalpages);
	/* Found nothing?!?! Either we hang forever, or we panic. */
	if (!p && oc->order != -1) {
		dump_header(oc, NULL, NULL);
		panic("Out of memory and no killable processes...\n");
	}
	if (p && p != (void *)-1UL) {
		oom_kill_process(oc, p, points, totalpages, NULL,
				 "Out of memory");
		/*
		 * Give the killed process a good chance to exit before trying
		 * to allocate memory again.
		 */
		schedule_timeout_killable(1);
	}
	return true;
}

/*
 * The pagefault handler calls here because it is out of memory, so kill a
 * memory-hogging task.  If any populated zone has ZONE_OOM_LOCKED set, a
 * parallel oom killing is already in progress so do nothing.
 */
void pagefault_out_of_memory(void)
{
	struct oom_control oc = {
		.zonelist = NULL,
		.nodemask = NULL,
		.gfp_mask = 0,
		.order = 0,
	};

	if (mem_cgroup_oom_synchronize(true))
		return;

	if (!mutex_trylock(&oom_lock))
		return;

	if (!out_of_memory(&oc)) {
		/*
		 * There shouldn't be any user tasks runnable while the
		 * OOM killer is disabled, so the current task has to
		 * be a racing OOM victim for which oom_killer_disable()
		 * is waiting for.
		 */
		WARN_ON(test_thread_flag(TIF_MEMDIE));
	}

	mutex_unlock(&oom_lock);
}


text:
<?php

namespace app\controllers;

use app\models\Product;
use app\models\Request;
use cs\base\BaseController;
use Yii;

class Admin_requestsController extends AdminBaseController
{
    public function actionIndex()
    {
        return $this->render();
    }

    public function actionView($id)
    {
        return $this->render([
            'item' => Request::find($id),
        ]);
    }

}


text:
package org.jesterj.ingest;

import com.google.common.io.Resources;
import com.needhamsoftware.unojar.JarClassLoader;
import io.github.classgraph.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.docopt.Docopt;
import org.jesterj.ingest.forkjoin.JesterJForkJoinThreadFactory;
import org.jesterj.ingest.model.Plan;
import org.jesterj.ingest.persistence.Cassandra;
import org.jesterj.ingest.utils.JesterJLoader;
import org.jesterj.ingest.utils.JesterjPolicy;
import org.jetbrains.annotations.NotNull;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.Policy;
import java.util.*;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.stream.Collectors;

/*
 * Created with IntelliJ IDEA.
 * User: gus
 * Date: 7/5/14
 */

/**
 * Start a running instance. Each instance should have an id and a password (freely chosen
 * by the user starting the process. The ID will be used to display the node in the control
 * console and the password is meant to provide temporary security until the node is
 * configured properly.
 */
public class Main {

  // WARNING: do not add a logger init to this class! See below for classloading highjinks that
  // force us to wait to initialize logging
  private static Logger log;

  private static final Object HAPPENS_BEFORE = new Object();

  public static String JJ_DIR;
  private static final Thread DUMMY_HOOK = new Thread();

  static {
    // set up a config dir in user's home dir
    String userDir = System.getProperty("user.home");
    File jjDir = new File(userDir + "/.jj");
    if (!jjDir.exists() && !jjDir.mkdir()) {
      throw new RuntimeException("could not create " + jjDir);
    } else {
      try {
        JJ_DIR = jjDir.getCanonicalPath();
      } catch (IOException e) {
        e.printStackTrace();
        System.exit(10);
      }
    }
  }

  public static void main(String[] args) {
//    Thread.sleep(10000); // debugger connect time

    synchronized (HAPPENS_BEFORE) {
      try {
        System.setProperty("java.util.concurrent.ForkJoinPool.common.threadFactory", JesterJForkJoinThreadFactory.class.getName());
        System.setProperty("cassandra.insecure.udf", "true");

        initClassloader();

        Thread contextClassLoaderFix = new Thread(() -> {
          // ensure that the main method completes before this thread runs.
          synchronized (HAPPENS_BEFORE) {
            try {
              initRMI();

              // Next check our args and die if they are FUBAR
              Map<String, Object> parsedArgs = usage(args);

              String id = (String) parsedArgs.get("<id>");
              String ourHome = JJ_DIR + "/" + id;
              String logDir = setLogDir(ourHome);
              System.out.println("Logs will be written to: " + logDir);
              String outfile = (String) parsedArgs.get("-z");

              String javaConfig = (String) parsedArgs.get("<plan.jar>");
              boolean runPlan = !Boolean.parseBoolean(String.valueOf(parsedArgs.get("--cassandra-only")));
              System.out.println("Looking for configuration class in " + javaConfig);
              if (outfile != null) {
                // in this case we aren't starting a node, and we don't care if logging doesn't make it to
                // cassandra (in fact better if it doesn't) so go ahead and call what we like INSIDE this if
                // block only.
                Plan p = loadJavaConfig(javaConfig);
                System.out.println("Generating visualization for " + p.getName() + " into " + outfile);
                BufferedImage img = p.visualize();
                ImageIO.write(img, "PNG", new File(outfile));
                System.exit(0);
              }
              startCassandra(parsedArgs);

              // this should reload the config with cassandra available.
              LogManager.getFactory().removeContext(LogManager.getContext(false));

              // now we are allowed to look at log4j2.xml
              log = LogManager.getLogger(Main.class);

              Properties sysProps = System.getProperties();
              for (Object prop : sysProps.keySet()) {
                log.trace(prop + "=" + sysProps.get(prop));
              }

              if (runPlan) {
                if (javaConfig != null) {
                  Plan p = loadJavaConfig(javaConfig);
                  log.info("Activating Plan: {}", p.getName());
                  p.activate();
                } else {
                  System.out.println("Please specify the java config via -Djj.javaConfig=<location of jar file>");
                  System.exit(11);
                }
              }
              while (true) {
                try {
                  System.out.print(".");
                  Thread.sleep(5000);
                } catch (InterruptedException e) {

                  // Yeah, I know this isn't going to do anything right now.. Placeholder to remind me to implement a real
                  // graceful shutdown... also keeps IDE from complaining stop() isn't used.

                  e.printStackTrace();
                  Cassandra.stop();
                  System.exit(0);
                }
              }

            } catch (Exception e) {
              e.printStackTrace();
              log.fatal("CRASH and BURNED:", e);
            }
          }
        });
        // unfortunately due to the hackery necessary to get things playing nice with one-jar, the contextClassLoader
        // is now out of sync with the system class loader, which messes up the Reflections library. So hack on hack...
        // todo: document why this reflection is necessary (I suspect I had some sort of security manager issue?) or remove
        // otherwise it seems like the following would be fine:
        // contextClassLoaderFix.setContextClassLoader(ClassLoader.getSystemClassLoader());
        Field _f_contextClassLoader = Thread.class.getDeclaredField("contextClassLoader");
        _f_contextClassLoader.setAccessible(true);
        _f_contextClassLoader.set(contextClassLoaderFix, ClassLoader.getSystemClassLoader());
        contextClassLoaderFix.setDaemon(false); // keep the JVM running please
        contextClassLoaderFix.start();

      } catch (Exception e) {
        System.out.println("CRASH and BURNED before starting main thread:");
        e.printStackTrace();
        try {
          Thread.sleep(1000);
        } catch (InterruptedException ex) {
          ex.printStackTrace();
        }
        System.exit(12);
      }
    }
  }

  @NotNull
  private static String setLogDir(String logdir) throws IOException {
    // set up log output dir
    String logDir = System.getProperty("jj.log.dir");
    if (logDir == null) {
      System.setProperty("jj.log.dir", logdir + "/logs");
    }
    logDir = System.getProperty("jj.log.dir");

    // Check that we can write to the log dir
    File logDirFile = new File(logDir);

    if (!logDirFile.mkdirs() && !(logDirFile.canWrite())) {
      System.out.println("Cannot write to " + logDir + " \n" +
          "Please fix the filesystem permissions or provide a writable location with -Djj.log.dir property on the command line.");
      System.exit(99);
    }
    String logConfig = logDir + "/log4j2.xml";
    System.setProperty("log4j.configurationFile", logConfig);
    File configFile = new File(logConfig);
    if (!configFile.exists()) {
      InputStream log4jxml = Main.class.getResourceAsStream("/log4j2.xml");
      Files.copy(log4jxml, configFile.toPath());
    }

    return logDir;
  }

  private static void startCassandra(Map<String, Object> parsedArgs) {
    String cassandraHome = (String) parsedArgs.get("--cassandra-home");
    File cassandraDir = null;
    if (cassandraHome != null) {
      cassandraHome = cassandraHome.replaceFirst("^~", System.getProperty("user.home"));
      cassandraDir = new File(cassandraHome);
      if (!cassandraDir.isDirectory()) {
        System.err.println("\nERROR: --cassandra-home must specify a directory\n");
        System.exit(13);
      }
    }
    String id = (String) parsedArgs.get("<id>");
    if (cassandraDir == null) {
      cassandraDir = new File(JJ_DIR + "/" + id + "/cassandra");
    }
    Cassandra.start(cassandraDir);
  }

  private static Plan loadJavaConfig(String javaConfig) throws InstantiationException, IllegalAccessException {
    File file = new File(javaConfig);
    if (!file.exists()) {
      System.err.println("File not found:" + file);
      System.exit(14);
    }

    boolean isUnoJar = false;
    try {
      JarFile test = new JarFile(file);
      Attributes attrs = test.getManifest().getMainAttributes();
      String attr = attrs.getValue("Archive-Type");
      isUnoJar = attr != null && attr.trim().equalsIgnoreCase("uno-jar");
    } catch (IOException e) {
      e.printStackTrace();
      System.exit(15);
    }
    boolean finalIsUnoJar = isUnoJar;
    if (log != null) {
      // can be null when outputting a visualization
      log.info("Loading from {} which is a {} file", () -> file, () ->
          finalIsUnoJar ? "Uno-Jar" : "Standard Jar");
    } else {
      System.out.println("Loading from "+file+" which is a "+(finalIsUnoJar ? "Uno-Jar" : "Standard Jar")+" file");
    }
    JesterJLoader jesterJLoader;

    File jarfile = new File(javaConfig);
    URL planConfigJarURL;
    try {
      planConfigJarURL = jarfile.toURI().toURL();
    } catch (MalformedURLException e) {
      throw new RuntimeException(e); // boom
    }

    jesterJLoader = (JesterJLoader) ClassLoader.getSystemClassLoader();

    ClassLoader loader;
    if (isUnoJar) {
      JarClassLoader jarClassLoader = new JarClassLoader(jesterJLoader, planConfigJarURL.toString());
      jarClassLoader.load(null);
      loader = jarClassLoader;
    } else {
      loader = new URLClassLoader(new URL[]{planConfigJarURL}, jesterJLoader);
    }
    jesterJLoader.addExtLoader(loader);

    try (ScanResult scanResult =
             new ClassGraph()
                 //.verbose()                   // Log to stderr
                 .overrideClassLoaders(loader)
                 .ignoreParentClassLoaders()
                 .enableClassInfo()
                 .enableAnnotationInfo()
                 .scan()) {                   // Start the scan
      ClassInfoList classesWithAnnotation;
      String routeAnnotation = JavaPlanConfig.class.getName();
      classesWithAnnotation = scanResult.getClassesWithAnnotation(routeAnnotation);
      List<String> planProducers = classesWithAnnotation.stream().map(ClassInfo::getName).collect(Collectors.toList());
      if (log != null) {
        // can be null when outputting a visualization
        log.info("Found the following @JavaPlanConfig classes (first in list will be used):{}", planProducers);
      } else {
        System.out.println("Found the following @JavaPlanConfig classes (first in list will be used):" + planProducers);
      }
      if (classesWithAnnotation.size() == 0) {
        System.err.println("No Plan Found!");
        System.exit(16);
      }
      @SuppressWarnings("rawtypes")
      Class config = jesterJLoader.loadClass(planProducers.get(0));
      //noinspection deprecation
      PlanProvider provider = (PlanProvider) config.newInstance();
      return provider.getPlan();
    } catch (ClassNotFoundException e) {
      System.err.println("Found a plan class but could not load Plan's class file!");
      System.exit(17);
      throw new RuntimeException(); // compiler doesn't understand system.exit
    }

  }

  /**
   * Set up security policy that allows RMI and JINI code to work. Also seems to be
   * helpful for running embedded cassandra. TODO: Minimize the permissions granted.
   */
  private static void initRMI() {
    // must do this before any jini code
    String policyFile = System.getProperty("java.security.policy");
    if (policyFile == null) {
      System.out.println("Installing JesterjPolicy");
      Policy.setPolicy(new JesterjPolicy());
    } else {
      System.out.println("Existing Policy File:" + policyFile);
    }
    System.setSecurityManager(new SecurityManager());
  }

  /**
   * Initialize the classloader. This method fixes up an issue with OneJar's class loaders. Nothing in or before
   * this method should touch logging, or 3rd party jars that logging that might try to setup log4j.
   *
   * @throws NoSuchFieldException   if the system class loader field has changed in this version of java and is not "scl"
   * @throws IllegalAccessException if we are unable to set the system class loader
   */
  private static void initClassloader() throws NoSuchFieldException, IllegalAccessException {
    // for river
    System.setProperty("java.rmi.server.RMIClassLoaderSpi", "net.jini.loader.pref.PreferredClassProvider");

    // fix bug in One-Jar with an ugly hack
    ClassLoader unoJarClassLoader = Main.class.getClassLoader();
    String name = unoJarClassLoader.getClass().getName();
    if ("com.needhamsoftware.unojar.JarClassLoader".equals(name)) {
      Field scl = ClassLoader.class.getDeclaredField("scl"); // Get system class loader
      scl.setAccessible(true); // Set accessible
      scl.set(null, new JesterJLoader(new URL[]{}, unoJarClassLoader)); // Update it to our class loader
    }
  }

  @SuppressWarnings("UnstableApiUsage")
  private static Map<String, Object> usage(String[] args) throws IOException {
    URL usage = Resources.getResource("usage.docopts.txt");
    String usageStr = Resources.toString(usage, StandardCharsets.UTF_8);
    Map<String, Object> result = new Docopt(usageStr).parse(args);
    System.out.println("\nReceived arguments:");
    for (String s : result.keySet()) {
      System.out.printf("   %s:%s\n", s, result.get(s));
    }
    if ((boolean) result.get("--help")) {
      System.out.println(usageStr);
      System.exit(18);
    }
    return result;
  }

  /**
   * This is a heuristic test for system shutdown. It is potentially expensive, so it should only be used in
   * code that is not performance sensitive. (i.e. code where an exception is already being thrown).
   *
   * @return true if the system is shutting down
   */

  public synchronized static boolean isNotShuttingDown() {
    try {
      Runtime.getRuntime().addShutdownHook(DUMMY_HOOK);
      Runtime.getRuntime().removeShutdownHook(DUMMY_HOOK);
    } catch (IllegalStateException e) {
      return false;
    }

    return true;
  }
}


text:
#include "CaelumPrecompiled.h"
#include "PointStarfield.h"
#include "GeometryFactory.h"
#include "CaelumExceptions.h"
#include "Astronomy.h"

using namespace Ogre;

namespace Caelum
{
	const Ogre::String PointStarfield::BILLBOARD_MATERIAL_NAME = "Caelum/StarPoint";
    const Ogre::Degree PointStarfield::DEFAULT_OBSERVER_POSITION_REBUILD_DELTA = Ogre::Degree(0.1);

	PointStarfield::PointStarfield (
			Ogre::SceneManager *sceneMgr,
			Ogre::SceneNode *caelumRootNode,
			bool initWithCatalogue)
	{
		mMag0PixelSize = 16;
		mMinPixelSize = 4;
		mMaxPixelSize = 6;
		mMagnitudeScale = Math::Pow(100, 0.2);
		mObserverLatitude = 45;
		mObserverLongitude = 0;
        mObserverPositionRebuildDelta = DEFAULT_OBSERVER_POSITION_REBUILD_DELTA;

        String uniqueId = StringConverter::toString ((size_t)this);

        MaterialPtr scriptMaterial = MaterialManager::getSingleton ().getByName (BILLBOARD_MATERIAL_NAME);
		if (scriptMaterial.isNull ()) {
			CAELUM_THROW_UNSUPPORTED_EXCEPTION ("Can't find point starfield material", "PointStarfield");
		}
        mMaterial.reset (scriptMaterial->clone (BILLBOARD_MATERIAL_NAME + uniqueId));
		mMaterial->load ();
		if (mMaterial->getBestTechnique () == 0) {
            CAELUM_THROW_UNSUPPORTED_EXCEPTION ("Can't load point starfield material: " + mMaterial->getUnsupportedTechniquesExplanation(), "PointStarfield");
		}

		sceneMgr->getRenderQueue()->getQueueGroup(CAELUM_RENDER_QUEUE_STARFIELD)->setShadowsEnabled (false);

		// We use a separate data source.
		Ogre::String objName = "Caelum/PointStarfield/" + uniqueId;
        mManualObj.reset (sceneMgr->createManualObject (objName));
        mManualObj->setDynamic(false);
		mManualObj->setRenderQueueGroup (CAELUM_RENDER_QUEUE_STARFIELD);
        mManualObj->setCastShadows(false);

		mNode.reset (caelumRootNode->createChildSceneNode ());
		mNode->attachObject (mManualObj.getPointer ());

		if (initWithCatalogue) {
			addBrightStarCatalogue ();
		}
	}

	PointStarfield::~PointStarfield ()
    {
	}

    void PointStarfield::notifyStarVectorChanged () {
        invalidateGeometry ();
    }

    void PointStarfield::clearAllStars () {
        mStars.clear();
        notifyStarVectorChanged ();
    }

	Real randReal () {
		return rand() / static_cast<float>(RAND_MAX);
	}

	Real randReal (Real min, Real max) {
		Real f = randReal ();
		return min * (1 - f) + max * f;
	}

	void PointStarfield::addRandomStars (int count)
	{
		for (int i = 0; i < count; ++i) {
			// Generate a vector inside a sphere
			Ogre::Vector3 pos;
			do {
				pos.x = randReal(-1, 1);
				pos.y = randReal(-1, 1);
				pos.z = randReal(-1, 1);
			} while (pos.squaredLength () >= 1);

			// Convert to rasc/decl angles.
			LongReal rasc, decl, dist;
			Astronomy::convertRectangularToSpherical(
					pos.x, pos.y, pos.z,
					rasc, decl, dist);

			Star s;
			s.RightAscension = Ogre::Degree (rasc);
			s.Declination = Ogre::Degree (decl);
			// This distribution is wrong.
			s.Magnitude = 6 * pos.squaredLength () + 1.5;
			mStars.push_back(s);
		}
		notifyStarVectorChanged ();
	}

	void PointStarfield::addStar (const BrightStarCatalogueEntry &entry) {
		Star s;
		s.RightAscension = Ogre::Degree(360 / 24.0f * (
				Math::Abs(entry.rasc_hour) +
				entry.rasc_min / 60.0f +
				entry.rasc_sec / 3600.0f));
		s.Declination = Ogre::Degree(Math::Sign(entry.decl_deg) * (
				Math::Abs(entry.decl_deg) +
				entry.decl_min / 60.0f +
				entry.decl_sec / 3600.0f));
		s.Magnitude = entry.magn;
		mStars.push_back(s);

        notifyStarVectorChanged ();
	}

	void PointStarfield::addBrightStarCatalogue (int count) {
		assert(count >= 0);
		if (count < BrightStarCatalogueSize) {
			// Only sort if we don't add everything.
			// It would be lovely if the catalogue was already sorted.
			std::vector<std::pair<Real, int> > vec;
			vec.reserve(BrightStarCatalogueSize);
			for (int i = 0; i < BrightStarCatalogueSize; ++i) {
				vec.push_back(std::make_pair(BrightStarCatalogue[i].magn, i));
			}
			sort(vec.begin(), vec.end());
			for (int i = 0; i < count; ++i) {
				addStar(BrightStarCatalogue[vec[i].second]);
			}
		} else {
			assert(count == BrightStarCatalogueSize);
			for (int i = 0; i < BrightStarCatalogueSize; ++i) {
				addStar(BrightStarCatalogue[i]);
			}
		}
        notifyStarVectorChanged ();
	}

	void PointStarfield::invalidateGeometry () {
		mValidGeometry = false;
	}

	void PointStarfield::ensureGeometry ()
	{
		if (mValidGeometry) {
			return;
		}

		//Ogre::LogManager::getSingleton ().logMessage ("Caelum: Recomputing starfield geometry.");

        size_t starCount = mStars.size();

        mManualObj->clear();
        mManualObj->estimateVertexCount(6 * starCount);
        mManualObj->begin(mMaterial->getName (), Ogre::RenderOperation::OT_TRIANGLE_LIST);
        for (uint i = 0; i < starCount; ++i)
        {
            const Star& star = mStars[i];

			// Determine position at J2000
			LongReal azm, alt;
			Astronomy::convertEquatorialToHorizontal(
					Astronomy::J2000,
					mObserverLatitude.valueDegrees(),
					mObserverLongitude.valueDegrees(),
					star.RightAscension.valueDegrees(), star.Declination.valueDegrees(),
					azm, alt);

    		Ogre::Vector3 pos;
		    pos.z = -Math::Cos (Ogre::Degree(azm)) * Math::Cos (Ogre::Degree(alt));
		    pos.x =  Math::Sin (Ogre::Degree(azm)) * Math::Cos (Ogre::Degree(alt));
		    pos.y = -Math::Sin (Ogre::Degree(alt));

            //mManualObj->colour (Ogre::ColourValue::White);
            mManualObj->position (pos);
            mManualObj->textureCoord (+1, -1, star.Magnitude);
            mManualObj->position (pos);
            mManualObj->textureCoord (+1, +1, star.Magnitude);
            mManualObj->position (pos);
            mManualObj->textureCoord (-1, -1, star.Magnitude);

            mManualObj->position (pos);
            mManualObj->textureCoord (-1, -1, star.Magnitude);
            mManualObj->position (pos);
            mManualObj->textureCoord (+1, +1, star.Magnitude);
            mManualObj->position (pos);
            mManualObj->textureCoord (-1, +1, star.Magnitude);
        }
        mManualObj->end();

        // Set infinite bounds on the starfield.
        AxisAlignedBox box;
        box.setInfinite ();
        mManualObj->setBoundingBox (box);

		mValidGeometry = true;
	}

	void PointStarfield::notifyCameraChanged (Ogre::Camera *cam) {
		CameraBoundElement::notifyCameraChanged (cam);

        // Shader params are changed for every camera.
        Pass* pass = mMaterial->getBestTechnique ()->getPass (0);
        GpuProgramParametersSharedPtr fpParams = pass->getFragmentProgramParameters ();
        GpuProgramParametersSharedPtr vpParams = pass->getVertexProgramParameters ();

        int height = cam->getViewport ()-> getActualHeight ();
        int width = cam->getViewport ()-> getActualWidth ();
        Real pixFactor = 1.0f / width;
        Real magScale = -Math::Log (mMagnitudeScale) / 2;
        Real mag0Size = mMag0PixelSize * pixFactor;
        Real minSize = mMinPixelSize * pixFactor;
        Real maxSize = mMaxPixelSize * pixFactor;
        Real aspectRatio = static_cast<Real>(width) / height;

        // These params are relative to the size of the screen.
        vpParams->setIgnoreMissingParams (true);
        vpParams->setNamedConstant ("mag_scale", magScale);
        vpParams->setNamedConstant ("mag0_size", mag0Size);
        vpParams->setNamedConstant ("min_size", minSize);
        vpParams->setNamedConstant ("max_size", maxSize);
        vpParams->setNamedConstant ("aspect_ratio", aspectRatio);
	}

	void PointStarfield::setFarRadius (Ogre::Real radius) {
        CameraBoundElement::setFarRadius(radius);
	    mNode->setScale (Ogre::Vector3::UNIT_SCALE * radius);
	}

	void PointStarfield::_update (const float time) {
		// This is probably wrong.
		Ogre::Quaternion orientation = Ogre::Quaternion::IDENTITY;
		orientation = orientation * Ogre::Quaternion (Ogre::Radian (-mObserverLatitude + Ogre::Degree (90)), Ogre::Vector3::UNIT_X);
		orientation = orientation * Ogre::Quaternion (Ogre::Radian (-time * 2 * Ogre::Math::PI), Ogre::Vector3::UNIT_Y);
		mNode->setOrientation (orientation);
        ensureGeometry ();
	}

	void PointStarfield::setObserverLatitude (Ogre::Degree value)
    {
		if (!Math::RealEqual (
                mObserverLatitude.valueDegrees (),
                value.valueDegrees (),
                this->getObserverPositionRebuildDelta ().valueDegrees ()))
        {
			mObserverLatitude = value;
			invalidateGeometry ();
		}
	}

	void PointStarfield::setObserverLongitude (Ogre::Degree value)
    {
		if (!Math::RealEqual (
                mObserverLongitude.valueDegrees (),
                value.valueDegrees (),
                this->getObserverPositionRebuildDelta ().valueDegrees ()))
        {
			mObserverLongitude = value;
			invalidateGeometry ();
		}
	}
}


text:
import React, { PropTypes } from 'react';

import { TodoPropType } from '../../../lib/prop-types';

const TodoListItemDelete = ({ deleteTodo, todo }) => {
  const handleClick = deleteTodo.bind(this, todo);

  return (
    <button className="destroy" onClick={handleClick} />
  );
};

TodoListItemDelete.propTypes = {
  deleteTodo: PropTypes.func.isRequired,
  todo:       TodoPropType.isRequired,
};

export default TodoListItemDelete;


text:
<?xml version="1.0" encoding="UTF-8" ?>
<constraint-mapping
    xmlns="http://symfony.com/schema/dic/constraint-mapping"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping
                        http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">

    <class name="Ekyna\Component\Characteristics\Entity\AbstractCharacteristic">
        <constraint name="Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity">
            <option name="fields">
                <value>identifier</value>
                <value>characteristics</value>
            </option>
            <option name="message">Cette caractéristique existe déja.</option>
        </constraint>
        <property name="identifier">
            <constraint name="NotBlank" />
        </property>
        <property name="characteristics">
            <constraint name="NotNull" />
            <constraint name="Valid" />
        </property>
        <getter property="value">
            <constraint name="NotNull" />
        </getter>
    </class>

    <class name="Ekyna\Component\Characteristics\Entity\AbstractCharacteristics">
        <property name="characteristics">
            <constraint name="Valid" />
        </property>
    </class>

    <class name="Ekyna\Component\Characteristics\Entity\ChoiceCharacteristicValue">
        <constraint name="Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity">
            <option name="fields">
                <value>identifier</value>
                <value>value</value>
            </option>
            <option name="message">Cette valeur de choix de caractéristique existe déja.</option>
        </constraint>
        <property name="value">
            <constraint name="NotBlank" />
        </property>
        <property name="identifier">
            <constraint name="NotBlank" />
        </property>
    </class>

</constraint-mapping>


text:
from __future__ import unicode_literals
from decimal import Decimal as D
import datetime

from django.test import TestCase
from django.utils import six
from oscar.apps.payment.models import Bankcard
from oscar.apps.payment import exceptions
import mock

from paypal.payflow import facade, models, codes

"""
See page 49 of the PDF for information on PayPal's testing set-up
"""

class TestAuthorize(TestCase):

    def setUp(self):
        self.card = Bankcard(
            number='4111111111111111',
            name='John Doe',
            expiry_date=datetime.date(2015, 8, 1),
        )

    def authorize(self):
        return facade.authorize('1234', D('10.00'), self.card)

    def test_returns_approved_txn(self):
        with mock.patch('paypal.payflow.gateway.authorize') as mock_f:
            mock_f.return_value = models.PayflowTransaction(
                result='0'
            )
            txn = self.authorize()
            self.assertTrue(txn.is_approved)

    def test_raises_exception_when_not_approved(self):
        with mock.patch('paypal.payflow.gateway.authorize') as mock_f:
            mock_f.return_value = models.PayflowTransaction(
                result='1'
            )
            with self.assertRaises(exceptions.UnableToTakePayment):
                self.authorize()

    def test_not_approved_exception_contains_useful_message(self):
        with mock.patch('paypal.payflow.gateway.authorize') as mock_f:
            mock_f.return_value = models.PayflowTransaction(
                result='23',
                respmsg='Invalid account number',
            )
            try:
                self.authorize()
            except exceptions.UnableToTakePayment as e:
                self.assertEqual("Invalid account number", six.text_type(e))

class TestSale(TestCase):

    def setUp(self):
        self.card = Bankcard(
            number='4111111111111111',
            name='John Doe',
            expiry_date=datetime.date(2015, 8, 1),
        )

    def sale(self):
        return facade.sale('1234', D('10.00'), self.card)

    def test_returns_approved_transaction(self):
        with mock.patch('paypal.payflow.gateway.sale') as mock_f:
            mock_f.return_value = models.PayflowTransaction(
                result='0'
            )
            txn = self.sale()
            self.assertTrue(txn.is_approved)

class TestDelayedCapture(TestCase):

    def test_returns_nothing_when_txn_is_approved(self):
        models.PayflowTransaction.objects.create(
            trxtype=codes.AUTHORIZATION,
            comment1='1234',
            pnref='V19A3A079142',
            response_time=0,
        )
        with mock.patch('paypal.payflow.gateway.delayed_capture') as mock_f:
            mock_f.return_value = models.PayflowTransaction(
                result='0'
            )
            facade.delayed_capture('1234')


text:
export * from './default-workspace-server';
export * from './workspace-backend-module';


text:
(function() {
    /**
     * Sprite constructor
     * @constructor
     * @memberof Kinetic
     * @augments Kinetic.Shape
     * @param {Object} config
     * @param {String} config.animation animation key
     * @param {Object} config.animations animation map
     * @param {Integer} [config.index] animation index
     * @param {Image} config.image image object
     * {{ShapeParams}}
     * {{NodeParams}}
     * @example
     * var animations = {

     *   idle: [{

     *     x: 2,

     *     y: 2,

     *     width: 70,

     *     height: 119

     *   }, {

     *     x: 71,

     *     y: 2,

     *     width: 74,

     *     height: 119

     *   }, {

     *     x: 146,

     *     y: 2,

     *     width: 81,

     *     height: 119

     *   }, {

     *     x: 226,

     *     y: 2,

     *     width: 76,

     *     height: 119

     *   }],

     *   punch: [{

     *     x: 2,

     *     y: 138,

     *     width: 74,

     *     height: 122

     *   }, {

     *     x: 76,

     *     y: 138,

     *     width: 84,

     *     height: 122

     *   }, {

     *     x: 346,

     *     y: 138,

     *     width: 120,

     *     height: 122

     *   }]

     * };

     *
     * var imageObj = new Image();

     * imageObj.onload = function() {

     *   var sprite = new Kinetic.Sprite({

     *     x: 200,

     *     y: 100,

     *     image: imageObj,

     *     animation: 'idle',

     *     animations: animations,

     *     frameRate: 7,

     *     index: 0

     *   });

     * };

     * imageObj.src = '/path/to/image.jpg'
     */
    Kinetic.Sprite = function(config) {
        this._initSprite(config);
    }

    Kinetic.Sprite.prototype = {
        _initSprite: function(config) {
            this.createAttrs();

            // call super constructor
            Kinetic.Shape.call(this, config);
            this.className = 'Sprite';
            this._setDrawFuncs();

            this.anim = new Kinetic.Animation();
            var that = this;
            this.on('animationChange', function() {
                // reset index when animation changes
                that.setIndex(0);
            });
        },
        drawFunc: function(canvas) {
            var anim = this.getAnimation(),
                index = this.getIndex(),
                f = this.getAnimations()[anim][index],
                context = canvas.getContext(),
                image = this.getImage();

            if(image) {
                context.drawImage(image, f.x, f.y, f.width, f.height, 0, 0, f.width, f.height);
            }
        },
        drawHitFunc: function(canvas) {
            var anim = this.getAnimation(),
                index = this.getIndex(),
                f = this.getAnimations()[anim][index],
                context = canvas.getContext();

            context.beginPath();
            context.rect(0, 0, f.width, f.height);
            context.closePath();
            canvas.fill(this);
        },
        /**
         * start sprite animation
         * @method
         * @memberof Kinetic.Sprite.prototype
         */
        start: function() {
            var that = this;
            var layer = this.getLayer();

            /*
             * animation object has no executable function because
             *  the updates are done with a fixed FPS with the setInterval
             *  below.  The anim object only needs the layer reference for
             *  redraw
             */
            this.anim.setLayers(layer);

            this.interval = setInterval(function() {
                var index = that.getIndex();
                that._updateIndex();
                if(that.afterFrameFunc && index === that.afterFrameIndex) {
                    that.afterFrameFunc();
                    delete that.afterFrameFunc;
                    delete that.afterFrameIndex;
                }
            }, 1000 / this.getFrameRate());

            this.anim.start();
        },
        /**
         * stop sprite animation
         * @method
         * @memberof Kinetic.Sprite.prototype
         */
        stop: function() {
            this.anim.stop();
            clearInterval(this.interval);
        },
        /**
         * set after frame event handler
         * @method
         * @memberof Kinetic.Sprite.prototype
         * @param {Integer} index frame index
         * @param {Function} func function to be executed after frame has been drawn
         */
        afterFrame: function(index, func) {
            this.afterFrameIndex = index;
            this.afterFrameFunc = func;
        },
        _updateIndex: function() {
            var index = this.getIndex(),
                animation = this.getAnimation(),
                animations = this.getAnimations(),
                anim = animations[animation],
                len = anim.length;

            if(index < len - 1) {
                this.setIndex(index + 1);
            }
            else {
                this.setIndex(0);
            }
        }
    };
    Kinetic.Util.extend(Kinetic.Sprite, Kinetic.Shape);

    // add getters setters
    Kinetic.Node.addGetterSetter(Kinetic.Sprite, 'animation');

    /**
     * set animation key
     * @name setAnimation
     * @method
     * @memberof Kinetic.Sprite.prototype
     * @param {String} anim animation key
     */

     /**
     * get animation key
     * @name getAnimation
     * @method
     * @memberof Kinetic.Sprite.prototype
     */

    Kinetic.Node.addGetterSetter(Kinetic.Sprite, 'animations');

    /**
     * set animations map
     * @name setAnimations
     * @method
     * @memberof Kinetic.Sprite.prototype
     * @param {Object} animations
     */

     /**
     * get animations map
     * @name getAnimations
     * @method
     * @memberof Kinetic.Sprite.prototype
     */

    Kinetic.Node.addGetterSetter(Kinetic.Sprite, 'image');

    /**
     * set image
     * @name setImage
     * @method
     * @memberof Kinetic.Sprite.prototype
     * @param {Image} image
     */

     /**
     * get image
     * @name getImage
     * @method
     * @memberof Kinetic.Sprite.prototype
     */

    Kinetic.Node.addGetterSetter(Kinetic.Sprite, 'index', 0);

    /**
     * set animation frame index
     * @name setIndex
     * @method
     * @memberof Kinetic.Sprite.prototype
     * @param {Integer} index frame index
     */

     /**
     * get animation frame index
     * @name getIndex
     * @method
     * @memberof Kinetic.Sprite.prototype
     */

    Kinetic.Node.addGetterSetter(Kinetic.Sprite, 'frameRate', 17);

    /**
     * set frame rate in frames / second.  Default is 17 frames per second.  Increase this number to make the sprite
     *  animation run faster, and decrease the number to make the sprite animation run slower
     * @name setFrameRate
     * @method
     * @memberof Kinetic.Sprite.prototype
     * @param {Integer} frameRate
     */

     /**
     * get frame rate
     * @name getFrameRate
     * @method
     * @memberof Kinetic.Sprite.prototype
     */

})();