text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/pnor/sfc_ast2500.C $                                  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016                             */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/*****************************************************************************/
// I n c l u d e s
/*****************************************************************************/
#include <sio/sio.H>
#include <sys/mmio.h>
#include <sys/task.h>
#include <sys/sync.h>
#include <string.h>
#include <devicefw/driverif.H>
#include <trace/interface.H>
#include <errl/errlentry.H>
#include <errl/errlmanager.H>
#include <errl/errludlogregister.H>
#include <targeting/common/targetservice.H>
#include <pnor/pnor_reasoncodes.H>
#include <sys/time.h>
#include <errl/hberrltypes.H>
#include <lpc/lpcif.H>
#include "sfc_ast2500.H"
#include "norflash.H"
#include "sfc_ast2X00.H"
#include <util/align.H>
#include "pnor_common.H"

/*****************************************************************************/
// C o n s t a n t s
/*****************************************************************************/

/*****************************************************************************/
// G l o b a l s
/*****************************************************************************/

// Initialized in pnorrp.C
extern trace_desc_t* g_trac_pnor;
/*****************************************************************************/
// M e t h o d s
/*****************************************************************************/
namespace PNOR {
/**
 * @brief Wrapper for device driver constructor
 */
errlHndl_t create_SfcDD( SfcDD*& o_sfc,
                         TARGETING::Target* i_proc )
{
    errlHndl_t l_err = NULL;
    TRACFCOMP( g_trac_pnor, "Creating SfcAST2500 object" );
    o_sfc = new SfcAST2500( l_err, i_proc );
    return l_err;
}

};

/**
 * @brief Constructor
 */
SfcAST2500::SfcAST2500( errlHndl_t& o_err,
                        TARGETING::Target* i_proc )
: SfcAST2X00(o_err,i_proc)
{
}

/**
 * @brief Initialize and configure the SFC hardware
 */
errlHndl_t SfcAST2500::hwInit( )
{
    TRACFCOMP( g_trac_pnor, ENTER_MRK"SfcAST2500::hwInit>" );
    errlHndl_t l_err = NULL;
    uint32_t l_lpc_addr;
    do
    {
        /* Enable device 0x0D*/
        uint8_t l_data = SIO::ENABLE_DEVICE;
        size_t l_len = sizeof(l_data);
        l_err = deviceOp( DeviceFW::WRITE,
                          TARGETING::MASTER_PROCESSOR_CHIP_TARGET_SENTINEL,
                          (&l_data),
                          l_len,
                          DEVICE_SIO_ADDRESS(SIO::iLPC2AHB,0x30));
        if(l_err) { break; }

        /* ----- Setup the SPI Controller ----- */

        /* Enable write command mode to CE0 */
        SpiCE0ControlReg10_t l_ctlregCE0;
        l_lpc_addr = CE0_CTRLREG_10 | SPIC_BASE_ADDR_AHB;
        l_err = ahbSioReadWrapper(l_ctlregCE0.data32, l_lpc_addr);
        if( l_err ) { break; }

        l_ctlregCE0.cmdMode=0b10; //10:Normal Write (CMD + Address + Write data)
        l_err = ahbSioWriteWrapper(l_ctlregCE0.data32, l_lpc_addr);
        if( l_err ) { break; }

/* @TODO RTC:162680
        // Enable write command mode to CE1
        SpiCE1ControlReg14_t l_ctlregCE1;
        l_lpc_addr = CE1_CTRLREG_14 | SPIC_BASE_ADDR_AHB;
        l_err = ahbSioReadWrapper(l_ctlregCE1.data32, l_lpc_addr);
        if( l_err ) { break; }

        l_ctlregCE1.cmdMode=0b10; //10:Normal Write (CMD + Address + Write data)
        l_err = ahbSioWriteWrapper(l_ctlregCE1.data32, l_lpc_addr);
        if( l_err ) { break; }
**/

        /* Enable writing to CE0 and CE1 */
        SpiConfigReg00_t confreg;
        l_lpc_addr = CONFREG_00 | SPIC_BASE_ADDR_AHB;
        l_err = ahbSioReadWrapper(confreg.data32, l_lpc_addr);
        if( l_err ) { break; }

        confreg.enableCE0Write = 1; //Enable flash memory write for CE0
        //@TODO RTC:162680 - confreg.enableCE1Write = 1;
        l_err = ahbSioWriteWrapper(confreg.data32, l_lpc_addr);
        if( l_err ) { break; }

        /*
         * Setup base CE Control reg for our use, four byte mode for address
         * selection and setting 2x clock cycles
         */
        SpiCEControlReg04_t l_ceCtrlReg;
        l_lpc_addr = CE_CTLREG_04 | SPIC_BASE_ADDR_AHB;
        l_err = ahbSioReadWrapper(confreg.data32, l_lpc_addr);
        if( l_err ) { break; }

        l_ceCtrlReg.enableCE0Div2 = 1; //Enable 2x clock cycles for CE0
        l_ceCtrlReg.fourByteModeCE0 = 1;
        /* @TODO RTC:162680
         * l_ceCtrlReg.enableCE1Div2 = 1; //Enable 2x clock cycles for CE1
         * l_ceCtrlReg.fourByteModeCE1 = 1;
         */
        l_err = ahbSioWriteWrapper(l_ceCtrlReg.data32, l_lpc_addr);
        if( l_err ) { break; }

        /*
         * Setup control regs for CE0 + CE1 for our use, switching
         * to 1-bit mode (ioMode == 0b00), clearing user mode if
         * set (cmdMode == 0b00)
         * etc...
         *
         * Also configure SPI clock to something safe
         * like HCLK/8 (24Mhz)
         */
        l_ctlregCE0.ioMode = 0b00; //single bit or controlled by bit[3]
        l_ctlregCE0.pulseWidth = 0x0; //0000: 16T (1T = 1 HCLK clock)
        l_ctlregCE0.cmdData = 0x00;
        l_ctlregCE0.spiClkFreq = 0x4; //HCLK/8
        l_ctlregCE0.dummyCycleRead1 = 0; //no dummy cycles
        l_ctlregCE0.dummyCycleRead2 = 0b00; //no dummy cycles
        l_ctlregCE0.cmdMode = 0b00; //00:Normal Read (03h + Address + Read data)

        /* @TODO RTC:162680
        l_ctlregCE1.ioMode = 0b00; //single bit or controlled by bit[3]
        l_ctlregCE1.pulseWidth = 0x0; //0000: 16T (1T = 1 HCLK clock)
        l_ctlregCE1.cmdData = 0x00;
        l_ctlregCE1.spiClkFreq = 0x4; //HCLK/8
        l_ctlregCE1.dummyCycleRead1 = 0; //no dummy cycles
        l_ctlregCE1.dummyCycleRead2 = 0b00; //no dummy cycles
        l_ctlregCE1.cmdMode = 0b00; //00:Normal Read (03h + Address + Read data)
        **/

        iv_ctlRegCE0Default = l_ctlregCE0; // Default setup is regular read mode
        // @TODO RTC:162680 iv_ctlRegCE1Default = l_ctlregCE1;

        // Configure CE0 for read
        l_lpc_addr = CE0_CTRLREG_10 | SPIC_BASE_ADDR_AHB;
        l_err = ahbSioWriteWrapper(l_ctlregCE0.data32, l_lpc_addr);
        if( l_err ) { break; }

        /*  @TODO RTC:162680
        // Configure CE1 for read
        l_lpc_addr = CE1_CTRLREG_14 | SPIC_BASE_ADDR_AHB;
        l_err = ahbSioWriteWrapper(l_ctlregCE1.data32, l_lpc_addr);
        if( l_err ) { break; }
        **/

        // Figure out what flash chip we have
        uint32_t chipid = 0;
        l_err = getNORChipId( chipid );
        if( l_err ) { break; }

        // Setup flash-specific settings here, if there are any

    } while(0);

    TRACFCOMP( g_trac_pnor, EXIT_MRK"SfcAST2500::hwInit> err=%.8X", ERRL_GETEID_SAFE(l_err) );
    return l_err;
}

/**
 * @brief Enter/exit command mode
 */
errlHndl_t SfcAST2500::commandMode( bool i_enter )
{
    errlHndl_t l_err = NULL;
    uint32_t l_lpc_addr;
    TRACDCOMP( g_trac_pnor, ENTER_MRK"SfcAST2500::commandMode(%d)", i_enter );

    /*
     * There is only a limited addressable window within LPC space.  The AST
     * has its control register space at too far of a distance from the read
     * space for them both to fit in a single window.  Rather than moving the
     * window around we will use the iLPC2AHB backdoor inside the SuperIO
     * controller to do both register accesses and to write into the flash.
     *
     * High level flow to write into control space:
     *    Stop active control (SPI04 Control Reg)
     *    Enable command mode (SPI04 Control Reg)
     *    Write actual command into flash base addr (0x0E000000)
     */

    do {
        //@TODO RTC:162680 - Does this path also need to enable
        //  the CE1 control reg (0x14)
        SpiCE0ControlReg10_t ctlreg = iv_ctlRegCE0Default;

        // Switch to user mode, CE# dropped
        ctlreg.stopActiveCtl = 1;
        ctlreg.cmdMode = 0b11; //User Mode (Read/Write Data)
        l_lpc_addr = CE0_CTRLREG_10 | SPIC_BASE_ADDR_AHB;
        l_err = ahbSioWriteWrapper(ctlreg.data32, l_lpc_addr);
        if( l_err ) { break; }

        if( i_enter ) //ast_sf_start_cmd
        {
            // user mode, CE# active
            ctlreg.stopActiveCtl = 0;
            l_err = ahbSioWriteWrapper(ctlreg.data32, l_lpc_addr);
            if( l_err ) { break; }
        }
        else //ast_sf_end_cmd
        {
            // Switch back to read mode
            l_err = ahbSioWriteWrapper(iv_ctlRegCE0Default.data32, l_lpc_addr);
            if( l_err ) { break; }
        }

    } while(0);

    TRACDCOMP( g_trac_pnor, EXIT_MRK"SfcAST2500::commandMode> err=%.8X", ERRL_GETEID_SAFE(l_err) );
    return l_err;
}


text:
@implementation UIImage (pixelColor)

- (UIColor*)colorAtPoint:(CGPoint)point {

    CFDataRef pixelData = CGDataProviderCopyData(CGImageGetDataProvider(self.CGImage));
    const UInt8* data = CFDataGetBytePtr(pixelData);

    int pixelInfo = ((self.size.width  * point.y) + point.x ) * 4; // The image is png

    UInt8 red   = data[pixelInfo];
    UInt8 green = data[pixelInfo + 1];
    UInt8 blue  = data[pixelInfo + 2];
    UInt8 alpha = data[pixelInfo + 3];
    CFRelease(pixelData);

    return [UIColor colorWithRed:red/255.0f
                           green:green/255.0f
                            blue:blue/255.0f
                           alpha:alpha/255.0f];
}

@end

redpajama_set_name: RedPajamaGithub


text:
package com.evolveum.midpoint.model.impl.expr;

import static com.evolveum.midpoint.test.IntegrationTestTools.display;
import static org.testng.AssertJUnit.assertEquals;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import org.xml.sax.SAXException;

