text:
"""Arm Compute Library supported operators."""
import tvm
from tvm import relay
from tvm._ffi import register_func
from tvm.relay import transform
from tvm.relay.build_module import bind_params_by_name
from tvm.relay.expr import const

from ...dataflow_pattern import is_constant, is_expr, is_op, wildcard
from ..strategy.generic import is_depthwise_conv2d
from .register import register_pattern_table

def is_arm_compute_runtime_enabled():
    """Check if the ACL graph executor is present.

    Returns
    -------
    ret: bool
        True if present, False if not.
    """
    check_enabled = tvm.get_global_func("relay.op.is_arm_compute_runtime_enabled", True)
    if check_enabled:
        return check_enabled()
    return False

def partition_for_arm_compute_lib(mod, params=None, **opts):
    """Partition the graph greedily offloading supported
    operators to Arm Compute Library.

    Parameters
    ----------
    mod : Module
        The module to run passes on.
    params : Optional[Dict[str, NDArray]]
        Constant input parameters.

    Returns
    -------
    ret : annotated and partitioned module.
    """
    if params:
        mod["main"] = bind_params_by_name(mod["main"], params)

    seq = tvm.transform.Sequential(
        [
            transform.InferType(),
            transform.MergeComposite(arm_compute_lib_pattern_table()),
            transform.AnnotateTarget("arm_compute_lib", False),
            transform.PartitionGraph(),
        ]
    )

    return seq(mod)

@register_func("relay.ext.arm_compute_lib.optimize")
def preprocess_module(mod):
    """
    Pre-process a module containing functions ready for ACL codegen. For now we enforce OHWI
    kernel layout and fold the transforms away.

    Parameters
    ----------
    mod : Module
        The module to run passes on.

    Returns
    -------
    preprocessed_mod : The processed module.
    """

    def convert_layout_conv2d(conv2d_function):
        def convert_conv(attrs, inputs, tinfos, desired_layouts):
            new_attrs = dict(attrs)
            data_info = tinfos[0]
            weight_info = tinfos[1]
            desired_data_layout, desired_kernel_layout = map(str, desired_layouts)
            new_attrs["data_layout"] = desired_data_layout
            new_attrs["kernel_layout"] = desired_kernel_layout

            if is_depthwise_conv2d(
                data_info.shape,
                attrs["data_layout"],
                weight_info.shape,
                attrs["kernel_layout"],
                attrs["groups"],
            ):
                dkl = desired_kernel_layout
                new_attrs["kernel_layout"] = dkl[3] + dkl[1:3] + dkl[0]
            return conv2d_function(*inputs, **new_attrs)

        return convert_conv

    with OpAttrContext(
        "nn.conv2d", "FTVMConvertOpLayout", convert_layout_conv2d(tvm.relay.nn.conv2d)
    ), OpAttrContext(
        "qnn.conv2d", "FTVMConvertOpLayout", convert_layout_conv2d(tvm.relay.qnn.op.conv2d)
    ):
        seq = tvm.transform.Sequential(
            [
                transform.ConvertLayout(
                    {"nn.conv2d": ["NHWC", "OHWI"], "qnn.conv2d": ["NHWC", "OHWI"]}
                ),
                transform.FoldConstant(),
            ]
        )
        preprocessed_mod = seq(mod)
    return preprocessed_mod

@register_pattern_table("arm_compute_lib")
def arm_compute_lib_pattern_table():
    """Get the ACL pattern table."""

    def conv_pattern():
        """Create a convolution pattern.

        Returns
        -------
        pattern : dataflow_pattern.AltPattern
            Denotes the convolution pattern.
        """
        pattern = is_op("nn.pad")(wildcard(), wildcard()) | wildcard()
        pattern = is_op("nn.conv2d")(pattern, is_constant())
        pattern = pattern.optional(lambda x: is_op("nn.bias_add")(x, is_constant()))
        pattern = pattern.optional(is_op("nn.relu"))
        return pattern

    def qnn_conv_pattern():
        """Create a quantized convolution pattern.

        Returns
        -------
        pattern : dataflow_pattern.AltPattern
            Denotes the convolution pattern.
        """
        pattern = is_op("nn.pad")(wildcard(), wildcard()) | wildcard()
        pattern = is_op("qnn.conv2d")(
            pattern, is_constant(), is_constant(), is_constant(), is_constant(), is_constant()
        )
        pattern = pattern.optional(lambda x: is_op("nn.bias_add")(x, is_constant()))
        pattern = pattern.optional(is_op("nn.relu"))
        pattern = is_op("qnn.requantize")(
            pattern, wildcard(), wildcard(), is_constant(), is_constant()
        )
        return pattern

    def dense_pattern():
        """Create a dense (fully-connected) pattern.

        Returns
        -------
        pattern : dataflow_pattern.AltPattern
            Denotes the convolution pattern.
        """
        pattern = is_op("nn.dense")(wildcard(), is_constant())
        pattern = pattern.optional(lambda x: is_op("nn.bias_add")(x, is_constant()))
        return pattern

    def qnn_dense_pattern():
        """Create a quantized dense (fully-connected) pattern.

        Returns
        -------
        pattern : dataflow_pattern.AltPattern
            Denotes the convolution pattern.
        """
        pattern = is_op("qnn.dense")(
            wildcard(), is_constant(), is_constant(), is_constant(), is_constant(), is_constant()
        )
        pattern = pattern.optional(lambda x: is_op("nn.bias_add")(x, is_constant()))
        pattern = is_op("qnn.requantize")(
            pattern, wildcard(), wildcard(), is_constant(), is_constant()
        )
        return pattern

    def avg_pool2d_pattern():
        """Creates a pattern that matches either quantized
        avg_pool2d or quantized global_avg_pool2d.

        Returns
        -------
        pattern : dataflow_pattern.AltPattern
            Denotes the convolution pattern.
        """
        pattern = is_op("cast")(wildcard())
        pattern = is_op("nn.avg_pool2d")(pattern) | is_op("nn.global_avg_pool2d")(pattern)
        pattern = is_op("cast")(pattern)
        return pattern

    def l2_pool2d_pattern():
        """Create an l2 pooling pattern from equivalent relay operators.

        Returns
        -------
        pattern : dataflow_pattern.AltPattern
            Denotes the convolution pattern.
        """
        pattern = is_op("power")(wildcard(), is_expr(const(2.0)))
        pattern = is_op("nn.avg_pool2d")(pattern)
        pattern = is_op("sqrt")(pattern)
        return pattern

    def check_conv(extract):
        """Check conv pattern is supported by ACL."""
        call = extract
        while call.op.name != "nn.conv2d":
            call = call.args[0]
        return conv2d(call)

    def check_qnn_conv(extract):
        """Check qnn conv pattern is supported by ACL."""
        if extract.attrs.out_dtype != "uint8":
            return False
        call = extract
        while call.op.name != "qnn.conv2d":
            call = call.args[0]
        return qnn_conv2d(call)

    def check_dense(extract):
        """Check conv pattern is supported by ACL."""
        call = extract
        while call.op.name != "nn.dense":
            call = call.args[0]
        return dense(call)

    def check_qnn_dense(extract):
        """Check qnn conv pattern is supported by ACL."""
        if extract.attrs.out_dtype != "uint8":
            return False
        call = extract
        while call.op.name != "qnn.dense":
            call = call.args[0]
        return qnn_dense(call)

    def check_avg_pool2d(extract):
        """Check average pool2d pattern is supported by ACL."""
        if extract.attrs.dtype != "uint8":
            return False
        pool = extract.args[0]
        if pool.args[0].attrs.dtype != "int32":
            return False
        return avg_pool2d(pool, from_quantized_composite=True)

    def check_l2_pool2d(extract):
        """Check l2 pool2d pattern is supported by ACL."""
        pool = extract.args[0]
        return avg_pool2d(pool)

    return [
        ("arm_compute_lib.conv2d", conv_pattern(), check_conv),
        ("arm_compute_lib.qnn_conv2d", qnn_conv_pattern(), check_qnn_conv),
        ("arm_compute_lib.dense", dense_pattern(), check_dense),
        ("arm_compute_lib.qnn_dense", qnn_dense_pattern(), check_qnn_dense),
        ("arm_compute_lib.qnn_conv2d", qnn_conv_pattern(), check_qnn_conv),
        ("arm_compute_lib.avg_pool2d", avg_pool2d_pattern(), check_avg_pool2d),
        ("arm_compute_lib.l2_pool2d", l2_pool2d_pattern(), check_l2_pool2d),
    ]

def _register_external_op_helper(op_name, supported=True):
    @tvm.ir.register_op_attr(op_name, "target.arm_compute_lib")
    def _func_wrapper(expr):
        return supported

    return _func_wrapper

_register_external_op_helper("reshape")

@tvm.ir.register_op_attr("nn.conv2d", "target.arm_compute_lib")
def conv2d(expr):
    """Check if the external ACL codegen for conv2d should be used."""
    attrs, args = expr.attrs, expr.args
    if attrs.data_layout != "NHWC":
        return False
    if attrs.out_dtype != "float32" and attrs.out_dtype != "":
        return False
    data_typ = args[0].checked_type
    if len(data_typ.shape) != 4 or data_typ.shape[0] != 1 or data_typ.dtype != "float32":
        return False
    kernel_typ = args[1].checked_type
    if len(kernel_typ.shape) != 4 or kernel_typ.dtype != "float32":
        return False
    is_depthwise = is_depthwise_conv2d(
        data_typ.shape,
        attrs["data_layout"],
        kernel_typ.shape,
        attrs["kernel_layout"],
        attrs["groups"],
    )
    if is_depthwise:
        return depthwise_conv2d(attrs, args)
    # ACL doesn't support grouped convolution
    if attrs.groups != 1 and not is_depthwise:
        return False
    return True

def qnn_conv2d(expr):
    """Check if the external ACL codegen for qnn.conv2d should be used."""
    attrs, args = expr.attrs, expr.args

    if attrs.data_layout != "NHWC":
        return False
    if attrs.out_dtype != "int32" and attrs.out_dtype != "":
        return False
    data_typ = args[0].checked_type
    if len(data_typ.shape) != 4 or data_typ.shape[0] != 1 or data_typ.dtype != "uint8":
        return False
    kernel_typ = args[1].checked_type
    if len(kernel_typ.shape) != 4 or kernel_typ.dtype != "uint8":
        return False
    is_depthwise = is_depthwise_conv2d(
        data_typ.shape,
        attrs["data_layout"],
        kernel_typ.shape,
        attrs["kernel_layout"],
        attrs["groups"],
    )
    if is_depthwise:
        return depthwise_conv2d(attrs, args)
    # ACL doesn't support grouped convolution
    if attrs.groups != 1 and not is_depthwise:
        return False
    return True

def depthwise_conv2d(attrs, args):
    """Check if the external ACL codegen for depthwise convolution should be used.

    Note
    ----
    Relay does not have a depthwise conv2d operator whilst ACL does. We simply
    separate the checks for depthwise for clarity.
    """
    kernel_typ = args[1].checked_type
    # Only supports 3x3, 5x5 depthwise
    if (
        kernel_typ.shape[0] not in [3, 5]
        or kernel_typ.shape[1] not in [3, 5]
        or kernel_typ.shape[0] != kernel_typ.shape[1]
    ):
        return False
    # Stride must be (1, 1) or (2, 2)
    if (attrs.strides[0], attrs.strides[1]) not in [(1, 1), (2, 2)]:
        return False
    return True

@tvm.ir.register_op_attr("nn.dense", "target.arm_compute_lib")
def dense(expr):
    """Check if the external ACL codegen for dense should be used."""
    attrs, args = expr.attrs, expr.args
    data_typ = args[0].checked_type
    if data_typ.dtype != "float32":
        return False
    kernel_typ = args[1].checked_type
    if len(kernel_typ.shape) != 2 or kernel_typ.dtype != "float32":
        return False
    if attrs.out_dtype != "float32" and attrs.out_dtype != "":
        return False
    return True

def qnn_dense(expr):
    """Check if the external ACL codegen for qnn.dense should be used."""
    attrs, args = expr.attrs, expr.args
    data_typ = args[0].checked_type
    if data_typ.dtype != "uint8":
        return False
    kernel_typ = args[1].checked_type
    if len(kernel_typ.shape) != 2 or kernel_typ.dtype != "uint8":
        return False
    if attrs.out_dtype != "int32":
        return False
    return True

