text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>storage_ptr</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.JSON">
<link rel="up" href="../allocators.html" title="Allocators">
<link rel="prev" href="background.html" title="Background">
<link rel="next" href="uses_allocator.html" title="Uses-allocator construction">

Home
Libraries
People
FAQ
More

storage_ptr

        Variable-length containers in this library all use dynamically allocated
        memory to store their contents. Callers can gain control over the strategy
        used for allocation by specifying a storage_ptr in select constructors
        and function parameter lists. A storage_ptr has these properties:

            A storage pointer always points to a valid, type-erased memory_resource.

            Default-constructed storage pointers reference the default
            resource, an implementation-defined instance which always
            uses the equivalent of global operator new and delete.

            Storage pointers constructed from a memory_resource*
            or polymorphic_allocator do not
            acquire ownership; the caller is responsible for ensuring that the lifetime
            of the resource extends until it is no longer referenced.

            A storage pointer obtained from make_shared_resource acquires
            shared ownership of the memory resource; the lifetime of the resource
            is extended until all copies of the storage pointer are destroyed.

            The storage pointer remembers the value of is_deallocate_trivial before
            type-erasing the resource, allowing the value to be queried at run-time.

        This lists all of the allocation-related types and functions available when
        using the library:

Table 1.7. Functions and Types

<colgroup>
<col>
<col>
</colgroup>

                  Name

                  Description

                  get_null_resource

                  Returns a pointer to a memory resource instance which always throws
                  an exception upon allocation. This is used to to achieve the invariant
                  that no parsing or container operation will dynamically allocate
                  memory.

                  is_deallocate_trivial

                  A customization point allowing a memory resource type to indicate
                  that calls to deallocate are trivial.

                  make_shared_resource

                  A function returning a smart pointer with shared ownership of a
                  newly allocated memory resource.

                  memory_resource

                  The abstract base class representing an allocator.

                  monotonic_resource

                  A memory resource which allocates large blocks of memory and has
                  a trivial deallocate function. Allocated memory is not freed until
                  the resource is destroyed, making it fast for parsing but not suited
                  for performing modifications.

                  polymorphic_allocator

                  An Allocator
                  which uses a reference to a memory_resource to perform
                  allocations.

                  static_resource

                  A memory resource that uses a single caller provided buffer. No
                  dynamic allocations are used. This is fast for parsing but not
                  suited for performing modifications.

                  storage_ptr

                  A smart pointer through which a memory_resource is managed
                  and accessed.

        Default
        Memory Resource

        The default memory resource wraps calls to the global
        heap allocation functions. This resource is not reference counted and has
        a non-trivial deallocate function. All default-constructed storage_ptr reference the same default
        memory resource:

storage_ptr sp1;
storage_ptr sp2;

assert( sp1.get() != nullptr );                         // always points to a valid resource
assert( sp1.get() == sp2.get() );                       // both point to the default resource
assert( *sp1.get() == *sp2.get() );                     // the default resource compares equal

        Default-constructed library containers use the default memory resource:

array arr;                                              // default construction
object obj;
string str;
value jv;

assert( jv.storage().get() == storage_ptr().get() );    // uses the default memory resource
assert( jv.storage().get() == arr.storage().get() );    // both point to the default resource
assert( *arr.storage() == *obj.storage() );             // containers use equivalent resources

        The default memory resource is well suited for general usage. It offers reasonable
        performance for parsing, and conservative memory usage for modification of
        the contents of containers.

        Monotonic
        Resource

        Consider the pattern of memory allocation during parsing: when an array,
        object, or string is encountered the parser accumulates elements in its temporary
        storage area. When all of the elements are known, a single memory allocation
        is requested from the resource when constructing the value. Thus, parsing
        only allocates and constructs containers at their final size. Memory is not
        reallocated; that is, a memory buffer never needs to grow by allocating a
        new larger buffer and deallocating the previous buffer.

        The monotonic_resource optimizes this
        memory allocation pattern by allocating increasingly large blocks of global
        memory internally and parceling those blocks out in smaller pieces to fulfill
        allocation requests. It has a trivial deallocate function. The monotonic
        resource does not actually deallocate memory until the resource is destroyed.
        Thus, it is ideally suited for the use-case where JSON is parsed, and the
        resulting value is then inspected but not modified.

        The resource to use when constructing values may be specified in calls to
        parse
        as shown here:

monotonic_resource mr;

value const jv = parse( "[1,2,3]", &mr );

        Or, to parse into a value with shared ownership of the memory resource:

value parse_value( string_view s)
{
    return parse( s, make_shared_resource< monotonic_resource >() );
}

        A monotonic resource may be optionally constructed with an initial buffer
        to use first, before going to the heap. This allows the caller to use stack
        space and avoid dynamic allocations for most parsed JSON, falling back to
        dynamic allocation from the heap if the input JSON is larger than average,
        as shown here:

template< class Handler >
void do_rpc( string_view s, Handler&& h )
{
    unsigned char buffer[ 8192 ];                       // Small stack buffer to avoid most allocations during parse
    monotonic_resource mr( buffer );                    // This resource will use our local buffer first
    value const jv = parse( s, &mr );                   // Parse the input string into a value that uses our resource
    h( jv );                                            // Call the handler to perform the RPC command
}

        Static
        Resource

        A static_resource
        constructs from a caller-provided buffer, and satisfies all memory allocation
        requests from the buffer. Once the buffer is exhausted, subsequent calls
        to allocate throw the exception std::bad_alloc.
        The resource offers a simple invariant: dynamic heap allocations are never
        performed.

        To use the resource, construct it with a local buffer:

unsigned char buffer[ 8192 ];
static_resource mr( buffer );                           // The resource will use our local buffer

        Null
        Resource

        The function get_null_resource returns a global
        instance of the null resource. This resource offers a simple invariant: all
        calls to allocate will throw the exception std::bad_alloc.
        An instance of the null resource can be used to make parsing guarantee that
        allocations from the heap are never made. This is explored in more detail
        in a later section.

        Allocator
        Propagation

        The containers array, object, and value all propagate the memory resource
        they were constructed with to child elements:

monotonic_resource mr;
array arr( &mr );                                       // construct an array using our resource
arr.emplace_back( "boost" );                            // insert a string
assert( *arr[0].as_string().storage() == mr );          // the resource is propagated to the string

        This propagation acts recursively, containers within containers will all
        have the resource propagated. Once a container is constructed, its memory
        resource can never be changed.

        Resource
        Lifetime

        It is important to note that storage_ptr supports both shared-ownership
        and reference lifetime models. Construction from a memory resource pointer
        does not transfer ownership:

{
    monotonic_resource mr;

    array arr( &mr );                                   // construct an array using our resource

    assert( ! arr.storage().is_shared() );              // no shared ownership
}

        When using a memory resource in this fashion, including the case where a
        storage pointer or container is constructed from a polymorphic_allocator, the caller
        must ensure that the lifetime of the resource is extended until it is no
        longer referenced by any variables; otherwise, undefined behavior is possible.

        Shared ownership is achieved using the function make_shared_resource, which creates
        a new, reference-counted memory resource using a dynamic memory allocation
        and returns it as a storage_ptr:

storage_ptr sp = make_shared_resource< monotonic_resource >();

string str( sp );

assert( sp.is_shared() );                               // shared ownership
assert( str.storage().is_shared() );                    // shared ownership

        When a storage pointer is constructed this way, the lifetime of the referenced
        memory resource is extended until all variables which reference it are destroyed.

        User-Defined
        Resource

        To implement custom memory allocation strategies, derive your class from
        memory_resource
        and implement the functions do_allocate,
        do_deallocate, and do_is_equal as seen in this example below,
        which logs each operation it performs to the console:

class logging_resource : public memory_resource
{
private:
    void* do_allocate( std::size_t bytes, std::size_t align ) override
    {
        std::cout << "Allocating " << bytes << " bytes with alignment " << align << '\n';

        return ::operator new( bytes );
    }

    void do_deallocate( void* ptr, std::size_t bytes, std::size_t align ) override
    {
        std::cout << "Deallocating " << bytes << " bytes with alignment " << align << " @ address " << ptr << '\n';

        return ::operator delete( ptr );
    }

    bool do_is_equal( memory_resource const& other ) const noexcept override
    {
        // since the global allocation and deallocation functions are used,
        // any instance of a logging_resource can deallocate memory allocated
        // by another instance of a logging_resource

        return dynamic_cast< logging_resource const* >( &other ) != nullptr;
    }
};

Copyright © 2019, 2020 Vinnie Falco
Copyright © 2020 Krystian Stasiowski

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
using NUnit.Framework;

public class BcpMessageTests {

    /// <summary>
    /// Tests the string to BCP message function.
    /// </summary>
    [Test]
    public void TestStringToBcpMessage()
    {
        BcpMessage message1 = BcpMessage.CreateFromRawMessage("hello");
        Assert.AreEqual(message1.Command, "hello");

        BcpMessage message2 = BcpMessage.CreateFromRawMessage("test?param1=value1&Param2=vALue2");
        Assert.AreEqual(message2.Command, "test");
        Assert.AreEqual(message2.Parameters["param1"], "value1");
        Assert.AreNotEqual(message2.Parameters["param2"], "value2");
        Assert.AreEqual(message2.Parameters["param2"], "vALue2");
        Assert.AreEqual(message2.Parameters["Param2"].Value, string.Empty);

        BcpMessage message3 = BcpMessage.CreateFromRawMessage("testing?param1=int:234&param2=float:45.34&param3");
        Assert.AreEqual(message3.Command, "testing");
        Assert.True(message3.Parameters["param1"].IsNumber);
        Assert.AreEqual(message3.Parameters["param1"].AsInt, 234);
        Assert.True(message3.Parameters["param2"].IsNumber);
        Assert.AreEqual(message3.Parameters["param2"].AsFloat, 45.34f);
        Assert.True(message3.Parameters["param3"].IsNull);
        Assert.AreEqual(message3.Parameters["param3"].Tag, BCP.SimpleJSON.JSONNodeType.NullValue);
        Assert.AreEqual(message3.Parameters["param3"].Value, "null");

        BcpMessage message4 = BcpMessage.CreateFromRawMessage("test_json?json%3D%7B%22src%22%3A%22Images%2FSun.png%22%2C%22name%22%3A%22sun1%22%2C%22hOffset%22%3A250%2C%22vOffset%22%3A250%2C%22alignment%22%3A%22center%22%7D");
        Assert.AreEqual(message4.Command, "test_json");
        Assert.True(message4.Parameters["src"].IsString);
        Assert.AreEqual(message4.Parameters["src"], "Images/Sun.png");
        Assert.True(message4.Parameters["name"].IsString);
        Assert.AreEqual(message4.Parameters["name"], "sun1");
        Assert.True(message4.Parameters["hOffset"].IsNumber);
        Assert.AreEqual(message4.Parameters["hOffset"].AsInt, 250);
        Assert.True(message4.Parameters["vOffset"].IsNumber);
        Assert.AreEqual(message4.Parameters["vOffset"].AsInt, 250);
        Assert.True(message4.Parameters["alignment"].IsString);
        Assert.AreEqual(message4.Parameters["alignment"], "center");
    }

    [Test]
    public void TestUnknownMessage()
    {
        BcpMessageController controller = new BcpMessageController();
        BcpMessage message = BcpMessage.CreateFromRawMessage("unknown?param1=noneType");
        Assert.Throws<BcpMessageException>(() => controller.ProcessMessage(message, false));
    }