import com.evolveum.midpoint.model.common.expression.ExpressionVariables;
import com.evolveum.midpoint.model.common.expression.script.ScriptExpression;
import com.evolveum.midpoint.model.common.expression.script.ScriptExpressionFactory;
import com.evolveum.midpoint.model.impl.AbstractInternalModelIntegrationTest;
import com.evolveum.midpoint.model.impl.controller.ModelController;
import com.evolveum.midpoint.model.test.AbstractModelIntegrationTest;
import com.evolveum.midpoint.prism.ItemDefinition;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.PrismPropertyDefinition;
import com.evolveum.midpoint.prism.PrismPropertyValue;
import com.evolveum.midpoint.prism.util.PrismTestUtil;
import com.evolveum.midpoint.schema.MidPointPrismContextFactory;
import com.evolveum.midpoint.schema.constants.MidPointConstants;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.task.api.TaskManager;
import com.evolveum.midpoint.test.util.TestUtil;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.PrettyPrinter;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ScriptExpressionEvaluatorType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;

/**
 *
 * @author lazyman
 * @author mederly
 *
 */
@ContextConfiguration(locations = { "classpath:ctx-model-test-main.xml" })
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public class TestModelExpressions extends AbstractModelIntegrationTest {

	private static final String TEST_DIR = "src/test/resources/expr";

	private static final QName PROPERTY_NAME = new QName(SchemaConstants.NS_C, "foo");

	private static final Trace LOGGER = TraceManager.getTrace(TestModelExpressions.class);

    private static final String CHEF_OID = "00000003-0000-0000-0000-000000000000";
    private static final String CHEESE_OID = "00000002-0000-0000-0000-000000000000";
    private static final String CHEESE_JR_OID = "00000002-0000-0000-0000-000000000001";
    private static final String ELAINE_OID = "00000001-0000-0000-0000-000000000000";
    private static final String LECHUCK_OID = "00000007-0000-0000-0000-000000000000";
    private static final String F0006_OID = "00000000-8888-6666-0000-100000000006";

    @Autowired(required=true)
	private ScriptExpressionFactory scriptExpressionFactory;

    @Autowired(required = true)
    private ModelController modelController;

    @Autowired(required = true)
    private TaskManager taskManager;

    private static final String TEST_EXPRESSIONS_OBJECTS = "./src/test/resources/expr/orgstruct.xml";

    @BeforeSuite
	public void setup() throws SchemaException, SAXException, IOException {
		PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX);
		PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY);
	}

	@Override
	public void initSystem(Task initTask, OperationResult initResult) throws Exception {
		super.initSystem(initTask, initResult);

		modelService.postInit(initResult);

		// Administrator
		PrismObject<UserType> userAdministrator = repoAddObjectFromFile(AbstractInternalModelIntegrationTest.USER_ADMINISTRATOR_FILE, UserType.class, initResult);
		repoAddObjectFromFile(AbstractInternalModelIntegrationTest.ROLE_SUPERUSER_FILE, RoleType.class, initResult);
		login(userAdministrator);
	}

	@Test
	public void testHello() throws Exception {
		final String TEST_NAME = "testHello";
		TestUtil.displayTestTile(this, TEST_NAME);

		// GIVEN
        OperationResult result = new OperationResult(TestModelExpressions.class.getName() + "." + TEST_NAME);

		ScriptExpressionEvaluatorType scriptType = parseScriptType("expression-func.xml");
		ItemDefinition outputDefinition = new PrismPropertyDefinition(PROPERTY_NAME, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext());
		ScriptExpression scriptExpression = scriptExpressionFactory.createScriptExpression(scriptType, outputDefinition, TEST_NAME);

		ExpressionVariables variables = null;

		// WHEN
		List<PrismPropertyValue<String>> scriptOutputs = scriptExpression.evaluate(variables, null, false, TEST_NAME, result);

		// THEN
		display("Script output", scriptOutputs);
		assertEquals("Unexpected numeber of script outputs", 1, scriptOutputs.size());
		PrismPropertyValue<String> scriptOutput = scriptOutputs.get(0);
		assertEquals("Unexpected script output", "Hello swashbuckler", scriptOutput.getValue());
	}

	private ScriptExpressionEvaluatorType parseScriptType(String fileName) throws SchemaException, IOException, JAXBException {
		ScriptExpressionEvaluatorType expressionType = PrismTestUtil.parseAtomicValue(
                new File(TEST_DIR, fileName), ScriptExpressionEvaluatorType.COMPLEX_TYPE);
		return expressionType;
	}

    private boolean imported = false;
    private void importIfNeeded() throws Exception {
        if (!imported) {
            importObjectFromFile(TEST_EXPRESSIONS_OBJECTS);
            imported = true;
        }
    }

    @Test
    public void testGetUserByOid() throws Exception {
        final String TEST_NAME = "testGetUserByOid";
        TestUtil.displayTestTile(this, TEST_NAME);

        // GIVEN
        OperationResult result = new OperationResult(TestModelExpressions.class.getName() + "." + TEST_NAME);

        importIfNeeded();

        PrismObject<UserType> chef = repositoryService.getObject(UserType.class, CHEF_OID, null, result);

        ScriptExpressionEvaluatorType scriptType = parseScriptType("expression-" + TEST_NAME + ".xml");
        ItemDefinition outputDefinition = new PrismPropertyDefinition(PROPERTY_NAME, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext());        ScriptExpression scriptExpression = scriptExpressionFactory.createScriptExpression(scriptType, outputDefinition, TEST_NAME);
        ExpressionVariables variables = new ExpressionVariables();
        variables.addVariableDefinition(new QName(SchemaConstants.NS_C, "user"), chef);

        // WHEN
        List<PrismPropertyValue<String>> scriptOutputs = scriptExpression.evaluate(variables, null, false, TEST_NAME, result);

        // THEN
        display("Script output", scriptOutputs);
        assertEquals("Unexpected number of script outputs", 1, scriptOutputs.size());
        PrismPropertyValue<String> scriptOutput = scriptOutputs.get(0);
        assertEquals("Unexpected script output", chef.asObjectable().getName().getOrig(), scriptOutput.getValue());
    }

    @Test
    public void testGetManagersOids() throws Exception {
        final String TEST_NAME = "testGetManagersOids";
        TestUtil.displayTestTile(this, TEST_NAME);

        // GIVEN
        OperationResult result = new OperationResult(TestModelExpressions.class.getName() + "." + TEST_NAME);

        importIfNeeded();

        PrismObject<UserType> chef = repositoryService.getObject(UserType.class, CHEF_OID, null, result);

        ScriptExpressionEvaluatorType scriptType = parseScriptType("expression-" + TEST_NAME + ".xml");
        ItemDefinition outputDefinition = new PrismPropertyDefinition(PROPERTY_NAME, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext());
        ScriptExpression scriptExpression = scriptExpressionFactory.createScriptExpression(scriptType, outputDefinition, TEST_NAME);
        ExpressionVariables variables = new ExpressionVariables();
        variables.addVariableDefinition(new QName(SchemaConstants.NS_C, "user"), chef);

        // WHEN
        List<PrismPropertyValue<String>> scriptOutputs = scriptExpression.evaluate(variables, null, false, TEST_NAME, result);

        // THEN
        display("Script output", scriptOutputs);
        assertEquals("Unexpected number of script outputs", 4, scriptOutputs.size());
        Set<String> oids = new HashSet<String>();
        oids.add(scriptOutputs.get(0).getValue());
        oids.add(scriptOutputs.get(1).getValue());
        oids.add(scriptOutputs.get(2).getValue());
        oids.add(scriptOutputs.get(3).getValue());
        Set<String> expectedOids = new HashSet<String>(Arrays.asList(new String[] { CHEESE_OID, CHEESE_JR_OID, ELAINE_OID, LECHUCK_OID }));
        assertEquals("Unexpected script output", expectedOids, oids);
    }

    @Test
    public void testGetOrgByName() throws Exception {
        final String TEST_NAME = "testGetOrgByName";
        TestUtil.displayTestTile(this, TEST_NAME);

        // GIVEN
        OperationResult result = new OperationResult(TestModelExpressions.class.getName() + "." + TEST_NAME);

        importIfNeeded();

        ScriptExpressionEvaluatorType scriptType = parseScriptType("expression-" + TEST_NAME + ".xml");
        ItemDefinition outputDefinition = new PrismPropertyDefinition(PROPERTY_NAME, DOMUtil.XSD_STRING, PrismTestUtil.getPrismContext());        ScriptExpression scriptExpression = scriptExpressionFactory.createScriptExpression(scriptType, outputDefinition, TEST_NAME);
        ExpressionVariables variables = new ExpressionVariables();

        // WHEN
        List<PrismPropertyValue<String>> scriptOutputs = scriptExpression.evaluate(variables, null, false, TEST_NAME, result);

        // THEN
        display("Script output", scriptOutputs);
        assertEquals("Unexpected number of script outputs", 1, scriptOutputs.size());
        assertEquals("Unexpected script output", F0006_OID, scriptOutputs.get(0).getValue());
    }

}


text:
import { Component } from '@angular/core';
import { Location } from '../location.model';
import { GenericSearchResultsComponent } from '../../app-shared/generic-search-results.component'

@Component({
    selector: 'location-search-results',
    templateUrl: '/dist/js/location/search/location-search-results.component.html',
})
export class LocationSearchResultsComponent extends GenericSearchResultsComponent<Location> { }