def check_dilation(attrs):
    """Prevents offloading if dilation other than (1, 1)"""
    if not isinstance(attrs, relay.op.op_attrs.GlobalPool2DAttrs):
        if not (len(attrs.dilation) == 2 and attrs.dilation[0] == 1 and attrs.dilation[1] == 1):
            return False
    return True

@tvm.ir.register_op_attr("nn.max_pool2d", "target.arm_compute_lib")
def max_pool2d(expr):
    """Check if the external ACL codegen for maxpool2d should be used."""
    attrs, args = expr.attrs, expr.args
    if attrs.layout != "NHWC":
        return False
    typ = args[0].checked_type
    if typ.dtype not in ["float32", "uint8"]:
        return False
    return check_dilation(attrs)

@tvm.ir.register_op_attr("nn.avg_pool2d", "target.arm_compute_lib")
def avg_pool2d(expr, from_quantized_composite=False):
    """Check if the external ACL codegen for avgpool2d should be used."""
    attrs, args = expr.attrs, expr.args
    typ = args[0].checked_type

    if from_quantized_composite:
        if typ.dtype != "int32":
            return False
    else:
        if typ.dtype not in ["float32"]:
            return False
    if attrs.layout != "NHWC":
        return False

    return check_dilation(attrs)

@tvm.ir.register_op_attr("nn.global_max_pool2d", "target.arm_compute_lib")
def global_max_pool2d(expr):
    """Check if the external ACL codegen for gloval_maxpool2d should be used."""
    attrs, args = expr.attrs, expr.args
    typ = args[0].checked_type
    if typ.dtype not in ["float32", "uint8"]:
        return False
    if attrs.layout != "NHWC":
        return False
    return True

@tvm.ir.register_op_attr("nn.global_avg_pool2d", "target.arm_compute_lib")
def global_avg_pool2d(expr):
    """Check if the external ACL codegen for global_avgpool2d should be used."""
    attrs, args = expr.attrs, expr.args
    typ = args[0].checked_type
    if typ.dtype not in ["float32"]:
        return False
    if attrs.layout != "NHWC":
        return False
    return True

@tvm.ir.register_op_attr("maximum", "target.arm_compute_lib")
def maximum(expr):
    """Check if the external ACL codegen for maximum should be used."""
    args = expr.args
    type_a = args[0].checked_type
    type_b = args[0].checked_type
    return (type_a.dtype == "float32") and (type_b.dtype == "float32")

@tvm.ir.register_op_attr("add", "target.arm_compute_lib")
def add(expr):
    """Check if the external ACL codegen for add should be used."""
    args = expr.args
    for typ in [args[0].checked_type, args[1].checked_type]:
        if typ.dtype != "float32":
            return False

    return True

@tvm.ir.register_op_attr("qnn.add", "target.arm_compute_lib")
def qnn_add(expr):
    """Check if the external ACL codegen for add should be used."""
    args = expr.args
    for typ in [args[0].checked_type, args[1].checked_type]:
        if typ.dtype != "uint8":
            return False

    return True

class OpAttrContext(object):
    """Temporarily changes the attr of an op."""

    def __init__(self, op_name, attr_key, attr_value):
        """Saves the required info for RAII pattern usage.

        Parameters
        ----------
        op_name : str
            The op name.

        attr_key : str
            The attribute name.

        attr_value : object
            The attribute value.
        """
        self.op = relay.op.get(op_name)
        self.attr_key = attr_key
        self.attr_value = attr_value

    def __enter__(self):
        self.older_attr = self.op.get_attr(self.attr_key)
        self.op.reset_attr(self.attr_key)
        self.op.set_attr(self.attr_key, self.attr_value)
        return self

    def __exit__(self, ptype, value, trace):
        self.op.reset_attr(self.attr_key)
        if self.older_attr:
            self.op.set_attr(self.attr_key, self.older_attr)


text:
require 'test_helper'

class TransportRequisitionsControllerTest < ActionDispatch::IntegrationTest
  include Devise::Test::IntegrationHelpers

  setup do
    sign_in users(:admin)
    @transport_requisition = transport_requisitions(:transport_requisition1)
    @location = locations(:location1)
    @operation = operations(:operation2)
    @user = users(:tr_creator)
  end

  test "should get index" do
    get transport_requisitions_url
    assert_response :success
  end

  test "should get new" do
    get new_transport_requisition_url
    assert_response :success
  end

  test "should create transport_requisition" do
    post transport_requisitions_url, params: { transport_requisition: { certified_by: @transport_requisition.certified_by, certified_date: @transport_requisition.certified_date, deleted_at: @transport_requisition.deleted_at, location_id: @transport_requisition.location_id, operation_id: @transport_requisition.operation_id, reference_number: @transport_requisition.reference_number, description: @transport_requisition.description, status: @transport_requisition.status } }

    assert_response :success
  end

  test "should show transport_requisition" do
    get transport_requisition_url('en',@transport_requisition)
    assert_response :success
  end

  test "should get edit" do
    get edit_transport_requisition_url('en',@transport_requisition)
    assert_response :success
  end

  test "should update transport_requisition" do
    patch transport_requisition_url('en',@transport_requisition), params: { transport_requisition: { certified_by: @transport_requisition.certified_by, certified_date: @transport_requisition.certified_date, deleted_at: @transport_requisition.deleted_at, location_id: @transport_requisition.location_id, operation_id: @transport_requisition.operation_id, reference_number: @transport_requisition.reference_number, description: @transport_requisition.description, status: @transport_requisition.status } }
    assert_redirected_to '/en/transport_requisitions.' + @transport_requisition.id.to_s
  end

  test "should destroy transport_requisition" do
    assert_difference('TransportRequisition.count', -1) do
      delete transport_requisition_url('en',@transport_requisition)
    end

    assert_redirected_to transport_requisitions_url
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * @file
 * Contains \Drupal\Core\DependencyInjection\ContainerNotInitializedException.
 */

namespace Drupal\Core\DependencyInjection;

/**
 * Exception thrown when a method is called that requires a container, but the
 * container is not initialized yet.
 *
 * @see \Drupal
 */
class ContainerNotInitializedException extends \RuntimeException {

}


text:
package org.apache.camel.component.jms.issues;

import org.apache.camel.ServiceStatus;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jms.AbstractJMSTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;

import static org.apache.camel.ServiceStatus.Started;
import static org.apache.camel.ServiceStatus.Stopped;
import static org.junit.jupiter.api.Assertions.assertEquals;

@TestInstance(TestInstance.Lifecycle.PER_METHOD)
public class JmsLifecycleIssueTest extends AbstractJMSTest {

    public static final String ROUTE_ID = "JmsLifecycleIssueTestRoute";
    public static final String ENDPOINT_URI = "activemq:JmsLifecycleIssueTest.processOrder";

    @Test
    public void routeThatIsStoppedAndThenResumedAcceptsMessage() throws Exception {
        assertThatRouteIs(Stopped);

        context.getRouteController().resumeRoute(ROUTE_ID);

        assertRouteWorks();
    }

    @Test
    public void routeThatIsStoppedSuspendedAndThenResumedAcceptsMessage() throws Exception {
        assertThatRouteIs(Stopped);

        context.getRouteController().resumeRoute(ROUTE_ID);
        context.getRouteController().resumeRoute(ROUTE_ID);

        assertRouteWorks();
    }

    private void assertThatRouteIs(ServiceStatus expectedStatus) {
        assertEquals(expectedStatus, context.getRouteController().getRouteStatus(ROUTE_ID));
    }

    private void assertRouteWorks() throws Exception {
        assertThatRouteIs(Started);

        getMockEndpoint("mock:result").expectedBodiesReceived("anything");

        template.sendBody(ENDPOINT_URI, "anything");

        assertMockEndpointsSatisfied();
    }

    @Override
    protected String getComponentName() {
        return "activemq";
    }

    @Override
    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                context.addRoutes(new RouteBuilder() {
                    @Override
                    public void configure() {
                        from(ENDPOINT_URI).routeId(ROUTE_ID).autoStartup(false)
                                .to("log:input")
                                .to("mock:result");
                    }
                });
            }
        };
    }
}


text:
FactoryGirl.define do
  factory :category do
    sequence(:name) { |n| "Category #{n}" }
    type 'Essential'
  end
end


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

<title>GyrocompassTest</title>
<meta name="date" content="2015-11-14">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

testing

Class GyrocompassTest

java.lang.Object

testing.GyrocompassTest

public class GyrocompassTest
extends java.lang.Object

Constructor Summary

Constructors

Constructor and Description

GyrocompassTest()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
testUpdateDirection()

void
testUpdatePitch()

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

GyrocompassTest

public GyrocompassTest()

Method Detail

testUpdateDirection

public void testUpdateDirection()

testUpdatePitch

public void testUpdatePitch()

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Can. J. Bot. 42: 416 (1964)

#### Original name
Cryptostictis hollosii Tóth

### Remarks
null


text:
#include "device.h"
#if DEVICE_ANALOGIN

#include "mbed_assert.h"
#include "analogin_api.h"

#include "pinmap.h"
#include "pinmap_function.h"
#include "PeripheralPins.h"

#include "em_adc.h"
#include "em_cmu.h"

uint8_t analogin_get_index(analogin_t *obj)
{
    return 0; //only one module availalbe
}

void analogin_preinit(analogin_t *obj, PinName pin)
{
    obj->adc = (ADC_TypeDef *) pinmap_peripheral(pin, PinMap_ADC);
    MBED_ASSERT((int) obj->adc != NC);

    obj->channel = pin_location(pin, PinMap_ADC);
    MBED_ASSERT((int) obj->channel != NC);
}

void analogin_init(analogin_t *obj, PinName pin)
{
    static uint8_t adc_initialized = 0;

    /* Init structure */
    analogin_preinit(obj, pin);

    /* Only initialize the ADC once */
    if (!adc_initialized) {
        /* Turn on the clock */
        CMU_ClockEnable(cmuClock_ADC0, true);

        /* Init with default settings */
        ADC_Init_TypeDef init = ADC_INIT_DEFAULT;
        init.prescale = 4;
        ADC_Init(obj->adc, &init);

        /* Init for single conversion use */
        ADC_InitSingle_TypeDef singleInit = ADC_INITSINGLE_DEFAULT;

        /* Measure input channel with Vdd reference. */
        singleInit.reference = adcRefVDD;
        singleInit.resolution = adcRes12Bit;
        singleInit.acqTime = adcAcqTime32;

        ADC_InitSingle(obj->adc, &singleInit);

        adc_initialized = 1;
    }
}

void analogin_enable(analogin_t *obj, uint8_t enable)
{
    //not avail for EFM32
}

void analogin_enable_pins(analogin_t *obj, uint8_t enable)
{
    //not avail for EFM32
}

void analogin_enable_interrupt(analogin_t *obj, uint32_t address, uint8_t enable)
{
    NVIC_SetVector(ADC0_IRQn, address);
    if (enable) {
        // enable end of conversion interrupt
        ADC_IntEnable(obj->adc, ADC_IEN_SCAN);
        ADC_IntSet(obj->adc, ADC_IF_SCAN);
        NVIC_EnableIRQ(ADC0_IRQn);
    } else {
        ADC_IntDisable(obj->adc, ADC_IEN_SCAN);
        ADC_IntClear(obj->adc, ADC_IF_SCAN);
        NVIC_DisableIRQ(ADC0_IRQn);
    }
}

uint16_t analogin_read_u16(analogin_t *obj)
{
    ADC_TypeDef *adc = obj->adc;
    uint16_t sample = 0;

    //Make sure a single conversion is not in progress
    adc->CMD = ADC_CMD_SINGLESTOP;

    // Make sure we are checking the correct channel
    adc->SINGLECTRL = (adc->SINGLECTRL & ~_ADC_SINGLECTRL_INPUTSEL_MASK) | obj->channel;

    ADC_Start(adc, adcStartSingle);

    /* Wait while conversion is active */
    while (adc->STATUS & ADC_STATUS_SINGLEACT);

    /* Get ADC result */
    sample = ADC_DataSingleGet(adc);

    /* The ADC has 12 bit resolution. We shift in 4 0s */
    /* from the right to make it a 16 bit number as expected */
    return sample << 4;
}