    [Test]
    public void TestHelloMessage()
    {
        BcpMessageController controller = new BcpMessageController();
        BcpMessage message = BcpMessage.CreateFromRawMessage("hello?version=1.1&controller_name=Unity%20Test%20Runner&controller_version=1.0");

        var eventRaised = false;
        BcpMessageController.OnHello += (name, args) => eventRaised = true;

        controller.ProcessMessage(message);
        Assert.True(eventRaised);
    }

    [Test]
    public void TestGoodbyeMessage()
    {
        BcpMessageController controller = new BcpMessageController();
        BcpMessage message = BcpMessage.CreateFromRawMessage("goodbye");

        var eventRaised = false;
        BcpMessageController.OnGoodbye += (name, args) => eventRaised = true;

        controller.ProcessMessage(message);
        Assert.True(eventRaised);
    }

    [Test]
    public void TestSwitchMessage()
    {
        BcpMessageController controller = new BcpMessageController();

        var eventRaised = false;
        BcpMessageController.OnSwitch += (name, args) => eventRaised = true;

        BcpMessage message = BcpMessage.CreateFromRawMessage("switch?name=s_test&state=int:1");
        controller.ProcessMessage(message);
        Assert.True(eventRaised);
    }

    [Test]
    public void TestSwitchMessageBadFormat1()
    {
        var eventRaised = false;
        BcpMessageController.OnSwitch += (name, args) => eventRaised = true;

        BcpMessageController controller = new BcpMessageController();
        BcpMessage message = BcpMessage.CreateFromRawMessage("switch");
        Assert.False(eventRaised);
        Assert.Throws<BcpMessageException>(() => controller.ProcessMessage(message));
    }

    [Test]
    public void TestSwitchMessageBadFormat2()
    {
        var eventRaised = false;
        BcpMessageController.OnSwitch += (name, args) => eventRaised = true;

        BcpMessageController controller = new BcpMessageController();
        BcpMessage message = BcpMessage.CreateFromRawMessage("switch?name=s_test");
        Assert.False(eventRaised);
        Assert.Throws<BcpMessageException>(() => controller.ProcessMessage(message));
    }

    [Test]
    public void TestSwitchMessageBadFormat3()
    {
        var eventRaised = false;
        BcpMessageController.OnSwitch += (name, args) => eventRaised = true;

        BcpMessageController controller = new BcpMessageController();
        BcpMessage message = BcpMessage.CreateFromRawMessage("switch?name=s_test&state=zzz");
        Assert.False(eventRaised);
        Assert.Throws<BcpMessageException>(() => controller.ProcessMessage(message));
    }

    [Test]
    public void TestBallStartMessage()
    {
        BcpMessageController controller = new BcpMessageController();
        BcpMessage message = BcpMessage.CreateFromRawMessage("ball_start?player_num=int:1&ball=int:1");

        var eventRaised = false;
        BcpMessageController.OnBallStart += (name, args) => eventRaised = true;

        controller.ProcessMessage(message);
        Assert.True(eventRaised);
    }

    [Test]
    public void TestBallEndMessage()
    {
        BcpMessageController controller = new BcpMessageController();
        BcpMessage message = BcpMessage.CreateFromRawMessage("ball_end");

        var eventRaised = false;
        BcpMessageController.OnBallEnd += (name, args) => eventRaised = true;

        controller.ProcessMessage(message);
        Assert.True(eventRaised);
    }

    [Test]
    public void TestModeStartMessage()
    {
        BcpMessageController controller = new BcpMessageController();
        BcpMessage message = BcpMessage.CreateFromRawMessage("mode_start?name=test&priority=int:1");

        var eventRaised = false;
        BcpMessageController.OnModeStart += (name, args) => eventRaised = true;

        controller.ProcessMessage(message);
        Assert.True(eventRaised);
    }

    [Test]
    public void TestModeStopMessage()
    {
        BcpMessageController controller = new BcpMessageController();
        BcpMessage message = BcpMessage.CreateFromRawMessage("mode_stop?name=test");

        var eventRaised = false;
        BcpMessageController.OnModeStop += (name, args) => eventRaised = true;

        controller.ProcessMessage(message);
        Assert.True(eventRaised);
    }

    [Test]
    public void TestPlayerAddedMessage()
    {
        BcpMessageController controller = new BcpMessageController();
        BcpMessage message = BcpMessage.CreateFromRawMessage("player_added?player_num=int:1");

        var eventRaised = false;
        BcpMessageController.OnPlayerAdded += (name, args) => eventRaised = true;

        controller.ProcessMessage(message);
        Assert.True(eventRaised);
    }

    [Test]
    public void TestPlayerTurnStartMessage()
    {
        BcpMessageController controller = new BcpMessageController();
        BcpMessage message = BcpMessage.CreateFromRawMessage("player_turn_start?player_num=int:1");

        var eventRaised = false;
        BcpMessageController.OnPlayerTurnStart += (name, args) => eventRaised = true;

        controller.ProcessMessage(message);
        Assert.True(eventRaised);
    }

    [Test]
    public void TestPlayerVariableMessage()
    {
        BcpMessageController controller = new BcpMessageController();
        BcpMessage message = BcpMessage.CreateFromRawMessage("player_variable?name=test&player_num=1&value=abc&prev_value=&change=");

        var eventRaised = false;
        BcpMessageController.OnPlayerVariable += (name, args) => eventRaised = true;

        controller.ProcessMessage(message);
        Assert.True(eventRaised);
    }

    [Test]
    public void TestPlayerScoreMessage()
    {
        BcpMessageController controller = new BcpMessageController();
        BcpMessage message = BcpMessage.CreateFromRawMessage("player_variable?name=score&player_num=1&value=int:1234&prev_value=int:0&change=int:1234");

        var variableEventRaised = false;
        var scoreEventRaised = false;
        BcpMessageController.OnPlayerVariable += (name, args) => variableEventRaised = true;
        BcpMessageController.OnPlayerScore += (name, args) => scoreEventRaised = true;

        controller.ProcessMessage(message);
        Assert.True(variableEventRaised);
        Assert.True(scoreEventRaised);
    }

    [Test]
    public void TestTriggerMessage()
    {
        BcpMessageController controller = new BcpMessageController();
        BcpMessage message = BcpMessage.CreateFromRawMessage("trigger?name=test");

        var eventRaised = false;
        BcpMessageController.OnTrigger += (name, args) => eventRaised = true;

        controller.ProcessMessage(message);
        Assert.True(eventRaised);
    }

    [Test]
    public void TestTimerStartedMessage()
    {
        BcpMessageController controller = new BcpMessageController(true);
        BcpMessage message = BcpMessage.CreateFromRawMessage("trigger?name=timer_test_started&ticks=int:10&ticks_remaining=int:10");

        var eventRaised = false;
        BcpMessageController.OnTimer += (name, args) => eventRaised = true;

        controller.ProcessMessage(message);
        Assert.True(eventRaised);
    }

    [Test]
    public void TestTimerStoppedMessage()
    {
        BcpMessageController controller = new BcpMessageController(true);
        BcpMessage message = BcpMessage.CreateFromRawMessage("trigger?name=timer_test_stopped&ticks=int:10&ticks_remaining=int:10");

        var eventRaised = false;
        BcpMessageController.OnTimer += (name, args) => eventRaised = true;

        controller.ProcessMessage(message);
        Assert.True(eventRaised);
    }

    [Test]
    public void TestTimerPausedMessage()
    {
        BcpMessageController controller = new BcpMessageController(true);
        BcpMessage message = BcpMessage.CreateFromRawMessage("trigger?name=timer_test_paused&ticks=int:10&ticks_remaining=int:10");

        var eventRaised = false;
        BcpMessageController.OnTimer += (name, args) => eventRaised = true;

        controller.ProcessMessage(message);
        Assert.True(eventRaised);
    }

    [Test]
    public void TestTimerCompletedMessage()
    {
        BcpMessageController controller = new BcpMessageController(true);
        BcpMessage message = BcpMessage.CreateFromRawMessage("trigger?name=timer_test_completed&ticks=int:10&ticks_remaining=int:10");

        var eventRaised = false;
        BcpMessageController.OnTimer += (name, args) => eventRaised = true;

        controller.ProcessMessage(message);
        Assert.True(eventRaised);
    }

    [Test]
    public void TestTimerTickMessage()
    {
        BcpMessageController controller = new BcpMessageController(true);
        BcpMessage message = BcpMessage.CreateFromRawMessage("trigger?name=timer_test_tick&ticks=int:10&ticks_remaining=int:10");

        var eventRaised = false;
        BcpMessageController.OnTimer += (name, args) => eventRaised = true;

        controller.ProcessMessage(message);
        Assert.True(eventRaised);
    }

    [Test]
    public void TestTimerTimeAddedMessage()
    {
        BcpMessageController controller = new BcpMessageController(true);
        BcpMessage message = BcpMessage.CreateFromRawMessage("trigger?name=timer_test_time_added&ticks=int:10&ticks_remaining=int:10&ticks_added=2");

        var eventRaised = false;
        BcpMessageController.OnTimer += (name, args) => eventRaised = true;

        controller.ProcessMessage(message);
        Assert.True(eventRaised);
    }

    [Test]
    public void TestTimerTimeSubtractedMessage()
    {
        BcpMessageController controller = new BcpMessageController(true);
        BcpMessage message = BcpMessage.CreateFromRawMessage("trigger?name=timer_test_time_subtracted&ticks=int:10&ticks_remaining=int:10&ticks_subtracted=2");

        var eventRaised = false;
        BcpMessageController.OnTimer += (name, args) => eventRaised = true;

        controller.ProcessMessage(message);
        Assert.True(eventRaised);
    }

    [Test]
    public void TestTiltMessage()
    {
        BcpMessageController controller = new BcpMessageController(true);
        BcpMessage message = BcpMessage.CreateFromRawMessage("trigger?name=tilt");

        var eventRaised = false;
        BcpMessageController.OnTilt += (name, args) => eventRaised = true;

        controller.ProcessMessage(message);
        Assert.True(eventRaised);
    }

    [Test]
    public void TestTiltWarningMessage()
    {
        BcpMessageController controller = new BcpMessageController(true);
        BcpMessage message = BcpMessage.CreateFromRawMessage("trigger?name=tilt_warning&warnings=2&warnings_remaining=1");

        var eventRaised = false;
        BcpMessageController.OnTiltWarning += (name, args) => eventRaised = true;

        controller.ProcessMessage(message);
        Assert.True(eventRaised);
    }

    [Test]
    public void TestSlamTiltMessage()
    {
        BcpMessageController controller = new BcpMessageController(true);
        BcpMessage message = BcpMessage.CreateFromRawMessage("trigger?name=slam_tilt");

        var eventRaised = false;
        BcpMessageController.OnSlamTilt += (name, args) => eventRaised = true;

        controller.ProcessMessage(message);
        Assert.True(eventRaised);
    }

    [Test]
    public void TestErrorMessage()
    {
        BcpMessageController controller = new BcpMessageController();
        BcpMessage message = BcpMessage.CreateFromRawMessage("error?message=An%20error%20occurred&command=xxx");

        var eventRaised = false;
        BcpMessageController.OnError += (name, args) => eventRaised = true;

        controller.ProcessMessage(message);
        Assert.True(eventRaised);
    }