text:
package com.amazonaws.services.lakeformation.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class BatchGrantPermissionsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * A list of failures to grant permissions to the resources.
     *

     */
    private java.util.List<BatchPermissionsFailureEntry> failures;

    /**
     *

     * A list of failures to grant permissions to the resources.
     *

     *
     * @return A list of failures to grant permissions to the resources.
     */

    public java.util.List<BatchPermissionsFailureEntry> getFailures() {
        return failures;
    }

    /**
     *

     * A list of failures to grant permissions to the resources.
     *

     *
     * @param failures
     *        A list of failures to grant permissions to the resources.
     */

    public void setFailures(java.util.Collection<BatchPermissionsFailureEntry> failures) {
        if (failures == null) {
            this.failures = null;
            return;
        }

        this.failures = new java.util.ArrayList<BatchPermissionsFailureEntry>(failures);
    }

    /**
     *

     * A list of failures to grant permissions to the resources.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setFailures(java.util.Collection)} or {@link #withFailures(java.util.Collection)} if you want to override
     * the existing values.
     *

     *
     * @param failures
     *        A list of failures to grant permissions to the resources.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public BatchGrantPermissionsResult withFailures(BatchPermissionsFailureEntry... failures) {
        if (this.failures == null) {
            setFailures(new java.util.ArrayList<BatchPermissionsFailureEntry>(failures.length));
        }
        for (BatchPermissionsFailureEntry ele : failures) {
            this.failures.add(ele);
        }
        return this;
    }

    /**
     *

     * A list of failures to grant permissions to the resources.
     *

     *
     * @param failures
     *        A list of failures to grant permissions to the resources.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public BatchGrantPermissionsResult withFailures(java.util.Collection<BatchPermissionsFailureEntry> failures) {
        setFailures(failures);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getFailures() != null)
            sb.append("Failures: ").append(getFailures());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof BatchGrantPermissionsResult == false)
            return false;
        BatchGrantPermissionsResult other = (BatchGrantPermissionsResult) obj;
        if (other.getFailures() == null ^ this.getFailures() == null)
            return false;
        if (other.getFailures() != null && other.getFailures().equals(this.getFailures()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getFailures() == null) ? 0 : getFailures().hashCode());
        return hashCode;
    }

    @Override
    public BatchGrantPermissionsResult clone() {
        try {
            return (BatchGrantPermissionsResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
package channel

import (
	"testing"

	"gotest.tools/v3/assert"
	"k8s.io/apimachinery/pkg/runtime/schema"

	v1beta1 "knative.dev/client/pkg/messaging/v1"
	"knative.dev/client/pkg/util"
)

func TestCreateChannelErrorCase(t *testing.T) {
	cClient := v1beta1.NewMockKnChannelsClient(t)
	cRecorder := cClient.Recorder()
	_, err := executeChannelCommand(cClient, "create")
	assert.Error(t, err, "'kn channel create' requires the channel name given as single argument")
	cRecorder.Validate()
}

func TestCreateChannelErrorCaseTypeFormat(t *testing.T) {
	cClient := v1beta1.NewMockKnChannelsClient(t)
	cRecorder := cClient.Recorder()
	_, err := executeChannelCommand(cClient, "create", "pipe", "--type", "foo::bar")
	assert.Error(t, err, "Error: incorrect value 'foo::bar' for '--type', must be in the format 'Group:Version:Kind' or configure an alias in kn config")
	cRecorder.Validate()
}

func TestCreateChannelDefaultChannel(t *testing.T) {
	cClient := v1beta1.NewMockKnChannelsClient(t)
	cRecorder := cClient.Recorder()
	cRecorder.CreateChannel(createChannel("pipe", "default", nil), nil)
	out, err := executeChannelCommand(cClient, "create", "pipe")
	assert.NilError(t, err, "channel should be created")
	assert.Assert(t, util.ContainsAll(out, "created", "pipe", "default"))
	cRecorder.Validate()
}

func TestCreateChannelWithTypeFlagInMemoryChannel(t *testing.T) {
	cClient := v1beta1.NewMockKnChannelsClient(t)
	cRecorder := cClient.Recorder()
	cRecorder.CreateChannel(createChannel("pipe", "default", &schema.GroupVersionKind{Group: "messaging.knative.dev", Version: "v1", Kind: "InMemoryChannel"}), nil)
	out, err := executeChannelCommand(cClient, "create", "pipe", "--type", "imc")
	assert.NilError(t, err, "channel should be created")
	assert.Assert(t, util.ContainsAll(out, "created", "pipe", "default"))
	cRecorder.Validate()
}


text:
#ifndef RANSACLINEDETECTOR_H
#define RANSACLINEDETECTOR_H

#include <iostream>

#include <ModuleFramework/Module.h>
#include <Representations/Infrastructure/FrameInfo.h>

#include "Tools/Debug/DebugRequest.h"
#include "Tools/Debug/DebugModify.h"
#include "Tools/Debug/DebugDrawings.h"
#include "Tools/Debug/DebugParameterList.h"

#include "ransac_tools.h"

#include "Representations/Infrastructure/FieldInfo.h"
#include "Representations/Perception/LineGraphPercept.h"
#include "Representations/Perception/LinePercept2018.h"

#include "Ellipse.h"

BEGIN_DECLARE_MODULE(RansacLineDetector)
PROVIDE(DebugRequest)
PROVIDE(DebugModify)
PROVIDE(DebugDrawings)
PROVIDE(DebugParameterList)

REQUIRE(LineGraphPercept)
REQUIRE(FieldInfo)

PROVIDE(RansacLinePercept)
PROVIDE(RansacCirclePercept2018)
END_DECLARE_MODULE(RansacLineDetector)

class RansacLineDetector: public RansacLineDetectorBase
{
public:
RansacLineDetector();
~RansacLineDetector();

virtual void execute();

private:
class Parameters: public ParameterList
{
public:
    Parameters() : ParameterList("RansacLineDetector")
    {
        PARAMETER_REGISTER(detect_lines_first) = false;

        //Lines
        PARAMETER_REGISTER(line.maxLines) = 11;
        PARAMETER_REGISTER(line.maxIterations) = 100;
        PARAMETER_REGISTER(line.minInliers) = 12;

        PARAMETER_REGISTER(line.outlierThresholdDist) = 70;
        PARAMETER_ANGLE_REGISTER(line.outlierThresholdAngle) = 8;

        PARAMETER_REGISTER(line.maxVariance) = 0.009;
        PARAMETER_REGISTER(line.max_length_for_var_check) = 800;
        PARAMETER_REGISTER(line.min_line_length) = 100;
        //PARAMETER_REGISTER(line.fit_lines_to_inliers) = false;

        //Circle
        PARAMETER_REGISTER(circle.maxIterations) = 50;
        PARAMETER_REGISTER(circle.minInliers) = 7;
        PARAMETER_REGISTER(circle.outlierThresholdDist) = 70;
        PARAMETER_ANGLE_REGISTER(circle.outlierThresholdAngle) = 8;

        PARAMETER_REGISTER(circle.enable) = true;
        PARAMETER_REGISTER(circle.refine) = true;

        PARAMETER_REGISTER(circle.validate) = true;
        PARAMETER_REGISTER(circle.validation_thresh) = 200;

        syncWithConfig();
    }

    bool detect_lines_first;

    struct Line {
        int maxLines;
        int maxIterations;
        int minInliers;
        double outlierThresholdDist;
        double outlierThresholdAngle;

        double maxVariance;
        double max_length_for_var_check;
        double min_line_length;

        //bool fit_lines_to_inliers;
    } line;

    struct Circle {
        int maxIterations;
        int minInliers;
        double outlierThresholdDist;
        double outlierThresholdAngle;

        bool enable;
        bool refine;

        bool validate;
        double validation_thresh;
    } circle;

} params;

// index vector on remaining outlier edgels
std::vector<size_t> outliers;

private: // detectors
ransac::RansacLine lineRansac;
ransac::RansacCircle circleRansac;

void find_middle_circle(std::vector<size_t>& inlier_idx);
void find_field_lines(std::vector<size_t>& inlier_idx);

int ransacEllipse(Ellipse& result);

private: // helper methods

/**
Get random items without replacement from a vector. Beware: This changes the order of the items.

@param vec vector to choose random item from.
@param ith choose the ith random item without replacement.
       Ex: For 3 random items without replacement call the function 3 times with ith=1, ith=2 and ith=3.
@return random item of the vector without replacement.
*/
size_t choose_random_from(std::vector<size_t> &vec, int ith)  const {
    int max = static_cast<int>(vec.size())-1;
    int random_pos = Math::random(ith, max);
    std::swap(vec[random_pos], vec[ith-1]);
    return vec[ith-1];
}
};

#endif // RANSACLINEDETECTOR_H


text:
module c3{

    /**
     * 一个二维平面 ,平面具有width,height,zIndex,material
     * @export
     * @class Plane
     * @extends {Display}
     */

    export class Plane extends Display{
        private $material:Material

        public get material():Material{
            return this.$material
        }
        public set material(material:Material){
            if(this.$material){
                this.$material._removeTarget(this)
            }
            this.$material = material
            material._addTarget(this)
            material.render(this)
        }