float analogin_read(analogin_t *obj)
{
    /* Convert from a uint16 to a float between 0 and 1 by division by 0xFFFF */
    return analogin_read_u16(obj) / (float) 0xFFFF;
}

#endif


text:
layout: post
title:  Pretested Integration Plugin
author: Lars Kruse
---

The blog post is a comprehensive description and guide to the Pretested Integration Plugin. It's a supplement to the plugin's [wiki page at Jenkins CI](https://wiki.jenkins-ci.org/display/JENKINS/Pretested+Integration+Plugin).

Another interesting source of information is our paper on the Continuous Delivery Git Flow - using this plugin. Download the paper as `PDF`: [CoDe:U Git Flow - a Continuous Delivery Approach](http://was.www.praqma.com/sites/default/files/img/git_flow_web.pdf){: target="_blank"}

### Install
The plugin is Open Source. The code base is available at GitHub and it is released to the Jenkins CI community. So if you'd like to install it on your own Jenkins master, it's simply business as usual: Go to "Manage Jenkins" on your Jenkins server and search for _pretested integration_.

### Taking over where the Git SCM plugin left
The Pretested Integration plugin collaborates with other plugins. All the features required to establish a workspace for the build are already implemented in the various SCM plugins available.

The Pretested Integration Plugin depends on Git SCM (or Mercurial SCM if you prefer) to do its thing. Hereafter it will take over and wrap the build step: Initially with a merge and afterwards a commit - if the build was successful.

The Git SCM plugin shall have its branch specifier set to the expression you would like the Pretested Integration plugin to integrate. We've come to like the keyword `ready` to indicate this, so we usually set the branch specifier like this:

The branch specifier in Git is set to build anything that comes from origin and matches ready/**.

In the section of "Additional Behaviours" we add:

* __Clean after checkout__ to make sure the workspace does not have any _left-overs_ from previous builds hanging around.
* __Prune stale remote-tracking branches__ to make sure that the branches the pretested integration plugin sees are the same as the one on the `origin`.

### Specifying the branch you want to integrate into
The Pretested Integration plugin is really simple to use. The footprint in the GUI isn't large either:

Simply check the plugin to use it. Git is default and so is the master branch as the target. Choose the strategy to use for the integration. Squashed commit is the default.

### Successfully integrated branches are deleted
When the pretested integration plugin has successfully integrated a branch it will delete it even in the `origin` clone.

A branch ready to be integrated is like raising a flag to initiate an action. If that action is successful, the flag should be lowered again.

On the other hand; if the integration is not successful and you get a failed build, then it's likely that you want to investigate what happened. In that case, everything is left intact for you to scrutinize.

You are welcome to fix the issue on the same branch and push it again - the plugin fully supports that.

### All work is delivered in one chunk
It's generally considered good practice that developers squash their commits to match the delivery of a task or a story. If a bugfix is scattered across several commits, the solution can be difficult to review, simply because it is not nicely wrapped up. Instead, squashed commits can be used to accumulate related work.

The Pretested Integration plugin does this for you, by only allowing fast-forward merges in the situation where the contribution is actually contained in just one single commit.

In all other events, you have two choices. Either merge using `--no-ff` (no fast forward) and hereby force a new commit with the accumulated changes - This is refered to as _Accumulated commits_ in the GUI.
Or even more elegant, simply use `--squash` and leave all the work on the branch behind. It's like a history rewrite, that doesn't actually ruin your history.
This strategy is the _Squashed commits_ radio button in the GUI. It's the default, recommended strategy.

The difference between the two are subtle, but important, to understand.

Have a look at this small sample tree created: Taking offset in the same commit on master, someone did two commits on a `dev` branch while someone else did two commits on a `fix` branch. The commits are then integrated using the Accumulated strategy (`--no-ff`). The picture below is then generated by running the `git show-branch --sparse` command.

A brief intro to what this command shows: In the top, above the line marked `---`, you see the branch heads in the repository. In this case there are three: `dev`, `fix` and `master`.  Below the same line you see the commits listed in chronological order. The oldest at the bottom and in the margin, a set of markers indicating which branch each commit belongs to. The beauty of Git is then, that a commit can easily belong to more than one branch. E.g. the `initial` commit was done on `master`, and both `dev` and `fix` branched off from this, so it belongs to all three branches.

Accumulated strategy as you can see, all commits actually belongs to master.

Imagine that you ran the `bisect` command (never tried it? [read the git manual](http://git-scm.com/book/en/Git-Tools-Debugging-with-Git) - it's awesome!) and you are on the `master` branch and go from `HEAD` to the commit named `initial`: In this situation your bisect would visit _all_ commits.

Maybe a little disappointing, since you probably would claim that the stuff you did on `dev` and `fix` are conceptually _delivered_ to `master` and shouldn't necessarily be regarded as _contained_.

OK, now let's have a look at the same situation using the _Squashed strategy_.

Squashed strategy Now things are starting to look just right: Only the deliveries actually belonging to master. Dev and fix branches are detached.

In this case, if you ran `bisect` as before, it would only visit the three commits that you conceptually agree belongs to master. _Neat eh?_

To wrap up the this story about commit strategies, we will show you the same situation once again using just a plain vanilla merge, where fast-forward merges are the default if possible.

Plain Vanilla merges Using fast forward merges may not give you what you want: Where is the commit that delivered dev to master? It's gone! Well, it was actually never there: When `dev` was merged into master it was fast-forwarded (because it's the default when possible), so at that point the HEAD of `master` is set to the commit named more dev changes and later it's forwarded to the latest on the fix branch. The trace is lost - the big picture becomes pretty blurry.

This is why the Pretested Integration plugin does not let you use plain vanilla merges.

### Why not use the squashed strategy - always?

Well, that is actually our recommendation, but it does have a few side effect that you should be aware of:

If I push a branch - say it's `dev` and I push it to `ready/dev` like this:

    git push origin dev:ready/dev

Meaning that my `dev` becomes `ready/dev` on my target, then that would trigger the integration. Perfect.

Now, if I wanted to continue using the `dev` branch, maybe do more stuff and deliver it again, then it would require that I first bring my local `dev` in sync with the remote master - It can be done like this:

    git checkout master
    git fetch origin --prune
    git pull origin master
    git checkout dev
    git merge master -m "restablishing the relationship"

The thing is that since the merge was done using `--squash`, the `dev` branch in internally recorded as not currently being delivered anywhere. If you wanted to delete the branch, you would be required to use force:

    git branch -d dev  # this would fail
    git branch -D dev  # while this would work

Not the behaviour you would normally expect from a branch that is - at least _conceptually_ - already delivered.

This peculiarity does not arise from the Pretested Integration plugin itself, but from the `--squash` merge. As you saw, using no strategy or even the _Accumulated strategy_ both have other side effects that are also undesired, and none of these are neither related to the Pretested Integration plugin.

It's pure Git.

If you can learn how to manoeuvre around it, the _Squashed strategy_ is indeed our recommendation. It implements a genuine pristine master and gives you the power of `bisect`, which is a powerful feature once you learn to tame it.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using WorkflowCore.Interface;
using WorkflowCore.Models;
using WorkflowCore.Testing;
using Xunit;

namespace WorkflowCore.IntegrationTests.Scenarios
{
    public class MiddlewareScenario : WorkflowTest<MiddlewareScenario.MyWorkflow, object>
    {
        private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(60);
        private static readonly TimeSpan Delay = TimeSpan.FromMilliseconds(5);
        private readonly List<TestWorkflowMiddleware> _workflowMiddleware = new List<TestWorkflowMiddleware>();
        private readonly List<TestStepMiddleware> _stepMiddleware = new List<TestStepMiddleware>();
        private readonly TestStep _step = new TestStep();

        public MiddlewareScenario()
        {
            Setup();
        }

        public TestWorkflowMiddleware[] PreMiddleware => _workflowMiddleware
            .Where(x => x.Phase == WorkflowMiddlewarePhase.PreWorkflow)
            .ToArray();

        public TestWorkflowMiddleware[] PostMiddleware => _workflowMiddleware
            .Where(x => x.Phase == WorkflowMiddlewarePhase.PostWorkflow)
            .ToArray();

        public class MyWorkflow: IWorkflow<object>
        {
            public string Id => nameof(MyWorkflow);

            public int Version => 1;

            public void Build(IWorkflowBuilder<object> builder) =>
                builder.StartWith<TestStep>();
        }

        public class TestStep : StepBodyAsync
        {

            public DateTime? StartTime { get; private set; }
            public DateTime? EndTime { get; private set; }
            public bool HasCompleted => StartTime.HasValue && EndTime.HasValue;

            public override async Task<ExecutionResult> RunAsync(IStepExecutionContext context)
            {
                StartTime = DateTime.UtcNow;
                await Task.Delay(Delay);
                EndTime = DateTime.UtcNow;
                return ExecutionResult.Next();
            }
        }

        public class TestWorkflowMiddleware : IWorkflowMiddleware
        {
            public TestWorkflowMiddleware(WorkflowMiddlewarePhase phase)
            {
                Phase = phase;
            }

            public WorkflowMiddlewarePhase Phase { get; }

            public DateTime? StartTime { get; private set; }
            public DateTime? EndTime { get; private set; }
            public bool HasCompleted => StartTime.HasValue && EndTime.HasValue;

            public async Task HandleAsync(WorkflowInstance workflow, WorkflowDelegate next)
            {
                StartTime = DateTime.UtcNow;
                await Task.Delay(Delay);
                await next();
                await Task.Delay(Delay);
                EndTime = DateTime.UtcNow;
            }
        }

        public class TestStepMiddleware : IWorkflowStepMiddleware
        {
            public DateTime? StartTime { get; private set; }
            public DateTime? EndTime { get; private set; }

            public bool HasCompleted => StartTime.HasValue && EndTime.HasValue;

            public async Task<ExecutionResult> HandleAsync(IStepExecutionContext context, IStepBody body, WorkflowStepDelegate next)
            {
                StartTime = DateTime.UtcNow;
                await Task.Delay(Delay);
                var result = await next();
                await Task.Delay(Delay);
                EndTime = DateTime.UtcNow;
                return result;
            }
        }

        protected override void ConfigureServices(IServiceCollection services)
        {
            base.ConfigureServices(services);

            services.AddTransient(_ => _step);

            // Configure 3 middleware of each type
            const int middlewareCount = 3;
            foreach (var _ in Enumerable.Range(0, middlewareCount))
            {
                var preMiddleware = new TestWorkflowMiddleware(WorkflowMiddlewarePhase.PreWorkflow);
                var postMiddleware = new TestWorkflowMiddleware(WorkflowMiddlewarePhase.PostWorkflow);
                _workflowMiddleware.Add(preMiddleware);
                _workflowMiddleware.Add(postMiddleware);
                services.AddWorkflowMiddleware(p => preMiddleware);
                services.AddWorkflowMiddleware(p => postMiddleware);
            }

            // Configure 3 step middleware
            foreach (var _ in Enumerable.Range(0, middlewareCount))
            {
                var middleware = new TestStepMiddleware();
                services.AddWorkflowStepMiddleware(p => middleware);
                _stepMiddleware.Add(middleware);
            }

        }

        [Fact(DisplayName = "Should run all workflow and step middleware")]
        public async Task Should_run_all_workflow_and_step_middleware()
        {
            var workflowId = await StartWorkflowAsync(new object());
            var status = await WaitForWorkflowToCompleteAsync(workflowId, Timeout);

            // Workflow should complete without errors
            status.Should().Be(WorkflowStatus.Complete);
            UnhandledStepErrors.Count.Should().Be(0);

            // Wait for post middleware to complete
            while (_workflowMiddleware.Any(x => !x.HasCompleted))
            {
                await Task.Delay(500);
            }

            // Each middleware should have run
            _workflowMiddleware.Should()
                .HaveCount(6).And
                .OnlyContain(x => x.HasCompleted);
            _stepMiddleware.Should()
                .HaveCount(3)
                .And
                .OnlyContain(x => x.HasCompleted);

            // Step middleware should have been run in order
            _stepMiddleware.Should().BeInAscendingOrder(x => x.StartTime);
            _stepMiddleware.Should().BeInDescendingOrder(x => x.EndTime);

            // Step should have been called after all step middleware
            _step.HasCompleted.Should().BeTrue();
            _step.StartTime.Should().BeAfter(_stepMiddleware.Last().StartTime.Value);
            _step.EndTime.Should().BeBefore(_stepMiddleware.Last().EndTime.Value);

            // Pre workflow middleware should have been run in order
            PreMiddleware.Should().BeInAscendingOrder(x => x.StartTime);
            PreMiddleware.Should().BeInDescendingOrder(x => x.EndTime);

            // Post workflow middleware should have been run in order
            PostMiddleware.Should().BeInAscendingOrder(x => x.StartTime);
            PostMiddleware.Should().BeInDescendingOrder(x => x.EndTime);
        }
    }
}


text:
namespace Anycmd.Edi.InfoConstraints.Rules
{
    using Engine.Host.Edi;
    using Engine.Info;
    using System;
    using System.ComponentModel.Composition;

    [Export(typeof(IInfoRule))]
    public class Int32InfoCheck : InfoRuleBase, IInfoRule
    {
        private const string ActorId = "9E7522F9-11B8-49D1-9803-D755A2A27530";
        private static readonly Guid id = new Guid(ActorId);
        private const string title = "Int32验证器";
        private const string description = "Int32验证器";
        private const string author = "xuexs";

        public Int32InfoCheck()
            : base(id, title, author, description)
        {

        }

        public ProcessResult Valid(string value)
        {
            try
            {
                bool isValid = true;
                var stateCode = Status.Ok;
                string msg = "Int32验证通过";
                Guid guid;
                if (!string.IsNullOrEmpty(value) && !Guid.TryParse(value, out guid))
                {
                    msg = "非法的Int32" + value;
                    stateCode = Status.InvalidInfoValue;
                    isValid = false;
                }

                return new ProcessResult(isValid, stateCode, msg);
            }
            catch (Exception ex)
            {
                return new ProcessResult(ex);
            }
        }

        protected override void Dispose(bool disposing)
        {

        }
    }
}


text:
/**
 * BoolArrayInitialization.cpp -
 * @author: Jonathan Beard
 * @version: Thu Feb 13 09:01:07 2014
 */
#include "BoolArrayInitialization.hpp"

using namespace Node;

BoolArrayInitialization::BoolArrayInitialization() :
   ArrayInitialization( "BoolArrayInitialization" )
{
   class_tree.addRelation( typeid( Node::ArrayInitialization ).hash_code(),
                           typeid( Node::BoolArrayInitialization ).hash_code() );
}


text:
@interface XKTableViewCell ()

@property (nonatomic, strong) UILabel *dayLabel;

@property (nonatomic, strong) UILabel *weekLabel;

@property (nonatomic, strong) UILabel *timeLabel;

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UILabel *detailLabel;

@property (nonatomic, strong) UIImageView *weatherImageView;

@property (nonatomic, strong) UIImageView *emotionImageView;

@property (nonatomic, strong) UIView *view;

@end

@implementation XKTableViewCell

-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {

        self.selectionStyle = UITableViewCellSelectionStyleNone;

        self.backgroundColor = [UIColor clearColor];

        [self initUserInterface];

    }
    return self;
}

- (void)initUserInterface {

    [self.view addSubview:self.dayLabel];

    [self.view addSubview:self.weekLabel];

    [self.view addSubview:self.timeLabel];

    [self.view addSubview:self.titleLabel];

    [self.view addSubview:self.detailLabel];

    [self.view addSubview:self.weatherImageView];

    [self.view addSubview:self.emotionImageView];

    [self.contentView addSubview:self.view];

    [self setNeedsUpdateConstraints];
}

- (void)updateConstraints {

    [self.view mas_makeConstraints:^(MASConstraintMaker *make) {

        make.left.equalTo(self.contentView).offset(8 * PROPORTION);

        make.right.equalTo(self.contentView).offset(-8 * PROPORTION);

        make.top.equalTo(self.contentView).offset(10 * PROPORTION);

        make.bottom.equalTo(self.contentView).offset(0);

    }];

    [self.dayLabel mas_makeConstraints:^(MASConstraintMaker *make) {

        make.left.equalTo(self.view).offset(10 * PROPORTION);

        make.top.equalTo(self.view).offset(15 * PROPORTION);

        make.width.offset(30 * PROPORTION);

        make.height.offset(30 * PROPORTION);

    }];

    [self.weekLabel mas_makeConstraints:^(MASConstraintMaker *make) {

        make.left.equalTo(self.view).offset(10 * PROPORTION);

        make.top.equalTo(self.dayLabel.mas_bottom).offset(8 * PROPORTION);

        make.height.offset(10 * PROPORTION);

        make.width.offset(33 * PROPORTION);
    }];

    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {

        make.left.equalTo(self.dayLabel.mas_right).offset(8 * PROPORTION);

        make.top.equalTo(self.view).offset(12 * PROPORTION);

        make.height.offset(10 * PROPORTION);

        make.width.offset(100 * PROPORTION);
    }];

    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {

        make.left.equalTo(self.timeLabel);

        make.top.equalTo(self.timeLabel.mas_bottom).offset(10 * PROPORTION);

        make.height.offset(12 * PROPORTION);

        make.width.offset(100 * PROPORTION);
    }];

    [self.detailLabel mas_makeConstraints:^(MASConstraintMaker *make) {

        make.left.equalTo(self.timeLabel);

        make.top.equalTo(self.titleLabel.mas_bottom).offset(10 * PROPORTION);

        make.height.offset(10 * PROPORTION);

        make.width.offset(150 * PROPORTION);
    }];

    [self.weatherImageView mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.equalTo(self.timeLabel);

        make.right.equalTo(self.view).offset(- 40 * PROPORTION);

        make.height.offset(20 * PROPORTION);

        make.width.offset(20 * PROPORTION);
    }];

    [self.emotionImageView mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.equalTo(self.timeLabel);

        make.right.equalTo(self.view).offset(- 10 * PROPORTION);

        make.height.offset(20 * PROPORTION);

        make.width.offset(20 * PROPORTION);
    }];

    [super updateConstraints];
}