    [Test]
    public void TestResetMessage()
    {
        BcpMessageController controller = new BcpMessageController();
        BcpMessage message = BcpMessage.CreateFromRawMessage("reset");

        var eventRaised = false;
        BcpMessageController.OnReset += (name, args) => eventRaised = true;

        controller.ProcessMessage(message);
        Assert.True(eventRaised);
    }

}

redpajama_set_name: RedPajamaGithub


text:
package plugin.exporter;

import gui.dialog.DocumentationExportDialog;
import org.w3c.dom.Document;
import plugin.OperationNameIcon;
import plugin.PluginsSettings;

import javax.swing.*;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.awt.*;
import java.io.*;
import java.util.HashMap;

/**
 * Default Diderot Documentation Exporter, exports project to html using an xslt file.
 * @author joseph
 */
public class DefaultDiderotDocumentationExporter extends DefaultDiderotProjectExporter
{
	static private HashMap<String, OperationNameIcon> availableOperations = new HashMap<>();

	static
	{
		availableOperations.put("Generate documentation", new OperationNameIcon("generateHtmlDocumentation", "exportweb"));
	}

	/**
	 * Copy directory recursively.
	 * @param source      the source
	 * @param destination the destination
	 * @return true if operation successful, false otherwise
	 */
	//method strongly inspired by kayz1's solution here: http://stackoverflow.com/questions/6214703/copy-entire-directory-contents-to-another-directory
	static public boolean copyDirectory(File source, File destination)
	{
		if (source.isDirectory())
		{
			if (!destination.exists() && !destination.mkdirs())
			{
				return false;
			}

			String files[] = source.list();

			for (String file : files)
			{
				File srcFile = new File(source, file);
				File destFile = new File(destination, file);

				if(!copyDirectory(srcFile, destFile))
				{
					return false;
				}
			}
		}
		else
		{
			InputStream in = null;
			OutputStream out = null;

			try
			{
				in = new FileInputStream(source);
				out = new FileOutputStream(destination);

				byte[] buffer = new byte[1024];

				int length;
				while ((length = in.read(buffer)) > 0)
				{
					out.write(buffer, 0, length);
				}
			}
			catch (Exception e)
			{
				try
				{
					in.close();
				}
				catch (IOException e1)
				{
					e1.printStackTrace();
					return false;
				}

				try
				{
					out.close();
				}
				catch (IOException e1)
				{
					e1.printStackTrace();
					return false;
				}
				return false;
			}
		}

		return true;
	}

	/**
	 * {@inheritDoc}
	 * @return {@inheritDoc}
	 */
	@Override
	public HashMap<String, OperationNameIcon> getAvailableExportingOperations()
	{
		return availableOperations;
	}

	/**
	 * {@inheritDoc}
	 * @return {@inheritDoc}
	 */
	@Override
	public String getPluginName()
	{
		return "Diredot default documentation exporter";
	}

	/**
	 * {@inheritDoc}
	 * @return {@inheritDoc}
	 */
	@Override
	public String getPluginAuthor()
	{
		return "Joseph Caillet";
	}

	/**
	 * {@inheritDoc}
	 * @return {@inheritDoc}
	 */
	@Override
	public String getPluginContactInformation()
	{
		return "https://github.com/JosephCaillet/Diderot";
	}

	/**
	 * {@inheritDoc}
	 * @return {@inheritDoc}
	 */
	@Override
	public String getPluginVersion()
	{
		return "1.0";
	}

	/**
	 * {@inheritDoc}
	 * @return {@inheritDoc}
	 */
	@Override
	public String getPluginDescription()
	{
		return "This default plugin generates web documentation of your routes.";
	}