        constructor(width:number,height:number,zIndex:number = 0){
            super()
            this.size(width,height,zIndex)
            this.className = 'c3-plane'
            this.update()
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Actors.CSharp;
using Akka.Actor;

namespace BattleShipConsole
{
    public class ConsoleReaderActor : BattleShipActor
    {
        private readonly HashSet<IActorRef> _subscribers = new HashSet<IActorRef>();
        private readonly object _read = new object();

        public ConsoleReaderActor()
        {
            Receive<IActorRef>(writer =>
            {
                if (!_subscribers.Add(writer))
                {
                    _subscribers.Remove(writer);
                }
            });

            Receive<string>(message =>
            {
                foreach (var actorRef in _subscribers)
                {
                    actorRef.Tell(message);
                }
                Self.Tell(_read);
            });

            ReceiveAny(message =>
            {
                var self = Self;
                Task.Run(() => Console.ReadLine())
                    .ContinueWith(task =>
                    {
                        if (task.IsFaulted || task.IsCanceled)
                        {
                            return string.Empty;
                        }
                        return task.Result;
                    }, TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.ExecuteSynchronously)
                    .PipeTo(self, self);
            });
        }

        protected override void PreStart()
        {
            Self.Tell(_read);
            base.PreStart();
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Alectoria ambigua Motyka

### Remarks
null


text:
use crate::{
    error::{
        ErrorInfo, ParseError,
        ParseResult::{self, *},
        ResultExt, StreamError, Token, Tracked,
    },
    parser::{
        combinator::{
            and_then, flat_map, map, map_input, spanned, AndThen, Either, FlatMap, Map, MapInput,
            Spanned,
        },
        error::{expected, message, silent, Expected, Message, Silent},
        repeat::Iter,
        sequence::{then, then_partial, then_ref, Then, ThenPartial, ThenRef},
    },
    stream::{Stream, StreamErrorFor, StreamOnce},
    ErrorOffset,
};

use self::{
    choice::{or, Or},
    sequence::{skip, with, Skip, With},
};

#[cfg(feature = "alloc")]
use alloc::boxed::Box;

/// Internal API. May break without a semver bump
#[macro_export]
#[doc(hidden)]
macro_rules! parse_mode {
    ($input_type: ty) => {
        #[inline]
        fn parse_partial(
            &mut self,
            input: &mut $input_type,
            state: &mut Self::PartialState,
        ) -> $crate::error::ParseResult<Self::Output, <$input_type as $crate::StreamOnce>::Error> {
            self.parse_mode($crate::parser::PartialMode::default(), input, state)
        }

        #[inline]
        fn parse_first(
            &mut self,
            input: &mut $input_type,
            state: &mut Self::PartialState,
        ) -> $crate::error::ParseResult<Self::Output, <$input_type as $crate::StreamOnce>::Error> {
            self.parse_mode($crate::parser::FirstMode, input, state)
        }
    };
}

pub mod byte;
pub mod char;
pub mod choice;
pub mod combinator;
pub mod error;
pub mod function;
pub mod range;
#[cfg(feature = "regex")]
#[cfg_attr(docsrs, doc(cfg(feature = "regex")))]
pub mod regex;
pub mod repeat;
pub mod sequence;
pub mod token;

/// By implementing the `Parser` trait a type says that it can be used to parse an input stream
/// into the type `Output`.
///
/// All methods have a default implementation but there needs to be at least an implementation of
/// [`parse_stream`], [`parse_stream`], or [`parse_lazy`]. If the last is implemented, an
/// implementation of [`add_error`] may also be required. See the documentation for
/// [`parse_lazy`] for details.
///
/// [`parse_stream`]: trait.Parser.html#method.parse_stream
/// [`parse_stream`]: trait.Parser.html#method.parse_stream
/// [`parse_lazy`]: trait.Parser.html#method.parse_lazy
/// [`add_error`]: trait.Parser.html#method.add_error
pub trait Parser<Input: Stream> {
    /// The type which is returned if the parser is successful.
    type Output;

    /// Determines the state necessary to resume parsing after more input is supplied.
    ///
    /// If partial parsing is not supported this can be set to `()`.
    type PartialState: Default;

    /// Entry point of the parser. Takes some input and tries to parse it.
    ///
    /// Returns the parsed result and the remaining input if the parser succeeds, or a
    /// error otherwise.
    ///
    /// This is the most straightforward entry point to a parser. Since it does not decorate the
    /// input in any way you may find the error messages a hard to read. If that is the case you
    /// may want to try wrapping your input with an [`easy::Stream`] or call [`easy_parse`]
    /// instead.
    ///
    /// [`easy::Stream`]: super::easy::Stream
    /// [`easy_parse`]: super::parser::EasyParser::easy_parse
    fn parse(
        &mut self,
        mut input: Input,
    ) -> Result<(Self::Output, Input), <Input as StreamOnce>::Error> {
        match self.parse_stream(&mut input).into() {
            Ok((v, _)) => Ok((v, input)),
            Err(error) => Err(error.into_inner().error),
        }
    }

    /// Entry point of the parser when using partial parsing.
    /// Takes some input and tries to parse it.
    ///
    /// Returns the parsed result and the remaining input if the parser succeeds, or a
    /// error otherwise.
    fn parse_with_state(
        &mut self,
        input: &mut Input,
        state: &mut Self::PartialState,
    ) -> Result<Self::Output, <Input as StreamOnce>::Error> {
        match self.parse_stream_partial(input, state).into() {
            Ok((v, _)) => Ok(v),
            Err(error) => Err(error.into_inner().error),
        }
    }

    /// Parses using the stream `input` by calling [`Stream::uncons`] one or more times.
    ///
    /// Semantically equivalent to [`parse_stream`], except this method returns a flattened result
    /// type, combining `Result` and [`Commit`] into a single [`ParseResult`].
    ///
    /// [`Stream::uncons`]: super::stream::StreamOnce::uncons
    /// [`parse_stream`]: Parser::parse_stream
    /// [`Commit`]: super::error::Commit
    /// [`ParseResult`]: super::error::ParseResult
    #[inline]
    fn parse_stream(
        &mut self,
        input: &mut Input,
    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error> {
        let before = input.checkpoint();
        let mut state = Default::default();
        let mut result = self.parse_first(input, &mut state);
        if let ParseResult::PeekErr(ref mut error) = result {
            ctry!(input.reset(before.clone()).committed());
            if let Ok(t) = input.uncons() {
                ctry!(input.reset(before).committed());
                error.error.add_unexpected(Token(t));
            } else {
                error.error.add(StreamErrorFor::<Input>::end_of_input());
            }
            self.add_error(error);
        }
        result
    }

    /// Parses using the stream `input` by calling [`Stream::uncons`] one or more times.
    ///
    /// Specialized version of [`parse_stream`] which permits error value creation to be
    /// skipped in the common case.
    ///
    /// When this parser returns `PeekErr`, this method is allowed to return an empty
    /// [`Error`]. The error value that would have been returned can instead be obtained by
    /// calling [`add_error`]. This allows a parent parser such as `choice` to skip the creation of
    /// an unnecessary error value, if an alternative parser succeeds.
    ///
    /// Parsers should seek to implement this function instead of the above two if errors can be
    /// encountered before consuming input. The default implementation always returns all errors,
    /// with [`add_error`] being a no-op.
    ///
    /// [`Stream::uncons`]: super::stream::StreamOnce::uncons
    /// [`parse_stream`]: Parser::parse_stream
    /// [`Error`]: super::stream::StreamOnce::Error
    /// [`add_error`]: trait.Parser.html#method.add_error
    #[inline]
    fn parse_lazy(
        &mut self,
        input: &mut Input,
    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error> {
        if input.is_partial() {
            // If a partial parser were called from a non-partial parser (as it is here) we must
            // reset the input to before the partial parser were called on errors that committed
            // data as that parser's partial state was just temporary and it will not be able to
            // resume itself
            let before = input.checkpoint();
            let result = self.parse_first(input, &mut Default::default());
            if let CommitErr(_) = result {
                ctry!(input.reset(before).committed());
            }
            result
        } else {
            self.parse_first(input, &mut Default::default())
        }
    }

    /// Adds the first error that would normally be returned by this parser if it failed with an
    /// `PeekErr` result.
    ///
    /// See [`parse_lazy`] for details.
    ///
    /// [`parse_lazy`]: trait.Parser.html#method.parse_lazy
    fn add_error(&mut self, _error: &mut Tracked<<Input as StreamOnce>::Error>) {}

    /// Like `parse_stream` but supports partial parsing.
    #[inline]
    fn parse_stream_partial(
        &mut self,
        input: &mut Input,
        state: &mut Self::PartialState,
    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error> {
        let before = input.checkpoint();
        let mut result = self.parse_partial(input, state);
        if let ParseResult::PeekErr(ref mut error) = result {
            ctry!(input.reset(before.clone()).committed());
            if let Ok(t) = input.uncons() {
                ctry!(input.reset(before).committed());
                error.error.add_unexpected(Token(t));
            } else {
                error.error.add(StreamErrorFor::<Input>::end_of_input());
            }
            self.add_error(error);
        }
        result
    }

    /// Parses using the stream `input` and allows itself to be resumed at a later point using
    /// `parse_partial` by storing the necessary intermediate state in `state`.
    ///
    /// Unlike `parse_partial` function this is allowed to assume that there is no partial state to
    /// resume.
    ///
    /// Internal API. May break without a semver bump
    /// Always overridden by the `parse_mode!` macro
    #[inline]
    #[doc(hidden)]
    fn parse_first(
        &mut self,
        input: &mut Input,
        state: &mut Self::PartialState,
    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error> {
        self.parse_partial(input, state)
    }

    /// Parses using the stream `input` and allows itself to be resumed at a later point using
    /// `parse_partial` by storing the necessary intermediate state in `state`
    ///
    /// Internal API. May break without a semver bump
    /// Always overridden by the `parse_mode!` macro
    #[inline]
    #[doc(hidden)]
    fn parse_partial(
        &mut self,
        input: &mut Input,
        state: &mut Self::PartialState,
    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error> {
        let _ = state;
        self.parse_lazy(input)
    }

    /// Internal API. May break without a semver bump
    #[doc(hidden)]
    #[inline]
    fn parse_mode<M>(
        &mut self,
        mode: M,
        input: &mut Input,
        state: &mut Self::PartialState,
    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
    where
        M: ParseMode,
        Self: Sized,
    {
        mode.parse(self, input, state)
    }

    /// Internal API. May break without a semver bump
    #[doc(hidden)]
    #[inline]
    fn parse_mode_impl<M>(
        &mut self,
        mode: M,
        input: &mut Input,
        state: &mut Self::PartialState,
    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
    where
        M: ParseMode,
        Self: Sized,
    {
        if mode.is_first() {
            self.parse_first(input, state)
        } else {
            self.parse_partial(input, state)
        }
    }

    /// Internal API. May break without a semver bump
    #[doc(hidden)]
    #[inline]
    fn parse_committed_mode<M>(
        &mut self,
        mode: M,
        input: &mut Input,
        state: &mut Self::PartialState,
    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
    where
        M: ParseMode,
        Self: Sized,
    {
        if mode.is_first() {
            FirstMode.parse_committed(self, input, state)
        } else {
            PartialMode::default().parse_committed(self, input, state)
        }
    }

    /// Returns how many parsers this parser contains
    ///
    /// Internal API: This should not be implemented explicitly outside of combine.
    #[doc(hidden)]
    fn parser_count(&self) -> ErrorOffset {
        ErrorOffset(1)
    }

    /// Internal API: This should not be implemented explicitly outside of combine.
    #[doc(hidden)]
    fn add_committed_expected_error(&mut self, _error: &mut Tracked<<Input as StreamOnce>::Error>) {
    }

    /// Borrows a parser instead of consuming it.
    ///
    /// Used to apply parser combinators on `self` without losing ownership.
    ///
    /// ```
    /// # extern crate combine;
    /// # use combine::*;
    /// # use combine::error::Commit;
    /// # use combine::parser::char::{digit, letter};
    /// fn test(input: &mut &'static str) -> StdParseResult<(char, char), &'static str> {
    ///     let mut p = digit();
    ///     let ((d, _), committed) = (p.by_ref(), letter()).parse_stream(input).into_result()?;
    ///     let (d2, committed) = committed.combine(|_| p.parse_stream(input).into_result())?;
    ///     Ok(((d, d2), committed))
    /// }
    ///
    /// fn main() {
    ///     let mut input = "1a23";
    ///     assert_eq!(
    ///         test(&mut input).map(|(t, c)| (t, c.map(|_| input))),
    ///         Ok((('1', '2'), Commit::Commit("3")))
    ///     );
    /// }
    /// ```
    fn by_ref(&mut self) -> &mut Self
    where
        Self: Sized,
    {
        self
    }

    /// Discards the value of the `self` parser and returns the value of `p`.
    /// Fails if any of the parsers fails.
    ///
    /// ```
    /// # extern crate combine;
    /// # use combine::*;
    /// # use combine::parser::char::digit;
    /// # fn main() {
    /// let result = digit()
    ///     .with(token('i'))
    ///     .parse("9i")
    ///     .map(|x| x.0);
    /// assert_eq!(result, Ok('i'));
    /// # }
    /// ```
    fn with<P2>(self, p: P2) -> With<Self, P2>
    where
        Self: Sized,
        P2: Parser<Input>,
    {
        with(self, p)
    }

    /// Discards the value of the `p` parser and returns the value of `self`.
    /// Fails if any of the parsers fails.
    ///
    /// ```
    /// # extern crate combine;
    /// # use combine::*;
    /// # use combine::parser::char::digit;
    /// # fn main() {
    /// let result = digit()
    ///     .skip(token('i'))
    ///     .parse("9i")
    ///     .map(|x| x.0);
    /// assert_eq!(result, Ok('9'));
    /// # }
    /// ```
    fn skip<P2>(self, p: P2) -> Skip<Self, P2>
    where
        Self: Sized,
        P2: Parser<Input>,
    {
        skip(self, p)
    }

    /// Parses with `self` followed by `p`.
    /// Succeeds if both parsers succeed, otherwise fails.
    /// Returns a tuple with both values on success.
    ///
    /// ```
    /// # extern crate combine;
    /// # use combine::*;
    /// # use combine::parser::char::digit;
    /// # fn main() {
    /// let result = digit()
    ///     .and(token('i'))
    ///     .parse("9i")
    ///     .map(|x| x.0);
    /// assert_eq!(result, Ok(('9', 'i')));
    /// # }
    /// ```
    fn and<P2>(self, p: P2) -> (Self, P2)
    where
        Self: Sized,
        P2: Parser<Input>,
    {
        (self, p)
    }

    /// Returns a parser which attempts to parse using `self`. If `self` fails without committing
    /// it tries to consume the same input using `p`.
    ///
    /// If you are looking to chain 3 or more parsers using `or` you may consider using the
    /// [`choice!`] macro instead, which can be clearer and may result in a faster parser.
    ///
    /// ```
    /// # extern crate combine;
    /// # use combine::*;
    /// # use combine::parser::char::{digit, string};
    /// # fn main() {
    /// let mut parser = string("let")
    ///     .or(digit().map(|_| "digit"))
    ///     .or(string("led"));
    /// assert_eq!(parser.parse("let"), Ok(("let", "")));
    /// assert_eq!(parser.parse("1"), Ok(("digit", "")));
    /// assert!(parser.parse("led").is_err());
    ///
    /// let mut parser2 = string("two").or(string("three"));
    /// // Fails as the parser for "two" consumes the first 't' before failing
    /// assert!(parser2.parse("three").is_err());
    ///
    /// // Use 'attempt' to make failing parsers always act as if they have not committed any input
    /// let mut parser3 = attempt(string("two")).or(attempt(string("three")));
    /// assert_eq!(parser3.parse("three"), Ok(("three", "")));
    /// # }
    /// ```
    ///
    /// [`choice!`]: super::choice!
    fn or<P2>(self, p: P2) -> Or<Self, P2>
    where
        Self: Sized,
        P2: Parser<Input, Output = Self::Output>,
    {
        or(self, p)
    }

    /// Parses using `self` and then passes the value to `f` which returns a parser used to parse
    /// the rest of the input.
    ///
    /// Since the parser returned from `f` must have a single type it can be useful to use the
    /// [`left`](Parser::left) and [`right`](Parser::right) methods to merge parsers of differing types into one.
    ///
    /// If you are using partial parsing you may want to use [`then_partial`](Parser::then_partial) instead.
    ///
    /// ```
    /// # #![cfg(feature = "std")]
    /// # extern crate combine;
    /// # use combine::*;
    /// # use combine::parser::char::digit;
    /// # use combine::error::Commit;
    /// # use combine::stream::easy;
    /// # fn main() {
    /// let result = digit()
    ///     .then(|d| {
    ///         if d == '9' {
    ///             value(9).left()
    ///         }
    ///         else {
    ///             unexpected_any(d).message("Not a nine").right()
    ///         }
    ///     })
    ///     .easy_parse("9");
    /// assert_eq!(result, Ok((9, "")));
    /// # }
    /// ```
    fn then<N, F>(self, f: F) -> Then<Self, F>
    where
        Self: Sized,
        F: FnMut(Self::Output) -> N,
        N: Parser<Input>,
    {
        then(self, f)
    }

    /// Variant of [`then`](Parser::then) which parses using `self` and then passes the value to `f` as a `&mut` reference.
    ///
    /// Useful when doing partial parsing since it does not need to store the parser returned by
    /// `f` in the partial state. Instead it will call `f` each to request a new parser each time
    /// parsing resumes and that parser is needed.
    ///
    /// Since the parser returned from `f` must have a single type it can be useful to use the
    /// [`left`](Parser::left) and [`right`](Parser::right) methods to merge parsers of differing types into one.
    ///
    /// ```
    /// # #![cfg(feature = "std")]
    /// # extern crate combine;
    /// # use combine::*;
    /// # use combine::parser::char::digit;
    /// # use combine::error::Commit;
    /// # use combine::stream::easy;
    /// # fn main() {
    /// let result = digit()
    ///     .then_partial(|d| {
    ///         if *d == '9' {
    ///             value(9).left()
    ///         }
    ///         else {
    ///             unexpected_any(*d).message("Not a nine").right()
    ///         }
    ///     })
    ///     .easy_parse("9");
    /// assert_eq!(result, Ok((9, "")));
    /// # }
    /// ```
    fn then_partial<N, F>(self, f: F) -> ThenPartial<Self, F>
    where
        Self: Sized,
        F: FnMut(&mut Self::Output) -> N,
        N: Parser<Input>,
    {
        then_partial(self, f)
    }

    /// Parses using `self` and then passes a reference to the value to `f` which returns a parser
    /// used to parse the rest of the input. The value is then combined with the output of `f`.
    ///
    /// Since the parser returned from `f` must have a single type it can be useful to use the
    /// `left` and `right` methods to merge parsers of differing types into one.
    ///
    /// ```
    /// # #![cfg(feature = "std")]
    /// # extern crate combine;
    /// # use combine::*;
    /// # use combine::parser::char::digit;
    /// # use combine::error::Commit;
    /// # use combine::stream::easy;
    /// # fn main() {
    /// let result = digit()
    ///     .then_ref(|d| {
    ///         if *d == '9' {
    ///             digit().left()
    ///         }
    ///         else {
    ///             unexpected_any(*d).message("Not a nine").right()
    ///         }
    ///     })
    ///     .easy_parse("98");
    /// assert_eq!(result, Ok((('9', '8'), "")));
    /// # }
    /// ```
    fn then_ref<N, F>(self, f: F) -> ThenRef<Self, F>
    where
        Self: Sized,
        F: FnMut(&Self::Output) -> N,
        N: Parser<Input>,
    {
        then_ref(self, f)
    }

    /// Uses `f` to map over the parsed value.
    ///
    /// ```
    /// # extern crate combine;
    /// # use combine::*;
    /// # use combine::parser::char::digit;
    /// # fn main() {
    /// let result = digit()
    ///     .map(|c| c == '9')
    ///     .parse("9")
    ///     .map(|x| x.0);
    /// assert_eq!(result, Ok(true));
    /// # }
    /// ```
    fn map<F, B>(self, f: F) -> Map<Self, F>
    where
        Self: Sized,
        F: FnMut(Self::Output) -> B,
    {
        map(self, f)
    }

    fn map_input<F, B>(self, f: F) -> MapInput<Self, F>
    where
        Self: Sized,
        F: FnMut(Self::Output, &mut Input) -> B,
    {
        map_input(self, f)
    }

    /// Uses `f` to map over the output of `self`. If `f` returns an error the parser fails.
    ///
    /// ```
    /// # extern crate combine;
    /// # use combine::*;
    /// # use combine::parser::char::digit;
    /// # use combine::parser::range::take;
    /// # fn main() {
    /// let result = take(4)
    ///     .flat_map(|bs| many(digit()).parse(bs).map(|t| t.0))
    ///     .parse("12abcd");
    /// assert_eq!(result, Ok((String::from("12"), "cd")));
    /// # }
    /// ```
    fn flat_map<F, B>(self, f: F) -> FlatMap<Self, F>
    where
        Self: Sized,
        F: FnMut(Self::Output) -> Result<B, <Input as StreamOnce>::Error>,
    {
        flat_map(self, f)
    }

    /// Parses with `self` and if it fails, adds the message `msg` to the error.
    ///
    /// ```
    /// # #![cfg(feature = "std")]
    /// # extern crate combine;
    /// # use combine::*;
    /// # use combine::stream::easy;
    /// # use combine::stream::position::{self, SourcePosition};
    /// # fn main() {
    /// let result = token('9')
    ///     .message("Not a nine")
    ///     .easy_parse(position::Stream::new("8"));
    /// assert_eq!(result, Err(easy::Errors {
    ///     position: SourcePosition::default(),
    ///     errors: vec![
    ///         easy::Error::Unexpected('8'.into()),
    ///         easy::Error::Expected('9'.into()),
    ///         easy::Error::Message("Not a nine".into())
    ///     ]
    /// }));
    /// # }
    /// ```
    fn message<S>(self, msg: S) -> Message<Self, S>
    where
        Self: Sized,
        S: for<'s> ErrorInfo<'s, Input::Token, Input::Range>,
    {
        message(self, msg)
    }

    /// Parses with `self` and if it fails without consuming any input any expected errors are
    /// replaced by `msg`. `msg` is then used in error messages as "Expected `msg`".
    ///
    /// ```
    /// # #![cfg(feature = "std")]
    /// # extern crate combine;
    /// # use combine::*;
    /// # use combine::error;
    /// # use combine::stream::easy;
    /// # use combine::stream::position::{self, SourcePosition};
    /// # fn main() {
    /// let result = token('9')
    ///     .expected("nine")
    ///     .easy_parse(position::Stream::new("8"));
    /// assert_eq!(result, Err(easy::Errors {
    ///     position: SourcePosition::default(),
    ///     errors: vec![
    ///         easy::Error::Unexpected('8'.into()),
    ///         easy::Error::Expected("nine".into())
    ///     ]
    /// }));
    ///
    /// let result = token('9')
    ///     .expected(error::Format(format_args!("That is not a nine!")))
    ///     .easy_parse(position::Stream::new("8"));
    /// assert_eq!(result, Err(easy::Errors {
    ///     position: SourcePosition::default(),
    ///     errors: vec![
    ///         easy::Error::Unexpected('8'.into()),
    ///         easy::Error::Expected("That is not a nine!".to_string().into())
    ///     ]
    /// }));
    /// # }
    /// ```
    fn expected<S>(self, msg: S) -> Expected<Self, S>
    where
        Self: Sized,
        S: for<'s> ErrorInfo<'s, Input::Token, Input::Range>,
    {
        expected(self, msg)
    }

    /// Parses with `self`, if it fails without consuming any input any expected errors that would
    /// otherwise be emitted by `self` are suppressed.
    ///
    /// ```
    /// # #![cfg(feature = "std")]
    /// # extern crate combine;
    /// # use combine::*;
    /// # use combine::stream::easy;
    /// # use combine::stream::position::{self, SourcePosition};
    /// # fn main() {
    /// let result = token('9')
    ///     .expected("nine")
    ///     .silent()
    ///     .easy_parse(position::Stream::new("8"));
    /// assert_eq!(result, Err(easy::Errors {
    ///     position: SourcePosition::default(),
    ///     errors: vec![
    ///         easy::Error::Unexpected('8'.into()),
    ///     ]
    /// }));
    /// # }
    /// ```
    fn silent(self) -> Silent<Self>
    where
        Self: Sized,
    {
        silent(self)
    }

    /// Parses with `self` and applies `f` on the result if `self` parses successfully.
    /// `f` may optionally fail with an error which is automatically converted to a `ParseError`.
    ///
    /// ```
    /// # extern crate combine;
    /// # use combine::*;
    /// # use combine::stream::position::{self, SourcePosition};
    /// # use combine::parser::char::digit;
    /// # fn main() {
    /// let mut parser = many1(digit())
    ///     .and_then(|s: String| s.parse::<i32>());
    /// let result = parser.easy_parse(position::Stream::new("1234")).map(|(x, state)| (x, state.input));
    /// assert_eq!(result, Ok((1234, "")));
    /// let result = parser.easy_parse(position::Stream::new("999999999999999999999999"));
    /// assert!(result.is_err());
    /// // Errors are report as if they occurred at the start of the parse
    /// assert_eq!(result.unwrap_err().position, SourcePosition { line: 1, column: 1 });
    /// # }
    /// ```
    fn and_then<F, O, E>(self, f: F) -> AndThen<Self, F>
    where
        Self: Parser<Input> + Sized,
        F: FnMut(Self::Output) -> Result<O, E>,
        E: Into<
            <Input::Error as ParseError<Input::Token, Input::Range, Input::Position>>::StreamError,
        >,
    {
        and_then(self, f)
    }

    /// Creates an iterator from a parser and a state. Can be used as an alternative to [`many`]
    /// when collecting directly into a `Extend` type is not desirable.
    ///
    /// ```
    /// # extern crate combine;
    /// # use combine::*;
    /// # use combine::parser::char::{char, digit};
    /// # fn main() {
    /// let mut buffer = String::new();
    /// let number = parser(|input| {
    ///     buffer.clear();
    ///     let mut iter = digit().iter(input);
    ///     buffer.extend(&mut iter);
    ///     let i = buffer.parse::<i32>().unwrap();
    ///     iter.into_result(i)
    /// });
    /// let result = sep_by(number, char(','))
    ///     .parse("123,45,6");
    /// assert_eq!(result, Ok((vec![123, 45, 6], "")));
    /// # }
    /// ```
    ///
    /// [`many`]: repeat::many
    fn iter(self, input: &mut Input) -> Iter<'_, Input, Self, Self::PartialState, FirstMode>
    where
        Self: Parser<Input> + Sized,
    {
        Iter::new(self, FirstMode, input, Default::default())
    }

    /// Creates an iterator from a parser and a state. Can be used as an alternative to [`many`]
    /// when collecting directly into a `Extend` type is not desirable.
    ///
    /// ```
    /// # extern crate combine;
    /// # use combine::*;
    /// # use combine::parser::char::{char, digit};
    /// # fn main() {
    /// let mut buffer = String::new();
    /// let number = parser(|input| {
    ///     buffer.clear();
    ///     let mut iter = digit().iter(input);
    ///     buffer.extend(&mut iter);
    ///     let i = buffer.parse::<i32>().unwrap();
    ///     iter.into_result(i)
    /// });
    /// let result = sep_by(number, char(','))
    ///     .parse("123,45,6");
    /// assert_eq!(result, Ok((vec![123, 45, 6], "")));
    /// # }
    /// ```
    ///
    /// [`many`]: repeat::many
    fn partial_iter<'a, 's, M>(
        self,
        mode: M,
        input: &'a mut Input,
        partial_state: &'s mut Self::PartialState,
    ) -> Iter<'a, Input, Self, &'s mut Self::PartialState, M>
    where
        Self: Parser<Input> + Sized,
        M: ParseMode,
    {
        Iter::new(self, mode, input, partial_state)
    }

    /// Turns the parser into a trait object by putting it in a `Box`. Can be used to easily
    /// return parsers from functions without naming the type.
    ///
    /// ```
    /// # use combine::*;
    /// # fn main() {
    /// fn test<'input, F>(
    ///     c: char,
    ///     f: F)
    ///     -> Box<dyn Parser<&'input str, Output = (char, char), PartialState = ()> + 'input>
    ///     where F: FnMut(char) -> bool + 'static
    /// {
    ///     combine::parser::combinator::no_partial((token(c), satisfy(f))).boxed()
    /// }
    /// let result = test('a', |c| c >= 'a' && c <= 'f')
    ///     .parse("ac");
    /// assert_eq!(result, Ok((('a', 'c'), "")));
    /// # }
    /// ```
    #[cfg(feature = "alloc")]
    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
    fn boxed<'a>(
        self,
    ) -> Box<dyn Parser<Input, Output = Self::Output, PartialState = Self::PartialState> + 'a>
    where
        Self: Sized + 'a,
    {
        Box::new(self)
    }

    /// Wraps the parser into the [`Either`](combinator::Either) enum which allows combinators such as [`then`](Parser::then) to return
    /// multiple different parser types (merging them to one)
    ///
    /// ```
    /// # extern crate combine;
    /// # use combine::*;
    /// # use combine::parser::char::{digit, letter};
    /// # fn main() {
    /// let mut parser = any().then(|c|
    ///     if c == '#' {
    ///         skip_many(satisfy(|c| c != '\n'))
    ///             .with(value("".to_string()))
    ///             .left()
    ///     } else {
    ///         many1(letter())
    ///             .map(move |mut s: String| { s.insert(0, c); s })
    ///             .right()
    ///     });
    ///
    /// let result = parser.parse("ac2");
    /// assert_eq!(result, Ok(("ac".to_string(), "2")));
    ///
    /// let result = parser.parse("# ac2");
    /// assert_eq!(result, Ok(("".to_string(), "")));
    /// # }
    /// ```
    fn left<R>(self) -> Either<Self, R>
    where
        Self: Sized,
        R: Parser<Input, Output = Self::Output>,
    {
        Either::Left(self)
    }

    /// Wraps the parser into the [`Either`](combinator::Either) enum which allows combinators such as [`then`](Parser::then) to return
    /// multiple different parser types (merging them to one)
    ///
    /// ```
    /// # extern crate combine;
    /// # use combine::*;
    /// # use combine::parser::char::{digit, letter};
    /// # fn main() {
    /// let mut parser = any().then(|c|
    ///     if c == '#' {
    ///         skip_many(satisfy(|c| c != '\n'))
    ///             .with(value("".to_string()))
    ///             .left()
    ///     } else {
    ///         many1(letter())
    ///             .map(move |mut s: String| { s.insert(0, c); s })
    ///             .right()
    ///     });
    ///
    /// let result = parser.parse("ac2");
    /// assert_eq!(result, Ok(("ac".to_string(), "2")));
    ///
    /// let result = parser.parse("# ac2");
    /// assert_eq!(result, Ok(("".to_string(), "")));
    /// # }
    /// ```
    fn right<L>(self) -> Either<L, Self>
    where
        Self: Sized,
        L: Parser<Input, Output = Self::Output>,
    {
        Either::Right(self)
    }

    /// Marks errors produced inside the `self` parser with the span from the start of the parse to
    /// the end of it.
    ///
    /// [`p.spanned()`]: ../trait.Parser.html#method.spanned
    ///
    /// ```
    /// use combine::{*, parser::{char::string, combinator::spanned}};
    /// use combine::stream::{easy, span};
    ///
    /// let input = "hel";
    /// let result = spanned(string("hello")).parse(
    ///     span::Stream::<_, easy::Errors<_, _, span::Span<_>>>::from(easy::Stream::from(input)),
    /// );
    /// assert!(result.is_err());
    /// assert_eq!(
    ///     result.unwrap_err().position.map(|p| p.translate_position(input)),
    ///     span::Span { start: 0, end: 3 },
    /// );
    /// ```
    fn spanned(self) -> Spanned<Self>
    where
        Self: Sized,
    {
        spanned(self)
    }
}

/// Provides the `easy_parse` method which provides good error messages by default
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub trait EasyParser<Input: Stream>: Parser<crate::easy::Stream<Input>>
where
    Input::Token: PartialEq,
    Input::Range: PartialEq,
{
    /// Entry point of the parser. Takes some input and tries to parse it, returning an easy to use
    /// and format error if parsing did not succeed.
    ///
    /// Returns the parsed result and the remaining input if the parser succeeds, or a
    /// This function wraps requires `Input == easy::Stream<Input>` which makes it return
    /// return `easy::Errors` if an error occurs. Due to this wrapping it is recommended that the
    /// parser `Self` is written with a generic input type.
    ///
    /// ```
    /// # #[macro_use]
    /// # extern crate combine;
    ///
    /// use combine::*;
    /// use combine::parser::repeat::many1;
    /// use combine::parser::char::letter;
    ///
    /// // Good!
    /// parser!{
    /// fn my_parser[Input]()(Input) -> String
    ///     where [Input: Stream<Token = char>]
    /// {
    ///     many1::<String, _, _>(letter())
    /// }
    /// }
    ///
    /// // Won't compile with `easy_parse` since it is specialized on `&str`
    /// parser!{
    /// fn my_parser2['a]()(&'a str) -> String
    ///     where [&'a str: Stream<Token = char, Range = &'a str>]
    /// {
    ///     many1(letter())
    /// }
    /// }
    ///
    /// fn main() {
    ///     assert_eq!(my_parser().parse("abc"), Ok(("abc".to_string(), "")));
    ///     // Would fail to compile if uncommented
    ///     // my_parser2().parse("abc")
    /// }
    /// ```
    ///
    /// [`ParseError`]: struct.ParseError.html
    fn easy_parse(
        &mut self,
        input: Input,
    ) -> Result<
        (<Self as Parser<crate::easy::Stream<Input>>>::Output, Input),
        crate::easy::ParseError<Input>,
    >
    where
        Input: Stream,
        crate::easy::Stream<Input>: StreamOnce<
            Token = Input::Token,
            Range = Input::Range,
            Error = crate::easy::ParseError<crate::easy::Stream<Input>>,
            Position = Input::Position,
        >,
        Input::Position: Default,
        Self: Sized + Parser<crate::easy::Stream<Input>>,
    {
        let input = crate::easy::Stream(input);
        self.parse(input).map(|(v, input)| (v, input.0))
    }
}

#[cfg(feature = "std")]
impl<Input, P> EasyParser<Input> for P
where
    P: ?Sized + Parser<crate::easy::Stream<Input>>,
    Input: Stream,
    Input::Token: PartialEq,
    Input::Range: PartialEq,
{
}

macro_rules! forward_deref {
    (Input) => {
        type Output = P::Output;
        type PartialState = P::PartialState;

        #[inline]
        fn parse_first(
            &mut self,
            input: &mut Input,
            state: &mut Self::PartialState,
        ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error> {
            (**self).parse_first(input, state)
        }

        #[inline]
        fn parse_partial(
            &mut self,
            input: &mut Input,
            state: &mut Self::PartialState,
        ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error> {
            (**self).parse_partial(input, state)
        }

        #[inline]
        fn add_error(&mut self, error: &mut Tracked<<Input as StreamOnce>::Error>) {
            (**self).add_error(error)
        }

        #[inline]
        fn add_committed_expected_error(
            &mut self,
            error: &mut Tracked<<Input as StreamOnce>::Error>,
        ) {
            (**self).add_committed_expected_error(error)
        }

        #[inline]
        fn parser_count(&self) -> ErrorOffset {
            (**self).parser_count()
        }
    };
}

impl<'a, P, Input> Parser<Input> for &'a mut P
where
    P: ?Sized + Parser<Input>,
    Input: Stream,
{
    forward_deref!(Input);
}

#[cfg(feature = "alloc")]
impl<P, Input> Parser<Input> for Box<P>
where
    P: ?Sized + Parser<Input>,
    Input: Stream,
{
    forward_deref!(Input);
}

/// Internal API. May break without a semver bump
#[doc(hidden)]
/// Specifies whether the parser must check for partial state that must be resumed
pub trait ParseMode: Copy {
    /// If `true` then the parser has no previous state to resume otherwise the parser *might* have
    /// state to resume which it must check.
    fn is_first(self) -> bool;
    /// Puts the mode into `first` parsing.
    fn set_first(&mut self);

    fn parse<P, Input>(
        self,
        parser: &mut P,
        input: &mut Input,
        state: &mut P::PartialState,
    ) -> ParseResult<P::Output, Input::Error>
    where
        P: Parser<Input>,
        Input: Stream;

    #[inline]
    fn parse_committed<P, Input>(
        self,
        parser: &mut P,
        input: &mut Input,
        state: &mut P::PartialState,
    ) -> ParseResult<P::Output, <Input as StreamOnce>::Error>
    where
        P: Parser<Input>,
        Input: Stream,
    {
        let before = input.checkpoint();
        let mut result = parser.parse_mode_impl(self, input, state);
        if let ParseResult::PeekErr(ref mut error) = result {
            ctry!(input.reset(before.clone()).committed());
            if let Ok(t) = input.uncons() {
                ctry!(input.reset(before).committed());
                error.error.add_unexpected(Token(t));
            } else {
                error.error.add(StreamErrorFor::<Input>::end_of_input());
            }
            parser.add_error(error);
        }
        result
    }
}

/// Internal API. May break without a semver bump
#[doc(hidden)]
#[derive(Copy, Clone)]
pub struct FirstMode;
impl ParseMode for FirstMode {
    #[inline]
    fn is_first(self) -> bool {
        true
    }
    #[inline]
    fn set_first(&mut self) {}

    fn parse<P, Input>(
        self,
        parser: &mut P,
        input: &mut Input,
        state: &mut P::PartialState,
    ) -> ParseResult<P::Output, Input::Error>
    where
        P: Parser<Input>,
        Input: Stream,
    {
        parser.parse_mode_impl(FirstMode, input, state)
    }
}

/// Internal API. May break without a semver bump
#[doc(hidden)]
#[derive(Copy, Clone, Default)]
pub struct PartialMode {
    pub first: bool,
}
impl ParseMode for PartialMode {
    #[inline]
    fn is_first(self) -> bool {
        self.first
    }

    #[inline]
    fn set_first(&mut self) {
        self.first = true;
    }

    fn parse<P, Input>(
        self,
        parser: &mut P,
        input: &mut Input,
        state: &mut P::PartialState,
    ) -> ParseResult<P::Output, Input::Error>
    where
        P: Parser<Input>,
        Input: Stream,
    {
        if self.is_first() {
            parser.parse_mode_impl(FirstMode, input, state)
        } else {
            parser.parse_mode_impl(self, input, state)
        }
    }
}


text:
from __future__ import absolute_import
from traits.api import Event, Color, Str, Any, Int
from traitsui.qt4.editor import Editor
# ============= standard library imports ========================
from pyface.qt.QtGui import QTextEdit, QPalette, QTextCursor, QTextTableFormat, QTextFrameFormat, \
    QTextTableCellFormat, QColor, QFont, QPlainTextEdit, QTextCharFormat
from traitsui.basic_editor_factory import BasicEditorFactory

# ============= local library imports  ==========================
class EditBlock:
    def __init__(self, cursor):
        self._cursor = cursor

    def __enter__(self, *args, **kw):
        self._cursor.beginEditBlock()

    def __exit__(self, *args, **kw):
        self._cursor.endEditBlock()

class _TextTableEditor(Editor):
    _pv = None
    _pc = None
    clear = Event
    refresh = Event
    control_klass = QTextEdit

    def init(self, parent):
        """

        """
        if self.control is None:
            self.control = self.control_klass()

            if self.factory.bg_color:
                p = QPalette()
                p.setColor(QPalette.Base, self.factory.bg_color)
                self.control.setPalette(p)
            self.control.setReadOnly(True)

        # self.object.on_trait_change(self._on_clear, self.factory.clear)

        self.sync_value(self.factory.refresh, 'refresh', mode='from')

    def _refresh_fired(self):
        self.update_editor()

    def update_editor(self, *args, **kw):
        """
        """
        self.control.clear()
        adapter = self.factory.adapter
        tables = adapter.make_tables(self.value)
        cursor = QTextCursor(self.control.textCursor())
        n = len(tables)

        for i, ti in enumerate(tables):

            self._add_table(ti, cursor)
            #             timethis(self._add_table, args=(ti, cursor), msg='add_table')
            if i < n - 1:
                self._add_table_hook(cursor)

    def _add_table_hook(self, cursor):
        pass

    def _add_table(self, tab, cursor):

        tab_fmt = QTextTableFormat()
        tab_fmt.setCellSpacing(0)
        tab_fmt.setCellPadding(3)

        border = tab.border
        if border:
            tab_fmt.setBorderStyle(QTextFrameFormat.BorderStyle_Solid)
        else:
            tab_fmt.setBorderStyle(QTextFrameFormat.BorderStyle_None)

        cursor.insertTable(tab.rows(), tab.cols(), tab_fmt)
        table = cursor.currentTable()

        with EditBlock(cursor):
            bc = QColor(self.factory.bg_color) if self.factory.bg_color else None
            ec, oc, hc = bc, bc, bc
            if self.factory.even_color:
                ec = QColor(self.factory.even_color)
            if self.factory.odd_color:
                oc = QColor(self.factory.odd_color)
            if self.factory.header_color:
                hc = QColor(self.factory.header_color)

            cell_fmt = QTextTableCellFormat()
            cell_fmt.setFontPointSize(10)
            css = '''font-size:{}px;'''.format(10)
            self.control.setStyleSheet(css)
            max_cols = max([len(row.cells) for row in tab.items])

            for ri, row in enumerate(tab.items):
                c = bc
                if row.color:
                    c = QColor(row.color)
                elif ri == 0:
                    c = hc
                else:
                    if (ri - 1) % 2 == 0:
                        c = ec
                    else:
                        c = oc
                if c:
                    cell_fmt.setBackground(c)

                span_offset = 0

                for ci, cell in enumerate(row.cells):
                    if cell.bg_color:
                        cell_fmt.setBackground(QColor(cell.bg_color))
                    if cell.bold:
                        cell_fmt.setFontWeight(QFont.Bold)
                    else:
                        cell_fmt.setFontWeight(QFont.Normal)

                    cs = cell.col_span
                    if cs:
                        if cs == -1:
                            cs = max_cols

                        table.mergeCells(ri, ci, 1, cs)

                    tcell = table.cellAt(ri, ci + span_offset)
                    cur = tcell.firstCursorPosition()
                    if hasattr(cell, 'html'):
                        cur.insertHtml('{}'.format(cell.html))

                    else:
                        tcell.setFormat(cell_fmt)
                        cur.insertText(cell.text)

                    if cs:
                        span_offset = cs

class _FastTextTableEditor(_TextTableEditor):
    """
        Uses a QPlainTextEdit instead of QTextEdit.

        doesn't use QTextTable.
        uses static column widths defined by the adapter
    """

    control_klass = QPlainTextEdit

    def _add_table_hook(self, cursor):
        cursor.insertText('\n')

    def _add_table(self, tab, cursor):
        fmt = QTextCharFormat()
        fmt.setFont(QFont(self.factory.font_name))
        fmt.setFontPointSize(self.factory.font_size)
        bc = QColor(self.factory.bg_color) if self.factory.bg_color else None
        ec, oc, hc = bc, bc, bc
        if self.factory.even_color:
            ec = QColor(self.factory.even_color)
        if self.factory.odd_color:
            oc = QColor(self.factory.odd_color)
        if self.factory.header_color:
            hc = QColor(self.factory.header_color)

        with EditBlock(cursor):
            for i, row in enumerate(tab.items):
                cell = row.cells[0]
                if cell.bold:
                    fmt.setFontWeight(QFont.Bold)
                else:
                    fmt.setFontWeight(QFont.Normal)

                if i == 0 and hc:
                    c = hc
                elif (i - 1) % 2 == 0:
                    c = ec
                else:
                    c = oc

                if c:
                    fmt.setBackground(c)

                txt = ''.join([u'{{:<{}s}}'.format(cell.width).format(cell.text)
                               for cell in row.cells
                               ])
                cursor.insertText(txt + '\n', fmt)

class TextTableEditor(BasicEditorFactory):
    klass = _TextTableEditor
    bg_color = Color
    odd_color = Str
    even_color = Str
    header_color = Str
    clear = Str
    adapter = Any
    refresh = Str
    font_size = Int(12)
    font_name = Str('courier')

class FastTextTableEditor(TextTableEditor):
    '''
    fast text table editor may no longer be necessary
    texttableeditor sped up significantly using beginEditBlock/endEditBlock
    '''
    klass = _FastTextTableEditor  # _TextTableEditor

# ============= EOF =============================================


text:
// Copyright 2005 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package org.ops4j.gaderian.chain;

import java.util.List;

/**
 * Service interface for gaderian.utilitiesChainBuilder, a service which can assemble an
 * implementation based on a command interface, and an ordered list of objects implementing that
 * interface (the "commands"). This is an implementation of the Gang of Four Chain Of Command
 * pattern.
 *

 * For each method in the interface, the chain implementation will call the corresponding method on
 * each command object in turn. If any of the command objects return true, then the chain of command
 * stops and the initial method invocation returns true. Otherwise, the chain of command continues
 * to the next command (and will return false if none of the commands returns true).
 *

 * For methods whose return type is not boolean, the chain stops with the first non-null (for object
 * types), or non-zero (for numeric types). The chain returns the value that was returned by the
 * command. The chain If the method return type is void, all command will be invoked.
 *

 * Method invocations will also be terminated if an exception is thrown.
 *
 * @author Howard M. Lewis Ship
 * @since 1.1
 */
public interface ChainBuilder
{
    /**
     * Builds an implementation.
     *
     * @param commandInterface
     *            the interface the implementation implements.
     * @param commands
     *            a non-null list of command objects implementing the interface.
     * @param toString
     *            The value to be returned from the implementation's toString()
     *            method (unless toString() is expressly part of the service
     *            interface, in which case it is treated as any other method.
     */
    public Object buildImplementation(Class commandInterface, List commands, String toString);
}


text:
html {
    background-color: white;
}

p, li {
    color: #000080;
}

a {
    color: #800080;
}

a:visited {
    color: #ff0000;
}

.right {
    float: right;

}

.left { float: left; }

section {
    clear: both;
    text-align: center;
    font-size: 0.8em;
    border-top: 1px solid black;
    border-bottom: 1px solid black;
}

header {
    font-weight: bold;
    font-size: 1.2em;
    text-align: center;
    border-bottom: 1px solid black;
}

span { font-size: 1.8em; }

footer { border-top: 1px solid black; }

/*
What is important to know when linking an external file (like a stylesheet) to an HTML file?

    It's important to understand relative linking. For example "/"" returns you to the root directory and starts there.
    "../" moves one directory back and starts there and so on.

What tricks did you use to help you with positioning? How hard was it to get the site as you wanted it?

    Even with my previous experience CSS can feel like a bit of hacking to get it right. Adding p tags to create a block
    element was how I achieved the seperate lines for the Geico part. Doing that helped solidfy my knowledge of what exactly
    "block" means. Getting the site to how I wanted it wasn't too difficult, but it was tricky when I had to update my HTML to make
    it easier to control with CSS.

What CSS did you use to modify the element style (like size, color, etc.)

    Mainly the "color" property and I used ems for size.

Did you modify the HTML to include classes or ids? If so, which did you chose and why? If you didn't, how would you know which one to add to your HTML?
When you compared your site to the actual code base, which do you think had cleaner code that followed best practices and why?

    I added a class to the bulleted points so I could float one set of 5 to the left and the other set to the right. I went with
    "ul class" and did so because I didn't think any of the new HTML5 tags were semantically appropriate for the task. Our Berkshire
    site definitely has cleaner code. The Berkshire site uses old-school tables to organize content on the site. That's a lot of
    HTML. We can achieve the same effects with much less code. Also it's easy to make our site mobile friendly where as tables are
    not.

*/


text:
'use strict';

module.exports = clickEvent;

function clickEvent(handler, opts) {
    opts = opts || {};

    return function clickHandler(ev) {
        ev.preventDefault();

        if (!opts.ctrl && ev.ctrlKey) {
            return;
        }

        if (!opts.meta && ev.metaKey) {
            return;
        }

        if (!opts.rightClick && ev.which === 2) {
            return;
        }

        handler();
    };
}


text:
var initialized = false;
var data = {
	// if this value is true no actual release will be performed,
	// to enable debug mode execute `grunt release -d=1`
	"debug": false,
	// execute `grunt release --env=production` for actual release
	"env": "development",
	"environments": ["development", "test", "staging", "production"],
	// flag is set to true when we execute release task
	"release": false
};
var child_process = require("child_process");
var _ = require("lodash");

exports.init = function(grunt) {
	"use strict";

	var exports = {};

	exports.config = function(key, value) {
		if (typeof arguments[1] !== "undefined") {
			return grunt.util.namespace.set(data, key, value);
		} else {
			return grunt.util.namespace.get(data, key);
		}
	};

	exports.exec = function(command, callback) {
		grunt.log.subhead(command.yellow);
		child_process.exec(command, function(err, stdout, stderr) {
			if (err) {
				grunt.fail.fatal(err);
			}
			if (stderr) {
				grunt.log.writeln(stderr);
			}
			callback(stdout, stderr);
		});
	};

	grunt.template.addDelimiters("configPlaceholder", "{%", "%}");
	exports.replacePlaceholdersOnCopy = function(text) {
		// return text as is if there are no placeholders
		if (!/{%=/.test(text)) return text;
		// we set the last parameter value to "init" because we want different
		// placeholders not to mix up with default ones ( {%=x%} instead of <%=x%> )
		return grunt.template.process(text, {
			"data": grunt.config("envConfig"),
			"delimiters": "configPlaceholder"
		});
	};

	if (!initialized) {
		initialized = true;
		exports.config("debug", !!grunt.option("debug"));
		var env = grunt.option("env");
		if (!_.contains(exports.config("environments"), env)) {
			env = "development";
		}
		exports.config("env", env);
		grunt.log.writeln("");
		grunt.log.writeln("DEBUG mode is " + (exports.config("debug") ? "ON".green : "OFF".red));
		grunt.log.writeln("Working in the " + (env === "production" ? "PRODUCTION".red : env.toUpperCase().green) + " environment");
		grunt.log.writeln("");
	}

	return exports;
};


text:
"use strict";
process.env.NODE_ENV = 'test';

var chai = require('../helper/setup-chai')
  , clients = require('../init/json/clients.json')
  , request = require('supertest')('http://localhost:5003')
  ;

describe('Auth', () => {
  var testClient = clients[0];
  var clientSecret = testClient.clientSecret;
  var clientCredentials = testClient.clientId + ':' + clientSecret;

  describe('Login with Password', () => {

    var accessToken;
    var refreshToken;

    it('should not allow request to authorise without token', (done) => {
      request
        .post('/auth/v1/authorise')
        .expect(400, done);
    });

    it('should allow tokens to be requested', (done) => {
      request
        .post('/auth/v1/token')
        .type('form')
        .auth(clientCredentials, '')
        .send({
          grant_type: 'password',
          username: '11bc6f7b9b0d0b0457673daf',
          password: 'test'
        })
        .expect(200)
        .end((err, res) => {
          accessToken = res.body.access_token;
          refreshToken = res.body.refresh_token;

          res.body.should.contain.keys(['access_token', 'refresh_token']);

          done();
        });
    });

    it('should allow users to authorise with valid access token', (done) => {
      request
        .post('/auth/v1/authorise')
        .set('Authorization', 'Bearer ' + accessToken)
        .expect(200)
        .end((err, res) => {
          res.body.should.contain.keys(['userId']);

          done();
        });
    });

  });
});


text:
package org.apache.river.test.spec.policyprovider.util.classes.dir02;

// java.io
import java.io.Serializable;

/**
 * This class is helper class for policyprovider testing.
 * This class can be downloaded using PreferredClassLoader or
 * can be found in the executing VM's classpath.
 */
public class Class03 implements Serializable {}


text:
package net.grandcentrix.tray.provider;

import android.database.Cursor;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Created by jannisveerkamp on 17.09.14.
 */
public class TrayItem {

    private final Date mCreated;

    private final String mKey;

    private final String mMigratedKey;

    private final String mModule;

    private final Date mUpdated;

    private final String mValue;

    /*package*/ TrayItem(final Cursor cursor) {
        mKey = cursor.getString(cursor.getColumnIndexOrThrow(
                TrayContract.Preferences.Columns.KEY));
        mValue = cursor.getString(cursor.getColumnIndexOrThrow(
                TrayContract.Preferences.Columns.VALUE));
        mModule = cursor.getString(cursor.getColumnIndexOrThrow(
                TrayContract.Preferences.Columns.MODULE));
        mCreated = new Date(cursor.getLong(cursor.getColumnIndexOrThrow(
                TrayContract.Preferences.Columns.CREATED)));
        mUpdated = new Date(cursor.getLong(cursor.getColumnIndexOrThrow(
                TrayContract.Preferences.Columns.UPDATED)));
        mMigratedKey = cursor.getString(cursor.getColumnIndexOrThrow(
                TrayContract.Preferences.Columns.MIGRATED_KEY));
    }

    public TrayItem(final String module, final String key, final String migratedKey,
            final String value, final Date created, final Date updated) {
        mCreated = created;
        mKey = key;
        mModule = module;
        mUpdated = updated;
        mValue = value;
        mMigratedKey = migratedKey;
    }

    public Date created() {
        return mCreated;
    }

    public String key() {
        return mKey;
    }

    public String migratedKey() {
        return mMigratedKey;
    }

    public String module() {
        return mModule;
    }

    @Override
    public String toString() {
        SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss dd.MM.yyyy", Locale.US);

        //noinspection StringBufferReplaceableByString
        return new StringBuilder()
                .append("key: ")
                .append(mKey)
                .append(", value: ")
                .append(mValue)
                .append(", module: ")
                .append(mModule)
                .append(", created: ")
                .append(sf.format(mCreated))
                .append(", updated: ")
                .append(sf.format(mUpdated))
                .append(", migratedKey: ")
                .append(mMigratedKey)
                .toString();
    }

    public Date updateTime() {
        return mUpdated;
    }

    public String value() {
        return mValue;
    }
}


text:
process.env.MONGOHQ_URL = 'mongodb://localhost:27017/jsonresume-tests';
process.env.POSTMARK_API_KEY = 'POSTMARK_API_TEST'; // http://blog.postmarkapp.com/post/913165552/handling-email-in-your-test-environment
var server = require('../../server');
var request = require('supertest')(server);
var should = require('should');
var bcrypt = require('bcrypt-nodejs');
var User = require('../../models/user');

describe('createSession: POST /session ', function() {

  var url = '/session';

  var user = {
    username: 'sessionLoginUsername',
    email: 'sessionLoginEmail',
    // FIXME should throw an error if we try to dave a raw Password
    // TODO use a mongoose virtual
    password: 'sessionLoginPassword',
  };
  user.hash = bcrypt.hashSync(user.password);

  before(function(done) {
    User.remove({}, function(err) { // TODO: move this into a beforeAll function
      User.create(user, done);
    });
  });

  it('should return 200 OK and a session for a valid user', function(done) {

    request.post(url)
      .send(user)
      .expect(200, function(err, res) {

        should.not.exist(err);
        res.body.should.have.property('session');

        res.body.should.have.properties({
          auth: true,
          email: user.email,
          message: 'loggedIn',
          username: user.username
        });

        done();
      });
  });

  it('should return 401 Unauthorized for an incorrect password', function(done) {

    request.post(url)
      .send({
        email: user.email,
        password: "different"
      })
      // HTTP status 401 UNAUTHORIZED
      .expect(401, function(err, res) {

        done()
      });
  });

  it('should return 401 Unauthorized for an unregistered email', function(done) {
    request.post(url)
      .send({
        email: "different",
        password: user.password
      })
      // HTTP status 401 UNAUTHORIZED
      .expect(401, function(err, res) {

        done()
      });
  });
});


text:
@class ZXBitMatrix;

/**
 * Aztec 2D code representation
 */
@interface ZXAztecCode : NSObject

/**
 * Number of data codewords
 */
@property (nonatomic, assign) int codeWords;

/**
 * Compact or full symbol indicator
 */
@property (nonatomic, assign) BOOL compact;

/**
 * Number of levels
 */
@property (nonatomic, assign) int layers;

/**
 * The symbol image
 */
@property (nonatomic, retain) ZXBitMatrix *matrix;

/**
 * Size in pixels (width and height)
 */
@property (nonatomic, assign) int size;

@end


text:
set -e

wget -O - http://ubuntu.hyperdex.org/hyperdex.gpg.key | apt-key add -
cat >> /etc/apt/sources.list.d/hyperdex.list << EOF
deb [arch=amd64] http://ubuntu.hyperdex.org trusty main
EOF
apt-get update
apt-get install -y hyperdex


text:
<?php

use yii\helpers\Html;
use kartik\widgets\ActiveForm;
use kartik\select2\Select2; // or kartik\select2\Select2
use yii\helpers\ArrayHelper;
/* @var $this yii\web\View */
/* @var $model frontend\models\UserObjectsSearch */
/* @var $form yii\widgets\ActiveForm */
?>

 <?= Yii::t('app', 'Search') ?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
        'type' => ActiveForm::TYPE_INLINE
    ]); ?>

    <?= $form->field($model, 'object_id', [
                    'options' =>['style'=>''],
                    'addon' => [
                        'append' => [
                            'content' => Html::submitButton('Go', ['class'=>'btn btn-primary']),
                            'asButton' => true
                        ]
                    ],
                ])->widget(Select2::classname(), [
                        'data' => ArrayHelper::map(\common\models\CsObjects::find()->all(), 'id', 'name'),
                        'options' => ['placeholder' => 'Select object type ...'],
                        'pluginOptions' => [
                            'allowClear' => true
                        ],
                    ]) ?>

    <?php //= Html::submitButton(Yii::t('app', 'Go'), ['class' => 'btn btn-primary']) ?>

    <?php // echo $form->field($model, 'loc_id') ?>

    <?php // echo $form->field($model, 'note') ?>

    <?php // echo $form->field($model, 'is_set') ?>

    <?php // echo $form->field($model, 'update_time') ?>

    <?php ActiveForm::end(); ?>


text:
using Common.Addins.GitVersion;

namespace Common.Utilities;

public record NugetPackage(string PackageName, FilePath FilePath, bool IsChocoPackage);

public record CodeCovCredentials(string Token);

public record GitHubCredentials(string Token, string? UserName = null);

public record NugetCredentials(string ApiKey);

public record ChocolateyCredentials(string ApiKey);

public record BuildVersion(GitVersion GitVersion, string? Version, string? Milestone, string? SemVersion, string? NugetVersion, string? ChocolateyVersion)
{
    public static BuildVersion Calculate(GitVersion gitVersion)
    {
        var version = gitVersion.MajorMinorPatch;
        var semVersion = gitVersion.SemVer;
        var nugetVersion = gitVersion.SemVer;
        var chocolateyVersion = gitVersion.MajorMinorPatch;

        if (!string.IsNullOrWhiteSpace(gitVersion.PreReleaseTag))
        {
            chocolateyVersion += $"-{gitVersion.PreReleaseTag?.Replace(".", "-")}";
        }

        if (!string.IsNullOrWhiteSpace(gitVersion.BuildMetaData))
        {
            semVersion += $"-{gitVersion.BuildMetaData}";
            chocolateyVersion += $"-{gitVersion.BuildMetaData}";
            nugetVersion += $".{gitVersion.BuildMetaData}";
        }

        return new BuildVersion(
            GitVersion: gitVersion,
            Version: version,
            Milestone: version,
            SemVersion: semVersion,
            NugetVersion: nugetVersion?.ToLowerInvariant(),
            ChocolateyVersion: chocolateyVersion?.ToLowerInvariant()
        );
    }
}

public record DockerImage(string Distro, string TargetFramework, Architecture Architecture, string Registry, bool UseBaseImage);

public enum DockerRegistry
{
    GitHub = 0,
    DockerHub = 1
}