- (void)setModel:(XKDiaryModel *)model {

    _model = model;

    self.dayLabel.text = model.day;

    self.weekLabel.text = model.week;

    self.titleLabel.text = model.title;

    self.detailLabel.text = [[self filterHTML:model.detail] stringByReplacingOccurrencesOfString:@"\n" withString:@""];

    self.emotionImageView.image = [UIImage imageNamed:model.emotion];

    self.weatherImageView.image = [UIImage imageNamed:model.weather];

    self.timeLabel.text = [NSDate getTimeFromDate:model.date];
}

- (NSString *)filterHTML:(NSString *)str {

    NSScanner * scanner = [NSScanner scannerWithString:str];
    NSString * text = nil;
    while([scanner isAtEnd]==NO)
    {
        //找到标签的起始位置
        [scanner scanUpToString:@"<" intoString:nil];
        //找到标签的结束位置
        [scanner scanUpToString:@">" intoString:&text];
        //替换字符
        str  =  [str  stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
    }

    return str;
}

#pragma mark -- getter
- (UILabel *)dayLabel {

    if (!_dayLabel) {
        _dayLabel = [UILabel configLabelWithFont:@"STHeitiSC-Medium" fontSize:23 * PROPORTION textAlignment:NSTextAlignmentCenter];
    }
    return _dayLabel;
}

- (UILabel *)weekLabel {

    if (!_weekLabel) {
        _weekLabel = [UILabel configLabelWithFont:@"CourierNewPSMT" fontSize:10 * PROPORTION textAlignment:NSTextAlignmentCenter];
        _weekLabel.text = @"星期六";
    }
    return _weekLabel;
}

- (UILabel *)timeLabel {

    if (!_timeLabel) {
        _timeLabel = [UILabel configLabelWithFont:@"STHeitiSC-Light" fontSize:10 * PROPORTION textAlignment:NSTextAlignmentLeft];
        _timeLabel.text = @"16:37";
    }
    return _timeLabel;
}

- (UILabel *)titleLabel {

    if (!_titleLabel) {
        _titleLabel = [UILabel configLabelWithFont:@"STHeitiSC-Medium" fontSize:14 * PROPORTION textAlignment:NSTextAlignmentLeft];
        _titleLabel.text = @"浪漫恋星空";
    }
    return _titleLabel;
}

- (UILabel *)detailLabel {

    if (!_detailLabel) {
        _detailLabel = [UILabel configLabelWithFont:@"STHeitiSC-Light" fontSize:12 * PROPORTION textAlignment:NSTextAlignmentLeft];
        _detailLabel.text = @"测试数据哈哈哈哈哈哈哈哈哈哈哈哈";
    }
    return _detailLabel;
}

- (UIImageView *)weatherImageView {

    if (!_weatherImageView) {
        _weatherImageView = [[UIImageView alloc] init];
    }
    return _weatherImageView;
}

- (UIImageView *)emotionImageView {

    if (!_emotionImageView) {
        _emotionImageView = [[UIImageView alloc] init];
    }
    return _emotionImageView;
}

- (UIView *)view {

    if (!_view) {
        _view = [[UIView alloc] init];
        _view.backgroundColor = [UIColor whiteColor];
        _view.layer.cornerRadius = 5 * PROPORTION;
    }
    return _view;
}

@end


text:
using Syste.Reflection;
using Syste.Runtie.CopilerServices;
using Syste.Runtie.InteropServices;

// General Inforation about an assebly is controlled through the following
// set of attributes. Change these attribute values to odify the inforation
// associated with an assebly.
[assebly: AsseblyTitle("02. Change Tiles")]
[assebly: AsseblyDescription("")]
[assebly: AsseblyConfiguration("")]
[assebly: AsseblyCopany("")]
[assebly: AsseblyProduct("02. Change Tiles")]
[assebly: AsseblyCopyright("Copyright ©  2017")]
[assebly: AsseblyTradeark("")]
[assebly: AsseblyCulture("")]

// Setting CoVisible to false akes the types in this assebly not visible
// to CO coponents.  If you need to access a type in this assebly fro
// CO, set the CoVisible attribute to true on that type.
[assebly: CoVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to CO
[assebly: Guid("34790cc8-4eec-45b9-8630-962ec19db114")]

// Version inforation for an assebly consists of the following four values:
//
//      ajor Version
//      inor Version
//      Build Nuber
//      Revision
//
// You can specify all the values or you can default the Build and Revision Nubers
// by using the '*' as shown below:
// [assebly: AsseblyVersion("1.0.*")]
[assebly: AsseblyVersion("1.0.0.0")]
[assebly: AsseblyFileVersion("1.0.0.0")]


text:
<?php

namespace PayPalRestApiClient\Tests;

use PayPalRestApiClient\Service\PaymentService;

class PaymentServiceTestCase extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $this->debug = true;
        $this->baseUrl = 'https://api.sandbox.paypal.com';
        $this->returnUrl = 'http://example.com/success';
        $this->cancelUrl = 'http://example.com/cancel';
        $this->total = "15.00";
        $this->currency = 'EUR';
        $this->description = 'My fantastic transaction description';

        $this->accessToken = $this->getMockBuilder('PayPalRestApiClient\Model\AccessToken')
            ->disableOriginalConstructor()
            ->getMock();

        $this->expectedRequest = $this->getMockBuilder('Guzzle\Http\Message\Request')
            ->disableOriginalConstructor()
            ->getMock();

        $this->expectedResponse = $this->getMockBuilder('Guzzle\Http\Message\Response')
            ->disableOriginalConstructor()
            ->setMethods(array('getStatusCode', 'getBody'))
            ->getMock();

        $this->client = $this->getMockBuilder('Guzzle\Http\Client')
            ->disableOriginalConstructor()
            ->setMethods(array('createRequest', 'send'))
            ->getMock();

        $this->builder = $this->getMockBuilder('PayPalRestApiClient\Builder\PaymentRequestBodyBuilder')
            ->disableOriginalConstructor()
            ->setMethods(array('build'))
            ->getMock();

        $this->service = new PaymentService(
            $this->client,
            $this->builder,
            $this->baseUrl,
            $this->debug
        );
    }

    protected function initAccessToken($type, $token)
    {
        $this->accessToken->expects($this->atLeastOnce())
            ->method('getTokenType')
            ->will($this->returnValue($type));

        $this->accessToken->expects($this->atLeastOnce())
            ->method('getAccessToken')
            ->will($this->returnValue($token));
    }

    protected function initResponse($status, $json)
    {
        $this->expectedResponse->expects($this->any())
            ->method('getStatusCode')
            ->will($this->returnValue($status));
        $this->expectedResponse->expects($this->any())
            ->method('getBody')
            ->will($this->returnValue($json));
    }

    protected function initBuilder($requestBody, $intent)
    {
        $this->builder->expects($this->once())
            ->method('build')
            ->will($this->returnValue(json_encode($requestBody)));
    }

    protected function initClient($requestBody, $uri = '/v1/payments/payment')
    {
        $this->client->expects($this->atLeastOnce())
            ->method('createRequest')
            ->with(
                'POST',
                $this->baseUrl.$uri,
                array(
                    'Accept' => 'application/json',
                    'Accept-Language' => 'en_US',
                    'Authorization' => $this->accessToken->getTokenType().' '.$this->accessToken->getAccessToken(),
                    'Content-Type' => 'application/json'
                ),
                json_encode($requestBody),
                array(
                    'debug' => $this->debug
                )
            )
            ->will($this->returnValue($this->expectedRequest));

        $this->client->expects($this->once())
            ->method('send')
            ->with($this->expectedRequest)
            ->will($this->returnValue($this->expectedResponse));
    }
}