	/**
	 * Generate html documentation.
	 */
	public void generateHtmlDocumentation()
	{
		String fileName = PluginsSettings.getPropertyValue(getClass().getName() + "documentationFolder");
		if(fileName == null)
		{
			fileName = PluginsSettings.getPropertyValue(DefaultDiderotProjectExporter.class.getName() + "projectFileName", ".");
		}

		String logoLocation = PluginsSettings.getPropertyValue(getClass().getName() + "documentationLogo", ".");
		boolean openBrowser = Boolean.parseBoolean(
				PluginsSettings.getPropertyValue(getClass().getName() + "documentationOpenInBrowser", "true"));

		DocumentationExportDialog exportDialog = new DocumentationExportDialog(parent, fileName, logoLocation, openBrowser);
		if(!exportDialog.display())
		{
			return;
		}

		openBrowser = exportDialog.isOpenInBrowserAsked();
		logoLocation = exportDialog.getLogoLocation();
		fileName = exportDialog.getExportLocation();

		if(!new File(fileName).isDirectory())
		{
			JOptionPane.showMessageDialog(parent,  fileName + " is not a folder.", "Export error", JOptionPane.ERROR_MESSAGE);
			return;
		}

		PluginsSettings.setPropertyValue(getClass().getName() + "documentationFolder", fileName);
		PluginsSettings.setPropertyValue(getClass().getName() + "documentationLogo", logoLocation);
		PluginsSettings.setPropertyValue(getClass().getName() + "documentationOpenInBrowser", String.valueOf(openBrowser));

		if(!fileName.endsWith("/"))
		{
			fileName = fileName + "/";
		}

		try
		{
			Document xmlSaveDocument = createDocument();

			StreamSource streamSource = new StreamSource("generateDocumentation.xsl");

			Transformer xmlTransformer = TransformerFactory.newInstance().newTransformer(streamSource);
			xmlTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
			xmlTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

			copyDirectory(new File("documentationTemplate/"), new File(fileName));

			File f = new File(fileName + "index.html");
			xmlTransformer.transform(new DOMSource(xmlSaveDocument), new StreamResult(f));

			File logo = new File(logoLocation);
			if(logo.exists() && logoLocation.toLowerCase().endsWith("png"))//because default value is ".", the current directory, which exists.
			{
				copyDirectory(logo, new File(fileName + "logo.png"));
			}

			if(openBrowser)
			{
				Desktop.getDesktop().browse(f.toURI());
			}
		}
		catch(ParserConfigurationException | TransformerException e)
		{
			e.printStackTrace();
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
              http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5" xmlns="http://java.sun.com/xml/ns/javaee">

    <!-- Servlets -->
    <servlet>
        <servlet-name>servlet</servlet-name>
        <servlet-class>hatanian.david.gwt.server.DemoServiceImpl</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>servlet</servlet-name>
        <url-pattern>/appenginedemo/demo</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>demo</servlet-name>
        <servlet-class>hatanian.david.gwt.server.DemoServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>demo</servlet-name>
        <url-pattern>/demoservlet</url-pattern>
    </servlet-mapping>

    <!-- Default page to serve -->
    <welcome-file-list>
        <welcome-file>AppEngineDemo.html</welcome-file>
    </welcome-file-list>
</web-app>


text:
using System.Runtime.Serialization;

namespace SecureAuth.Sdk
{
    [DataContract]
    public class OathTokenRequest : BaseRequest
    {
        [DataMember(Name = "password", EmitDefaultValue = false)]
        public string Password { get; set; }

        [DataMember(Name = "token", EmitDefaultValue = false)]
        public string Token { get; set; }

        [DataMember(Name = "factor_id", EmitDefaultValue = false)]
        public string FactorId { get; set; }

        public OathTokenRequest(string domain, string userId, string password, string token, string factorId)
            : base(userId, "oath", domain)
        {
            this.Password = password;
            this.Token = token;
            this.FactorId = factorId;
        }
    }
}


text:
require 'rails_helper'

RSpec.describe BookLink, type: :model do
  let(:book_link) { FactoryGirl.build(:book_link) }

  it 'should have a valid factory' do
    expect(book_link).to be_valid
  end
end


text:
package org.hbird.business.groundstation.hamlib.radio.protocol;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.when;

import java.util.List;

import org.hbird.business.groundstation.base.DriverContext;
import org.hbird.business.groundstation.configuration.RadioDriverConfiguration;
import org.hbird.business.groundstation.hamlib.radio.RadioState;
import org.hbird.exchange.interfaces.IEntityInstance;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

/**
 *
 */
@RunWith(MockitoJUnitRunner.class)
public class SetVfoTest {

    public static final String OK_RESPONSE = "set_vfo: VFOA\nRPRT 0";
    public static final String ERROR_RESPONSE = "set_vfo: N/A\nRPRT -1";

    @Mock
    private DriverContext<RadioDriverConfiguration, String, String> context;

    @Mock
    private RadioState state;

    private SetVfo setVfo;

    private InOrder inOrder;

    /**
     * @throws java.lang.Exception
     */
    @Before
    public void setUp() throws Exception {
        setVfo = new SetVfo();
        inOrder = inOrder(context, state);
        when(context.getDeviceState()).thenReturn(state);
    }

    @Test
    public void testGetKey() throws Exception {
        assertEquals(SetVfo.KEY, setVfo.getKey());
    }

    @Test
    public void testHandle() throws Exception {
        List<IEntityInstance> result = setVfo.handle(context, OK_RESPONSE);
        assertNotNull(result);
        assertEquals(0, result.size());
        inOrder.verify(context, times(1)).getDeviceState();
        inOrder.verify(state, times(1)).setCurrentVfo("VFOA");
        inOrder.verifyNoMoreInteractions();
    }

    @Test
    public void testHandleError() throws Exception {
        List<IEntityInstance> result = setVfo.handle(context, ERROR_RESPONSE);
        assertNotNull(result);
        assertEquals(0, result.size());
        inOrder.verifyNoMoreInteractions();
    }

    @Test
    public void testCreateCommand() throws Exception {
        assertEquals("+V VFOA\n", SetVfo.createCommand("VFOA"));
        assertEquals("+V VFOB\n", SetVfo.createCommand("VFOB"));
    }
}


text:
**This feature is only present on the `dev` branch / image.**

**It's still considered experimental and subject to change.**

You can generate certificate that are not tied to containers environment variable by mounting a user configuration file inside the container at `/app/letsencrypt_user_data`. This feature also require sharing the `/etc/nginx/conf.d` folder between the **nginx-proxy** and **letsencrypt-nginx-proxy-companion** container (and the **docker-gen** container if you are running a [three container setup](./Advanced-usage.md)):

```bash
$ docker run --detach \
    --name nginx-proxy \
    --publish 80:80 \
    --publish 443:443 \
    --volume /etc/nginx/certs \
    --volume /etc/nginx/vhost.d \
    --volume /etc/nginx/conf.d \
    --volume /usr/share/nginx/html \
    --volume /var/run/docker.sock:/tmp/docker.sock:ro \
    jwilder/nginx-proxy
```
```bash
$ docker run --detach \
    --name nginx-proxy-letsencrypt \
    --volumes-from nginx-proxy \
    --volume /var/run/docker.sock:/var/run/docker.sock:ro \
    --volume /path/to/your/config_file:/app/letsencrypt_user_data:ro \
    jrcs/letsencrypt-nginx-proxy-companion
```

The user configuration file is a collection of bash variables and array, and follows the syntax of the `/app/letsencrypt_service_data` file that get created by **docker-gen**.

### Required configuration parameters:

`LETSENCRYPT_STANDALONE_CERTS` : a bash array containing identifier(s) for you standalone certificate(s). Each element in the array has to be unique. Those identifiers are internal to the container process and won't ever be visible to the outside world or appear on your certificate.

`LETSENCRYPT_uniqueidentifier_HOST` : a bash array containing domain(s) that will be covered by the certificate corresponding to `uniqueidentifier`.

Each identifier in `LETSENCRYPT_STANDALONE_CERTS` must have its own corresponding `LETSENCRYPT_uniqueidentifier_HOST` array.

**Minimal example generating a single certificate for a single domain:**

```bash
LETSENCRYPT_STANDALONE_CERTS=('uniqueidentifier')
LETSENCRYPT_uniqueidentifier_HOST=('yourdomain.tld')
```

**Example with multiple certificates and domains:**

```bash
LETSENCRYPT_STANDALONE_CERTS=('web' 'app' 'othersite')
LETSENCRYPT_web_HOST=('yourdomain.tld' 'www.yourdomain.tld')
LETSENCRYPT_app_HOST=('myapp.yourdomain.tld' 'myapp.yourotherdomain.tld' 'service.yourotherdomain.tld')
LETSENCRYPT_othersite_HOST=('yetanotherdomain.tld')
```

### Optional configuration parameters:

Those are all single bash variables.

`LETSENCRYPT_uniqueidentifier_EMAIL` : must be a valid email and will be used by Let's Encrypt to warn you of impeding certificate expiration (should the automated renewal fail).

`LETSENCRYPT_uniqueidentifier_KEYSIZE` : determines the size of the requested private key (in bit, defaults to 4096).

`LETSENCRYPT_uniqueidentifier_TEST` : if set to true, the corresponding certificate will be a test certificates: it won't have the 5 certs/week/domain limits and will be signed by an untrusted intermediate (ie it won't be trusted by browsers).

`LETSENCRYPT_uniqueidentifier_ACCOUNT_ALIAS` : see the [ACME account documentation](./Let's-Encrypt-and-ACME.md#multiple-accounts-per-endpoint).

### Picking up changes to letsencrypt_user_data

The container does not actively watch the `/app/letsencrypt_user_data` file for changes.

Changes will either be picked up every hour when the service loop execute again, or by using `docker exec your-le-container-name-or-id /app/signal_le_service` to manually trigger the service loop execution.

### Proxying to something else than a Docker container

Please see the [**nginx-proxy** documentation](https://github.com/jwilder/nginx-proxy#proxy-wide).

No support will be provided on the **letsencrypt-nginx-proxy-companion** repo for proxying related issues or questions.


text:
// Template Source: BaseMethodRequestBuilder.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.requests;
import com.microsoft.graph.requests.ChannelCompleteMigrationRequest;
import com.microsoft.graph.models.Channel;

import com.microsoft.graph.http.BaseActionRequestBuilder;
import com.microsoft.graph.core.IBaseClient;
import com.google.gson.JsonElement;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;

// **NOTE** This file was generated by a tool and any changes will be overwritten.

/**
 * The class for the Channel Complete Migration Request Builder.
 */
public class ChannelCompleteMigrationRequestBuilder extends BaseActionRequestBuilder<Channel> {

    /**
     * The request builder for this ChannelCompleteMigration
     *
     * @param requestUrl     the request URL
     * @param client         the service client
     * @param requestOptions the options for this request
     */
    public ChannelCompleteMigrationRequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
        super(requestUrl, client, requestOptions);
    }

    /**
     * Creates the ChannelCompleteMigrationRequest
     *
     * @param requestOptions the options for the request
     * @return the ChannelCompleteMigrationRequest instance
     */
    @Nonnull
    public ChannelCompleteMigrationRequest buildRequest(@Nullable final com.microsoft.graph.options.Option... requestOptions) {
        return buildRequest(getOptions(requestOptions));
    }

    /**
     * Creates the ChannelCompleteMigrationRequest with specific requestOptions instead of the existing requestOptions
     *
     * @param requestOptions the options for the request
     * @return the ChannelCompleteMigrationRequest instance
     */
    @Nonnull
    public ChannelCompleteMigrationRequest buildRequest(@Nonnull final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
        final ChannelCompleteMigrationRequest request = new ChannelCompleteMigrationRequest(
                getRequestUrl(),
                getClient(),
                requestOptions);
        return request;
    }
}


text:
import sys
import mechanize
import re
import argparse
import getpass

class PasswdPromptAction(argparse.Action):

    def __init__(self,
                 option_strings,
                 dest=None,
                 nargs=0,
                 default=None,
                 required=False,
                 type=None,
                 metavar=None,
                 help=None):
        super(PasswdPromptAction, self).__init__(
            option_strings=option_strings,
            dest=dest,
            nargs=nargs,
            default=default,
            required=required,
            type=type,
            metavar=metavar,
            help=help)

    def __call__(self, parser, args, values, option_strings=None):
        passwd = getpass.getpass()
        setattr(args, self.dest, passwd)

def check_mybenefit(username, passwd, company, product, verbose):
    browser = mechanize.Browser(factory=mechanize.RobustFactory())
    browser.set_debug_http(verbose)
    url = 'https://system.mybenefit.pl/mybenefit/login.html'
    browser.addheaders = [
        ( 'User-Agent', '''Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:35.0)
				 Gecko/20100101 Firefox/35.0'''),
        ('Referer', 'https://system.mybenefit.pl/mybenefit/login.html'),
        ( 'Host', '''system.mybenefit.pl'''),
        ( 'Accept', '''text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'''),
        ( 'Accept-Language', '''en-US,en;q=0.5'''),
    ]

    browser.open(url)
    browser.select_form(nr=0)
    browser.form.set_all_readonly(False)
    browser.form['j_username_input'] = username
    browser.form['j_password'] = passwd
    browser.form['j_context'] = company
    browser.form['j_username'] = '||'.join([username, company])

    result = browser.submit()
    url_points_realization = 'https://system.mybenefit.pl/mybenefit/bankpoints-realization.html'
    if re.search('
Podaj login, hasło i nazwę swojej firmy
',
                 result.get_data()):
        print '[!] Login failed!'
        return False

    points_realization = browser.open(url_points_realization)
    if re.search(product, points_realization.read()):
        print "[+] Product: \"%s\" was found !" % product
    else:
        print '[+] Nothing found.'

    if verbose:
        print result.get_data()

def main():
    parser = argparse.ArgumentParser()
    group = parser.add_argument_group('Check offer')
    group.add_argument("-o", "--offering", type=str,
                       help="Offering/product name")
    group.add_argument("-u", "--username", type=str, help="User name")
    group.add_argument(
        "-p",
        "--password",
        type=str,
        help="Prompt for the password",
        action=PasswdPromptAction)
    group.add_argument("-c", "--company", type=str, help="Company name")

    parser.add_argument(
        "-v",
        "--verbose",
        help="Verbose mode",
        default=False,
        action='store_true')

    args = parser.parse_args()
    if args.offering and args.username and args.password and args.company:
        return check_mybenefit(args.username, args.password,
                               args.company, args.offering, args.verbose)
    else:
        parser.print_help()

if __name__ == "__main__":
    sys.exit(main())


text:
layout: post
title: "Angry Birds conquistará el corazón de Facebook el Día de San Valentín"
category: genbeta
---

A día de hoy **podemos jugar a Angry Birds casi en cualquier dispositivo**, de
hecho empieza a haber aplicaciones para televisiones, pero todavía quedaba una
pequeña aldea (en este caso americana, no gala) donde Angry Birds todavía no
se había posado: Facebook. Y es que la idea de los creadores es que puedas
jugar siempre, estés donde estés; e incluso van más allá porque tus logros se
sincronizarán entre diferentes dispositivos.

Está claro que **la lucha por nuestra productividad la tenemos perdida**. Y
por si no invertíamos suficientemente tiempo en Facebook, como si de un
flechazo a traición se tratara, Angry Birds aterrizará y plantará su _huevo
explosivo_ en todos nuestros muros el Día de San Valentín.

Aunque, queramos o no, al final le tendremos que echarle un vistazo, seguro
que viene con novedades ya que si la aplicación para Facebook será gratuita,
ofrecerán ventajas y **pájaros más potentes mediante pequeños pagos**. Así que
ahora se llevan nuestro tiempo, y también, cada día más, nuestro dinero… ¡pero
es tan divertido!

Vía | [The Next Web](http://thenextweb.com/facebook/2012/01/26/angry-birds-
are-flocking-to-facebook-as-valentines-day-launch-is-revealed)

Artículo extraído de [Genbeta](http://www.genbeta.com).


text:
import {DataSource} from '@angular/cdk/collections';
import {
  AfterContentInit,
  Component,
  ContentChildren,
  Input,
  OnInit,
  QueryList,
  ViewChild
} from '@angular/core';
import {MatSort} from '@angular/material/sort';
import {
  MatColumnDef,
  MatHeaderRowDef,
  MatRowDef,
  MatTable,
  MatTableDataSource
} from '@angular/material/table';

export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  symbol: string;
}

const ELEMENT_DATA: PeriodicElement[] = [
  {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
  {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
  {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
  {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
  {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
  {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
  {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
  {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
  {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
  {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
];

/**
 * @title Table example that shows how to wrap a table component for definition and behavior reuse.
 */
@Component({
  selector: 'table-wrapped-example',
  styleUrls: ['table-wrapped-example.css'],
  templateUrl: 'table-wrapped-example.html',
})
export class TableWrappedExample implements OnInit {
  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  dataSource = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA);

  @ViewChild('sort', {static: true}) sort: MatSort;

  ngOnInit() {
    this.dataSource.sort = this.sort;
  }
}

/**
 * Table component that accepts column and row definitions in its content to be registered to the
 * table.
 */
@Component({
  selector: 'wrapper-table',
  templateUrl: 'wrapper-table.html',
  styles: [`
    table {
      width: 100%;
    }
  `]
})
export class WrapperTable<T> implements AfterContentInit {
  @ContentChildren(MatHeaderRowDef) headerRowDefs: QueryList<MatHeaderRowDef>;
  @ContentChildren(MatRowDef) rowDefs: QueryList<MatRowDef<T>>;
  @ContentChildren(MatColumnDef) columnDefs: QueryList<MatColumnDef>;

  @ViewChild(MatTable, {static: true}) table: MatTable<T>;

  @Input() columns: string[];

  @Input() dataSource: DataSource<T>;

  ngAfterContentInit() {
    this.columnDefs.forEach(columnDef => this.table.addColumnDef(columnDef));
    this.rowDefs.forEach(rowDef => this.table.addRowDef(rowDef));
    this.headerRowDefs.forEach(headerRowDef => this.table.addHeaderRowDef(headerRowDef));
  }
}


text:
<?php
use Qobo\Utils\ModuleConfig\ClassType;
use Qobo\Utils\ModuleConfig\ConfigType;
use Qobo\Utils\ModuleConfig\Parser\ListParser;
use Qobo\Utils\ModuleConfig\Parser\Parser;
use Qobo\Utils\ModuleConfig\PathFinder\V2\ConfigPathFinder;
use Qobo\Utils\ModuleConfig\PathFinder\V2\DuplicatesPathFinder;
use Qobo\Utils\ModuleConfig\PathFinder\V2\FieldsPathFinder;
use Qobo\Utils\ModuleConfig\PathFinder\V2\ListPathFinder;
use Qobo\Utils\ModuleConfig\PathFinder\V2\MenusPathFinder;
use Qobo\Utils\ModuleConfig\PathFinder\V2\MigrationPathFinder;
use Qobo\Utils\ModuleConfig\PathFinder\V2\ReportsPathFinder;
use Qobo\Utils\ModuleConfig\PathFinder\V2\ViewPathFinder;

// Class map of finders and parser for each
// support configuration type
$classTypeFinder = (string)ClassType::FINDER();
$classTypeParser = (string)ClassType::PARSER();

return [
    'ModuleConfig' => [
        'schemaPath' => implode(DIRECTORY_SEPARATOR, [
            ROOT,
            'src', 'ModuleConfig', 'Parser', 'Schema',
        ]),
        'cacheConfig' => 'default',
        'classMapVersion' => 'V3',
        'classMap' => [
            'V3' => [
                (string)ConfigType::MIGRATION() => [
                    $classTypeFinder => MigrationPathFinder::class,
                    $classTypeParser => Parser::class,
                ],
                (string)ConfigType::MODULE() => [
                    $classTypeFinder => ConfigPathFinder::class,
                    $classTypeParser => Parser::class,
                ],
                (string)ConfigType::LISTS() => [
                    $classTypeFinder => ListPathFinder::class,
                    $classTypeParser => ListParser::class,
                ],
                (string)ConfigType::FIELDS() => [
                    $classTypeFinder => FieldsPathFinder::class,
                    $classTypeParser => Parser::class,
                ],
                (string)ConfigType::MENUS() => [
                    $classTypeFinder => MenusPathFinder::class,
                    $classTypeParser => Parser::class,
                ],
                (string)ConfigType::REPORTS() => [
                    $classTypeFinder => ReportsPathFinder::class,
                    $classTypeParser => Parser::class,
                ],
                (string)ConfigType::VIEW() => [
                    $classTypeFinder => ViewPathFinder::class,
                    $classTypeParser => Parser::class,
                ],
                (string)ConfigType::DUPLICATES() => [
                    $classTypeFinder => DuplicatesPathFinder::class,
                    $classTypeParser => Parser::class,
                ],
            ],
        ],
    ],
];


text: No stats provided


text:
import gc
import numpy as np
import xarray as xr
from xarray.ufuncs import sign as xr_sign

from . import dc_utilities as utilities
from .dc_utilities import create_default_clean_mask
from datetime import datetime
import warnings

def _tsmi(dataset):
    out = (dataset.red + dataset.green) * 0.0001 / 2
    return out.where(out>0, 0)

def tsm(dataset_in, clean_mask=None, no_data=0):
    """
    Calculate Total Suspended Matter (TSM) for water.

    Parameters
    ----------
    dataset_in: xarray.Dataset
        Dataset retrieved from the Data Cube.
        Must have 'red' and 'green' data variables.
    clean_mask: np.ndarray
        A NumPy array with dtype boolean
        True for values considered clean;
        if no clean mask is supplied, all values will be considered clean
    no_data: numeric
        no data pixel value; default: -9999

    Raises
    ------
    ValueError
        if dataset_in is an empty xarray.Dataset.
    """
    assert 'red' in dataset_in and 'green' in dataset_in, "Red and Green bands are required for the TSM analysis."
    # Default to masking nothing.
    if clean_mask is None:
        clean_mask = create_default_clean_mask(dataset_in)

    tsm = 3983 * _tsmi(dataset_in)**1.6246
    tsm = tsm.where(clean_mask, no_data)

    # Create xarray of data
    _coords = { key:dataset_in[key] for key in dataset_in.dims.keys()}
    dataset_out = xr.Dataset({'tsm': tsm}, coords=_coords)
    return dataset_out

def mask_water_quality(dataset_in, wofs):
    import scipy.ndimage.filters as conv

    wofs_criteria = wofs.where(wofs > 0.8)
    wofs_criteria.values[wofs_criteria.values > 0] = 0
    kernel = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]])

    mask = conv.convolve(wofs_criteria.values, kernel, mode='constant')
    mask = mask.astype(np.float32)

    dataset_out = dataset_in.copy(deep=True)
    for var in dataset_out.data_vars:
        dataset_out[var].values += mask
    dataset_out.where(dataset_out != np.nan, 0)

    return dataset_out

def watanabe_chlorophyll(dataset_in, clean_mask=None, no_data=0):
    assert 'red' in dataset_in and 'nir' in dataset_in, "Red and NIR bands are required for the Watanabe Chlorophyll analysis."
    # Default to masking nothing.
    if clean_mask is None:
        clean_mask = create_default_clean_mask(dataset_in)

    chl_a = 925.001 * (dataset_in.nir.astype('float64') / dataset_in.red.astype('float64')) - 77.16
    chl_a.values[np.invert(clean_mask)] = no_data  # Contains data for clear pixels

    # Create xarray of data
    time = dataset_in.time
    latitude = dataset_in.latitude
    longitude = dataset_in.longitude
    dataset_out = xr.Dataset(
        {
            'watanabe_chlorophyll': chl_a
        }, coords={'time': time,
                   'latitude': latitude,
                   'longitude': longitude})
    return dataset_out

def nazeer_chlorophyll(dataset_in, clean_mask=None, no_data=0):
    # Default to masking nothing.
    if clean_mask is None:
        clean_mask = create_default_clean_mask(dataset_in)

    chl_a = (0.57 * (dataset_in.red.astype('float64') * 0.0001) /
             (dataset_in.blue.astype('float64') * 0.0001)**2) - 2.61
    chl_a.values[np.invert(clean_mask)] = no_data  # Contains data for clear pixels

    # Create xarray of data
    time = dataset_in.time
    latitude = dataset_in.latitude
    longitude = dataset_in.longitude
    dataset_out = xr.Dataset(
        {
            'nazeer_chlorophyll': chl_a
        }, coords={'time': time,
                   'latitude': latitude,
                   'longitude': longitude})
    return dataset_out


text:
require "rulers/version"
require "rulers/routing"
require "rulers/util"
require "rulers/dependencies"
require "rulers/controller"
require "rulers/file_model"

module Rulers
  class Application
    def call(env) #Redefine
      if env['PATH_INFO'] == '/favicon.ico'
        return [404, {'Content-Type' => 'text/html'}, []]
      end

      begin
        klass, act = get_controller_and_action(env)
        STDERR.puts "#{klass}, #{act}: klass, act"
        controller = klass.new(env)
        STDERR.puts "controller: #{controller.inspect}"
        text = controller.send(act)
        STDERR.puts "text: #{text}"
        if controller.get_response
          st, hd, rs = controller.get_response.to_a
          [st, hd, [rs.body].flatten]
        else
          [200, {'Content-Type' => 'text/html'}, [text]]
        end
      rescue Exception => e
        STDERR.puts e.inspect
        error = e.inspect + "\n" + e.backtrace.join("\n")
        [500, {'Content-Type' => 'text/text'}, [error]]
      end
    end
  end

  class Controller
    include Rulers::Model
  end
end


text:
Как уже упоминалось в [readme](../README_RU.md), TARS — не npm-модуль, поэтому его обновление не происходит одной командой в консоли.

Есть несколько типов обновлений TARS:

* Обновление зависимостей до последних стабильных.
* Обновление TARS целиком.

Первый тип обновления можно выполнить командой `gulp update-deps` (подробнее в основном [readme](../README_RU.md#basic-commands)), а для второго требуется выполнить несколько действий.

Вообще, в рамках мажорной версии (1.\*.\*, например) можно переносить папку markup (папка, в которой должны находиться исходники вашего проекта), в любую версию. В любой версии в рамках одной мажорной сборка пройдет успешно. Данное утверждение справедливо для TARS выше (и включая) версии 1.2.0. До 1.2.0 были небольшие изменения в файловой структуре и способе подключения модулей в handlebars. Все изменения доступны в [changelog](changelog.md).

Таким образом, чтобы получить новую функциональность, которая вышла в новой минорной версии (\*.4.\*, например) достаточно:

* [Скачать новый TARS](https://github.com/2gis/tars/archive/master.zip).
* Проинициализировать его с теми настройками, которые есть в вашем текущем проекте.
* Перенести папку markup из текущего проекта в новый TARS.

После этого вы можете спокойно использовать новый функционал.
Подробнее о системе версионирования можно прочитать [здесь](http://semver.org/lang/ru).

Есть исключение из этого правила. Например, была добавлена работа с coffee-файлами в одной из минорных версий. Если ваш проект использует только js, то вы также можете использовать любую минорную версию в рамках мажорной. Если вы хотите использовать coffee-файлы, то необходимо выбирать только ту версию, в которой были добавлены таски для работы с ними или версию выше.

В основном [readme](../README_RU.md) обязательно будет указано с какой версии есть доступ к той или иной функциоанльности.

Также, если вы вносили изменения в файлы сборщика (что угодно еще, кроме папки markup), то необходимо эти изменения перенести вручную. Все последние изменения в файлах сборщика будут доступны по ссылке: [История изменений](changelog.md).

Для перехода от одной мажорной версии к другой будет написано соответсвующее руководство.


text:
.. _contributing:

#######################
Contributing to Monitor
#######################

Pull requests, code style, testing guidelines, ...


text:
sap.ui.define(['sap/ui/base/ManagedObject'], function(ManagedObject) {
	"use strict";

	/**
	 * Implementation of the Context API
	 *
	 * @class
	 * @extends sap.ui.base.ManagedObject
	 *
	 * @author SAP SE
	 * @version 1.50.8
	 *
	 * @constructor
	 * @private
	 * @since 1.38
	 * @experimental Since 1.38. This class is experimental and provides only limited functionality. Also the API might be
	 *               changed in future.
	 */
	var Context = ManagedObject.extend("sap.ui.fl.context.Context", {
		metadata : {
			library : "sap.ui.fl",
			properties : {
				configuration : {
					type : "object"
				},
				content : {
					type : "object"
				}
			},
			aggregations : {
				contextProviders : {
					type : "object",
					multiple : true
				}
			},
			events : {}
		}
	});

	Context.prototype.getValue = function(aRequest) {
		return this._getProviderContent(aRequest, "getValue");
	};

	Context.prototype.getValueHelp = function(aRequest) {
		return this._getProviderContent(aRequest, "getValueHelp");
	};

	var fnRemoveDomainFromRequest = function(sDomain, sRequest)  {
		if (sDomain.indexOf(sRequest) !== -1){
			//partial or full request for a domain, return all values of the domain
			return undefined;
		}
		if (sRequest.indexOf(sDomain + ".") !== -1){
			//sub request for a domain, return all values of the domain
			return sRequest.substring(sDomain.length + 1);
		}
		throw new Error("Invalid request for sap.ui.fl.context - domain:" + sDomain + "request:" + sRequest);
	};

	Context.prototype._getProviderContent = function(aRequest, sPropertyName) {

		var that = this;
		var aPromises = [];
		var aRequestByDomain = [];

		var fnHandleOneDomain = function(sRequest) {
			var sAssuredDomain = that._assureDomain(sRequest);
			if (sAssuredDomain) {
				var oPromise = that._loadProvider(sAssuredDomain);
				aPromises.push(oPromise);

				aRequestByDomain.push({
					domain : sAssuredDomain,
					request : fnRemoveDomainFromRequest(sAssuredDomain, sRequest)
				});
			} else {
				//unkown domain
				aRequestByDomain.push({
					domain : undefined,
					request : sRequest
				});
			}
		};

		var fnMassUpdateConfiguration = function(aDomainProviderPairs) {
			var mConfiguration = that.getConfiguration();
			var bConfigurationChanged = false;
			for (var i = 0; i < aDomainProviderPairs.length; i++) {
				var oPair = aDomainProviderPairs[i];
				if (oPair) {
					mConfiguration[oPair.domain] = oPair.provider;
					bConfigurationChanged = true;
				}
			}
			if (bConfigurationChanged) {
				that.setConfiguration(mConfiguration);
			}
		};

		if (aRequest instanceof Array) {
			aRequest.forEach(function(sRequest){
				fnHandleOneDomain(sRequest);
			});
		} else if (aRequest === undefined) {
			for ( var sDomain in this.getConfiguration()) {
				aPromises.push(this._loadProvider(sDomain));
			}
			aRequestByDomain = Object.keys(this.getConfiguration()).map(function(sDomain){
				return {
					domain : sDomain,
					request : undefined
				};
			});
		}

		return Promise.all(aPromises).then(fnMassUpdateConfiguration).then(function() {
			return that._mergeProviderContent(aRequestByDomain, sPropertyName, aRequest);
		});
	};

	Context.prototype._assureDomain = function(oDomain) {
		var mConfiguration = this.getConfiguration();
		if (mConfiguration.hasOwnProperty(oDomain)) {
			return oDomain;
		} else {
			var aKeys = Object.keys(mConfiguration);
			for (var i = 0; i < aKeys.length; i++) {
				var sKey = aKeys[i];
				if (oDomain.indexOf(sKey) === 0 || sKey.indexOf(oDomain) === 0) {
					return sKey;
				}
			}
		}
		return null;
	};

	Context.prototype._loadProvider = function(sDomain, mConfiguration) {
		var sActConfigPath = this.getConfiguration()[sDomain];
		if (typeof (sActConfigPath) === "string") {

			return new Promise(function(resolve, reject) {
				try {
					sap.ui.require([sActConfigPath], function(ProviderConstructor){
						var oProvider = new ProviderConstructor();
						resolve({
							"domain" : sDomain,
							"provider" : oProvider
						});
					});
				} catch (oError) {
					jQuery.sap.log.error(oError);
					resolve(); // recover from error, but deliver no information
					return;
				}
			});
		} else {
			return Promise.resolve();
		}
	};

	Context.prototype._mergeProviderContent = function(aRequestByDomain, sPropertyName, aRequest) {

		var aPromises = [];

		var mConfiguration = this.getConfiguration();
		aRequestByDomain.forEach(function(oRequest){
			if (mConfiguration.hasOwnProperty(oRequest.domain)) {
				var oActProvider = mConfiguration[oRequest.domain];
				if (oActProvider instanceof sap.ui.fl.context.BaseContextProvider) {
					aPromises.push(oActProvider[sPropertyName].call(oActProvider, oRequest.request).then(function(mValue){
						var mSingleResult = {};
						var sResultKey = oRequest.domain;
						if (oRequest.request){
							sResultKey = sResultKey + "." + oRequest.request;
						}
						mSingleResult[sResultKey] = mValue;
						return mSingleResult;
					}));
				}
			} else {
				var mSingleResult = {};
				mSingleResult[oRequest.request] = undefined;
				aPromises.push(Promise.resolve(mSingleResult));
			}
		});

		return Promise.all(aPromises).then(function(aResults) {
			return aResults.reduce(function(mResults, mCurrent) {
				//jQuery.extend will not merge undefined properties => do it on our own
				var sKey = Object.keys(mCurrent)[0];
				mResults[sKey] = mCurrent[sKey];
				return mResults;
			}, {});
		});

	};

	return Context;

}, /* bExport= */true);


text:
//********************************************************************
//*
//* Warning: This file was generated by MDE4CPP Generator
//*
//********************************************************************

#ifndef UML_PACKAGE_EXECUTION_HPP
#define UML_PACKAGE_EXECUTION_HPP

#include "PSCS/Semantics/StructuredClassifiers/impl/CS_ObjectImpl.hpp"
#include "umlReflectionExec/NamespaceObject.hpp"
#include "umlReflectionExec/PackageableElementObject.hpp"
#include "umlReflectionExec/TemplateableElementObject.hpp"

template <class T>
class Bag;

namespace uml
{
	class Package;
}

namespace uml
{
	class Element;
	class ConnectorEnd;
}

namespace UML
{
	class PackageObject : virtual public UML::NamespaceObject , virtual public UML::PackageableElementObject , virtual public UML::TemplateableElementObject
	{
		public:
		    //constructors
		    PackageObject(PackageObject &obj);
		    PackageObject(std::shared_ptr<uml::Package>);
		 	PackageObject();
		    //destructor
		    virtual ~PackageObject();

		    virtual std::shared_ptr<ecore::EObject> copy();
			PackageObject& operator=(PackageObject const&);

			virtual void destroy();

			virtual std::shared_ptr<uml::Package> getPackageValue() const;
			virtual std::shared_ptr<uml::Element> getUmlValue() const;
			virtual void setUmlValue(std::shared_ptr<uml::Element>);
			virtual void setPackageValue(std::shared_ptr<uml::Package>);
			virtual void setThisPackageObjectPtr(std::weak_ptr<PackageObject> thisObjectPtr);
			virtual bool equals(std::shared_ptr<fUML::Semantics::Values::Value> otherValue);
			virtual std::string toString();
			virtual std::shared_ptr<Bag<PSCS::Semantics::StructuredClassifiers::CS_Object>> getDirectContainers();
			virtual void removeValue(std::shared_ptr<uml::StructuralFeature> feature, std::shared_ptr<fUML::Semantics::Values::Value> values);
			virtual std::shared_ptr<Bag<fUML::Semantics::Values::Value>> getValues(std::shared_ptr<uml::StructuralFeature> feature, std::shared_ptr<Bag<fUML::Semantics::SimpleClassifiers::FeatureValue>> featureValues);
			virtual std::shared_ptr<fUML::Semantics::SimpleClassifiers::FeatureValue> retrieveFeatureValue(std::shared_ptr<uml::StructuralFeature> feature);
			virtual void setFeatureValue(std::shared_ptr<uml::StructuralFeature> feature, std::shared_ptr<Bag<fUML::Semantics::Values::Value>> value, int position);
			virtual void assignFeatureValue(std::shared_ptr<uml::StructuralFeature> feature, std::shared_ptr<Bag<fUML::Semantics::Values::Value>> value, int position);
			virtual std::shared_ptr<Bag<fUML::Semantics::SimpleClassifiers::FeatureValue>> retrieveFeatureValues();

			virtual std::shared_ptr<Bag<PSCS::Semantics::StructuredClassifiers::CS_Link>> getLinks(std::shared_ptr<PSCS::Semantics::StructuredClassifiers::CS_InteractionPoint> interactionPoint);
			virtual std::shared_ptr<Bag<fUML::Semantics::Values::Value>> retrieveEndValueAsInteractionPoint(std::shared_ptr<fUML::Semantics::Values::Value> endValue, std::shared_ptr<uml::ConnectorEnd> end);

		protected:
			std::shared_ptr<uml::Package> m_PackageValue = nullptr;
	};
}
#endif /* end of include guard: UML_PACKAGE_OBJECT_HPP */


text:
using UnityEngine;

namespace BehaviorDesigner.Runtime.Tasks.Basic.UnityPlayerPrefs
{
    [TaskCategory("Basic/PlayerPrefs")]
    [TaskDescription("Saves the PlayerPrefs.")]
    public class Save : Action
    {
        public override TaskStatus OnUpdate()
        {
            PlayerPrefs.Save();

            return TaskStatus.Success;
        }
    }
}


text:
package nl.knaw.huygens.timbuctoo.v5.datastores.rssource;

import com.google.common.base.Charsets;
import nl.knaw.huygens.timbuctoo.v5.filestorage.exceptions.LogStorageFailedException;

import javax.ws.rs.core.MediaType;
import java.nio.charset.Charset;

public class ChangesQuadGenerator {
  private final String defaultGraph;

  public ChangesQuadGenerator(String defaultGraph) {
    this.defaultGraph = defaultGraph;
  }

  public String delRelation(String subject, String predicate, String object, String graph) {
    if (graph == null) {
      graph = defaultGraph;
    }
    return "-" + "<" + subject + "> <" + predicate + "> <" + object + "> <" + graph + "> .\n";
  }

  public String delValue(String subject, String predicate, String value, String valueType, String graph) {
    value = escapeCharacters(value);
    if (graph == null) {
      graph = defaultGraph;
    }

    return "-" + "<" + subject + "> <" + predicate + "> \"" + value + "\"^^<" + valueType + "> <" + graph + "> .\n";
  }

  private String escapeCharacters(String value) {
    return value
      .replace("\\", "\\\\")
      .replace("\n", "\\n")
      .replace("\r", "\\r")
      .replace("\"", "\\\"");
  }

  public String delLanguageTaggedString(String subject, String predicate, String value, String language, String graph) {
    value = escapeCharacters(value);
    if (graph == null) {
      graph = defaultGraph;
    }
    return "-" + "<" + subject + "> <" + predicate + "> \"" + value + "\"@" + language + " <" + graph + "> .\n";
  }

  public MediaType getMediaType() {
    return new MediaType("application", "vnd.timbuctoo-rdf.nquads_unified_diff");
  }

  public Charset getCharset() {
    return Charsets.UTF_8;
  }

  public String onRelation(String subject, String predicate, String object, String graph) {
    if (graph == null) {
      graph = defaultGraph;
    }
    return "+" + "<" + subject + "> <" + predicate + "> <" + object + "> <" + graph + "> .\n";
  }

  public String onValue(String subject, String predicate, String value, String valueType, String graph) {
    value = escapeCharacters(value);
    if (graph == null) {
      graph = defaultGraph;
    }
    return "+" + "<" + subject + "> <" + predicate + "> \"" + value + "\"^^<" + valueType + "> <" + graph + "> .\n";
  }

  public String onLanguageTaggedString(String subject, String predicate, String value, String language, String graph) {
    value = escapeCharacters(value);
    if (graph == null) {
      graph = defaultGraph;
    }
    return "+" + "<" + subject + "> <" + predicate + "> \"" + value + "\"@" + language + " <" + graph + "> .\n";
  }
}


text:
/**
* @Author: BingWu Yang <detailyang>
* @Date:   2016-03-11T12:16:28+08:00
* @Email:  detailyang@gmail.com
* @Last modified by:   detailyang
* @Last modified time: 2016-04-21T00:39:01+08:00
* @License: The MIT License (MIT)
*/

import React, { Component } from 'react';
import Antd, { Table, Button, Row, Col, Input, Icon, Popconfirm } from 'antd';
import { connect } from 'react-redux';

import OAuthEditModal from './OAuthEditModal';
import { fetchOAuthList, setOAuthPage, setOAuthKeyword, deleteOAuth } from '../actions';

const InputGroup = Input.Group;

class OAuth extends Component {

  constructor(props) {
    super(props);
    this.state = {
      editModalVisible: false,
      editModalId: 0,
    };
  }

  componentWillMount() {
    this.fetchOAuthList();
  }

  handleCreateClick() {
    this.setState({ editModalVisible: true, editModalId: 0 });
  }

  handleEditClick(record) {
    this.setState({ editModalVisible: true, editModalId: record.id });
  }

  handleDeleteClick(record) {
    this.props.deleteOAuth(record.id)
      .then(() => {
        Antd.message.success('删除成功');
        this.fetchOAuthList();
      })
      .catch(() => {
        Antd.message.error('删除失败');
      });
  }

  handleKeywordKeyDown(e) {
    if (e.key === 'Enter') {
      this.handleSearchClick();
    }
  }

  handleSearchClick() {
    this.fetchOAuthList();
  }

  fetchOAuthList() {
    return this.props.fetchOAuthList()
      .catch(error => Antd.message.error(error.message));
  }

  renderEditModal() {
    if (!this.state.editModalVisible) {
      return '';
    }

    const handleOk = () => {
      this.setState({ editModalVisible: false });
      this.fetchOAuthList();
    };

    const handleCancel = () => {
      this.setState({ editModalVisible: false });
    };

    return (
      <OAuthEditModal
        id={this.state.editModalId}
        visible={this.state.editModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      />);
  }

  renderFilter() {
    const { setOAuthKeyword } = this.props;
    return (
      <Row style={{ marginBottom: '10px' }}>
        <Col span="2">
          <Button type="primary" onClick={::this.handleCreateClick}>
            <Icon type="plus" />新建
          </Button>
        </Col>
        <Col span="4" offset="18">
          <InputGroup className="ant-search-input" size="default">
            <Input
              defaultValue={this.state.keyword}
              onChange={e => { setOAuthKeyword(e.target.value); }}
              onKeyDown={::this.handleKeywordKeyDown}
            />

              <Button className="ant-search-btn" onClick={this.handleSearchClick}>
                <Icon type="search" />
              </Button>

          </InputGroup>
        </Col>
      </Row>
    );
  }

  renderTable() {
    const columns = [
      {
        title: 'id',
        dataIndex: 'id',
        key: 'id',
      }, {
        title: 'name',
        dataIndex: 'name',
        key: 'name',
      }, {
        title: 'domain',
        dataIndex: 'domain',
        key: 'domain',
      }, {
        title: 'callback',
        dataIndex: 'callback',
        key: 'callback',
      }, {
        title: 'secret',
        dataIndex: 'secret',
        key: 'secret',
      }, {
        title: '操作',
        dataIndex: 'x',
        key: 'x',
        render: (value, record) => {
          return (

              <Button
                type="ghost"
                size="small"
                onClick={() => this.handleEditClick(record)}
              >编辑</Button>
              <Popconfirm
                placement="left"
                title="确认删除?"
                onConfirm={() => this.handleDeleteClick(record)}
              >
                <Button type="ghost" size="small">删除</Button>
              </Popconfirm>

          );
        },
      },
    ];

    const {
        OAuth: { list, loading, total, page, per_page },
        setOAuthPage,
      } = this.props;

    list.forEach(item => {
      item.key = item.id;
    });

    const pagination = {
      total,
      current: page,
      pageSize: per_page,
      showTotal: (total) => `共 ${total} 条`,
      onChange: (_page) => {
        setOAuthPage(_page);
        this.fetchOAuthList();
      },
    };

    return (

  );
  }
  render() {
    return (

        {this.renderEditModal()}
        {this.renderFilter()}
        {this.renderTable()}

    );
  }
}

export default connect(
  ({ OAuth }) => ({ OAuth }),
  { fetchOAuthList, setOAuthPage, setOAuthKeyword, deleteOAuth }
)(OAuth);


text:
/**
 * Created by Primoz on 19.7.2016.
 */

app.service("InputService", function () {

    this.multiplier = 5;

    // region KEYBOARD ACTIONS
    this.ACTION = {
        ROT_X_NEG: 0,
        ROT_X_POS: 1,
        ROT_Y_NEG: 2,
        ROT_Y_POS: 3,
        ROT_Z_NEG: 4,
        ROT_Z_POS: 5,

        MV_X_NEG: 6,
        MV_X_POS: 7,
        MV_Y_NEG: 8,
        MV_Y_POS: 9,
        MV_Z_NEG: 10,
        MV_Z_POS: 11,
    };
    // endregion

    // region DEFAULT KEYMAP INIT
    this.DEFAULT_KEYMAP = {};
    this.DEFAULT_KEYMAP[83] = this.ACTION.ROT_X_NEG; // S
    this.DEFAULT_KEYMAP[87] = this.ACTION.ROT_X_POS; // W

    this.DEFAULT_KEYMAP[68] = this.ACTION.ROT_Y_NEG; // D
    this.DEFAULT_KEYMAP[65] = this.ACTION.ROT_Y_POS; // A

    this.DEFAULT_KEYMAP[69] = this.ACTION.ROT_Z_NEG; // R
    this.DEFAULT_KEYMAP[81] = this.ACTION.ROT_Z_POS; // Q

    this.DEFAULT_KEYMAP[37] = this.ACTION.MV_X_NEG; // LEFT ARROW
    this.DEFAULT_KEYMAP[39] = this.ACTION.MV_X_POS; // RIGHT ARROW

    this.DEFAULT_KEYMAP[38] = this.ACTION.MV_Z_NEG; // UP ARROW
    this.DEFAULT_KEYMAP[40] = this.ACTION.MV_Z_POS; // DOWN ARROW

    this.DEFAULT_KEYMAP[70] = this.ACTION.MV_Y_NEG; // R
    this.DEFAULT_KEYMAP[82] = this.ACTION.MV_Y_POS; // F
    // endregion

    // Holds currently active keyboard keymap
    this.activeKeymap = JSON.parse(JSON.stringify(this.DEFAULT_KEYMAP));

    let self = this;

    // Reference to the keyboard controller singleton
    let keyboardManager = M3D.KeyboardInput.instance;

    // Reference to the gamepad controller singleton
    let gamepadManager = M3D.GamepadInput.instance;

    // Reference to the mouse controller singleton
    let mouseManager = M3D.MouseInput.instance;

    // Structures used to hold navigators input data
    this.navigatorsInput = {
        rotation: new THREE.Vector3(0, 0, 0),
        translation: new THREE.Vector3(0, 0, 0),
        reset: function () {
            this.rotation.set(0, 0, 0);
            this.translation.set(0, 0, 0);
        }
    };

    let keyboardInput = new Set();
    let inputData = null;

    // Updates and returns combined input values
    this.update = function () {
        keyboardInput.clear();

        // Map the keys into actions using the active keymap
        let pressedKeys = Array.from(keyboardManager.update());

        for (let i = 0; i < pressedKeys.length; i++) {
            let action = self.activeKeymap[pressedKeys[i]];

            if (action != null) {
                keyboardInput.add(action);
            }
        }

        // Combine input data
        inputData = { keyboard: keyboardInput,
                      mouse: mouseManager.update(),
                      gamepads: gamepadManager.update(),
                      navigators: self.navigatorsInput,
                      multiplier: self.multiplier };

        return inputData;
    };

    /**
     * Animation loop should call update before calling this function
     * @returns {*} inputData
     */
    this.getInputData = function () {
        return inputData;
    };

    this.setMouseSourceObject = function (object) {
        mouseManager.setSourceObject(object);
    }
});


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>

        <a href="<?= base_url();?>">STEMS CPanel

         <?php if($this->session->flashdata('msg') != ''){?>

Login Failure

              <?php echo $this->session->flashdata('msg');?>

<?php  }?>

        <form action="<?= base_url();?>" method="post" autocomplete="off">

            <input type="text" name="email" class="form-control" placeholder="Login ID">

            <input type="password" name="password" class="form-control" placeholder="Login PIN">

                 <input type="checkbox"> Remember Me

              <button type="submit" class="btn btn-success btn-block btn-flat">Sign In</button>

        </form>

- OR -

           Go to API Docs


text:
include $(POCO_BASE)/build/rules/global

objects = SampleApp

target         = SampleApp
target_version = 1
target_libs    = PocoUtil PocoXML PocoFoundation

include $(POCO_BASE)/build/rules/exec


text:
namespace lua
{
	enum class error
	{
		success = 0,
		run = LUA_ERRRUN,
		syntax = LUA_ERRSYNTAX,
		mem = LUA_ERRMEM,
		err = LUA_ERRERR,

		///extra error code returned by luaL_loadfile
		file = LUA_ERRFILE
	};

	struct lua_error_category : boost::system::error_category
	{
		virtual const char *name() const BOOST_SYSTEM_NOEXCEPT SILICIUM_OVERRIDE;
		virtual std::string message(int ev) const SILICIUM_OVERRIDE;
	};

	inline const char *lua_error_category::name() const BOOST_SYSTEM_NOEXCEPT
	{
		return "lua";
	}

	inline std::string lua_error_category::message(int ev) const
	{
		switch (ev)
		{
		case LUA_ERRMEM: return "LUA_ERRMEM";
		case LUA_ERRRUN: return "LUA_ERRRUN";
		case LUA_ERRSYNTAX: return "LUA_ERRSYNTAX";
		case LUA_ERRERR: return "LUA_ERRERR";
		}
		return "";
	}

	inline boost::system::error_category const &get_lua_error_category()
	{
		static lua_error_category const instance;
		return instance;
	}
}

#endif


text:
IMPLEMENT_CONOBJECT(GuiMissionAreaEditorCtrl);

ConsoleDocClass( GuiMissionAreaEditorCtrl,
   "@brief Specialized GUI used for editing the MissionArea in a level\n\n"
   "Editor use only.\n\n"
   "@internal"
);

GuiMissionAreaEditorCtrl::GuiMissionAreaEditorCtrl()
{
}

GuiMissionAreaEditorCtrl::~GuiMissionAreaEditorCtrl()
{
}

bool GuiMissionAreaEditorCtrl::onAdd()
{
   if( !Parent::onAdd() )
      return false;

   return true;
}

void GuiMissionAreaEditorCtrl::initPersistFields()
{
   Parent::initPersistFields();
}

void GuiMissionAreaEditorCtrl::get3DCursor( GuiCursor *&cursor,
                                       bool &visible,
                                       const Gui3DMouseEvent &event_ )
{
   //cursor = mAddNodeCursor;
   //visible = false;

   cursor = NULL;
   visible = false;

   GuiCanvas *root = getRoot();
   if ( !root )
      return;

   S32 currCursor = PlatformCursorController::curArrow;

   if ( root->mCursorChanged == currCursor )
      return;

   PlatformWindow *window = root->getPlatformWindow();
   PlatformCursorController *controller = window->getCursorController();

   // We've already changed the cursor,
   // so set it back before we change it again.
   if( root->mCursorChanged != -1)
      controller->popCursor();

   // Now change the cursor shape
   controller->pushCursor(currCursor);
   root->mCursorChanged = currCursor;
}

void GuiMissionAreaEditorCtrl::setSelectedMissionArea( MissionArea *missionArea )
{
   mSelMissionArea = missionArea;

   if ( mSelMissionArea != NULL )
      Con::executef( this, "onMissionAreaSelected", missionArea->getIdString() );
   else
      Con::executef( this, "onMissionAreaSelected" );
}

DefineEngineMethod( GuiMissionAreaEditorCtrl, setSelectedMissionArea, void, (const char * missionAreaName), (""), "" )
{
   if ( dStrcmp( missionAreaName, "" )==0 )
      object->setSelectedMissionArea(NULL);
   else
   {
      MissionArea *missionArea = NULL;
      if ( Sim::findObject( missionAreaName, missionArea ) )
         object->setSelectedMissionArea(missionArea);
   }
}

DefineEngineMethod( GuiMissionAreaEditorCtrl, getSelectedMissionArea, const char*, (), , "" )
{
   MissionArea *missionArea = object->getSelectedMissionArea();
   if ( !missionArea )
      return NULL;

   return missionArea->getIdString();
}


text:
struct Result {

    // data members
    std::vector<int> FragmentLengths;
    std::vector<int> ReadLengths;

    // ctors & dtor
    Result(void) { }
    Result(const Result& other)
        : FragmentLengths(other.FragmentLengths)
        , ReadLengths(other.ReadLengths)
    { }
    ~Result(void) { }
};

#endif // RESULT_H


text:
package source

import (
	"io"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"

	"github.com/anchore/stereoscope/pkg/file"
)

func TestExcludingResolver(t *testing.T) {

	tests := []struct {
		name      string
		locations []string
		excludeFn excludeFn
		expected  []string
	}{
		{
			name:      "keeps locations",
			locations: []string{"a", "b", "c"},
			excludeFn: func(s string) bool {
				return false
			},
			expected: []string{"a", "b", "c"},
		},
		{
			name:      "removes locations",
			locations: []string{"d", "e", "f"},
			excludeFn: func(s string) bool {
				return true
			},
			expected: []string{},
		},
		{
			name:      "removes first match",
			locations: []string{"g", "h", "i"},
			excludeFn: func(s string) bool {
				return s == "g"
			},
			expected: []string{"h", "i"},
		},
		{
			name:      "removes last match",
			locations: []string{"j", "k", "l"},
			excludeFn: func(s string) bool {
				return s == "l"
			},
			expected: []string{"j", "k"},
		},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			resolver := &mockResolver{
				locations: test.locations,
			}
			excludingResolver := NewExcludingResolver(resolver, test.excludeFn)

			locations, _ := excludingResolver.FilesByPath()
			assert.ElementsMatch(t, locationPaths(locations), test.expected)

			locations, _ = excludingResolver.FilesByGlob()
			assert.ElementsMatch(t, locationPaths(locations), test.expected)

			locations, _ = excludingResolver.FilesByMIMEType()
			assert.ElementsMatch(t, locationPaths(locations), test.expected)

			locations = []Location{}

			channel := excludingResolver.AllLocations()
			for location := range channel {
				locations = append(locations, location)
			}
			assert.ElementsMatch(t, locationPaths(locations), test.expected)

			diff := difference(test.locations, test.expected)

			for _, path := range diff {
				assert.False(t, excludingResolver.HasPath(path))
				c, err := excludingResolver.FileContentsByLocation(makeLocation(path))
				assert.Nil(t, c)
				assert.Error(t, err)
				m, err := excludingResolver.FileMetadataByLocation(makeLocation(path))
				assert.Empty(t, m.LinkDestination)
				assert.Error(t, err)
				l := excludingResolver.RelativeFileByPath(makeLocation(""), path)
				assert.Nil(t, l)
			}

			for _, path := range test.expected {
				assert.True(t, excludingResolver.HasPath(path))
				c, err := excludingResolver.FileContentsByLocation(makeLocation(path))
				assert.NotNil(t, c)
				assert.Nil(t, err)
				m, err := excludingResolver.FileMetadataByLocation(makeLocation(path))
				assert.NotEmpty(t, m.LinkDestination)
				assert.Nil(t, err)
				l := excludingResolver.RelativeFileByPath(makeLocation(""), path)
				assert.NotNil(t, l)
			}
		})
	}
}

// difference returns the elements in `a` that aren't in `b`.
func difference(a, b []string) []string {
	mb := make(map[string]struct{}, len(b))
	for _, x := range b {
		mb[x] = struct{}{}
	}
	var diff []string
	for _, x := range a {
		if _, found := mb[x]; !found {
			diff = append(diff, x)
		}
	}
	return diff
}

func makeLocation(path string) Location {
	return Location{
		Coordinates: Coordinates{
			RealPath:     path,
			FileSystemID: "",
		},
		VirtualPath: "",
		ref:         file.Reference{},
	}
}

func locationPaths(locations []Location) []string {
	paths := []string{}
	for _, l := range locations {
		paths = append(paths, l.RealPath)
	}
	return paths
}

type mockResolver struct {
	locations []string
}

func (r *mockResolver) getLocations() ([]Location, error) {
	out := []Location{}
	for _, path := range r.locations {
		out = append(out, makeLocation(path))
	}
	return out, nil
}

func (r *mockResolver) FileContentsByLocation(_ Location) (io.ReadCloser, error) {
	return io.NopCloser(strings.NewReader("Hello, world!")), nil
}

func (r *mockResolver) FileMetadataByLocation(_ Location) (FileMetadata, error) {
	return FileMetadata{
		LinkDestination: "MOCK",
	}, nil
}

func (r *mockResolver) HasPath(_ string) bool {
	return true
}

func (r *mockResolver) FilesByPath(_ ...string) ([]Location, error) {
	return r.getLocations()
}

func (r *mockResolver) FilesByGlob(_ ...string) ([]Location, error) {
	return r.getLocations()
}

func (r *mockResolver) FilesByMIMEType(_ ...string) ([]Location, error) {
	return r.getLocations()
}

func (r *mockResolver) RelativeFileByPath(_ Location, path string) *Location {
	return &Location{
		Coordinates: Coordinates{
			RealPath: path,
		},
	}
}

func (r *mockResolver) AllLocations() <-chan Location {
	c := make(chan Location)
	go func() {
		defer close(c)
		locations, _ := r.getLocations()
		for _, location := range locations {
			c <- location
		}
	}()
	return c
}


text: rustup run nightly cargo build --no-default-features --features unstable


text:
angular.module('run.controller', [])

.controller('RunController',
  function ($scope, $timeout, $interval, $window,
            $location, $route, Geo, Run, Profile) {

  $scope.userLocation;
  $scope.destination;
  $scope.hasHours = true;

  var startTime;
  var runTime;
  var statusUpdateLoop;
  var startLat;
  var startLong;
  var FINISH_RADIUS = 0.0002; // miles?

  // Math functions
  var sqrt = Math.sqrt;
  var floor = Math.floor;
  var random = Math.random;
  var pow2 = function (num) {
    return Math.pow(num, 2);
  };

  // Update run timer
  var updateTotalRunTime = function () {
    var secondsRan = moment().diff(startTime, 'seconds');
    runTime = moment().minute(0).second(secondsRan);
  };

  // Define waiting messages for the user while Google maps loads...
  var messages = [
    "Finding the best route for you",
    "Scanning the streets",
    "Charging runtime engine",
    "Looking into the eye of the tiger"
  ];

  var setRunMessage = function () {
    $scope.runMessage = messages[floor(random() * messages.length)] + "...";
  };

  // Display random waiting message
  $interval(setRunMessage, random() * 1000, messages.length);

  $scope.startRun = function () {
    // Simulate finishing run for manual testing
    // setTimeout(finishRun, 4000); // simulate finishing run for manual testing
    startTime = moment();
    $scope.raceStarted = true;
    statusUpdateLoop = $interval(updateStatus, 100);
    Run.setPointsInTime($scope);
    Run.setInitialMedalGoal($scope);
    document.getElementById('map').style.height = "93vh";
    document.getElementById('botNav').style.height = "7vh";
  };

  // Generate a new map or route after initial map has been loaded
  $scope.regenRace = function () {
    $route.reload();
  };

  // Generates google map with current location marker and run route details
  var makeInitialMap = function () {
    Geo.makeInitialMap($scope);
  };

  makeInitialMap();

  // Handle end run conditions. Update user profile to reflect latest run.
  var finishRun = function () {
    $scope.$parent.runTime = runTime.format('mm:ss');
    var medal = $scope.$parent.achievement = $scope.currentMedal;

    var date = new Date();

    var endLocation = {
      latitude: $scope.destination.lat,
      longitude: $scope.destination.long
    };
    var googleExpectedTime = null;
    var actualTime = runTime;

    var currentRunObject = {
      date: date,
      startLocation: {
        longitude: null,
        latitude: null
      },
      endLocation: {
        longitude: $scope.destination.long,
        latitude: $scope.destination.lat
      },
      googleExpectedTime: null,
      actualTime: runTime,
      medalReceived: medal,
      racedAgainst: null
    };

    // Update current user's profile
    Profile.getUser()
    .then(function (user) {
      var achievements = user.achievements;
      var previousRuns = user.runs;
      //update achievments object
      achievements[medal] = achievements[medal] + 1;
      $window.localStorage.setItem('achievements', JSON.stringify(achievements));
      //update runs object
      previousRuns.push(currentRunObject);
      updatedAchievementsData = {
        achievements: achievements,
        runs: previousRuns
      };
      Profile.updateUser(updatedAchievementsData, user)
      .then(function (updatedProfile) {
        return updatedProfile;
      })
      .catch(function (err) {
        console.error(err);
      });
    });

    $interval.cancel(statusUpdateLoop);
    $location.path('/finish');
  };

  // Check if user is in close proximity to destination
  var checkIfFinished = function () {
    if ($scope.destination && $scope.userLocation) {
      var distRemaining = distBetween($scope.userLocation, $scope.destination);
      if (distRemaining < FINISH_RADIUS) {
        finishRun();
      }
    }
  };

  // Calculate distance between two coordinates
  var distBetween = function (loc1, loc2) {
    return sqrt(pow2(loc1.lat - loc2.lat) + pow2(loc1.lng - loc2.lng));
  };

  // Update geographical location and timers
  var updateStatus = function () {
    Geo.updateCurrentPosition($scope);
    updateTotalRunTime();
    Run.updateGoalTimes($scope);
    checkIfFinished();
  };

  // Stop geotracker upon canceling run
  // Does this make sure to stop tracking if they close the window? --> all scripts die when the browser is no longer interpreting them
  $scope.$on('$destroy', function () {
    $interval.cancel(statusUpdateLoop);
  });
});


text:
from sys import argv

script, fileName = argv

fileHandle = open(fileName)

print("file:", fileName)
fileContent = fileHandle.read()
print(fileContent)
fileContent2 = fileHandle.read()

print("Content read 2: %r" % fileContent2)


text:
cask 'gitmoji' do
  version '1.0.1'
  sha256 '7961f9be82688c98cc62d0df70b59251d94848c9b6669a6a39d6ae4fc7ad10d1'

  url "https://github.com/Meadowcottage/gitmoji/releases/download/#{version}/Gitmoji-#{version}.dmg"
  appcast 'https://github.com/Meadowcottage/gitmoji/releases.atom',
          checkpoint: '61237d048c9f1a59aa553afd7d9b633b9efe9af17be1bdea8f9242c3248cc0f7'
  name 'gitmoji'
  homepage 'https://github.com/Meadowcottage/gitmoji'

  app 'gitmoji.app'

  zap trash: [
               '~/Library/Application Support/gitmoji',
               '~/Library/Preferences/com.Meadowcottage.Gitmoji.helper.plist',
               '~/Library/Preferences/com.Meadowcottage.Gitmoji.plist',
               '~/Library/Saved Application State/com.Meadowcottage.Gitmoji.savedState',
             ]
end