text:
#ifndef SoftLinking_h
#define SoftLinking_h

#include <windows.h>
#include <wtf/Assertions.h>

#pragma mark - Soft-link helper macros

#define SOFT_LINK_LIBRARY_HELPER(lib, suffix) \
    static HMODULE lib##Library() \
    { \
        static HMODULE library = LoadLibraryW(L###lib suffix); \
        return library; \
    }

#define SOFT_LINK_GETPROCADDRESS GetProcAddress
#define SOFT_LINK_LIBRARY(lib) SOFT_LINK_LIBRARY_HELPER(lib, L".dll")
#define SOFT_LINK_DEBUG_LIBRARY(lib) SOFT_LINK_LIBRARY_HELPER(lib, L"_debug.dll")

#pragma mark - Soft-link macros for use within a single source file

#define SOFT_LINK(library, functionName, resultType, callingConvention, parameterDeclarations, parameterNames) \
    static resultType callingConvention init##functionName parameterDeclarations; \
    static resultType (callingConvention*softLink##functionName) parameterDeclarations = init##functionName; \
    \
    static resultType callingConvention init##functionName parameterDeclarations \
    { \
        softLink##functionName = reinterpret_cast<resultType (callingConvention*) parameterDeclarations>(SOFT_LINK_GETPROCADDRESS(library##Library(), #functionName)); \
        ASSERT(softLink##functionName); \
        return softLink##functionName parameterNames; \
    } \
    \
    inline resultType functionName parameterDeclarations \
    { \
        return softLink##functionName parameterNames; \
    }

#define SOFT_LINK_OPTIONAL(library, functionName, resultType, callingConvention, parameterDeclarations) \
    typedef resultType (callingConvention *functionName##PtrType) parameterDeclarations; \
    static functionName##PtrType functionName##Ptr() \
    { \
        static functionName##PtrType ptr; \
        static bool initialized; \
        \
        if (initialized) \
            return ptr; \
        initialized = true; \
        \
        ptr = reinterpret_cast<functionName##PtrType>(SOFT_LINK_GETPROCADDRESS(library##Library(), #functionName)); \
        return ptr; \
    } \

#define SOFT_LINK_LOADED_LIBRARY(library, functionName, resultType, callingConvention, parameterDeclarations) \
    typedef resultType (callingConvention *functionName##PtrType) parameterDeclarations; \
    static functionName##PtrType functionName##Ptr() \
    { \
        static functionName##PtrType ptr; \
        static bool initialized; \
        \
        if (initialized) \
            return ptr; \
        initialized = true; \
        \
        static HINSTANCE libraryInstance = ::GetModuleHandle(L#library); \
        \
        ptr = reinterpret_cast<functionName##PtrType>(SOFT_LINK_GETPROCADDRESS(libraryInstance, #functionName)); \
        return ptr; \
    } \

/*
    In order to soft link against functions decorated with __declspec(dllimport), we prepend "softLink_" to the function names.
    If you use SOFT_LINK_DLL_IMPORT(), you will also need to #define the function name to account for this, e.g.:

    SOFT_LINK_DLL_IMPORT(myLibrary, myFunction, ...)
    #define myFunction softLink_myFunction
*/
#define SOFT_LINK_DLL_IMPORT(library, functionName, resultType, callingConvention, parameterDeclarations, parameterNames) \
    static resultType callingConvention init##functionName parameterDeclarations; \
    static resultType(callingConvention*softLink##functionName) parameterDeclarations = init##functionName; \
    \
    static resultType callingConvention init##functionName parameterDeclarations \
    { \
        softLink##functionName = reinterpret_cast<resultType (callingConvention*)parameterDeclarations>(SOFT_LINK_GETPROCADDRESS(library##Library(), #functionName)); \
        ASSERT(softLink##functionName); \
        return softLink##functionName parameterNames; \
    } \
    \
    inline resultType softLink_##functionName parameterDeclarations \
    { \
        return softLink##functionName parameterNames; \
    }

#define SOFT_LINK_DLL_IMPORT_OPTIONAL(library, functionName, resultType, callingConvention, parameterDeclarations) \
    typedef resultType (callingConvention *functionName##PtrType) parameterDeclarations; \
    static functionName##PtrType functionName##Ptr() \
    { \
        static functionName##PtrType ptr; \
        static bool initialized; \
        \
        if (initialized) \
            return ptr; \
        initialized = true; \
        \
        ptr = reinterpret_cast<resultType(callingConvention*)parameterDeclarations>(SOFT_LINK_GETPROCADDRESS(library##Library(), #functionName)); \
        return ptr; \
    } \

#define SOFT_LINK_DLL_IMPORT_OPTIONAL(library, functionName, resultType, callingConvention, parameterDeclarations) \
    typedef resultType (callingConvention *functionName##PtrType) parameterDeclarations; \
    static functionName##PtrType functionName##Ptr() \
    { \
        static functionName##PtrType ptr; \
        static bool initialized; \
        \
        if (initialized) \
            return ptr; \
        initialized = true; \
        \
        ptr = reinterpret_cast<resultType(callingConvention*)parameterDeclarations>(SOFT_LINK_GETPROCADDRESS(library##Library(), #functionName)); \
        return ptr; \
    } \

/*
    Variables exported by a DLL need to be accessed through a function.
    If you use SOFT_LINK_VARIABLE_DLL_IMPORT(), you will also need to #define the variable name to account for this, e.g.:

    SOFT_LINK_VARIABLE_DLL_IMPORT(myLibrary, myVar, int)
    #define myVar get_myVar()
*/
#define SOFT_LINK_VARIABLE_DLL_IMPORT(library, variableName, variableType) \
    static variableType get##variableName() \
    { \
        static variableType* ptr = reinterpret_cast<variableType*>(SOFT_LINK_GETPROCADDRESS(library##Library(), #variableName)); \
        ASSERT(ptr); \
        return *ptr; \
    } \

/*
    Note that this will only work for variable types for which a return value of 0 can signal an error.
 */
#define SOFT_LINK_VARIABLE_DLL_IMPORT_OPTIONAL(library, variableName, variableType) \
    static variableType get##variableName() \
    { \
        static variableType* ptr = reinterpret_cast<variableType*>(SOFT_LINK_GETPROCADDRESS(library##Library(), #variableName)); \
        if (!ptr) \
            return 0; \
        return *ptr; \
    } \

#pragma mark - Soft-link macros for sharing across multiple source files

// See Source/WebCore/platform/cf/CoreMediaSoftLink.{cpp,h} for an example implementation.

#define SOFT_LINK_FRAMEWORK_FOR_HEADER(functionNamespace, framework) \
    namespace functionNamespace { \
    extern HMODULE framework##Library(bool isOptional = false); \
    bool is##framework##FrameworkAvailable(); \
    inline bool is##framework##FrameworkAvailable() { \
        return framework##Library(true) != nullptr; \
    } \
    }

#define SOFT_LINK_FRAMEWORK_HELPER(functionNamespace, framework, suffix) \
    namespace functionNamespace { \
    HMODULE framework##Library(bool isOptional = false); \
    HMODULE framework##Library(bool isOptional) \
    { \
        static HMODULE library = LoadLibraryW(L###framework suffix); \
        ASSERT_WITH_MESSAGE_UNUSED(isOptional, isOptional || library, "Could not load %s", L###framework suffix); \
        return library; \
    } \
    }

#define SOFT_LINK_FRAMEWORK(functionNamespace, framework) SOFT_LINK_FRAMEWORK_HELPER(functionNamespace, framework, L".dll")
#define SOFT_LINK_DEBUG_FRAMEWORK(functionNamespace, framework) SOFT_LINK_FRAMEWORK_HELPER(functionNamespace, framework, L"_debug.dll")

#ifdef DEBUG_ALL
#define SOFT_LINK_FRAMEWORK_FOR_SOURCE(functionNamespace, framework) SOFT_LINK_DEBUG_FRAMEWORK(functionNamespace, framework)
#else
#define SOFT_LINK_FRAMEWORK_FOR_SOURCE(functionNamespace, framework) SOFT_LINK_FRAMEWORK(functionNamespace, framework)
#endif

#define SOFT_LINK_CONSTANT_FOR_HEADER(functionNamespace, framework, variableName, variableType) \
    namespace functionNamespace { \
    variableType get_##framework##_##variableName(); \
    }

#define SOFT_LINK_CONSTANT_FOR_SOURCE(functionNamespace, framework, variableName, variableType) \
    namespace functionNamespace { \
    static void init##framework##variableName(void* context) { \
        variableType* ptr = reinterpret_cast<variableType*>(SOFT_LINK_GETPROCADDRESS(framework##Library(), #variableName)); \
        RELEASE_ASSERT(ptr); \
        *static_cast<variableType*>(context) = *ptr; \
    } \
    variableType get_##framework##_##variableName(); \
    variableType get_##framework##_##variableName() \
    { \
        static variableType constant##framework##variableName; \
        static dispatch_once_t once; \
        dispatch_once_f(&once, static_cast<void*>(&constant##framework##variableName), init##framework##variableName); \
        return constant##framework##variableName; \
    } \
    }

#define SOFT_LINK_CONSTANT_MAY_FAIL_FOR_HEADER(functionNamespace, framework, variableName, variableType) \
    namespace functionNamespace { \
    bool canLoad_##framework##_##variableName(); \
    bool init_##framework##_##variableName(); \
    variableType get_##framework##_##variableName(); \
    }

#define SOFT_LINK_CONSTANT_MAY_FAIL_FOR_SOURCE(functionNamespace, framework, variableName, variableType) \
    namespace functionNamespace { \
    static variableType constant##framework##variableName; \
    bool init_##framework##_##variableName(); \
    bool init_##framework##_##variableName() \
    { \
        variableType* ptr = reinterpret_cast<variableType*>(SOFT_LINK_GETPROCADDRESS(framework##Library(), #variableName)); \
        if (!ptr) \
            return false; \
        constant##framework##variableName = *ptr; \
        return true; \
    } \
    bool canLoad_##framework##_##variableName(); \
    bool canLoad_##framework##_##variableName() \
    { \
        static bool loaded = init_##framework##_##variableName(); \
        return loaded; \
    } \
    variableType get_##framework##_##variableName(); \
    variableType get_##framework##_##variableName() \
    { \
        return constant##framework##variableName; \
    } \
    }

#define SOFT_LINK_FUNCTION_FOR_HEADER(functionNamespace, framework, functionName, resultType, parameterDeclarations, parameterNames) \
    namespace functionNamespace { \
    extern resultType(__cdecl*softLink##framework##functionName) parameterDeclarations; \
    inline resultType softLink_##framework##_##functionName parameterDeclarations \
    { \
        return softLink##framework##functionName parameterNames; \
    } \
    }

#define SOFT_LINK_FUNCTION_FOR_SOURCE(functionNamespace, framework, functionName, resultType, parameterDeclarations, parameterNames) \
    namespace functionNamespace { \
    static resultType __cdecl init##framework##functionName parameterDeclarations; \
    resultType(__cdecl*softLink##framework##functionName) parameterDeclarations = init##framework##functionName; \
    static resultType __cdecl init##framework##functionName parameterDeclarations \
    { \
        softLink##framework##functionName = reinterpret_cast<resultType (__cdecl*)parameterDeclarations>(SOFT_LINK_GETPROCADDRESS(framework##Library(), #functionName)); \
        RELEASE_ASSERT(softLink##framework##functionName); \
        return softLink##framework##functionName parameterNames; \
    } \
    }

#define SOFT_LINK_FUNCTION_MAY_FAIL_FOR_HEADER(functionNamespace, framework, functionName, resultType, parameterDeclarations, parameterNames) \
    WTF_EXTERN_C_BEGIN \
    resultType functionName parameterDeclarations; \
    WTF_EXTERN_C_END \
    namespace functionNamespace { \
    extern resultType (*softLink##framework##functionName) parameterDeclarations; \
    bool canLoad_##framework##_##functionName(); \
    bool init_##framework##_##functionName(); \
    resultType softLink_##framework##_##functionName parameterDeclarations; \
    }

#define SOFT_LINK_FUNCTION_MAY_FAIL_FOR_SOURCE(functionNamespace, framework, functionName, resultType, parameterDeclarations, parameterNames) \
    WTF_EXTERN_C_BEGIN \
    resultType functionName parameterDeclarations; \
    WTF_EXTERN_C_END \
    namespace functionNamespace { \
    resultType (*softLink##framework##functionName) parameterDeclarations = 0; \
    bool init_##framework##_##functionName(); \
    bool init_##framework##_##functionName() \
    { \
        ASSERT(!softLink##framework##functionName); \
        softLink##framework##functionName = reinterpret_cast<resultType (__cdecl*)parameterDeclarations>(SOFT_LINK_GETPROCADDRESS(framework##Library(), #functionName)); \
        return !!softLink##framework##functionName; \
    } \
    \
    bool canLoad_##framework##_##functionName(); \
    bool canLoad_##framework##_##functionName() \
    { \
        static bool loaded = init_##framework##_##functionName(); \
        return loaded; \
    } \
    \
    resultType softLink_##framework##_##functionName parameterDeclarations; \
    resultType softLink_##framework##_##functionName parameterDeclarations \
    { \
        ASSERT(softLink##framework##functionName); \
        return softLink##framework##functionName parameterNames; \
    } \
    }

#endif // SoftLinking_h


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

<link rel="stylesheet" type="text/css" href="../../docs/css/style.css"/>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>

<title>Apache JMeter - User's Manual: Building a Monitor Test Plan</title>

Index

Next

Prev

13. Building a Monitor Test Plan

In this section, you will learn how to create a

Test Plan

 to monitor webservers. Monitors
are useful for a stress testing and system management. Used with stress
testing, the monitor provides additional information about server performance.
It also makes it easier to see the relationship between server performance
and response time on the client side. As a system administration tool, the
monitor provides an easy way to monitor multiple servers from one console.
The monitor was designed to work with the status servlet in Tomcat 5. In
theory, any servlet container that supports JMX (Java Management Extension)
can port the status servlet to provide the same information.

For those who want to use the monitor with other servlet or EJB containers,
Tomcat's status servlet should work with other containers for the memory
statistics without any modifications. To get thread information, you will
need to change the MBeanServer lookup to retrieve the correct MBeans.

13.1 Adding A Server

The first step is to add a

Thread Group

element.  The Thread Group tells JMeter the number of threads you want. Always use
1, since we are using JMeter as a monitor. This is very important for those not
familiar with server monitors. As a general rule, using multiple threads for a
single server is bad and can create significant stress.

Go ahead and add the ThreadGroup element by first selecting the Test Plan,
clicking your right mouse button to get the Add menu, and then select
Add --> ThreadGroup.

You should now see the Thread Group element under Test Plan.  If you do not
see the element, "expand" the Test Plan tree by clicking on the Test Plan element.

Figure 13.1. Thread Group with Default Values

Change the loop count to forever (or some large number) so that enough samples are generated.

13.2 HTTP Auth Manager

Add the
HTTP Authorization Manager
 to the Thread Group element
(Add --> Config element --> HTTP Authorization Manager). Enter the username
and password for your webserver. Important note: the monitor only works with
Tomcat5 build 5.0.19 and newer. For instructions on how to setup Tomcat, please
refer to tomcat 5 documentation.

 leave the base URL blank

 enter the username

 enter the password

13.3 Adding HTTP Request

Add the
HTTP Request
 to the Thread Group element
(Add --> Sampler --> HTTP Request). Then, select the HTTP Request element
in the tree and edit the following properties):

Change the Name field to "Server Status".

Enter the IP address or Hostname

Enter the port number

Set the Path field to "/manager/status" if you're using Tomcat.

Add a request parameter named "XML" in uppercase. Give it a value of
"true" in lowercase.

Check "Use as Monitor" at the bottom of the sampler

13.4 Adding Constant Timer

Add a timer to this thread group (Add --> Timer --> Constant Timer).
Enter 5000 milliseconds in the "Thread Delay" box. In general, using intervals shorter
than 5 seconds will add stress to your server. Find out what is an acceptable interval
before you deploy the monitor in your production environment.

13.5 Adding a Listener to Store the Results

If you want to save the raw results from the server, add a simple data

Listener

. If you want to save the
 calculated statistics, enter a filename in the listener. If you want to save both
 the raw data and statistics, make sure you use different filenames.

Select the thread group element and add a
Simple Data Writer
 listener
(Add --> Listener --> Simple Data Writer).  Next, you need to specify a directory
and filename of the output file.  You can either type it into the filename field, or
select the Browse button and browse to a directory and then enter a filename.

13.6 Adding Monitor Results

Add the

Listener

 by selecting the
test plan element (Add --> Listener -- > Monitor Results).

By default, the Listener will select the results from the first connector in the sample response.
The Connector prefix field can be used to select a different connector.
If specified, the Listener will choose the first connector which matches the prefix.
If no match is found, then the first connector is selected.

There are two tabs in
the monitor results listener. The first is the "Health", which displays the status of
the last sample the monitor received. The second tab is "Performance", which shows a
historical view of the server's performance.

A quick note about how health is calculated. Typically, a server will crash if
it runs out of memory, or reached the maximum number of threads. In the case of
Tomcat 5, once the threads are maxed out, requests are placed in a queue until a
thread is available. The relative importance of threads vary between containers, so
the current implementation uses 50/50 to be conservative. A container that is more
efficient with thread management might not see any performance degradation, but
the used memory definitely will show an impact.

The performance graph shows four different lines. The free memory line shows how
much free memory is left in the current allocated block. Tomcat 5 returns the maximum
memory, but it is not graphed. In a well tuned environment, the server should never
reach the maximum memory.

Note the graph has captions on both sides of the graph. On the left is percent and
the right is dead/healthy. If the memory line spikes up and down rapidly, it could
indicate memory thrashing. In those situations, it is a good idea to profile the
application with Borland OptimizeIt or JProbe. What you want to see is a regular
pattern for load, memory and threads. Any erratic behavior usually indicates poor
performance or a bug of some sort.

Index

Next

Prev

Copyright © 1999-2014, Apache Software Foundation

$Id: build-monitor-test-plan.xml 1392938 2012-10-02 14:46:26Z pmouawad $

Apache, Apache JMeter, JMeter, the Apache feather, and the Apache JMeter logo are
trademarks of the Apache Software Foundation.

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace React\Promise;

use React\Promise\PromiseAdapter\CallbackPromiseAdapter;

class DeferredTest extends TestCase
{
    use PromiseTest\FullTestTrait;

    public function getPromiseTestAdapter(callable $canceller = null)
    {
        $d = new Deferred($canceller);

        return new CallbackPromiseAdapter([
            'promise' => [$d, 'promise'],
            'resolve' => [$d, 'resolve'],
            'reject'  => [$d, 'reject'],
            'notify'  => [$d, 'progress'],
            'settle'  => [$d, 'resolve'],
        ]);
    }

    /** @test */
    public function progressIsAnAliasForNotify()
    {
        $deferred = new Deferred();

        $sentinel = new \stdClass();

        $mock = $this->createCallableMock();
        $mock
            ->expects($this->once())
            ->method('__invoke')
            ->with($sentinel);

        $deferred->promise()
            ->then($this->expectCallableNever(), $this->expectCallableNever(), $mock);

        $deferred->progress($sentinel);
    }
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <event2/event.h>

#include "t2u.h"
#include "t2u_internal.h"

#define MAX_CONTROL_BUFF_LEN (1600)

static int compare_name(void *a, void *b)
{
    return strcmp((char *)a, (char *)b);
}

static void process_udp_cb_(evutil_socket_t sock, short events, void *arg)
{
    int recv_bytes;
    char *buff = (char *) malloc(T2U_MESS_BUFFER_MAX);
    t2u_message_data *mdata;
    t2u_event *ev = (t2u_event *)arg;
    t2u_runner *runner = ev->runner_;
    t2u_context *context = ev->context_;

    recv_bytes = recv(sock, buff, T2U_MESS_BUFFER_MAX, 0);
    if (recv_bytes <= 0)
    {
        /* error on context's udp socket */
        LOG_(3, "recv from udp socket failed, context: %p", context);
        free(buff);
        return;
    }

    mdata = (t2u_message_data *)(void *)buff;
    mdata->magic_ = ntohl(mdata->magic_);
    mdata->version_ = ntohs(mdata->version_);
    mdata->oper_ = ntohs(mdata->oper_);
    mdata->handle_ = ntoh64(mdata->handle_);
    mdata->seq_ = ntohl(mdata->seq_);

    if (((int)recv_bytes < (int)sizeof(t2u_message_data)) ||
        (mdata->magic_ != T2U_MESS_MAGIC) ||
        (mdata->version_ != 0x0001))
    {
        /* unknown packet */
        LOG_(2, "recv unknown packet from context: %p", context);
        unknown_callback uc = get_unknown_func_();
        if (uc)
        {
            uc(context, buff, recv_bytes);
        }
        free(buff);
        return;
    }

    switch (mdata->oper_)
    {
    case connect_request:
        {
            char *service = mdata->payload;
            t2u_rule *rule = rbtree_lookup(context->rules_, service);
            if (rule)
            {
                t2u_rule_handle_connect_request(rule, mdata);
            }
            else
            {
                LOG_(2, "no rule match the service: %s", service);
            }
            free(buff);
        }
        break;
    case connect_response:
        {
            /* find with self handle */
            uint64_t compare_handle = mdata->handle_ & 0x00000000ffffffff;
            t2u_session *session = find_session_in_context(context, compare_handle, 0);
            if (session)
            {
                t2u_session_handle_connect_response(session, mdata);
            }
            else
            {
                LOG_(2, "no session match the handle: %llu -> %llu", mdata->handle_, compare_handle);
            }
            free(buff);
        }
        break;
    case data_request:
        {
            t2u_session *session = find_session_in_context(context, mdata->handle_, 1);
            if (session)
            {
                t2u_session_handle_data_request(session, mdata, recv_bytes);
            }
            else
            {
                LOG_(2, "no session match the handle: %llu", mdata->handle_);
            }
            free(buff);
        }
        break;
    case data_response:
        {
            t2u_session *session = find_session_in_context(context, mdata->handle_, 1);
            if (session)
            {
                /* find it in send queue */
                t2u_message *message = rbtree_lookup(session->send_mess_, &mdata->seq_);
                if (message)
                {
                    t2u_message_handle_data_response(message, mdata);
                }
                else
                {
                    LOG_(2, "no message match the seq: %d", mdata->seq_);
                }
            }
            else
            {
                LOG_(2, "no session match the handle: %llu", mdata->handle_);
            }
            free(buff);
        }
        break;
    case retrans_request:
        {
            t2u_session *session = find_session_in_context(context, mdata->handle_, 1);
            if (session)
            {
                /* find it in send queue */
                t2u_message *message = rbtree_lookup(session->send_mess_, &mdata->seq_);
                if (message)
                {
                    t2u_message_handle_retrans_request(message, mdata);
                }
                else
                {
                    LOG_(2, "no message match the seq: %d", mdata->seq_);
                }
            }
            else
            {
                LOG_(2, "no session match the handle: %llu", mdata->handle_);
            }
            free(buff);
        }
        break;
    case close_request:
    {
        t2u_session *session = find_session_in_context(context, mdata->handle_, 1);
        if (session)
        {
            LOG_(1, "close session:%p, as peer already closed.", session);
            t2u_delete_connected_session(session, 1);
        }
        free(buff);
    }
        break;
    default:
        {
            /* unknown packet */
            LOG_(2, "recv unknown packet from context: %p, type: %d", context, mdata->oper_);
            free(buff);
        }
        break;
    }
}

static void add_context_cb_(t2u_runner *runner, void *arg)
{
    t2u_context *context = (t2u_context *)arg;

    context->ev_udp_ = t2u_event_new();
    context->ev_udp_->runner_ = runner;
    context->ev_udp_->context_ = context;

    context->ev_udp_->event_ = event_new(runner->base_, context->sock_,
        EV_READ|EV_PERSIST, process_udp_cb_, context->ev_udp_);
    assert(NULL != context->ev_udp_->event_);

    event_add(context->ev_udp_->event_, NULL);
    rbtree_insert(runner->contexts_, context, context);

	LOG_(1, "add context:%p to runner: %p, sock: %d", context, runner, context->sock_);
}

/* init */
t2u_context * t2u_add_context(t2u_runner *runner, sock_t sock)
{
    control_data cdata;
    t2u_context *context = (t2u_context *) malloc(sizeof(t2u_context));
    assert(context != NULL);
    memset(context, 0, sizeof(t2u_context));

    evutil_make_socket_nonblocking(sock);

    context->rules_ = rbtree_init(compare_name);
    context->sock_ = sock;
    context->utimeout_ = 500;
    context->uretries_ = 3;
    context->udp_slide_window_ = 16;
    context->session_timeout_ = 900;
    context->runner_ = runner;

    cdata.func_ = add_context_cb_;
    cdata.arg_ = context;

    LOG_(0, "create new context %p with sock %d", (void *)context, (int)sock);

    t2u_runner_control(runner, &cdata);

    return context;
}

/* context free */
static void delete_context_cb_(t2u_runner *runner, void *arg)
{
    t2u_context *context = (t2u_context *)arg;

    /* remove rules with this context */
    while (context->rules_->root)
    {
        rbtree_node *node = context->rules_->root;
        void *remove = node->data;

        t2u_delete_rule((t2u_rule *)remove);
    }
    /* remove the tree */
    free(context->rules_);
    context->rules_ = NULL;

    /* remove the events */
    t2u_delete_event(context->ev_udp_);
    context->ev_udp_ = NULL;

    /* remove from runner */
    rbtree_remove(runner->contexts_, context);

    LOG_(0, "delete the context %p with sock %d", (void *)context, (int)context->sock_);

    free(context);
    return;
}

/* context free */
void t2u_delete_context(t2u_context *context)
{
    control_data cdata;
    memset(&cdata, 0, sizeof(cdata));

    cdata.func_ = delete_context_cb_;
    cdata.arg_ = context;
    t2u_runner_control(context->runner_, &cdata);
    return;
}

void t2u_send_message_data(t2u_context *context, char *data, size_t size, t2u_session * session)
{
    if (session)
    {
        session->last_send_ts_ = time(NULL);
    }

#if 1
    send(context->sock_, data, size, 0);
#else
    int a = rand();
    if (a % 10)
    {
        send(context->sock_, data, size, 0);
    }
    else
    {
        t2u_message_data *md = data;
        LOG_(1, "xxxxxxxxxxxxxxx drop. %d", ntohl(md->seq_));
    }
#endif
}


text:
require 'sinatra'

module Twinkies
  class Server
    def initialize(config)
      @tweet_db = config.tweet_db
      @username = config.username
      @password = config.password
    end

    def run
      setup_db
      start_tweet_refresher
      handle_request
      Sinatra::Base.run!
    end

    def setup_db
      DataMapper.setup(:default, "sqlite3://#{@tweet_db}")
      DataMapper.auto_upgrade!
    end

    def start_tweet_refresher
      Thread.abort_on_exception = true
      Thread.new do
        loop do
          puts "refreshing tweets..."
          Item.refresh @username, @password
          sleep 60
        end
      end
    end

    def handle_request
      username = @username # instance_eval..
      Sinatra::Base.get '/feed.xml' do
        pieces = ['http://', request.env['SERVER_NAME']]
        pieces << ":#{request.env['SERVER_PORT']}" unless request.env['SERVER_PORT'].to_i == 80
        pieces << request.env['REQUEST_PATH']
        request_path = pieces.join
        RssWriter.new(username, request_path, Item.latest).rss
      end
    end
  end
end


text:
var SubButtonView = function(settings){
	var defaultSetting = {
		parent : null,
		subButton: null,
		onClick:null
	};

	$.extend(defaultSetting, settings);

	var self = this;
	this.id = settings.subButton !=null ? settings.subButton.id : settings.parent.id + '_-1';
	this.id = 'subMenu_menu_' + this.id;

    this.init = function(){
    	$('#sub_pre_menu_list_' + settings.parent.id).append(getHtml());
    	$('#'+self.id).click(function(){
    		settings.onClick(settings.subButton);
    	});
	}

	var getHtml = function(){
		var content = settings.subButton == null ? '' : ''+''+settings.subButton.name+'';

		return '
'+
                   ''+
                       ''+
                           content+
                       ''+
                   ''+
               '
';
	};
}


text:
set -e
SCRIPT_DIR=$(dirname $0) && ([ -n "$SETUP" ] && ${SETUP?}) || source ${SCRIPT_DIR?}/setup.sh $*
cd ${SOURCES_DIR?}/jsoncpp && git checkout ${JSONCPP_VERSION?}
export_cross_compiler && sanity_check_cross_compiler
cd_clone ${SOURCES_DIR?}/jsoncpp ${WORK_DIR?}/jsoncpp

# ===========================================================================
# configuration:

section_configuring jsoncpp

cmake \
   ${SOURCES_DIR?}/jsoncpp \
  -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE?} \
  -DBUILD_STATIC_LIBS=ON \
  -DBUILD_SHARED_LIBS=OFF \
  -DJSONCPP_WITH_TESTS=OFF \
  -DARCHIVE_INSTALLS_DIR="." # TODO: enforce
return_code $?

# ===========================================================================
# cross-compile:

section_cross_compiling jsoncpp
make -j2
return_code $?

# ===========================================================================
# install:

section_installing jsoncpp
make DESTDIR="${INSTALLS_DIR?}/jsoncpp" install
return_code $?

# ===========================================================================

section "done" jsoncpp
tree ${INSTALLS_DIR?}/jsoncpp

# ===========================================================================


text:
using DragonSpark.Runtime.Execution;
using DragonSpark.Text;

namespace DragonSpark.Diagnostics.Logging.Text;

sealed class DetailsFormatter : IFormatter<Details>
{
	public static DetailsFormatter Default { get; } = new DetailsFormatter();

	DetailsFormatter() : this(TimestampFormat.Default) {}

	readonly string _format;

	public DetailsFormatter(string format) => _format = format;

	public string Get(Details parameter) => $"[{parameter.Observed.ToString(_format)}] {parameter.Name}";
}


text:
@interface NNDateLabelFormatter : NSObject

+ (void)setUpDateLabel:(UILabel *)eventDateLabel andSuffixLabel:(UILabel *)eventDateSuffixLabel forDate:(NSDate *)date;

@end


text:
try:
    import json
except ImportError:
    import simplejson as json

from flask import jsonify, render_template, request
import urllib
import urllib2
from jinja2.filters import FILTERS

from Maraschino import app
from maraschino.tools import *
from maraschino import logger

def sab_http():
    if get_setting_value('sabnzbd_https') == '1':
        return 'https://'
    else:
        return 'http://'

def sabnzbd_url_no_api():
    url_base = get_setting_value('sabnzbd_host')
    port = get_setting_value('sabnzbd_port')
    webroot = get_setting_value('sabnzbd_webroot')

    if port:
        url_base = '%s:%s' % (url_base, port)

    if webroot:
        url_base = '%s/%s' % (url_base, webroot)

    return sab_http() + url_base

def sabnzbd_url(mode, extra=""):
    return '%s/api?apikey=%s&mode=%s&output=json%s' % (sabnzbd_url_no_api(), get_setting_value('sabnzbd_api'), mode, extra)

def sab_link():
    SABNZBD_HOST = get_setting_value('sabnzbd_host')
    SABNZBD_PORT = get_setting_value('sabnzbd_port')
    SABNZBD_API = get_setting_value('sabnzbd_api')
    SABNZBD_WEBROOT = get_setting_value('sabnzbd_webroot')

    SABNZBD_URL = '%s%s:%s' % (sab_http(), SABNZBD_HOST, SABNZBD_PORT)

    if SABNZBD_WEBROOT:
        SABNZBD_URL = '%s/%s' % (SABNZBD_URL, SABNZBD_WEBROOT)

    return '%s/api?apikey=%s' % (SABNZBD_URL, SABNZBD_API)

def add_to_sab_link(nzb):
    if get_setting_value('sabnzbd_api') != None:
        return '%s&mode=addurl&name=%s&output=json' % (sab_link(), nzb)
    return False

FILTERS['add_to_sab'] = add_to_sab_link

def sabnzbd_api(method='', params='', use_json=True, dev=False):

    url = sabnzbd_url(method, extra=params)
    r = urllib2.Request(url)
    data = urllib2.urlopen(r).read()

    if dev:
        print url
        print data
    if use_json:
        data = json.JSONDecoder().decode(data)
    return data

@app.route('/xhr/sabnzbd/')
@app.route('/xhr/sabnzbd/<queue_status>')
@requires_auth
def xhr_sabnzbd(queue_status='hide'):
    old_config = False

    if not get_setting_value('sabnzbd_host'):
        if get_setting_value('sabnzbd_url') != None:
            old_config = True

    downloading = None
    sabnzbd = None
    download_speed = None
    downloading = None
    message = None

    try:
        result = urllib.urlopen(sabnzbd_url('queue')).read()
        sabnzbd = json.JSONDecoder().decode(result)
        sabnzbd = sabnzbd['queue']

        download_speed = format_number(int((sabnzbd['kbpersec'])[:-3]) * 1024) + '/s'

        if sabnzbd['slots']:
            for item in sabnzbd['slots']:
                if item['status'] == 'Downloading':
                    downloading = item
                    break

    except:
        pass

    if not sabnzbd:
        message = 'There was a problem reaching SabNZBd.'

    return render_template('sabnzbd/queue.html',
        sabnzbd=sabnzbd,
        item=downloading,
        download_speed=download_speed,
        old_config=old_config,
        queue_status=queue_status,
        show_empty=get_setting_value('sabnzbd_show_empty') == '1',
        message=message
    )

@app.route('/xhr/sabnzbd/queue/<action>/')
@app.route('/xhr/sabnzbd/queue/pause/<time>')
@requires_auth
def sabnzb_queue(action="pause", time=None):
    if not time:
        try:
            result = urllib.urlopen(sabnzbd_url(action)).read()
            sabnzbd = json.JSONDecoder().decode(result)
        except:
            pass
    else:
        try:
            result = urllib.urlopen(sabnzbd_url('config', '&name=set_pause&value=' + time)).read()
            sabnzbd = json.JSONDecoder().decode(result)
        except:
            pass

    if sabnzbd:
        return jsonify({'status': sabnzbd['status']})

    return jsonify({'status': False})

@app.route('/xhr/sabnzbd/custom_pause/')
@requires_auth
def sabnzbd_custom_pause():
    return render_template('sabnzbd/pause.html')

@app.route('/xhr/sabnzbd/speedlimit/<int:speed>/')
@requires_auth
def sabnzb_speed_limit(speed):
    try:
        result = urllib.urlopen(sabnzbd_url('config', '&name=speedlimit&value=%i' % (speed))).read()
        sabnzbd = json.JSONDecoder().decode(result)
        if sabnzbd:
            return jsonify({'status': sabnzbd['status']})
    except:
        pass

    return jsonify({'status': False})

@app.route('/xhr/sabnzbd/individual/<state>/<id>/')
@requires_auth
def sabnzb_individual_toggle(state, id):
    try:
        result = urllib.urlopen(sabnzbd_url('queue', '&name=%s&value=%s' % (state, id))).read()
        sabnzbd = json.JSONDecoder().decode(result)
        if sabnzbd:
            return jsonify({'status': sabnzbd['status']})
    except:
        pass

    return jsonify({'status': False})

@app.route('/sabnzbd/add/', methods=['POST'])
def add_to_sab():
    try:
        url = request.form['url']
    except:
        return jsonify({'error': 'Did not receive URL variable'})

    try:
        return urllib.urlopen(url).read()
    except:
        return jsonify({'error': 'Failed to open URL: %s' % (url)})

@app.route('/xhr/sabnzbd/history/delete/<id>/')
@requires_auth
def sabnzb_history_delete(id):
    try:
        logger.log('SabNZBd :: Deleting item from history: %s' % id, 'INFO')
        result = urllib.urlopen(sabnzbd_url('history', '&name=delete&value=%s' % (id))).read()
        sabnzbd = json.JSONDecoder().decode(result)
        if sabnzbd:
            return jsonify({'status': sabnzbd['status']})
    except:
        pass

    return jsonify({'status': False})

@app.route('/xhr/sabnzbd/history/retry/<id>/')
@requires_auth
def sabnzb_history_retry(id):
    try:
        logger.log('SabNZBd :: Retrying item: %s' % id, 'INFO')
        result = urllib.urlopen(sabnzbd_url('retry', '&value=%s' % (id))).read()
        sabnzbd = json.JSONDecoder().decode(result)
        if sabnzbd:
            return jsonify({'status': sabnzbd['status']})
    except:
        pass

    return jsonify({'status': False})


text:
package com.lyj.base.aop;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

public class Before implements MethodBeforeAdvice {

	@Override
	public void before(Method method, Object[] args, Object target)
			throws Throwable {
		System.out.println("before advice begin...");
		System.out.println("method :" + method);
		System.out.println("args :" + args);
		System.out.println("target :" + target);
		System.out.println("before advice end...");
	}

}


text:
<?php

use App\Helpers\Helper;
use App\User;
use Illuminate\Support\Facades\Auth;

class HelpersTest extends TestCase
{
    private $user;

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

        $this->user = factory(User::class)->create();
        Auth::login($this->user);
    }

    /**
     * Message stack test.
     *
     * @return void
     */
    public function testResponseMessage()
    {

        $stack = rand(0, 614);

        $outputType = gettype(Helper::responseMessage($stack));

        $assetAgainst = ($stack > 600)? 'string' : 'NULL';

        $this->assertEquals($assetAgainst, $outputType);

    }

    /**
     * Field validator test.
     *
     * @return void
     */
    public function testFieldCheck()
    {
        $validSample =
            [
                'boolean'    => true,
                'decimals'    => 12.2324344,
                'email'      => 'edmond@devless.io',
                'integer'    => 1,
                'password'   => 'al32j4hk2jh4hghg23hghj',
                'percentage' => 1,
                'reference'  => 1,
                'text'       => 'string',
                'textarea'   => 'string',
                'timestamp'  => 12345,
                'url'        => 'https://devless.io/#!/main',
                'base64'     => 'any string',

            ];

        $invalidSample =
            [
                'boolean'    => 'true',
                'decimals'   => 'string instead of decimal',
                'email'      => 'edmonddevless.io',
                'integer'    => 'string here',
                'password'   => true,
                'percentage' => 12.4,
                'reference'  => 'ref',
                'text'       => 1,
                'textarea'   => 2,
                'timestamp'  => 'timestamp',
                'url'        => 'devless.io/#!/main',
                'base64'     => 2,

            ];

        $fieldTypes  = Helper::$validator_type;

        foreach($fieldTypes as $fieldType => $vaidatorKey){

            //check against valid field types
            $output = Helper::field_check($validSample[$fieldType], $fieldType);
            $this->assertTrue($output);

            //check against wrong field types
            $output = Helper::field_check($invalidSample[$fieldType], $fieldType);
            $type   = gettype($output);
            $this->assertEquals('object', $type);
        }
    }

    /**
     * url query string test.
     *
     * @return void
     */
    public function testQueryString()
    {
        $_SERVER['QUERY_STRING'] = 'name=edmond&name=charles&age=12';

        $output = Helper::query_string();
        $this->assertEquals($output['name'][0],'edmond');
        $this->assertEquals($output['name'][1],'charles');
        $this->assertEquals($output['age'][0],'12');

        //query string when parameters are not set
        unset($_SERVER['QUERY_STRING']);
        $output = Helper::query_string();
        $this->assertEquals('', $output);
    }

    /**
     * sessionTimestamp test.
     *
     * @return void
     */
    public function testSessionTimestamp()
    {
        $sessionTime = Helper::session_timestamp();

        $formattedSessionTime = date('Y-m-d',strtotime($sessionTime));

        $this->assertEquals(date('Y-m-d'), $formattedSessionTime);
    }
}


text:
/**
 *
 */
package de.quaddy_services.report.format;

import java.text.DecimalFormat;

public class MinuteTimeFormat implements TimeFormat {
	private String name;

	MinuteTimeFormat(String aName) {
		// protected
		name = aName;
	}

	private DecimalFormat format = new DecimalFormat("00");

	@Override
	public String format(long aTimeInMillis) {
		long tempSec = (aTimeInMillis / 1000) % 60;
		long tempMin = aTimeInMillis / (60 * 1000);
		return format.format(tempMin) + ":" + format.format(tempSec);
	}

	@Override
	public int maxLength() {
		return 6;
	}

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

	@Override
	public long roundToDisplay(long aTimeInMillis) {
		// Round to minutes
		double tempWithDecimals = 1.0 * aTimeInMillis / (60 * 1000);
		long tempRounded = Math.round(tempWithDecimals);
		return Math.round(tempRounded * (1.0 * 60 * 1000));
	}

}


text:
@implementation SDLCreateWindowResponse

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- (instancetype)init {
    if (self = [super initWithName:SDLRPCFunctionNameCreateWindow]) {
    }
    return self;
}
#pragma clang diagnostic pop

@end


text:
#ifndef QXTPROXYSTYLE_H

#define QXTPROXYSTYLE_H

#include <QStyle>
#include "qxtglobal.h"

class QXT_GUI_EXPORT QxtProxyStyle : public QStyle
{
    Q_OBJECT
public:
    explicit QxtProxyStyle(const QString& baseStyle);
    virtual ~QxtProxyStyle();

    virtual void drawComplexControl(ComplexControl control, const QStyleOptionComplex* option, QPainter* painter, const QWidget* widget = 0) const;
    virtual void drawControl(ControlElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget = 0)  const;
    virtual void drawItemPixmap(QPainter* painter, const QRect& rect, int alignment, const QPixmap& pixmap) const;
    virtual void drawItemText(QPainter* painter, const QRect& rect, int alignment, const QPalette& pal, bool enabled, const QString& text, QPalette::ColorRole textRole = QPalette::NoRole) const;
    virtual void drawPrimitive(PrimitiveElement elem, const QStyleOption* option, QPainter* painter, const QWidget* widget = 0) const;
    virtual QPixmap generatedIconPixmap(QIcon::Mode iconMode, const QPixmap& pixmap, const QStyleOption* option) const;
    virtual SubControl hitTestComplexControl(ComplexControl control, const QStyleOptionComplex* option, const QPoint& pos, const QWidget* widget = 0) const;
    virtual QRect itemPixmapRect(const QRect& rect, int alignment, const QPixmap& pixmap) const;
    virtual QRect itemTextRect(const QFontMetrics& metrics, const QRect& rect, int alignment, bool enabled, const QString& text) const;
    virtual int pixelMetric(PixelMetric metric, const QStyleOption* option = 0, const QWidget* widget = 0) const;
    virtual void polish(QWidget* widget);
    virtual void polish(QApplication* app);
    virtual void polish(QPalette& pal);
    virtual QSize sizeFromContents(ContentsType type, const QStyleOption* option, const QSize& contentsSize, const QWidget* widget = 0) const;
    virtual QPalette standardPalette() const;
    virtual QPixmap standardPixmap(StandardPixmap standardPixmap, const QStyleOption* option = 0, const QWidget* widget = 0) const;
    virtual int styleHint(StyleHint hint, const QStyleOption* option = 0, const QWidget* widget = 0, QStyleHintReturn* returnData = 0) const;
    virtual QRect subControlRect(ComplexControl control, const QStyleOptionComplex* option, SubControl subControl, const QWidget* widget = 0) const;
    virtual QRect subElementRect(SubElement element, const QStyleOption* option, const QWidget* widget = 0) const;
    virtual void unpolish(QWidget* widget);
    virtual void unpolish(QApplication* app);

protected Q_SLOTS:
    QIcon standardIconImplementation(StandardPixmap standardIcon, const QStyleOption* option = 0, const QWidget* widget = 0) const;

private:
    QStyle* style;
};

#endif // QXTPROXYSTYLE_H


text:
var Dugong = {};

//Constants
Dugong.stalkLength =  200; //Distance between nodes
Dugong.boxMinHeight =  50;
Dugong.boxRatio =       2; //Width-to-height ratio of nodes.
Dugong.canvasMargin = 100; //Margin around outside of map
Dugong.boxMargin =      10; //Margin inside each box

//Makes an SVG element
Dugong.e = function(elem, opts) {
  var e = document.createElementNS("http://www.w3.org/2000/svg", elem);
  if (opts) {
    var keys = Object.keys(opts);
    for (var i=0;i<keys.length;i++) {
      var key = keys[i];
      if (key == "innerHTML")   e[key] = opts[key]
      else                      e.setAttributeNS(null, key, opts[key]);
    }
  }
  return e;
}

// Represents the diagram itself
Dugong.Diagram = function(elem){
  //HTML element the diagram is displayed in
  this.parentElement = elem;

  //SVG element
  this.svg = Dugong.e("svg");
  this.svg.setAttributeNS(null,"class", "dugong");

  //Cause nodes to settle down. Specify a maximum number of iterations to avoid
  //infinite loops
  this.repulse = function(maxIterations) {
    if (maxIterations == null) maxIterations = 1;
    var nodes = this.nodes;

    for (var i=0;i<maxIterations;i++) {
      var currentEnergy = this.energy();
      this.eachNode(function(){ this.repulse(nodes) });
      if (currentEnergy == this.energy()) return;
    }
  }

  //Overall energy of the diagram, equal to sum of energy of
  //every node
  this.energy = function() {
    var totalEnergy = 0;
    var nodes = this.nodes;
    this.eachNode(function(){ totalEnergy += this.energy(nodes) });
    return totalEnergy;
  }

  //Redraw the diagram, by redrawing every node (and by extention every connector)
  this.redraw = function() { this.eachNode(function(){ this.redraw() }); }
  //Resize every node to fit its text
  this.resize = function() { this.eachNode(function(){ this.resize() }); }

  //Run a function on every node
  this.eachNode = function(fnc) { for (var i=0;i<this.nodes.length;i++) fnc.bind(this.nodes[i])(); }

  //Set svg viewbox to the appropriate size, based on contents and margin
  this.zoom = function() {
    var extents = {l:0,r:0,t:0,b:0};
    this.eachNode(function(){
      var centre = this.centre();
      if (centre.x < extents.l) extents.l = centre.x;
      if (centre.x > extents.r) extents.r = centre.x;
      if (centre.y < extents.t) extents.t = centre.y;
      if (centre.y > extents.b) extents.b = centre.y;
    });

    this.svg.setAttributeNS(null, "viewBox",
      (extents.l-Dugong.canvasMargin) + " " + (extents.t-Dugong.canvasMargin) + " " +
      (extents.r - extents.l + 2*Dugong.canvasMargin) + " " + (extents.b - extents.t + 2*Dugong.canvasMargin));
  }

  // Constructor

  //Base of everything else
  this.rootNode = null;
  //All nodes
  this.nodes = [];

  //Parse an indented list into a set of nodes with tree-like heirarchy
  var indentTree = {};

  var lines = elem.innerHTML.replace(/(^\s+|\s+$)/g,"").split("\n");
  var indentRegex = /^(\s+)(.*)/

  for (var i=0;i<lines.length;i++) {
    var line = lines[i];

    // Create node, assign to canvas
    var node = new Dugong.Node(line);
    this.nodes.push(node);
    if (!this.rootNode) this.rootNode = node;

    var indent = 0;
    var match = indentRegex.exec(line);
    if (match) {
      indent = match[1].length;
      node.name = match[2];
    }

    //Work out the best parent for this node. Best parent the node with the highest
    //indent which is less than this node. If multiple nodes, pick the last node created.
    var treeKeys = Object.keys(indentTree);
    var bestParent = null;
    var bestParentIndent = -1;
    for (var j=0;j<treeKeys.length;j++) {
      var key = treeKeys[j];
      if (key >= indent)
        delete indentTree[key];
      else if (key > bestParentIndent) {
        bestParentIndent = key;
        bestParent = indentTree[key];
      }
    }
    if (bestParent) bestParent.addChild(node);
    indentTree[indent] = node;
  }

  //Replace element's inner html with the svg
  elem.innerHTML = "";
  elem.appendChild(this.svg);
  var d = this;

  //Build elements
  this.eachNode(function(){ this.attachSkeleton(d) });
  this.eachNode(function(){ this.attachBoxes(d) });

  //Set to be the right size etc.
  this.zoom();
  this.redraw();
}

// A Node is a point on the SVG diagram. It keeps track of its position,
// energy, and can draw itself. So clever.
Dugong.Node = function(name) {
  //Name (inner html of node)
  this.name = name;

  //Node size
  this.height = Dugong.boxMinHeight;
  this.width = Dugong.boxMinHeight * Dugong.boxMinHeight * Dugong.boxRatio;

  //Children of the node itself
  this.children = [];

  //Parent node. If null, indicates node is root
  this.parent = null;

  this.g = Dugong.e("g");
  //The box the text fits into
  this.box = Dugong.e("rect", {rx: 12});
  this.g.appendChild(this.box);
  //The text, inside a div inside a foreignObject
  this.text = Dugong.e("foreignObject", {requiredExtentions: "http://www.w3.org/1999/xhtml"});
  this.g.appendChild(this.text);
  var foDiv = document.createElement("div");
  foDiv.style.display = "inline-block";
  foDiv.style.minWidth = "100%";
  foDiv.innerHTML = this.name;
  this.text.appendChild(foDiv);

  //The connector line to the parent. Even root has one, hiding it under the box
  this.connector = Dugong.e("line", {stroke: "#000"});

  //Generation 0 is root, 1 is root's children, etc.
  this.generation = function() {
    if (this.parent == null) return 0;
    else return this.parent.generation() + 1;
  }

  //Position stuff
  this.centre = function() {
    if (this.parent == null) //Occurs at 0,0
      return new Dugong.Point(0,0);
    else { //Occurs at offset to parent
      var offset = Dugong.Point.fromAngleAndRadius(this.parent.angleTo(this), Dugong.stalkLength);
      return this.parent.centre().add(offset);
    }
  }

  //Build the connectors into a skeleton. Happens before boxes are drawn
  this.attachSkeleton = function(diagram) {
    diagram.svg.appendChild(this.connector);
  }

  //Draw the boxes onto the diagram
  this.attachBoxes = function(diagram) {
    diagram.svg.appendChild(this.g);
  }

  //Resize the element so text fits in the box
  this.resize = function() {
    var fObject = this.text;
    var div = fObject.childNodes[0];

    //Set best height
    var currentHeight = Dugong.boxMinHeight;
    var currentWidth = currentHeight * Dugong.boxRatio;
    while (true) {
      fObject.setAttributeNS(null,"height", currentHeight - Dugong.boxMargin*2);
      fObject.setAttributeNS(null,"width", currentWidth - Dugong.boxMargin*2);

      if (div.offsetHeight > (currentHeight - Dugong.boxMargin*2) ||
          div.offsetWidth > (currentWidth - Dugong.boxMargin*2)) {
        currentHeight += 1;
        currentWidth = currentHeight * Dugong.boxRatio;
      }
      else
        break;
    }

    this.height = currentHeight;
    this.width = currentHeight * Dugong.boxRatio;
  }

  //Redraw all elements based on the node's centre.
  this.redraw = function() {
    var centre = this.centre();
    var halfWidth = this.width / 2;
    var halfHeight = this.height / 2;
    var generationClass = "gen-" + this.generation();

    this.g.setAttributeNS(null, "class", generationClass);

    this.box.setAttributeNS(null, "x", centre.x - halfWidth);
    this.box.setAttributeNS(null, "y", centre.y - halfHeight);
    this.box.setAttributeNS(null, "width", this.width);
    this.box.setAttributeNS(null, "height", this.height);

    this.text.setAttributeNS(null, "x", centre.x - halfWidth + Dugong.boxMargin);
    this.text.setAttributeNS(null, "y", centre.y - halfHeight + Dugong.boxMargin);
    this.text.setAttributeNS(null, "width", this.width - 2*Dugong.boxMargin);
    this.text.setAttributeNS(null, "height", this.height - 2*Dugong.boxMargin);

    this.connector.setAttributeNS(null, "x1", centre.x);
    this.connector.setAttributeNS(null, "y1", centre.y);
    if (this.parent) {
      var parentCentre = this.parent.centre();
      this.connector.setAttributeNS(null, "x2", parentCentre.x);
      this.connector.setAttributeNS(null, "y2", parentCentre.y);
    }
    else {
      this.connector.setAttributeNS(null, "x2", centre.x);
      this.connector.setAttributeNS(null, "y2", centre.y);
    }
    this.connector.setAttributeNS(null, "class", generationClass);
  }

  //Add a child to the node, rearrange all children so they're equi-angled
  this.addChild = function(c) {
    c.parent = this;
    this.children.push({node: c, angle: 0});
    this.arrangeChildren();
  }

  //What's the angle from this node to one of its children?
  // Returns null if c is not a child of this node
  this.angleTo = function(c) {
    for (var i=0;i<this.children.length;i++) {
      var child = this.children[i];
      if (child.node == c) return child.angle;
    }
    return null;
  }

  //Arrange the children of this node in a little arc in front of it.
  this.arrangeChildren = function() {
    var arc = this.arc();
    var originAngle = 0;

    if (this.parent)
      originAngle = (this.parent.angleTo(this) - arc / 2) % (Math.PI*2);

    var arcPerChild = arc / this.children.length;
    originAngle += (arcPerChild / 2);

    for (var i=0;i<this.children.length;i++) {
      var child = this.children[i];
      var angle = (originAngle + arcPerChild * i) % (Math.PI*2);
      child.angle = angle;
      child.node.arrangeChildren();
    }
  }

  //The amount of a full circle that this node takes up.
  //Think of this as the "shadow" this node casts from the root node.
  this.arc = function() {
    if (this.parent)
      return this.parent.arc() / this.parent.children.length;
    else
      return Math.PI*2;
  }

  //Moves a child node around this node by a given amount in radians
  this.nudgeChild = function(child, amount) {
    for (var i=0;i<this.children.length;i++) {
      var c = this.children[i];
      if (c.node == child) {
        c.angle = c.angle + amount;
        return;
      }
    }
  }

  //Returns the energy of this node. A node's energy is proportional
  //to the number of other nodes close to it. If a value delta is provided,
  //the node will first be nudged by this amount.
  this.energy = function(nodes,delta) {
    if (this.parent == null) return 0;

    if (delta)
      this.parent.nudgeChild(this, delta);

    var totalEnergy = 0;
    var myCentre = this.centre();

    for (var i=0;i<nodes.length;i++) {
      if (nodes[i] == this) continue
      totalEnergy += 1 / myCentre.squaredDistanceTo(nodes[i].centre());
    }

    if (delta)
      this.parent.nudgeChild(this, -delta);

    return totalEnergy;
  }

  //Moves the node around trying to find the best (least energetic) spot
  //for it to be in.
  this.repulse = function(nodes) {
    if (this.parent == null) return;
    var lowestEnergy = this.energy(nodes);
    var bestNudge = 0;
    for (var nudge=-1;nudge<=1;nudge+=0.05) {
      var energy = this.energy(nodes, nudge);
      if (energy < lowestEnergy) {
        lowestEnergy = energy;
        bestNudge = nudge;
      }
    }

    if (bestNudge != 0)
      this.parent.nudgeChild(this, bestNudge);
  }
}

// The Point! An x,y point.
Dugong.Point = function(x,y) {
  this.x = x;
  this.y = y;

  //Add a point to another
  this.add = function(anotherPoint) {
    return new Dugong.Point(this.x + anotherPoint.x, this.y + anotherPoint.y);
  }

  //Returns the square of the distance between two points
  this.squaredDistanceTo = function(p) {
    return Math.pow(this.x - p.x,2) + Math.pow(this.y - p.y,2);
  }
}

//Create an x,y point given an angle and radius from 0,0
Dugong.Point.fromAngleAndRadius = function(t,r) {
  var x = r * Math.cos(t);
  var y = r * Math.sin(t);
  return new Dugong.Point(x,y);
}

//Populate. Call this method to start dugong working
Dugong.populate = function(klass) {
  window.addEventListener("load", function(){
    var dugongElements = document.getElementsByClassName(klass);
    for (var i=0;i<dugongElements.length;i++) {
      var thisElem = dugongElements[i];
      if (thisElem.tagName == "svg") continue;

      var diagram = new Dugong.Diagram(thisElem);
      diagram.resize();

      diagram.repulse(100);
      diagram.redraw();
      diagram.zoom();
    }
  },false);
}


text:
<?php
use GetSky\ParserExpressions\Rules\AbstractRule;
use GetSky\ParserExpressions\Rules\Sequence;
use GetSky\ParserExpressions\Rules\Row;

class AbstractRuleTest extends PHPUnit_Framework_TestCase
{

    public function testInterface()
    {
        $this->assertInstanceOf(
            'GetSky\ParserExpressions\RuleInterface',
            $this->getObject()
        );

    }

    public function testGetName()
    {
        $rule = $this->getObject();
        $name = $this->getAccessibleProperty(AbstractRule::class, 'name');

        $name->setValue($rule, 'TestName');
        $this->assertSame('TestName', $rule->getName());

        $name->setValue($rule, 'Sequence');
        $this->assertSame('Sequence', $rule->getName());

    }

    public function testToRule()
    {
        $rule = $this->getObject();

        $string = $rule->toRule('String');
        $this->assertInstanceOf(Row::class, $string);

        $sequence = $rule->toRule([$string, $string]);
        $this->assertInstanceOf(Sequence::class, $sequence);
    }

    /**
     * @return AbstractRule
     */
    private function getObject()
    {
        return $this->getMockBuilder(AbstractRule::class)
            ->getMockForAbstractClass();
    }

    private function getAccessibleProperty($class, $name)
    {
        $property = new ReflectionProperty($class, $name);
        $property->setAccessible(true);
        return $property;
    }
}


text:
/**
 */
package gluemodel.CIM.IEC61970.Generation.Production;

import gluemodel.CIM.IEC61970.Core.PowerSystemResource;

import org.eclipse.emf.common.util.EList;

/**
 *
 * A representation of the model object 'Reservoir'.
 *
 *
 *

 * The following features are supported:
 *

 *

 *
{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getActiveStorageCapacity Active Storage Capacity}

 *
{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getUpstreamFromHydroPowerPlants Upstream From Hydro Power Plants}

 *
{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getSpillsIntoReservoirs Spills Into Reservoirs}

 *
{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getSpillsFromReservoir Spills From Reservoir}

 *
{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getLevelVsVolumeCurves Level Vs Volume Curves}

 *
{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getInflowForecasts Inflow Forecasts}

 *
{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getSpillTravelDelay Spill Travel Delay}

 *
{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getRiverOutletWorks River Outlet Works}

 *
{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getNormalMinOperateLevel Normal Min Operate Level}

 *
{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getSpillwayCrestLevel Spillway Crest Level}

 *
{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getFullSupplyLevel Full Supply Level}

 *
{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getSpillwayCapacity Spillway Capacity}

 *
{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getTargetLevelSchedule Target Level Schedule}

 *
{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getSpillWayGateType Spill Way Gate Type}

 *
{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getSpillwayCrestLength Spillway Crest Length}

 *
{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getEnergyStorageRating Energy Storage Rating}

 *
{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getGrossCapacity Gross Capacity}

 *
{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getHydroPowerPlants Hydro Power Plants}

 *

 *
 * @see gluemodel.CIM.IEC61970.Generation.Production.ProductionPackage#getReservoir()
 * @model annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='A water storage facility within a hydro system, including: ponds, lakes, lagoons, and rivers. The storage is usually behind some type of dam.'"
 *        annotation="http://langdale.com.au/2005/UML Profile\040documentation='A water storage facility within a hydro system, including: ponds, lakes, lagoons, and rivers. The storage is usually behind some type of dam.'"
 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='A water storage facility within a hydro system, including: ponds, lakes, lagoons, and rivers. The storage is usually behind some type of dam.' Profile\040documentation='A water storage facility within a hydro system, including: ponds, lakes, lagoons, and rivers. The storage is usually behind some type of dam.'"
 * @generated
 */
public interface Reservoir extends PowerSystemResource {
	/**
	 * Returns the value of the 'Active Storage Capacity' attribute.
	 *
	 *

	 * If the meaning of the 'Active Storage Capacity' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Active Storage Capacity' attribute.
	 * @see #setActiveStorageCapacity(float)
	 * @see gluemodel.CIM.IEC61970.Generation.Production.ProductionPackage#getReservoir_ActiveStorageCapacity()
	 * @model dataType="gluemodel.CIM.IEC61970.Domain.Volume" required="true"
	 *        annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Storage volume between the full supply level and the normal minimum operating level'"
	 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Storage volume between the full supply level and the normal minimum operating level'"
	 * @generated
	 */
	float getActiveStorageCapacity();

	/**
	 * Sets the value of the '{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getActiveStorageCapacity Active Storage Capacity}' attribute.
	 *
	 *
	 * @param value the new value of the 'Active Storage Capacity' attribute.
	 * @see #getActiveStorageCapacity()
	 * @generated
	 */
	void setActiveStorageCapacity(float value);

	/**
	 * Returns the value of the 'Upstream From Hydro Power Plants' reference list.
	 * The list contents are of type {@link gluemodel.CIM.IEC61970.Generation.Production.HydroPowerPlant}.
	 * It is bidirectional and its opposite is '{@link gluemodel.CIM.IEC61970.Generation.Production.HydroPowerPlant#getGenSourcePumpDischargeReservoir Gen Source Pump Discharge Reservoir}'.
	 *
	 *

	 * If the meaning of the 'Upstream From Hydro Power Plants' reference list isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Upstream From Hydro Power Plants' reference list.
	 * @see gluemodel.CIM.IEC61970.Generation.Production.ProductionPackage#getReservoir_UpstreamFromHydroPowerPlants()
	 * @see gluemodel.CIM.IEC61970.Generation.Production.HydroPowerPlant#getGenSourcePumpDischargeReservoir
	 * @model opposite="GenSourcePumpDischargeReservoir"
	 *        annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Generators are supplied water from or pumps discharge water to an upstream reservoir'"
	 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Generators are supplied water from or pumps discharge water to an upstream reservoir'"
	 * @generated
	 */
	EList<HydroPowerPlant> getUpstreamFromHydroPowerPlants();

	/**
	 * Returns the value of the 'Spills Into Reservoirs' reference list.
	 * The list contents are of type {@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir}.
	 * It is bidirectional and its opposite is '{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getSpillsFromReservoir Spills From Reservoir}'.
	 *
	 *

	 * If the meaning of the 'Spills Into Reservoirs' reference list isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Spills Into Reservoirs' reference list.
	 * @see gluemodel.CIM.IEC61970.Generation.Production.ProductionPackage#getReservoir_SpillsIntoReservoirs()
	 * @see gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getSpillsFromReservoir
	 * @model opposite="SpillsFromReservoir"
	 *        annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='A reservoir may spill into a downstream reservoir'"
	 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='A reservoir may spill into a downstream reservoir'"
	 * @generated
	 */
	EList<Reservoir> getSpillsIntoReservoirs();

	/**
	 * Returns the value of the 'Spills From Reservoir' reference.
	 * It is bidirectional and its opposite is '{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getSpillsIntoReservoirs Spills Into Reservoirs}'.
	 *
	 *

	 * If the meaning of the 'Spills From Reservoir' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Spills From Reservoir' reference.
	 * @see #setSpillsFromReservoir(Reservoir)
	 * @see gluemodel.CIM.IEC61970.Generation.Production.ProductionPackage#getReservoir_SpillsFromReservoir()
	 * @see gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getSpillsIntoReservoirs
	 * @model opposite="SpillsIntoReservoirs"
	 *        annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='A reservoir may spill into a downstream reservoir'"
	 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='A reservoir may spill into a downstream reservoir'"
	 * @generated
	 */
	Reservoir getSpillsFromReservoir();

	/**
	 * Sets the value of the '{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getSpillsFromReservoir Spills From Reservoir}' reference.
	 *
	 *
	 * @param value the new value of the 'Spills From Reservoir' reference.
	 * @see #getSpillsFromReservoir()
	 * @generated
	 */
	void setSpillsFromReservoir(Reservoir value);

	/**
	 * Returns the value of the 'Level Vs Volume Curves' reference list.
	 * The list contents are of type {@link gluemodel.CIM.IEC61970.Generation.Production.LevelVsVolumeCurve}.
	 * It is bidirectional and its opposite is '{@link gluemodel.CIM.IEC61970.Generation.Production.LevelVsVolumeCurve#getReservoir Reservoir}'.
	 *
	 *

	 * If the meaning of the 'Level Vs Volume Curves' reference list isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Level Vs Volume Curves' reference list.
	 * @see gluemodel.CIM.IEC61970.Generation.Production.ProductionPackage#getReservoir_LevelVsVolumeCurves()
	 * @see gluemodel.CIM.IEC61970.Generation.Production.LevelVsVolumeCurve#getReservoir
	 * @model opposite="Reservoir"
	 *        annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='A reservoir may have a level versus volume relationship.'"
	 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='A reservoir may have a level versus volume relationship.'"
	 * @generated
	 */
	EList<LevelVsVolumeCurve> getLevelVsVolumeCurves();

	/**
	 * Returns the value of the 'Inflow Forecasts' reference list.
	 * The list contents are of type {@link gluemodel.CIM.IEC61970.Generation.Production.InflowForecast}.
	 * It is bidirectional and its opposite is '{@link gluemodel.CIM.IEC61970.Generation.Production.InflowForecast#getReservoir Reservoir}'.
	 *
	 *

	 * If the meaning of the 'Inflow Forecasts' reference list isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Inflow Forecasts' reference list.
	 * @see gluemodel.CIM.IEC61970.Generation.Production.ProductionPackage#getReservoir_InflowForecasts()
	 * @see gluemodel.CIM.IEC61970.Generation.Production.InflowForecast#getReservoir
	 * @model opposite="Reservoir"
	 *        annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='A reservoir may have a \"natural\" inflow forecast.'"
	 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='A reservoir may have a \"natural\" inflow forecast.'"
	 * @generated
	 */
	EList<InflowForecast> getInflowForecasts();

	/**
	 * Returns the value of the 'Spill Travel Delay' attribute.
	 *
	 *

	 * If the meaning of the 'Spill Travel Delay' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Spill Travel Delay' attribute.
	 * @see #setSpillTravelDelay(float)
	 * @see gluemodel.CIM.IEC61970.Generation.Production.ProductionPackage#getReservoir_SpillTravelDelay()
	 * @model dataType="gluemodel.CIM.IEC61970.Domain.Seconds" required="true"
	 *        annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='The spillway water travel delay to the next downstream reservoir'"
	 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='The spillway water travel delay to the next downstream reservoir'"
	 * @generated
	 */
	float getSpillTravelDelay();

	/**
	 * Sets the value of the '{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getSpillTravelDelay Spill Travel Delay}' attribute.
	 *
	 *
	 * @param value the new value of the 'Spill Travel Delay' attribute.
	 * @see #getSpillTravelDelay()
	 * @generated
	 */
	void setSpillTravelDelay(float value);

	/**
	 * Returns the value of the 'River Outlet Works' attribute.
	 *
	 *

	 * If the meaning of the 'River Outlet Works' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'River Outlet Works' attribute.
	 * @see #setRiverOutletWorks(String)
	 * @see gluemodel.CIM.IEC61970.Generation.Production.ProductionPackage#getReservoir_RiverOutletWorks()
	 * @model required="true"
	 *        annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='River outlet works for riparian right releases or other purposes'"
	 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='River outlet works for riparian right releases or other purposes'"
	 * @generated
	 */
	String getRiverOutletWorks();

	/**
	 * Sets the value of the '{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getRiverOutletWorks River Outlet Works}' attribute.
	 *
	 *
	 * @param value the new value of the 'River Outlet Works' attribute.
	 * @see #getRiverOutletWorks()
	 * @generated
	 */
	void setRiverOutletWorks(String value);

	/**
	 * Returns the value of the 'Normal Min Operate Level' attribute.
	 *
	 *

	 * If the meaning of the 'Normal Min Operate Level' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Normal Min Operate Level' attribute.
	 * @see #setNormalMinOperateLevel(float)
	 * @see gluemodel.CIM.IEC61970.Generation.Production.ProductionPackage#getReservoir_NormalMinOperateLevel()
	 * @model dataType="gluemodel.CIM.IEC61970.Domain.WaterLevel" required="true"
	 *        annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Normal minimum operating level below which the penstocks will draw air'"
	 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Normal minimum operating level below which the penstocks will draw air'"
	 * @generated
	 */
	float getNormalMinOperateLevel();

	/**
	 * Sets the value of the '{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getNormalMinOperateLevel Normal Min Operate Level}' attribute.
	 *
	 *
	 * @param value the new value of the 'Normal Min Operate Level' attribute.
	 * @see #getNormalMinOperateLevel()
	 * @generated
	 */
	void setNormalMinOperateLevel(float value);

	/**
	 * Returns the value of the 'Spillway Crest Level' attribute.
	 *
	 *

	 * If the meaning of the 'Spillway Crest Level' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Spillway Crest Level' attribute.
	 * @see #setSpillwayCrestLevel(float)
	 * @see gluemodel.CIM.IEC61970.Generation.Production.ProductionPackage#getReservoir_SpillwayCrestLevel()
	 * @model dataType="gluemodel.CIM.IEC61970.Domain.WaterLevel" required="true"
	 *        annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Spillway crest level above which water will spill'"
	 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Spillway crest level above which water will spill'"
	 * @generated
	 */
	float getSpillwayCrestLevel();

	/**
	 * Sets the value of the '{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getSpillwayCrestLevel Spillway Crest Level}' attribute.
	 *
	 *
	 * @param value the new value of the 'Spillway Crest Level' attribute.
	 * @see #getSpillwayCrestLevel()
	 * @generated
	 */
	void setSpillwayCrestLevel(float value);

	/**
	 * Returns the value of the 'Full Supply Level' attribute.
	 *
	 *

	 * If the meaning of the 'Full Supply Level' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Full Supply Level' attribute.
	 * @see #setFullSupplyLevel(float)
	 * @see gluemodel.CIM.IEC61970.Generation.Production.ProductionPackage#getReservoir_FullSupplyLevel()
	 * @model dataType="gluemodel.CIM.IEC61970.Domain.WaterLevel" required="true"
	 *        annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Full supply level, above which water will spill. This can be the spillway crest level or the top of closed gates.'"
	 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Full supply level, above which water will spill. This can be the spillway crest level or the top of closed gates.'"
	 * @generated
	 */
	float getFullSupplyLevel();

	/**
	 * Sets the value of the '{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getFullSupplyLevel Full Supply Level}' attribute.
	 *
	 *
	 * @param value the new value of the 'Full Supply Level' attribute.
	 * @see #getFullSupplyLevel()
	 * @generated
	 */
	void setFullSupplyLevel(float value);

	/**
	 * Returns the value of the 'Spillway Capacity' attribute.
	 *
	 *

	 * If the meaning of the 'Spillway Capacity' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Spillway Capacity' attribute.
	 * @see #setSpillwayCapacity(float)
	 * @see gluemodel.CIM.IEC61970.Generation.Production.ProductionPackage#getReservoir_SpillwayCapacity()
	 * @model required="true"
	 *        annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='The flow capacity of the spillway in cubic meters per second'"
	 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='The flow capacity of the spillway in cubic meters per second'"
	 * @generated
	 */
	float getSpillwayCapacity();

	/**
	 * Sets the value of the '{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getSpillwayCapacity Spillway Capacity}' attribute.
	 *
	 *
	 * @param value the new value of the 'Spillway Capacity' attribute.
	 * @see #getSpillwayCapacity()
	 * @generated
	 */
	void setSpillwayCapacity(float value);

	/**
	 * Returns the value of the 'Target Level Schedule' reference.
	 * It is bidirectional and its opposite is '{@link gluemodel.CIM.IEC61970.Generation.Production.TargetLevelSchedule#getReservoir Reservoir}'.
	 *
	 *

	 * If the meaning of the 'Target Level Schedule' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Target Level Schedule' reference.
	 * @see #setTargetLevelSchedule(TargetLevelSchedule)
	 * @see gluemodel.CIM.IEC61970.Generation.Production.ProductionPackage#getReservoir_TargetLevelSchedule()
	 * @see gluemodel.CIM.IEC61970.Generation.Production.TargetLevelSchedule#getReservoir
	 * @model opposite="Reservoir"
	 *        annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='A reservoir may have a water level target schedule.'"
	 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='A reservoir may have a water level target schedule.'"
	 * @generated
	 */
	TargetLevelSchedule getTargetLevelSchedule();

	/**
	 * Sets the value of the '{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getTargetLevelSchedule Target Level Schedule}' reference.
	 *
	 *
	 * @param value the new value of the 'Target Level Schedule' reference.
	 * @see #getTargetLevelSchedule()
	 * @generated
	 */
	void setTargetLevelSchedule(TargetLevelSchedule value);

	/**
	 * Returns the value of the 'Spill Way Gate Type' attribute.
	 * The literals are from the enumeration {@link gluemodel.CIM.IEC61970.Generation.Production.SpillwayGateType}.
	 *
	 *

	 * If the meaning of the 'Spill Way Gate Type' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Spill Way Gate Type' attribute.
	 * @see gluemodel.CIM.IEC61970.Generation.Production.SpillwayGateType
	 * @see #setSpillWayGateType(SpillwayGateType)
	 * @see gluemodel.CIM.IEC61970.Generation.Production.ProductionPackage#getReservoir_SpillWayGateType()
	 * @model annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Type of spillway gate, including parameters'"
	 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Type of spillway gate, including parameters'"
	 * @generated
	 */
	SpillwayGateType getSpillWayGateType();

	/**
	 * Sets the value of the '{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getSpillWayGateType Spill Way Gate Type}' attribute.
	 *
	 *
	 * @param value the new value of the 'Spill Way Gate Type' attribute.
	 * @see gluemodel.CIM.IEC61970.Generation.Production.SpillwayGateType
	 * @see #getSpillWayGateType()
	 * @generated
	 */
	void setSpillWayGateType(SpillwayGateType value);

	/**
	 * Returns the value of the 'Spillway Crest Length' attribute.
	 *
	 *

	 * If the meaning of the 'Spillway Crest Length' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Spillway Crest Length' attribute.
	 * @see #setSpillwayCrestLength(float)
	 * @see gluemodel.CIM.IEC61970.Generation.Production.ProductionPackage#getReservoir_SpillwayCrestLength()
	 * @model dataType="gluemodel.CIM.IEC61970.Domain.Length" required="true"
	 *        annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='The length of the spillway crest'"
	 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='The length of the spillway crest'"
	 * @generated
	 */
	float getSpillwayCrestLength();

	/**
	 * Sets the value of the '{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getSpillwayCrestLength Spillway Crest Length}' attribute.
	 *
	 *
	 * @param value the new value of the 'Spillway Crest Length' attribute.
	 * @see #getSpillwayCrestLength()
	 * @generated
	 */
	void setSpillwayCrestLength(float value);

	/**
	 * Returns the value of the 'Energy Storage Rating' attribute.
	 *
	 *

	 * If the meaning of the 'Energy Storage Rating' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Energy Storage Rating' attribute.
	 * @see #setEnergyStorageRating(float)
	 * @see gluemodel.CIM.IEC61970.Generation.Production.ProductionPackage#getReservoir_EnergyStorageRating()
	 * @model required="true"
	 *        annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='The reservoir\'s energy storage rating in energy for given head conditions'"
	 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='The reservoir\'s energy storage rating in energy for given head conditions'"
	 * @generated
	 */
	float getEnergyStorageRating();

	/**
	 * Sets the value of the '{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getEnergyStorageRating Energy Storage Rating}' attribute.
	 *
	 *
	 * @param value the new value of the 'Energy Storage Rating' attribute.
	 * @see #getEnergyStorageRating()
	 * @generated
	 */
	void setEnergyStorageRating(float value);

	/**
	 * Returns the value of the 'Gross Capacity' attribute.
	 *
	 *

	 * If the meaning of the 'Gross Capacity' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Gross Capacity' attribute.
	 * @see #setGrossCapacity(float)
	 * @see gluemodel.CIM.IEC61970.Generation.Production.ProductionPackage#getReservoir_GrossCapacity()
	 * @model dataType="gluemodel.CIM.IEC61970.Domain.Volume" required="true"
	 *        annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Total capacity of reservoir'"
	 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Total capacity of reservoir'"
	 * @generated
	 */
	float getGrossCapacity();

	/**
	 * Sets the value of the '{@link gluemodel.CIM.IEC61970.Generation.Production.Reservoir#getGrossCapacity Gross Capacity}' attribute.
	 *
	 *
	 * @param value the new value of the 'Gross Capacity' attribute.
	 * @see #getGrossCapacity()
	 * @generated
	 */
	void setGrossCapacity(float value);

	/**
	 * Returns the value of the 'Hydro Power Plants' reference list.
	 * The list contents are of type {@link gluemodel.CIM.IEC61970.Generation.Production.HydroPowerPlant}.
	 * It is bidirectional and its opposite is '{@link gluemodel.CIM.IEC61970.Generation.Production.HydroPowerPlant#getReservoir Reservoir}'.
	 *
	 *

	 * If the meaning of the 'Hydro Power Plants' reference list isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Hydro Power Plants' reference list.
	 * @see gluemodel.CIM.IEC61970.Generation.Production.ProductionPackage#getReservoir_HydroPowerPlants()
	 * @see gluemodel.CIM.IEC61970.Generation.Production.HydroPowerPlant#getReservoir
	 * @model opposite="Reservoir"
	 *        annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Generators discharge water to or pumps are supplied water from a downstream reservoir'"
	 *        annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Generators discharge water to or pumps are supplied water from a downstream reservoir'"
	 * @generated
	 */
	EList<HydroPowerPlant> getHydroPowerPlants();

} // Reservoir


text:
extern "C" {
#endif

typedef union uwb {
    unsigned w;
    unsigned char b[4];
} WBunion;

unsigned* md5( const char *msg, int mlen);

#ifdef __cplusplus
}
#endif

#endif


text:
package io.reflectoring.solid.lsp.paymentexample.redesigned.validators;

import io.reflectoring.solid.lsp.paymentexample.common.exceptions.PaymentInstrumentInvalidException;
import java.util.Date;

public class BankCardBasicValidator implements IPaymentInstrumentValidator {
    String name;
    String cardNumber;
    String verificationCode;
    Date expiryDate;

    public BankCardBasicValidator(String name, String cardNumber, String verificationCode, Date expiryDate) {
        this.name = name;
        this.cardNumber = cardNumber;
        this.verificationCode = verificationCode;
        this.expiryDate = expiryDate;
    }

    @Override
    public void validate() throws PaymentInstrumentInvalidException {
        // basic validation on name, expiryDate etc.
        if (name == null || name.isEmpty()) {
            throw new PaymentInstrumentInvalidException("Name is invalid");
        }
        // other basic validations
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Concordion.Api;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using Concordion.Internal.Commands;

namespace Concordion.Spec
{
    class ProcessingResult
    {
        private readonly IResultSummary resultSummary;
        private readonly EventRecorder eventRecorder;
        private readonly string documentXML;

        public long SuccessCount
        {
            get
            {
                return resultSummary.SuccessCount;
            }
        }

        public long FailureCount
        {
            get
            {
                return resultSummary.FailureCount;
            }
        }

        public long ExceptionCount
        {
            get
            {
                return resultSummary.ExceptionCount;
            }
        }

        public bool HasFailures
        {
            get
            {
                return FailureCount + ExceptionCount != 0;
            }
        }

        public bool IsSuccess
        {
            get
            {
                return !HasFailures;
            }
        }

        public ProcessingResult(IResultSummary resultSummary, EventRecorder eventRecorder, string documentXML)
        {
            this.resultSummary = resultSummary;
            this.eventRecorder = eventRecorder;
            this.documentXML = documentXML;
        }

        public string SuccessOrFailureInWords()
        {
            return HasFailures ? "FAILURE" : "SUCCESS";
        }

        public XElement GetOutputFragment()
        {
            foreach (var descendant in GetXDocument().Root.Descendants("fragment"))
            {
                return descendant;
            }
            return null;
        }

        public string GetOutputFragmentXML()
        {
            var fragment = GetOutputFragment();
            var xmlFragmentBuilder = new StringBuilder();
            foreach (var child in fragment.Elements())
            {
                //xmlFragmentBuilder.Append(child.ToString(SaveOptions.DisableFormatting).Replace(" xmlns:concordion=\"http://www.concordion.org/2007/concordion\"", String.Empty));
                xmlFragmentBuilder.Append(child.ToString().Replace(" xmlns:concordion=\"http://www.concordion.org/2007/concordion\"", String.Empty));
            }

            return xmlFragmentBuilder.ToString();
        }

        public XDocument GetXDocument()
        {
            return XDocument.Parse(documentXML);
        }

        public FailureReportedEventArgs GetLastAssertEqualsFailureEvent()
        {
            return eventRecorder.GetLast<FailureReportedEventArgs>();
        }
    }
}


text:
from __future__ import absolute_import

from datetime import datetime, timedelta

from sentry.models import GroupHash
from sentry.testutils import TestCase, SnubaTestCase
from sentry.utils import snuba

class SnubaUtilTest(TestCase, SnubaTestCase):
    def test_filter_keys_set(self):
        snuba.raw_query(
            start=datetime.now(),
            end=datetime.now(),
            filter_keys={"project_id": set([1]), "logger": set(["asdf"])},
            aggregations=[["count()", "", "count"]],
        )

    def test_shrink_timeframe(self):
        now = datetime.now()
        year_ago = now - timedelta(days=365)

        issues = None
        assert snuba.shrink_time_window(issues, year_ago) == year_ago

        issues = []
        assert snuba.shrink_time_window(issues, year_ago) == year_ago

        group1 = self.create_group()
        group1.first_seen = now - timedelta(hours=1)
        group1.last_seen = now
        group1.save()
        GroupHash.objects.create(project_id=group1.project_id, group=group1, hash="a" * 32)

        group2 = self.create_group()
        GroupHash.objects.create(project_id=group2.project_id, group=group2, hash="b" * 32)

        issues = [group1.id]
        assert snuba.shrink_time_window(issues, year_ago) == now - timedelta(hours=1, minutes=5)

        issues = [group1.id, group2.id]
        assert snuba.shrink_time_window(issues, year_ago) == year_ago

        # with pytest.raises(snuba.QueryOutsideGroupActivityError):
        #    # query a group for a time range before it had any activity
        #    snuba.raw_query(
        #        start=group1.first_seen - timedelta(days=1, hours=1),
        #        end=group1.first_seen - timedelta(days=1),
        #        filter_keys={
        #            'project_id': [group1.project_id],
        #            'issue': [group1.id],
        #        },
        #        aggregations=[
        #            ['count()', '', 'count'],
        #        ],
        #    )

    def test_override_options(self):
        assert snuba.OVERRIDE_OPTIONS == {"consistent": False}
        with snuba.options_override({"foo": 1}):
            assert snuba.OVERRIDE_OPTIONS == {"foo": 1, "consistent": False}
            with snuba.options_override({"foo": 2}):
                assert snuba.OVERRIDE_OPTIONS == {"foo": 2, "consistent": False}
            assert snuba.OVERRIDE_OPTIONS == {"foo": 1, "consistent": False}
        assert snuba.OVERRIDE_OPTIONS == {"consistent": False}


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>emus.autocorrelation — emus  documentation</title>

  <link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />

             emus

  <form id="rtd-search-form" class="wy-form" action="../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

Background

Quickstart

Data Structures

EMUS Modules

          emus

Docs »

Module code »

emus.autocorrelation

Source code for emus.autocorrelation

# -*- coding: utf-8 -*-
""" Tools for analyzing the autocorrelation time of a time series.

The ipce and icce routines are implementations of the initial positive correlation time estimator, and the initial convex correlation estimator proposed by Geyer [1]_.
The acor algorithm was proposed by Sokal [2]_.  The associated code, as well as the code for constructiing autocorrelation functions is taken from the emcee package [3]_.

.. [1] C.J. Geyer. Statistical Science (1992): 473-483.
.. [2] A. Sokal, Functional Integration. Spring, Boston, MA, 1997. 131-192.
.. [3] D. Foreman-Mackey, D.W. Hogg, D. Lang, and J. Goodman. Publications of the Astronomical Society of the Pacific 125.925 (2013): 306.
"""
import numpy as np
import logging

def _next_pow_two(n):
    """Returns the next power of two greater than or equal to `n`"""
    i = 1
    while i < n:
        i = i << 1
    return i

def _auto_window(taus, c):
    m = np.arange(len(taus)) < c * taus
    if np.any(m):
        return np.argmin(m)
    return len(taus) - 1

[docs]def autocorrfxn(x):
    """Estimate the normalized autocorrelation function of a 1-D series

    Parameters
    ----------
    x : ndarray
        The time series of which to calculate the autocorrelation function.

    Returns
    -------
    acfxn : ndarray
        The autocorrelation as a function of lag time.
    """
    x = np.atleast_1d(x)
    if len(x.shape) != 1:
        raise ValueError("invalid dimensions for 1D autocorrelation function")
    n = _next_pow_two(len(x))

    # Compute the FFT and then (from that) the auto-correlation function
    f = np.fft.fft(x - np.mean(x), n=2*n)
    acf = np.fft.ifft(f * np.conjugate(f))[:len(x)].real
    acf /= acf[0]
    return acf

[docs]def ipce(x):
    """ The initial positive correlation time estimator for the autocorrelation time, as proposed by Geyer.

    Parameters
    ----------
    x : ndarray
        The time series of which to calculate the autocorrelation function.

    Returns
    -------
    tau : float
        Estimate of the autocorrelation time.
    mean : float
        Average value of x
    sigma : float
        Estimate of the square root of the autocovariance of x

    """
    x = np.copy(x)
    mean = np.average(x)
    corrfxn = autocorrfxn(x)
    lagmax = int(len(x) / 2)
    i = 0
    t = 0
    while i < 0.5*lagmax:
        gamma = corrfxn[2*i] + corrfxn[2*i+1]
        if gamma < 0.0:
            #            print 'stop at ',2*i
            break
        else:
            t += gamma
        i += 1
    tau = 2*t - 1
    var = np.var(x)
    sigma = np.sqrt(var * tau / len(x))
    return tau, mean, sigma

[docs]def integrated_time(x, c=5, tol=50, quiet=False):
    """ Estimate the integrated autocorrelation time of a time series.
    This estimate uses the iterative procedure described on page 16 of
    `Sokal's notes <http://www.stat.unc.edu/faculty/cji/Sokal.pdf>`_ to
    determine a reasonable window size.

    Parameters
    ----------
    x : ndarray
        The time series of which to calculate the autocorrelation function.
    c : float
        The step size for the window search. Default is 5.
    tol : int
        The minimum number of autocorrelation times needed to trust the estimate. Default is 50.
    quiet : bool, optional
        This argument controls the behavior when the chain is too short. If True, gives a warning instead of raising an error.  Default is True

    Returns
    -------
    tau : float
        Estimate of the autocorrelation time.

    Raises
    ------
        ValueError: If the autocorrelation time can't be reliably estimated
            from the chain and ``quiet`` is ``False``. This normally means
            that the chain is too short.
    """
    x = np.atleast_1d(x)
    if len(x.shape) == 1:
        x = x[:, np.newaxis, np.newaxis]
    if len(x.shape) == 2:
        x = x[:, :, np.newaxis]
    if len(x.shape) != 3:
        raise ValueError("invalid dimensions")

    n_t, n_w, n_d = x.shape
    tau_est = np.empty(n_d)
    windows = np.empty(n_d, dtype=int)

    # Loop over parameters
    for d in range(n_d):
        f = np.zeros(n_t)
        for k in range(n_w):
            f += autocorrfxn(x[:, k, d])
        f /= n_w
        taus = 2.0*np.cumsum(f)-1.0
        windows[d] = _auto_window(taus, c)
        tau_est[d] = taus[windows[d]]

    # Check convergence
    flag = tol * tau_est > n_t

    # Warn or raise in the case of non-convergence
    if np.any(flag):
        msg = (
            "The chain is shorter than {0} times the integrated "
            "autocorrelation time for {1} parameter(s). Use this estimate "
            "with caution and run a longer chain!\n"
        ).format(tol, np.sum(flag))
        msg += "N/{0} = {1:.0f};\ntau: {2}".format(tol, n_t/tol, tau_est)
        if not quiet:
            raise ValueError(msg)
        logging.warning(msg)

    return tau_est

[docs]def acor(x, tol=10, quiet=True):
    """ Acor algorithm, as proposed by Sokal and implemented in EMCEE.

    Parameters
    ----------
    x : ndarray
        The time series of which to calculate the autocorrelation function.
    tol : int, optional
        The minimum number of autocorrelation times needed to trust the estimate.  Default is 10.
    quiet : bool, optional
        This argument controls the behavior when the chain is too short. If True, gives a warning instead of raising an error.  Default is True

    Returns
    -------
    tau : float
        Estimate of the autocorrelation time.
    mean : float
        Average value of x
    sigma : float
        Estimate of the square root of the autocovariance of x
    """
    mean = np.average(x)
    tau = integrated_time(x, tol=tol, quiet=quiet)
    var = np.var(x)
    sigma = np.sqrt(var * tau / len(x))
    return tau, mean, sigma

[docs]def icce(x):
    """The initial convex correlation time estimator for the autocorrelation time, as proposed by Geyer.

    Parameters
    ----------
    x : ndarray
        The time series of which to calculate the autocorrelation function.

    Returns
    -------
    tau : float
        Estimate of the autocorrelation time.
    mean : float
        Average value of x
    sigma : float
        Estimate of the square root of the autocovariance of x

    """
    x = np.copy(x)
    lagmax = int(len(x) / 2)
    corrfxn = autocorrfxn(x)
    t = corrfxn[0] + corrfxn[1]
    i = 1
    gammapast = t
    gamma = corrfxn[2*i] = corrfxn[2*i+1]
    while i < 0.5*lagmax-2:
        gammafuture = corrfxn[2*i+2] + corrfxn[2*i+3]
        if gamma > 0.5*(gammapast+gammafuture):
            break
        else:
            t += gamma
            gammapast = gamma
            gamma = gammafuture
        i += 1
    tau = 2*t - 1
    var = np.var(x)
    mean = np.average(x)
    sigma = np.sqrt(var * tau / len(x))
    return tau, mean, sigma

def _get_iat_method(iat_method):
    """Control routine for selecting the method used to calculate integrated
    autocorrelation times (iat)

    Parameters
    ----------
    iat_method : string, optional
        Routine to use for calculating said iats.  Accepts 'ipce', 'acor', and 'icce'.

    Returns
    -------
    iatroutine : function
        The function to be called to estimate the integrated autocorrelation time.

    """
    if iat_method == 'acor':
        # from autocorrelation import acor
        iatroutine = acor
    elif iat_method == 'ipce':
        # from autocorrelation import ipce
        iatroutine = ipce
    elif iat_method == 'icce':
        # from autocorrelation import icce
        iatroutine = icce
    else:
        raise ValueError('Method for calculation iat not recognized.')
    return iatroutine

        © Copyright 2016, Erik H Thiede.

  Built with Sphinx using a theme provided by Read the Docs.