text:
import proto  # type: ignore

__protobuf__ = proto.module(
    package="google.ads.googleads.v12.errors",
    marshal="google.ads.googleads.v12",
    manifest={"CampaignDraftErrorEnum",},
)

class CampaignDraftErrorEnum(proto.Message):
    r"""Container for enum describing possible campaign draft errors.
    """

    class CampaignDraftError(proto.Enum):
        r"""Enum describing possible campaign draft errors."""
        UNSPECIFIED = 0
        UNKNOWN = 1
        DUPLICATE_DRAFT_NAME = 2
        INVALID_STATUS_TRANSITION_FROM_REMOVED = 3
        INVALID_STATUS_TRANSITION_FROM_PROMOTED = 4
        INVALID_STATUS_TRANSITION_FROM_PROMOTE_FAILED = 5
        CUSTOMER_CANNOT_CREATE_DRAFT = 6
        CAMPAIGN_CANNOT_CREATE_DRAFT = 7
        INVALID_DRAFT_CHANGE = 8
        INVALID_STATUS_TRANSITION = 9
        MAX_NUMBER_OF_DRAFTS_PER_CAMPAIGN_REACHED = 10
        LIST_ERRORS_FOR_PROMOTED_DRAFT_ONLY = 11

__all__ = tuple(sorted(__protobuf__.manifest))


text:
function cf = cfX_PDF(t,pdfFun,method,tol)
%cfX_PDF Computes the characteristic function of the continuos
% distribution defined by its PDF function, pdfFun = @(x) pdf(x), here we
% assume x>=0, computed for real vector argument t.
%
% DEFINITION:
%  cfX_PDF is based on the standard integral representation of the
%  characteristic function of the continuous distribution defined by its
%  PDF (here PDF is represented by the function handle pdfFun(x) defined
%  for x >= 0). Then,
%    CF(t) = Integral_0^inf exp(i*t*x) * pdfFun(x) dx.
%  Alternatively, by using the half-space Fourier Integral Transformation
%  (FIT), which could improve the highly oscillatory behaviour of the
%  integrand function, we get
%    CF(t) = Integral_0^inf (i/t) * exp(-x) * pdfFun(i*x/t) dx.
%  If we define the integrand as
%    funCF(t,x) = (i/t) * exp(-x) * pdfFun(i*x/t),
%  then by using a stabilizing transformation from [0,inf] to [0,1], we can
%  evaluate the CF by the following (well behaved) integral:
%    CF(t) = Integral_0^1 2x/(1-x)^3 * funCF(t,(x/(1-x))^2) dx.
%
%  Selection of the proper method (standard definition or the integral
%  transformation FIT) depends on the distribution and the particular form
%  of its PDF.
%
%  cfX_PDF evaluates this integral by using the MATLAB built in function
%  'integral', with precission specified by tolerance tol (default value is
%  tol = 1e-6).
%
% SYNTAX:
%  cf = cfX_PDF(t,pdfFun,method,tol)
%
% INPUTS:
%  t      - real vector, where the characteristic function CF(t) will
%           be evaluated,
%  pdfFun - function handle used as the PDF function with the argument x,
%           for x >= 0. However, pdfFun(z) should accept as an input value
%           any complex matrix z,
%  method - set the method used to compute the characteristic function,
%           either method = 'def' (or the standard definition of CF by using
%           the pdf) or method = 'fit' (by using the half-space Fourier
%           integral transform of the pdf). Default value is method =
%           'def'.
%  tol    - relative tolerance parameter used in the built-in Matlab
%           numerical integration algorithm 'integral'. Default value is
%           tol = 1e-6.
%
% OUTPUT:
%  cf     - (complex) vector of the characteristic function values,
%            evalated at the required t, i.e. CF(t).
%
% EXAMPLE1 (CF of the Exponential distribution with mu = 1)
%  pdfFun = @(x) exp(-x);
%  t  = linspace(-20,20,2^10+1)';
%  cf = cfX_PDF(t,pdfFun);
%  plot(t,real(cf),t,imag(cf));grid
%  title('Characteristic function of the Exponential distribution')
%
% EXAMPLE2 (CF of the LogNormal distribution with mu = 0, sigma = 1)
%  mu     = 0;
%  sigma  = 1;
%  pdfFun = @(x) exp(-0.5*((log(x)-mu)./sigma).^2)./(x.*sqrt(2*pi).*sigma);
%  method = 'fit';
%  t  = linspace(-20,20,2^10+1)';
%  cf = cfX_PDF(t,pdfFun,method);
%  plot(t,real(cf),t,imag(cf));grid
%  title('Characteristic function of the LogNormal distribution')
%
% EXAMPLE3 (CDF/PDF of the LogNormal distribution with mu = 0, sigma = 1)
%  mu     = 0;
%  sigma  = 1;
%  pdfFun = @(x) exp(-0.5*((log(x)-mu)./sigma).^2)./(x.*sqrt(2*pi).*sigma);
%  method = 'fit';
%  cf = @(t) cfX_PDF(t,pdfFun,method);
%  clear options
%  options.xMin = 0;
%  result = cf2DistGP(cf,[],[],options);
%
% EXAMPLE4 (CF of the Weibull distribution with a = 1.5, and small b<1)
%  a      = 1.5;
%  b      = 0.5;
%  pdfFun = @(x) (x./a).^(b-1) .* exp(-((x./a).^b)) .* b ./ a;
%  method = 'fit';
%  t  = linspace(-20,20,2^10+1)';
%  cf = cfX_PDF(t,pdfFun,method);
%  plot(t,real(cf),t,imag(cf));grid
%  title('Characteristic function of the Weibull distribution')
%
% EXAMPLE5 (CF of the Weibull distribution with a = 1.5, and large b > 1)
%  a      = 1.5;
%  b      = 3.5;
%  pdfFun = @(x) (x./a).^(b-1) .* exp(-((x./a).^b)) .* b ./ a;
%  method = 'def';
%  t  = linspace(-10,10,2^10+1)';
%  cf = cfX_PDF(t,pdfFun,method);
%  plot(t,real(cf),t,imag(cf));grid
%  title('Characteristic function of the Weibull distribution')
%
% REFERENCES:
% [1] WITKOVSKY, V.: On the exact computation of the density and of
%     the quantiles of linear combinations of t and F random
%     variables. Journal of Statistical Planning and Inference 94
%     (2001), 1–13.
% [2] WITKOVSKY V. (2016). Numerical inversion of a characteristic
%     function: An alternative tool to form the probability distribution of
%     output quantity in linear measurement models. Acta IMEKO, 5(3), 32-44.
% [3] WITKOVSKY V., WIMMER G., DUBY T. (2016). Computing the aggregate loss
%     distribution based on numerical inversion of the compound empirical
%     characteristic function of frequency and severity. Working Paper.
%     Insurance: Mathematics and Economics.
% [4] DUBY T., WIMMER G., WITKOVSKY V.(2016). MATLAB toolbox CRM for
%     computing distributions of collective risk models.  Working Paper.
%     Journal of Statistical Software.

% (c) 2016 Viktor Witkovsky (witkovsky@gmail.com)
% Ver.: 21-Jul-2017 20:53:22

%% ALGORITHM
%cf = cfX_PDF(t,pdfFun,method,tol);

%% CHECK THE INPUT PARAMETERS

if nargin < 1
    error(message('VW:cfX_PDF:TooFewInputs'));
end
if nargin < 2, pdfFun = []; end
if nargin < 3, method = []; end
if nargin < 4, tol = []; end

if isempty(pdfFun)
    pdfFun = @(x) exp(-x);
end

if isempty(method)
    method = 'definition';
end

if isempty(tol)
    tol = 1e-6;
end
reltol = tol;

%% EVALUATE THE CHARACTERISTIC FUNCTION: cfX_PDF(t,pdfFun)

sz = size(t);
t  = t(:);
cf = ones(size(t));
id = t~=0;

switch lower(method)
    case {'def','definition','standard','direct'}
        cf(id) = integral(@(x) bsxfun(@times,funCFdef(pdfFun,t(id), ...
            (x/(1-x))^2), 2*x/(1-x)^3),0,1,'ArrayValued',true, ...
            'RelTol',reltol);
    case {'fit','fourier','transform'}
        cf(id) = integral(@(x) bsxfun(@times,funCFfit(pdfFun,t(id), ...
            (x/(1-x))^2), 2*x/(1-x)^3),0,1,'ArrayValued',true, ...
            'RelTol',reltol);
    otherwise
        cf(id) = integral(@(x) bsxfun(@times,funCFdef(pdfFun,t(id), ...
            (x/(1-x))^2), 2*x/(1-x)^3),0,1,'ArrayValued',true, ...
            'RelTol',reltol);
end
cf = reshape(cf,sz);

end
%% Function funCFdef
function f = funCFdef(pdfFun,t,x)
%funCFdef Integrand function of the integral representation of the
%  characteristic function CF defined by using the pdfFun(x),
%  for x >=0, and the real (vector) argument t.
%
% SYNTAX:
%  f = funCFdef(pdfFun,t,x)

% Viktor Witkovsky (witkovsky@gmail.com)
% Ver.: 21-Jul-2017 20:53:22

%% ALGORITHM
x  = x(:)';
f  = pdfFun(x) .* exp(1i*t*x);
end
%% Function funCFfit
function f = funCFfit(pdfFun,t,x)
%funCFfit Integrand function of the integral representation of the
%  characteristic function CF of the distribution defined by using the
%  half-space Fourier Integral Transform (FIT) of its pdfFun(x),
%  for x >=0, and the real (vector) argument t.
%
% SYNTAX:
%    f = funCFfit(pdfFun,t,x)

% Viktor Witkovsky (witkovsky@gmail.com)
% Ver.: 21-Jul-2017 20:53:22

%% ALGORITHM
ti  = 1./t(:);
x  = x(:)';
ot = ones(size(ti));
ox = ones(size(x));
f  = (1i*ti*ox) .* pdfFun(1i*ti*x) .* exp(-ot*x);
end


text:
<tool id="enasearch_retrieve_analysis_report" name="Retrieve an analysis report" version="@WRAPPER_VERSION@.0">
    <description></description>
    <macros>
        <import>macros.xml</import>
        <import>search_macros.xml</import>
    </macros>
    <expand macro="requirements"/>
    <expand macro="version"/>
    <command detect_errors="aggressive"><![CDATA[
enasearch
    retrieve_analysis_report
    --accession '$accession'
    @FIELDS@
    --file '$output'
    ]]></command>
    <inputs>
        <expand macro="accession"/>
        <param argument="--fields" type="select" optional="true" multiple="true" label="Fields to return">
            <expand macro="analysis_fields"/>
        </param>
    </inputs>
    <outputs>
        <data name="output" format="tabular" label="${tool.name} on ${accession}"/>
    </outputs>
    <tests>
        <test>
            <param name="accession" value="ERZ009929"/>
            <output name="output" file="retrieve_analysis_report_output1.tabular"/>
        </test>
        <test>
            <param name="accession" value="ERZ009929"/>
            <param name="fields" value="analysis_accession"/>
            <output name="output" md5="7249f93fac05d1e6746a076e1ae445b5"/>
        </test>
        <test>
            <param name="accession" value="ERZ009929"/>
            <param name="fields" value="analysis_accession,sample_accession,scientific_name"/>
            <output name="output" md5="af4ba9b125b27525979ab6ea6a2b3637"/>
        </test>
    </tests>
    <help><![CDATA[
**What it does**

This tool retrieve an analysis report for an accession id
    ]]></help>
    <expand macro="citations"/>
</tool>


text:
#include <qpa/qwindowsysteminterface.h>
#include <QtGui/QOpenGLContext>
#include <QtGui/QOpenGLShaderProgram>
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonArray>
#include <QtCore/QJsonObject>
#include <QtDebug>

#include <QtPlatformSupport/private/qdevicediscovery_p.h>

#include "qeglplatformcursor_p.h"
#include "qeglplatformintegration_p.h"

QT_BEGIN_NAMESPACE

/*!
    \class QEGLPlatformCursor
    \brief Mouse cursor implementation using OpenGL.
    \since 5.2
    \internal
    \ingroup qpa
 */

QEGLPlatformCursor::QEGLPlatformCursor(QPlatformScreen *screen)
    : m_visible(true),
      m_screen(screen),
      m_program(0),
      m_vertexCoordEntry(0),
      m_textureCoordEntry(0),
      m_textureEntry(0),
      m_deviceListener(0),
      m_updater(screen)
{
    QByteArray hideCursorVal = qgetenv("QT_QPA_EGLFS_HIDECURSOR");
    if (!hideCursorVal.isEmpty())
        m_visible = hideCursorVal.toInt() == 0;
    if (!m_visible)
        return;

    // Try to load the cursor atlas. If this fails, m_visible is set to false and
    // paintOnScreen() and setCurrentCursor() become no-ops.
    initCursorAtlas();

    // initialize the cursor
#ifndef QT_NO_CURSOR
    QCursor cursor(Qt::ArrowCursor);
    setCurrentCursor(&cursor);
#endif
}

QEGLPlatformCursor::~QEGLPlatformCursor()
{
    resetResources();
    delete m_deviceListener;
}

void QEGLPlatformCursor::setMouseDeviceDiscovery(QDeviceDiscovery *dd)
{
    if (m_visible && dd) {
        m_deviceListener = new QEGLPlatformCursorDeviceListener(dd, this);
        updateMouseStatus();
    }
}

void QEGLPlatformCursor::updateMouseStatus()
{
    m_visible = m_deviceListener->hasMouse();
}

QEGLPlatformCursorDeviceListener::QEGLPlatformCursorDeviceListener(QDeviceDiscovery *dd, QEGLPlatformCursor *cursor)
    : m_cursor(cursor)
{
    m_mouseCount = dd->scanConnectedDevices().count();
    connect(dd, SIGNAL(deviceDetected(QString)), SLOT(onDeviceAdded()));
    connect(dd, SIGNAL(deviceRemoved(QString)), SLOT(onDeviceRemoved()));
}

bool QEGLPlatformCursorDeviceListener::hasMouse() const
{
    return m_mouseCount > 0;
}

void QEGLPlatformCursorDeviceListener::onDeviceAdded()
{
    ++m_mouseCount;
    m_cursor->updateMouseStatus();
}

void QEGLPlatformCursorDeviceListener::onDeviceRemoved()
{
    --m_mouseCount;
    m_cursor->updateMouseStatus();
}

void QEGLPlatformCursor::resetResources()
{
    if (QOpenGLContext::currentContext()) {
        delete m_program;
        glDeleteTextures(1, &m_cursor.customCursorTexture);
        glDeleteTextures(1, &m_cursorAtlas.texture);
    }
    m_program = 0;
    m_cursor.customCursorTexture = 0;
    m_cursor.customCursorPending = !m_cursor.customCursorImage.isNull();
    m_cursorAtlas.texture = 0;
}

void QEGLPlatformCursor::createShaderPrograms()
{
    static const char *textureVertexProgram =
        "attribute highp vec2 vertexCoordEntry;\n"
        "attribute highp vec2 textureCoordEntry;\n"
        "varying highp vec2 textureCoord;\n"
        "void main() {\n"
        "   textureCoord = textureCoordEntry;\n"
        "   gl_Position = vec4(vertexCoordEntry, 1.0, 1.0);\n"
        "}\n";

    static const char *textureFragmentProgram =
        "uniform sampler2D texture;\n"
        "varying highp vec2 textureCoord;\n"
        "void main() {\n"
        "   gl_FragColor = texture2D(texture, textureCoord).bgra;\n"
        "}\n";

    m_program = new QOpenGLShaderProgram;
    m_program->addShaderFromSourceCode(QOpenGLShader::Vertex, textureVertexProgram);
    m_program->addShaderFromSourceCode(QOpenGLShader::Fragment, textureFragmentProgram);
    m_program->link();

    m_vertexCoordEntry = m_program->attributeLocation("vertexCoordEntry");
    m_textureCoordEntry = m_program->attributeLocation("textureCoordEntry");
    m_textureEntry = m_program->attributeLocation("texture");
}

void QEGLPlatformCursor::createCursorTexture(uint *texture, const QImage &image)
{
    if (!*texture)
        glGenTextures(1, texture);
    glBindTexture(GL_TEXTURE_2D, *texture);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    glTexImage2D(GL_TEXTURE_2D, 0 /* level */, GL_RGBA, image.width(), image.height(), 0 /* border */,
                 GL_RGBA, GL_UNSIGNED_BYTE, image.constBits());
}

void QEGLPlatformCursor::initCursorAtlas()
{
    static QByteArray json = qgetenv("QT_QPA_EGLFS_CURSOR");
    if (json.isEmpty())
        json = ":/cursor.json";

    QFile file(QString::fromUtf8(json));
    if (!file.open(QFile::ReadOnly)) {
        m_visible = false;
        return;
    }

    QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
    QJsonObject object = doc.object();

    QString atlas = object.value(QLatin1String("image")).toString();
    Q_ASSERT(!atlas.isEmpty());

    const int cursorsPerRow = object.value(QLatin1String("cursorsPerRow")).toDouble();
    Q_ASSERT(cursorsPerRow);
    m_cursorAtlas.cursorsPerRow = cursorsPerRow;

    const QJsonArray hotSpots = object.value(QLatin1String("hotSpots")).toArray();
    Q_ASSERT(hotSpots.count() == Qt::LastCursor + 1);
    for (int i = 0; i < hotSpots.count(); i++) {
        QPoint hotSpot(hotSpots[i].toArray()[0].toDouble(), hotSpots[i].toArray()[1].toDouble());
        m_cursorAtlas.hotSpots << hotSpot;
    }

    QImage image = QImage(atlas).convertToFormat(QImage::Format_ARGB32_Premultiplied);
    m_cursorAtlas.cursorWidth = image.width() / m_cursorAtlas.cursorsPerRow;
    m_cursorAtlas.cursorHeight = image.height() / ((Qt::LastCursor + cursorsPerRow) / cursorsPerRow);
    m_cursorAtlas.width = image.width();
    m_cursorAtlas.height = image.height();
    m_cursorAtlas.image = image;
}

#ifndef QT_NO_CURSOR
void QEGLPlatformCursor::changeCursor(QCursor *cursor, QWindow *window)
{
    Q_UNUSED(window);
    const QRect oldCursorRect = cursorRect();
    if (setCurrentCursor(cursor))
        update(oldCursorRect | cursorRect());
}

bool QEGLPlatformCursor::setCurrentCursor(QCursor *cursor)
{
    if (!m_visible)
        return false;

    const Qt::CursorShape newShape = cursor ? cursor->shape() : Qt::ArrowCursor;
    if (m_cursor.shape == newShape && newShape != Qt::BitmapCursor)
        return false;

    if (m_cursor.shape == Qt::BitmapCursor) {
        m_cursor.customCursorImage = QImage();
        m_cursor.customCursorPending = false;
    }
    m_cursor.shape = newShape;
    if (newShape != Qt::BitmapCursor) { // standard cursor
        const float ws = (float)m_cursorAtlas.cursorWidth / m_cursorAtlas.width,
                    hs = (float)m_cursorAtlas.cursorHeight / m_cursorAtlas.height;
        m_cursor.textureRect = QRectF(ws * (m_cursor.shape % m_cursorAtlas.cursorsPerRow),
                                      hs * (m_cursor.shape / m_cursorAtlas.cursorsPerRow),
                                      ws, hs);
        m_cursor.hotSpot = m_cursorAtlas.hotSpots[m_cursor.shape];
        m_cursor.texture = m_cursorAtlas.texture;
        m_cursor.size = QSize(m_cursorAtlas.cursorWidth, m_cursorAtlas.cursorHeight);
    } else {
        QImage image = cursor->pixmap().toImage();
        m_cursor.textureRect = QRectF(0, 0, 1, 1);
        m_cursor.hotSpot = cursor->hotSpot();
        m_cursor.texture = 0; // will get updated in the next render()
        m_cursor.size = image.size();
        m_cursor.customCursorImage = image;
        m_cursor.customCursorPending = true;
    }

    return true;
}
#endif

void QEGLPlatformCursorUpdater::update(const QPoint &pos, const QRegion &rgn)
{
    m_active = false;
    QWindowSystemInterface::handleExposeEvent(m_screen->topLevelAt(pos), rgn);
    QWindowSystemInterface::flushWindowSystemEvents();
}

void QEGLPlatformCursorUpdater::scheduleUpdate(const QPoint &pos, const QRegion &rgn)
{
    if (m_active)
        return;

    m_active = true;

    // Must not flush the window system events directly from here since we are likely to
    // be a called directly from QGuiApplication's processMouseEvents. Flushing events
    // could cause reentering by dispatching more queued mouse events.
    QMetaObject::invokeMethod(this, "update", Qt::QueuedConnection,
                              Q_ARG(QPoint, pos), Q_ARG(QRegion, rgn));
}

void QEGLPlatformCursor::update(const QRegion &rgn)
{
    m_updater.scheduleUpdate(m_cursor.pos, rgn);
}

QRect QEGLPlatformCursor::cursorRect() const
{
    return QRect(m_cursor.pos - m_cursor.hotSpot, m_cursor.size);
}

QPoint QEGLPlatformCursor::pos() const
{
    return m_cursor.pos;
}

void QEGLPlatformCursor::setPos(const QPoint &pos)
{
    const QRect oldCursorRect = cursorRect();
    m_cursor.pos = pos;
    update(oldCursorRect | cursorRect());
}

void QEGLPlatformCursor::pointerEvent(const QMouseEvent &event)
{
    if (event.type() != QEvent::MouseMove)
        return;
    const QRect oldCursorRect = cursorRect();
    m_cursor.pos = event.screenPos().toPoint();
    update(oldCursorRect | cursorRect());
}

void QEGLPlatformCursor::paintOnScreen()
{
    if (!m_visible)
        return;

    const QRectF cr = cursorRect();
    const QRect screenRect(m_screen->geometry());
    const GLfloat x1 = 2 * (cr.left() / screenRect.width()) - 1;
    const GLfloat x2 = 2 * (cr.right() / screenRect.width()) - 1;
    const GLfloat y1 = 1 - (cr.top() / screenRect.height()) * 2;
    const GLfloat y2 = 1 - (cr.bottom() / screenRect.height()) * 2;
    QRectF r(QPointF(x1, y1), QPointF(x2, y2));

    draw(r);
}

void QEGLPlatformCursor::draw(const QRectF &r)
{
    if (!m_program) {
        // one time initialization
        createShaderPrograms();

        if (!m_cursorAtlas.texture) {
            createCursorTexture(&m_cursorAtlas.texture, m_cursorAtlas.image);

            if (m_cursor.shape != Qt::BitmapCursor)
                m_cursor.texture = m_cursorAtlas.texture;
        }
    }

    if (m_cursor.shape == Qt::BitmapCursor && m_cursor.customCursorPending) {
        // upload the custom cursor
        createCursorTexture(&m_cursor.customCursorTexture, m_cursor.customCursorImage);
        m_cursor.texture = m_cursor.customCursorTexture;
        m_cursor.customCursorPending = false;
    }

    Q_ASSERT(m_cursor.texture);

    m_program->bind();

    const GLfloat x1 = r.left();
    const GLfloat x2 = r.right();
    const GLfloat y1 = r.top();
    const GLfloat y2 = r.bottom();
    const GLfloat cursorCoordinates[] = {
        x1, y2,
        x2, y2,
        x1, y1,
        x2, y1
    };

    const GLfloat s1 = m_cursor.textureRect.left();
    const GLfloat s2 = m_cursor.textureRect.right();
    const GLfloat t1 = m_cursor.textureRect.top();
    const GLfloat t2 = m_cursor.textureRect.bottom();
    const GLfloat textureCoordinates[] = {
        s1, t2,
        s2, t2,
        s1, t1,
        s2, t1
    };

    glBindTexture(GL_TEXTURE_2D, m_cursor.texture);

    m_program->enableAttributeArray(m_vertexCoordEntry);
    m_program->enableAttributeArray(m_textureCoordEntry);

    m_program->setAttributeArray(m_vertexCoordEntry, cursorCoordinates, 2);
    m_program->setAttributeArray(m_textureCoordEntry, textureCoordinates, 2);

    m_program->setUniformValue(m_textureEntry, 0);

    glEnable(GL_BLEND);
    glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
    glDisable(GL_DEPTH_TEST); // disable depth testing to make sure cursor is always on top
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    glDisable(GL_BLEND);

    glBindTexture(GL_TEXTURE_2D, 0);
    m_program->disableAttributeArray(m_textureCoordEntry);
    m_program->disableAttributeArray(m_vertexCoordEntry);

    m_program->release();
}

QT_END_NAMESPACE


text:
[![Gem Version](https://badge.fury.io/rb/rubocop.svg)](http://badge.fury.io/rb/rubocop)
[![Dependency Status](https://gemnasium.com/bbatsov/rubocop.svg)](https://gemnasium.com/bbatsov/rubocop)
[![Build Status](https://travis-ci.org/bbatsov/rubocop.svg?branch=master)](https://travis-ci.org/bbatsov/rubocop)
[![Coverage Status](https://img.shields.io/codeclimate/coverage/github/bbatsov/rubocop.svg)](https://codeclimate.com/github/bbatsov/rubocop)
[![Code Climate](https://codeclimate.com/github/bbatsov/rubocop/badges/gpa.svg)](https://codeclimate.com/github/bbatsov/rubocop)
[![Inline docs](http://inch-ci.org/github/bbatsov/rubocop.svg)](http://inch-ci.org/github/bbatsov/rubocop)
[![Gratipay Team](https://img.shields.io/gratipay/team/rubocop.svg?maxAge=2592000)](https://gratipay.com/rubocop/)

> Role models are important.

> -- Officer Alex J. Murphy / RoboCop

**RuboCop** is a Ruby static code analyzer. Out of the box it will
enforce many of the guidelines outlined in the community
[Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide).

Most aspects of its behavior can be tweaked via various
[configuration options](https://github.com/bbatsov/rubocop/blob/master/config/default.yml).

Apart from reporting problems in your code, RuboCop can also
automatically fix some of the problems for you.

[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/bbatsov/rubocop?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

You can support my work on RuboCop via
[Salt](https://salt.bountysource.com/teams/rubocop) and
[Gratipay](https://gratipay.com/rubocop/).

[![Support via Gratipay](https://cdn.rawgit.com/gratipay/gratipay-badge/2.1.3/dist/gratipay.png)](https://gratipay.com/rubocop/)

## Installation

**RuboCop**'s installation is pretty standard:

```sh
$ gem install rubocop
```

If you'd rather install RuboCop using `bundler`, don't require it in your `Gemfile`:

```rb
gem 'rubocop', require: false
```

RuboCop's development is moving at a very rapid pace and there are
often backward-incompatible changes between minor releases (since we
haven't reached version 1.0 yet). To prevent an unwanted RuboCop update you
might want to use a conservative version locking in your `Gemfile`:

```rb
gem 'rubocop', '~> 0.46.0', require: false
```

## Quickstart

Just type `rubocop` in a Ruby project's folder and watch the magic happen.

```
$ cd my/cool/ruby/project
$ rubocop
```

## Official manual

You can read a ton more about RuboCop in its [official manual](http://rubocop.readthedocs.io).

## Compatibility

RuboCop supports the following Ruby implementations:

* MRI 2.0
* MRI 2.1
* MRI 2.2
* MRI 2.3
* JRuby 9.0+
* Rubinius 2.0+

## Team

Here's a list of RuboCop's core developers:

* [Bozhidar Batsov](https://github.com/bbatsov)
* [Jonas Arvidsson](https://github.com/jonas054)
* [Yuji Nakayama](https://github.com/yujinakayama)
* [Evgeni Dzhelyov](https://github.com/edzhelyov)

## Logo

RuboCop's logo was created by [Dimiter Petrov](https://www.chadomoto.com/). You can find the logo in various
formats [here](https://github.com/bbatsov/rubocop/tree/master/logo).

The logo is licensed under a
[Creative Commons Attribution-NonCommercial 4.0 International License](http://creativecommons.org/licenses/by-nc/4.0/deed.en_GB).

## Contributors

Here's a [list](https://github.com/bbatsov/rubocop/graphs/contributors) of
all the people who have contributed to the development of RuboCop.

I'm extremely grateful to each and every one of them!

If you'd like to contribute to RuboCop, please take the time to go
through our short
[contribution guidelines](CONTRIBUTING.md).

Converting more of the Ruby Style Guide into RuboCop cops is our top
priority right now. Writing a new cop is a great way to dive into RuboCop!

Of course, bug reports and suggestions for improvements are always
welcome. GitHub pull requests are even better! :-)

You can also support my work on RuboCop via
[Salt](https://salt.bountysource.com/teams/rubocop) and
[Gratipay](https://gratipay.com/rubocop/).

[![Support via Gratipay](https://cdn.rawgit.com/gratipay/gratipay-badge/2.1.3/dist/gratipay.png)](https://gratipay.com/rubocop/)

## Changelog

RuboCop's changelog is available [here](CHANGELOG.md).

## Copyright

Copyright (c) 2012-2016 Bozhidar Batsov. See [LICENSE.txt](LICENSE.txt) for
further details.


text:
require "test_helper"

# Single search controller test.
class SrchRefsDefQueriesRefIdWInstListHasInstWLimit < ActionController::TestCase
  tests SearchController

  test "search reference id with instances limited" do
    ref = references(:bucket_reference_for_default_instances)
    get(:search,
        { query_target: "references",
          query_string: "id: #{ref.id} show-instances: limit:10" },
        username: "fred",
        user_full_name: "Fred Jones",
        groups: [])
    assert_response :success
    assert_select "#search-results-summary",
                  /[0-9][0-9] records\b/,
                  "Should find some records"
    assert_select "#search-results-summary",
                  /\b10 records\b/,
                  "Should say 10 records"
  end
end


text:
========
Advanced
========

Variable Parameters to Mock Functions
-------------------------------------

IgnoreArg()
^^^^^^^^^^^^^^^^^

And()
^^^^^^^^^^^

Or()
^^^^^^^^^^

Is()
^^^^^^^^^^

IsA()
^^^^^^^^^^^

IsAlmost()
^^^^^^^^^^^^^^^^

StringContains()
^^^^^^^^^^^^^^^^^^^^^^

Regex()
^^^^^^^^^^^^^

In()
^^^^^^^^^^

Not()
^^^^^^^^^^^

ContainsKeyValue()
^^^^^^^^^^^^^^^^^^^^^^^^

ContainsAttributeValue()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

SameElementAs()
^^^^^^^^^^^^^^^^^^^^^

Calling Mock Objects Multiple Times
-----------------------------------

Mimic is pretty strict about which functions are called, and how many times they're
called. This could be tedious if the same function is called with the same Parameters
and you were required to setup those expectations repeatedly.

In a situation in which the function ``my_call`` is called three times during the
course of a test, you could do this:

.. sourcecode:: python

    my_object.my_call().and_return(True)
    my_object.my_call().and_return(True)
    my_object.my_call().and_return(True)

However, you can chain a ``multiple_times()`` call into the first call.

.. sourcecode:: python

    my_object.my_call().multiple_times().and_return(True)
    # Done! :)

Now, if you wanted to make sure it got called three times and no more or no less:

.. sourcecode:: python

    my_object.my_call().multiple_times(3).and_return(True)

.. _stubbing_out_a_class:

Stubbing Out A Class
--------------------

If you need to make an instance with the characteristic of a particular class,
and whose instance attributes and methods you wish to be able to control, try
``stub_out_class_with_mocks``. This is particularly useful when an object is
instanstiated within the code tested by your test.

.. sourcecode:: python

    self.mimic.stub_out_class_with_mocks(my_module, 'MyClass')
    mock_object = my_module.MyClass()
    # Setup any expectations you want for MyClass

Now you have an object that you can set any expectations you need to override
for your testing.

MockAnything Objects
--------------------

These are sort of like a mock object created by ``stub_out_class_with_mocks``
however, you don't even need to specify a class. It's an empty vessel with which
any expectations you want. This is useful whenever you might need an object, but
the code you're testing isn't responsible for its creation (e.g. you can pass it
into the function).

.. sourcecode:: python

    fake_result = self.mimic.create_mock_anything()
    fake_result.result = 'Some fake result data'
    fake_connection = self.mimic.create_mock_anything()
    fake_connection.query(mimic.ignore_arg()).and_return(fake_result)

Stubbing Out Python Builtins
----------------------------

For example, if you need to mock out a python builtin such as ``open``, the
following code would work:

.. sourcecode:: python

    # Assuming you've setup your mimic instance as self.mimic
    fake_conf_file = StringIO.StringIO('')
    self.mimic.stub_out_with_mock(sys.modules['__builtin__'], 'open')
    sys.modules['__builtin__'].open('path/to/file.txt', 'r').and_return(
        fake_conf_file
    )

    self.mimic.replay_all()

    # Calls you would need to make that interact with filesystems, etc.


text:
 license: Licensed to the Apache Software Foundation (ASF) under one
         or more contributor license agreements.  See the NOTICE file
         distributed with this work for additional information
         regarding copyright ownership.  The ASF licenses this file
         to you under the Apache License, Version 2.0 (the
         "License"); you may not use this file except in compliance
         with the License.  You may obtain a copy of the License at

           http://www.apache.org/licenses/LICENSE-2.0

         Unless required by applicable law or agreed to in writing,
         software distributed under the License is distributed on an
         "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
         KIND, either express or implied.  See the License for the
         specific language governing permissions and limitations
         under the License.
---

# backbutton

The event fires when the user presses the back button.

    document.addEventListener("backbutton", yourCallbackFunction, false);

## Details

To override the default back-button behavior, register an event
listener for the `backbutton` event, typically by calling
`document.addEventListener` once you receive the `deviceready` event.
It is no longer necessary to call any other method to override the
back-button behavior.

## Supported Platforms

- Android
- BlackBerry WebWorks (OS 5.0 and higher)
- Windows Phone 7 and 8

## Quick Example

    document.addEventListener("backbutton", onBackKeyDown, false);

    function onBackKeyDown() {
        // Handle the back button
    }

## Full Example

    <!DOCTYPE html>
    <html>
      <head>
        <title>Back Button Example</title>

        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
        <script type="text/javascript" charset="utf-8">

        // Wait for device API libraries to load
        //
        function onLoad() {
            document.addEventListener("deviceready", onDeviceReady, false);
        }

        // device APIs are available
        //
        function onDeviceReady() {
            // Register the event listener
            document.addEventListener("backbutton", onBackKeyDown, false);
        }

        // Handle the back button
        //
        function onBackKeyDown() {
        }

        </script>
      </head>
      <body onload="onLoad()">
      </body>
    </html>


text:
PROGDIR=$(dirname "$0")
. "$PROGDIR/prebuilt-common.sh"

PROGRAM_PARAMETERS="<dst-dir>"
PROGRAM_DESCRIPTION="\
This script allows you to generate a 'wrapper toolchain', i.e. a set of
simple scripts that act as toolchain binaries (e.g. my-cc, my-c++, my-ld,
etc...) but call another installed toolchain instead, possibly with additional
command-line options.

For example, imagine we want a toolchain that generates 32-bit binaries while
running on a 64-bit system, we could call this script as:

   $PROGNAME --cflags="-m32" --cxxflags="-m32" --ldflags="-m32" /tmp/my-toolchain

Then, this will create programs like:

   /tmp/my-toolchain/my-cc
   /tmp/my-toolchain/my-gcc
   /tmp/my-toolchain/my-c++
   /tmp/my-toolchain/my-g++
   /tmp/my-toolchain/my-ld
   ...

Where the compilers and linkers will add the -m32 flag to the command-line before
calling the host version of 'cc', 'gcc', etc...

Generally speaking:

  - The 'destination toolchain' is the one that will be called by the
    generated wrapper script. It is identified by a 'destination prefix'
    (e.g. 'x86_64-linux-gnu-', note the dash at the end).

    If is empty by default, but can be changed with --dst-prefix=<prefix>

  - The 'source prefix' is the prefix added to the generated toolchain scripts,
    it is 'my-' by default, but can be changed with --src-prefix=<prefix>

  - You can use --cflags, --cxxflags, --ldflags, etc... to add extra
    command-line flags for the generated compiler, linker, etc.. scripts

"

DEFAULT_SRC_PREFIX="my-"
DEFAULT_DST_PREFIX=""

SRC_PREFIX=$DEFAULT_SRC_PREFIX
register_var_option "--src-prefix=<prefix>" SRC_PREFIX "Set source toolchain prefix"

DST_PREFIX=$DEFAULT_DST_PREFIX
register_var_option "--dst-prefix=<prefix>" DST_PREFIX "Set destination toolchain prefix"

EXTRA_CFLAGS=
register_var_option "--cflags=<options>" EXTRA_CFLAGS "Add extra C compiler flags"

EXTRA_CXXFLAGS=
register_var_option "--cxxflags=<options>" EXTRA_CXXFLAGS "Add extra C++ compiler flags"

EXTRA_LDFLAGS=
register_var_option "--ldflags=<options>" EXTRA_LDFLAGS "Add extra linker flags"

EXTRA_ASFLAGS=
register_var_option "--asflags=<options>" EXTRA_ASFLAGS "Add extra assembler flags"

EXTRA_ARFLAGS=
register_var_option "--arflags=<options>" EXTRA_ARFLAGS "Add extra archiver flags"

CCACHE=
register_var_option "--ccache=<prefix>" CCACHE "Use ccache compiler driver"

PROGRAMS="cc gcc c++ g++ cpp as ld ar ranlib strip strings nm objdump dlltool"
register_var_option "--programs=<list>" PROGRAMS "List of programs to generate wrapper for"

extract_parameters "$@"

PROGRAMS=$(commas_to_spaces "$PROGRAMS")
if [ -z "$PROGRAMS" ]; then
    panic "Empty program list, nothing to do!"
fi

DST_DIR="$PARAMETERS"
if [ -z "$DST_DIR" ]; then
    panic "Please provide a destination directory as a parameter! See --help for details."
fi

mkdir -p "$DST_DIR"
fail_panic "Could not create destination directory: $DST_DIR"

# Generate a small wrapper program
#
# $1: program name, without any prefix (e.g. gcc, g++, ar, etc..)
# $2: source prefix (e.g. 'i586-mingw32msvc-')
# $3: destination prefix (e.g. 'i586-px-mingw32msvc-')
# $4: destination directory for the generate program
#
gen_wrapper_program ()
{
    local PROG="$1"
    local SRC_PREFIX="$2"
    local DST_PREFIX="$3"
    local DST_FILE="$4/${SRC_PREFIX}$PROG"
    local FLAGS=""
    local LDL_FLAGS=""

    case $PROG in
      cc|gcc)
          FLAGS=$FLAGS" $EXTRA_CFLAGS"
          LDL_FLAGS="-ldl"
          ;;
      c++|g++)
          FLAGS=$FLAGS" $EXTRA_CXXFLAGS"
          LDL_FLAGS="-ldl"
          ;;
      ar) FLAGS=$FLAGS" $EXTRA_ARFLAGS";;
      as) FLAGS=$FLAGS" $EXTRA_ASFLAGS";;
      ld|ld.bfd|ld.gold) FLAGS=$FLAGS" $EXTRA_LDFLAGS";;
    esac

    if [ -n "$CCACHE" ]; then
        DST_PREFIX=$CCACHE" "$DST_PREFIX
    fi

    cat > "$DST_FILE" << EOF
#!/bin/sh
# Auto-generated, do not edit
${DST_PREFIX}$PROG $FLAGS "\$@" $LDL_FLAGS
EOF
    chmod +x "$DST_FILE"
    log "Generating: ${SRC_PREFIX}$PROG"
}

log "Generating toolchain wrappers in: $DST_DIR"

for PROG in $PROGRAMS; do
  gen_wrapper_program $PROG "$SRC_PREFIX" "$DST_PREFIX" "$DST_DIR"
done

log "Done!"


text:
function X = lleEmbed(Y, dims, neighbours)

% LLEEMBED Embed data set with LLE.
%
%	Description:
%	X = lleEmbed(Y, dims, neighbours)
%

% Wrapper for Sam Roweis' LLE code.

% Note LLE code uses the transpose of a design matrix.
if nargin < 3
  neighbours = 7;
end
if any(any(isnan(Y)))
  error('Cannot initialise gplvm using LLE when missing data is present.')
else
  X = lle(Y', neighbours, dims);
  X = X';
  % Rescale X so that variance is 1 and mean is zero.
  meanX = mean(X);
  X = X-ones(size(Y, 1), 1)*meanX;
  varX = var(X);
  X = X*diag(sqrt(1./varX));
end


text:
package com.pacificmetrics.common.web;

import java.io.IOException;

import javax.faces.application.ResourceHandler;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebFilter(servletNames={"Faces Servlet"})
public class NoCacheFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpReq = (HttpServletRequest) request;
        HttpServletResponse httpRes = (HttpServletResponse) response;

        if (!httpReq.getRequestURI().startsWith(httpReq.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER)) { // Skip JSF resources (CSS/JS/Images/etc)
            httpRes.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
            httpRes.setHeader("Pragma", "no-cache"); // HTTP 1.0.
            httpRes.setDateHeader("Expires", 0); // Proxies.
        }

        chain.doFilter(request, response);
    }

    // ...

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    	// Do nothing because of X and Y.
    }

    @Override
    public void destroy() {
    	// Do nothing because of X and Y.
    }
}


text:
@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [MyThemes restoreLastTheme];

    // status bar

    ThemeStatusBarStylePicker *statusPicker = [ThemeStatusBarStylePicker pickerWithStringStyles:globalStatusBarStringStyles];

    [[UIApplication sharedApplication] theme_setStatusBarStyle:statusPicker animated:YES];

    // navigation bar

    UINavigationBar *navigationBar = [UINavigationBar appearance];

    NSShadow *shadow = [[NSShadow alloc] init];
    shadow.shadowOffset = CGSizeZero;

    NSMutableArray *titleAttributes = [NSMutableArray array];

    for (NSString *rgba in globalBarTextColors) {
        UIColor *color = [[UIColor alloc] initWithRgba_throws:rgba error:nil];
        NSDictionary *attr = @{
            NSForegroundColorAttributeName: color,
            NSFontAttributeName: [UIFont systemFontOfSize:16],
            NSShadowAttributeName: shadow
        };
        [titleAttributes addObject:attr];
    }

    navigationBar.theme_tintColor = globalBarTextColorPicker;
    navigationBar.theme_barTintColor = globalBarTintColorPicker;
    navigationBar.theme_titleTextAttributes = [ThemeDictionaryPicker pickerWithDicts:titleAttributes];

    // tab bar

    UITabBar *tabBar = [UITabBar appearance];
    tabBar.theme_tintColor = globalBarTextColorPicker;
    tabBar.theme_barTintColor = globalBarTintColorPicker;

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application { }

- (void)applicationDidEnterBackground:(UIApplication *)application { }

- (void)applicationWillEnterForeground:(UIApplication *)application { }

- (void)applicationDidBecomeActive:(UIApplication *)application { }

- (void)applicationWillTerminate:(UIApplication *)application {
    [MyThemes saveLastTheme];
}

@end


text:
#region Copyright

#endregion

#region

using Autodesk.DesignScript.Runtime;
using Dynamo.Models;
using System.Collections.Generic;
using Dynamo.Nodes;
using Kodestruct.Concrete.ACI318_14;
using Concrete.ACI318.General;
using Concrete.ACI318.General.Reinforcement;
using Concrete.ACI318.General.Concrete;
using Dynamo.Graph.Nodes;
using KodestructAci = Kodestruct.Concrete.ACI;
using KodestructAci14 = Kodestruct.Concrete.ACI318_14;
using Kodestruct.Common.CalculationLogger;

#endregion

namespace Concrete.ACI318.Section.SectionTypes
{

    /// <summary>
    ///   Rectangular section four sides
    ///   Category:   Concrete.ACI318_14.General
    /// </summary>

    [IsDesignScriptCompatible]
    public partial class RectangularSectionFourSideReinforced : ConcreteFlexureAndAxiaSection
    {

        [IsVisibleInDynamoLibrary(false)]
        internal RectangularSectionFourSideReinforced(double b, double h, double A_sTopBottom, double A_sLeftRight,
         double c_cntrTopBottom, double c_cntrLeftRight, ConcreteMaterial ConcreteMaterial, RebarMaterial LongitudinalRebarMaterial,
            bool hasTies = false)
        {

            KodestructAci.ConfinementReinforcementType ConfinementReinforcementType;
            if (hasTies == true)
            {
                ConfinementReinforcementType = KodestructAci.ConfinementReinforcementType.Ties;
            }
            else
            {
                ConfinementReinforcementType = KodestructAci.ConfinementReinforcementType.NoReinforcement;
            }

            base.ConcreteMaterial = ConcreteMaterial; //duplicate save of concrete material into base Dynamo class

            FlexuralSectionFactory flexureFactory = new FlexuralSectionFactory();
            ConcreteSectionFlexure fs = flexureFactory.GetRectangularSectionFourSidesDistributed(b, h,A_sTopBottom, A_sLeftRight,
                c_cntrTopBottom, c_cntrLeftRight,
                ConcreteMaterial.Concrete, LongitudinalRebarMaterial.Material,ConfinementReinforcementType);

            this.FlexuralSection = fs;
        }

        /// <summary>
        /// Rectangular section with reinforcement on 4-sides
        /// </summary>
        /// <param name="b">Width of compression face of member</param>
        /// <param name="h">Overall thickness, height, or depth of member</param>
        /// <param name="A_sTopBottom">Total area of top/bottom reinforcement (per face)</param>
        /// <param name="A_sLeftRight">Total area of reinforcement on left-hand/right-hand side face (per face)</param>
        /// <param name="c_cntrTopBottom">Concrete cover to tension rebar centroid (top or bottom face)</param>
        /// <param name="c_cntrLeftRight">Concrete cover to tension rebar centroid (side faces)</param>
        /// <param name="ConcreteMaterial">Concrete material</param>
        /// <param name="LongitudinalRebarMaterial">Rebar material for longitudinal bars</param>
        /// <param name="hasTies">Identifies if member has ties around longitudinal reinforcement</param>
        /// <returns name="RectangularSectionFourSideReinforced">  Section [OBJECT] </returns>

        public static RectangularSectionFourSideReinforced ByWidthHeigthAndReinforcementArea(double b, double h, double A_sTopBottom,  double A_sLeftRight,
         double c_cntrTopBottom, double c_cntrLeftRight,
            ConcreteMaterial ConcreteMaterial, RebarMaterial LongitudinalRebarMaterial, bool HasTies = true)
        {
            return new RectangularSectionFourSideReinforced(b, h, A_sTopBottom, A_sLeftRight, c_cntrTopBottom, c_cntrLeftRight,
                ConcreteMaterial, LongitudinalRebarMaterial,HasTies);
        }

    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <TextView
    android:id="@+id/sandbox_group"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="60px"
    android:paddingTop="10px"
    android:paddingBottom="10px"
    android:textSize="26sp"
    android:textStyle="bold"
    />
</LinearLayout>