text:
package org.kuali.coeus.common.committee.impl.dao.ojb;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ojb.broker.query.Criteria;
import org.apache.ojb.broker.query.Query;
import org.apache.ojb.broker.query.QueryFactory;
import org.kuali.coeus.common.committee.impl.bo.CommitteeBatchCorrespondenceBase;
import org.kuali.coeus.common.committee.impl.dao.CommitteeBatchCorrespondenceDao;
import org.kuali.rice.core.framework.persistence.ojb.dao.PlatformAwareDaoBaseOjb;
import org.kuali.rice.krad.service.util.OjbCollectionAware;

import java.sql.Date;
import java.util.List;

/**
 *
 * This class is the OJB implementation of CommitteeBatchCorrespondenceDao
 * which provides enhanced database access functionality.
 */
public abstract class CommitteeBatchCorrespondenceDaoOjbBase<CBC extends CommitteeBatchCorrespondenceBase> extends PlatformAwareDaoBaseOjb implements OjbCollectionAware, CommitteeBatchCorrespondenceDao<CBC> {

    private static final Log LOG = LogFactory.getLog(CommitteeBatchCorrespondenceDaoOjbBase.class);

    private static final String BATCH_CORRESPONDENCE_TYPE_CODE = "batchCorrespondenceTypeCode";
    private static final String BATCH_RUN_DATE = "batchRunDate";

    @Override
    @SuppressWarnings("unchecked")
    public List<CBC> getCommitteeBatchCorrespondence(String batchCorrespondenceTypeCode, Date startDate, Date endDate) {
        Criteria crit = new Criteria();
        crit.addEqualTo(BATCH_CORRESPONDENCE_TYPE_CODE, batchCorrespondenceTypeCode);
        if (startDate != null) {
            crit.addGreaterOrEqualThan(BATCH_RUN_DATE, startDate);
        }
        if (endDate != null) {
            crit.addLessOrEqualThan(BATCH_RUN_DATE, endDate);
        }

        Query q = QueryFactory.newQuery(getCommitteeBatchCorrespondenceBOClassHook(), crit, true);
        logQuery(q);
        return (List<CBC>) getPersistenceBrokerTemplate().getCollectionByQuery(q);
    }

    protected abstract Class<CBC> getCommitteeBatchCorrespondenceBOClassHook();

    /**
     * Logs the Query
     * @param q the query
     */
    private static void logQuery(Query q) {
        if (LOG.isDebugEnabled()) {
            LOG.debug(q.toString());
        }
    }

}


text:
package org.vizzini.core;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;

import org.junit.Test;

/**
 * Provides tests for the TimePrinter class.
 */
public final class TimePrinterTest
{
    /**
     * Test the formatElapsedTime() method.
     */
    @Test
    public void formatElapsedTime100()
    {
        final String title = "Test";
        final long start = 1;
        final long end = 101;
        final TimePrinter timePrinter = new TimePrinter();

        final String result = timePrinter.formatElapsedTime(title, start, end);

        assertNotNull(result);
        assertThat(result, is("Test elapsed time 0:00 (100 ms)"));
    }

    /**
     * Test the formatElapsedTime() method.
     */
    @Test
    public void formatElapsedTime10000()
    {
        final String title = "Test";
        final long start = 1;
        final long end = 10001;
        final TimePrinter timePrinter = new TimePrinter();

        final String result = timePrinter.formatElapsedTime(title, start, end);

        assertNotNull(result);
        assertThat(result, is("Test elapsed time 0:10 (10000 ms)"));
    }

    /**
     * Test the formatElapsedTime() method.
     */
    @Test
    public void formatElapsedTime100000()
    {
        final String title = "Test";
        final long start = 1;
        final long end = 100001;
        final TimePrinter timePrinter = new TimePrinter();

        final String result = timePrinter.formatElapsedTime(title, start, end);

        assertNotNull(result);
        assertThat(result, is("Test elapsed time 1:40 (100000 ms)"));
    }

    /**
     * Test the formatElapsedTime() method.
     */
    @Test
    public void formatElapsedTime1000000()
    {
        final String title = "Test";
        final long start = 1;
        final long end = 1000001;
        final TimePrinter timePrinter = new TimePrinter();

        final String result = timePrinter.formatElapsedTime(title, start, end);

        assertNotNull(result);
        assertThat(result, is("Test elapsed time 16:40 (1000000 ms)"));
    }

    /**
     * Test the formatElapsedTime() method.
     */
    @Test
    public void formatElapsedTimeBadOrder()
    {
        final String title = "Test";
        final long start = 10001;
        final long end = 1;
        final TimePrinter timePrinter = new TimePrinter();

        final String result = timePrinter.formatElapsedTime(title, start, end);

        assertNotNull(result);
        assertThat(result, is("Test elapsed time 0:10 (10000 ms)"));
    }

    /**
     * Test the formatElapsedTime() method.
     */
    @Test
    public void formatElapsedTimeTitleEmpty()
    {
        final String title = "";
        final long start = 1;
        final long end = 10001;
        final TimePrinter timePrinter = new TimePrinter();

        final String result = timePrinter.formatElapsedTime(title, start, end);

        assertNotNull(result);
        assertThat(result, is("Elapsed time 0:10 (10000 ms)"));
    }

    /**
     * Test the formatElapsedTime() method.
     */
    @Test
    public void formatElapsedTimeTitleNull()
    {
        final String title = null;
        final long start = 1;
        final long end = 10001;
        final TimePrinter timePrinter = new TimePrinter();

        final String result = timePrinter.formatElapsedTime(title, start, end);

        assertNotNull(result);
        assertThat(result, is("Elapsed time 0:10 (10000 ms)"));
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

require_once Mage::getBaseDir('lib') . DS . 'ComproPago' . DS . 'vendor' . DS . 'autoload.php';

use CompropagoSdk\Resources\Payments\Cash as sdkCash;

class ComproPago_Cash_Model_Providers
{
	/**
	 * Create the array options for the config page
	 * @return array
	 */
	public function toOptionArray()
	{
		$options = [];
		$providers = (new sdkCash)->getDefaultProviders();

		foreach ($providers as $provider)
		{
			$options[] = [
				'value' => $provider['internal_name'],
				'label' => $provider['name']
			];
		}

		return $options;
	}
}


text:
package org.apache.camel.example.fhir;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Named;
import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.v24.message.ORU_R01;
import ca.uhn.hl7v2.model.v24.segment.PID;
import org.apache.camel.LoggingLevel;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.cdi.ContextName;
import org.apache.camel.component.properties.PropertiesComponent;
import org.apache.http.ProtocolException;
import org.hl7.fhir.dstu3.model.Patient;

public class Application {

    @ContextName("camel-example-fhir-cdi")
    static class FhirRoute extends RouteBuilder {

        @Override
        public void configure() {
            from("file:{{input}}").routeId("fhir-example")
                .onException(ProtocolException.class)
                    .handled(true)
                    .log(LoggingLevel.ERROR, "Error connecting to FHIR server with URL:{{serverUrl}}, please check the application.properties file ${exception.message}")
                    .end()
                .onException(HL7Exception.class)
                    .handled(true)
                    .log(LoggingLevel.ERROR, "Error unmarshalling ${file:name} ${exception.message}")
                    .end()
                .log("Converting ${file:name}")
                // unmarshall file to hl7 message
                .unmarshal().hl7()
                // very simple mapping from a HLV2 patient to dstu3 patient
                .process(exchange -> {
                    ORU_R01 msg = exchange.getIn().getBody(ORU_R01.class);
                    final PID pid = msg.getPATIENT_RESULT().getPATIENT().getPID();
                    String surname = pid.getPatientName()[0].getFamilyName().getFn1_Surname().getValue();
                    String name = pid.getPatientName()[0].getGivenName().getValue();
                    String patientId = msg.getPATIENT_RESULT().getPATIENT().getPID().getPatientID().getCx1_ID().getValue();
                    Patient patient = new Patient();
                    patient.addName().addGiven(name);
                    patient.getNameFirstRep().setFamily(surname);
                    patient.setId(patientId);
                    exchange.getIn().setBody(patient);
                })
                // marshall to JSON for logging
                .marshal().fhirJson("{{fhirVersion}}")
                .log("Inserting Patient: ${body}")
                // create Patient in our FHIR server
                .to("fhir://create/resource?inBody=resourceAsString&serverUrl={{serverUrl}}&fhirVersion={{fhirVersion}}")
                // log the outcome
                .log("Patient created successfully: ${body.getCreated}");
        }
    }

    @Produces
    @ApplicationScoped
    @Named("properties")
    PropertiesComponent properties() {
        return new PropertiesComponent("classpath:application.properties");
    }
}


text:
package com.mitchellbdunn.chip8.model;

import com.mitchellbdunn.chip8.Chip8;
import java.awt.Toolkit;
import java.util.Observable;
import java.util.Random;
import java.util.Stack;

/**
 *
 * @author Mitch
 */
public class Cpu extends Observable {

    // Chip8 units
    private Keyboard keyboard;
    private Screen screen;
    private Memory memory;

    // Cpu variables
    private int[] registerV;
    private int registerI;
    private Stack<Integer> stack;
    private int delayTimer;
    private int soundTimer;
    private int programCounter;
    private final Random rng;
    private boolean running;

    public Cpu() {
        initializeCpu();
        rng = new Random();
    }

    public final void initializeCpu() {
        running = false;
        registerV = new int[16];
        for (int i = 0; i < 0xF; i++) {
            registerV[i] = 0;
        }
        registerI = 0;
        stack = new Stack<Integer>();
        delayTimer = 0;
        soundTimer = 0;
        programCounter = 0x200;
    }

    public void run() {
        running = true;
        while (running) {
            int opcode = memory.getOpcode(getProgramCounter());
            runOpcode(opcode);
            try {
                Thread.sleep(5);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * Returns a boolean representing the bit value
     * @param number The number to check the bit of
     * @param position The bit position to check from within
     * the number.  The LSB is at position 0.
     * @return
     */
    public static boolean getBit(int number, int position) {
        return (((number >> position) & 1) == 1);
    }

    public void runOpcode(int opcode) {
        // Get the possible variables needed from the opcode
        int nnn = (opcode & 0x0FFF);
        int nn = (opcode & 0x00FF);
        int n = (opcode & 0x000F);
        int x = (opcode & 0x0F00) >> 8;
        int y = (opcode & 0x00F0) >> 4;

        // Increase the program counter; there are some opcodes where
        // this won't matter since we set the program counter there
        incrementProgramCounter();

        // Run the appropriate opcode
        switch (opcode & 0xF000) {
            case 0x0000:
                switch (opcode & 0x000F) {
                    case 0x0000:
                        opcode00E0();
                        break;
                    case 0x000E:
                        opcode00EE();
                        break;
                }
                break;
            case 0x1000:
                opcode1NNN(nnn);
                break;
            case 0x2000:
                opcode2NNN(nnn);
                break;
            case 0x3000:
                opcode3XNN(x, nn);
                break;
            case 0x4000:
                opcode4XNN(x, nn);
                break;
            case 0x5000:
                opcode5XY0(x, y);
                break;
            case 0x6000:
                opcode6XNN(x, nn);
                break;
            case 0x7000:
                opcode7XNN(x, nn);
                break;
            case 0x8000:
                switch (opcode & 0x000F) {
                    case 0x0000:
                        opcode8XY0(x, y);
                        break;
                    case 0x0001:
                        opcode8XY1(x, y);
                        break;
                    case 0x0002:
                        opcode8XY2(x, y);
                        break;
                    case 0x0003:
                        opcode8XY3(x, y);
                        break;
                    case 0x0004:
                        opcode8XY4(x, y);
                        break;
                    case 0x0005:
                        opcode8XY5(x, y);
                        break;
                    case 0x0006:
                        opcode8XY6(x, y);
                        break;
                    case 0x0007:
                        opcode8XY7(x, y);
                        break;
                    case 0x000E:
                        opcode8XYE(x, y);
                        break;
                }
                break;
            case 0x9000:
                opcode9XY0(x, y);
                break;
            case 0xA000:
                opcodeANNN(nnn);
                break;
            case 0xB000:
                opcodeBNNN(nnn);
                break;
            case 0xC000:
                opcodeCXNN(x, nn);
                break;
            case 0xD000:
                opcodeDXYN(x, y, n);
                break;
            case 0xE000:
                switch (opcode & 0x000F) {
                    case 0x000E:
                        opcodeEX9E(x);
                        break;
                    case 0x0001:
                        opcodeEXA1(x);
                        break;
                }
                break;
            case 0xF000:
                switch (opcode & 0x00FF) {
                    case 0x0007:
                        opcodeFX07(x);
                        break;
                    case 0x000A:
                        opcodeFX0A(x);
                        break;
                    case 0x0015:
                        opcodeFX15(x);
                        break;
                    case 0x0018:
                        opcodeFX18(x);
                        break;
                    case 0x001E:
                        opcodeFX1E(x);
                        break;
                    case 0x0029:
                        opcodeFX29(x);
                        break;
                    case 0x0033:
                        opcodeFX33(x);
                        break;
                    case 0x0055:
                        opcodeFX55(x);
                        break;
                    case 0x0065:
                        opcodeFX65(x);
                        break;
                }
                break;
            default:
                System.out.println("Unknown opcode: " + Integer.toHexString(opcode));
        }

        // Decrement delay and sound timers, if sound timer is
        // greater than zero, then play a sound
        if (delayTimer > 0) {
            delayTimer--;
        }
        if (soundTimer > 0) {
            Toolkit.getDefaultToolkit().beep();
            soundTimer--;
        }
    }

    /**
     * Clears the screen.
     */
    private void opcode00E0() {
        screen.initializeScreen();
    }

    /**
     * Returns from a subroutine.
     */
    private void opcode00EE() {
        programCounter = stack.pop();
        incrementProgramCounter();
    }

    /**
     * Jumps to address NNN.
     *
     * @param nnn address to set program counter to.
     */
    private void opcode1NNN(int nnn) {
        programCounter = nnn;
    }

    /**
     * Calls subroutine at NNN.
     *
     * @param nnn address of start of subroutine.
     */
    private void opcode2NNN(int nnn) {
        stack.push(programCounter - 2);
        programCounter = nnn;
    }

    /**
     * Skips the next instruction if VX equals NN.
     *
     * @param x register to check for equality.
     * @param nn value to check if equal to register VX.
     */
    private void opcode3XNN(int x, int nn) {
        if (registerV[x] == nn) {
            incrementProgramCounter();
        }
    }

    /**
     * Skips the next instruction if VX doesn't equal NN.
     *
     * @param x register to check for equality.
     * @param nn value to check if not equal to register VX.
     */
    private void opcode4XNN(int x, int nn) {
        if (registerV[x] != nn) {
            incrementProgramCounter();
        }
    }

    /**
     * Skips the next instruction if VX equals VY.
     *
     * @param x register to check for equality.
     * @param y register to check for equality.
     */
    private void opcode5XY0(int x, int y) {
        if (registerV[x] == registerV[y]) {
            incrementProgramCounter();
        }
    }

    /**
     * Sets VX to NN.
     *
     * @param x register to set value.
     * @param nn value to set for register VX.
     */
    private void opcode6XNN(int x, int nn) {
        registerV[x] = nn;
    }

    /**
     * Adds NN to VX.
     *
     * @param x register to add value to.
     * @param nn value to add to register VX.
     */
    private void opcode7XNN(int x, int nn) {
        registerV[x] += nn;
    }

    /**
     * Sets VX to the value of VY.
     *
     * @param x register to set value.
     * @param y register to get the value to set in register VX.
     */
    private void opcode8XY0(int x, int y) {
        registerV[x] = registerV[y];
    }

    /**
     * Sets VX to VX or VY.
     *
     * @param x register to set value.
     * @param y register to perform bitwise OR with register VX.
     */
    private void opcode8XY1(int x, int y) {
        registerV[x] = registerV[x] | registerV[y];
    }

    /**
     * Sets VX to VX and VY.
     *
     * @param x register to set value.
     * @param y register to perform bitwise AND with register VX.
     */
    private void opcode8XY2(int x, int y) {
        registerV[x] = registerV[x] & registerV[y];
    }

    /**
     * Sets VX to VX xor VY.
     *
     * @param x register to set value.
     * @param y register to perform bitwise XOR with register VX.
     */
    private void opcode8XY3(int x, int y) {
        registerV[x] = registerV[x] ^ registerV[y];
    }

    /**
     * Adds VY to VX. VF is set to 1 when there's a carry, and to 0 when there
     * isn't.
     *
     * @param x register to add value to.
     * @param y register to get value and to add to register VX.
     */
    private void opcode8XY4(int x, int y) {
        registerV[x] += registerV[y];
        registerV[0xF] = getBit(registerV[x], 8) ? 1 : 0;
        registerV[x] &= 0xFF;
    }

    /**
     * VY is subtracted from VX. VF is set to 0 when there's a borrow, and 1
     * when there isn't.
     *
     * @param x register to subtract value from.
     * @param y register to get value to subtract from register VX.
     */
    private void opcode8XY5(int x, int y) {
        if (registerV[x] >= registerV[y]) {
            registerV[0xF] = 1;
            registerV[x] -= registerV[y];
        } else {
            registerV[0xF] = 0;
            registerV[x] = (int) (0xFF + (registerV[x] - registerV[y] + 1));
        }
    }

    /**
     * Shifts VX right by one. VF is set to the value of the least significant
     * bit of VX before the shift.
     *
     * @param x register to shift bits right by one.
     * @param y not used.
     */
    private void opcode8XY6(int x, int y) {
        registerV[0xF] = getBit(registerV[x], 0) ? 1 : 0;
        registerV[x] >>>= 1;
    }

    /**
     * Sets VX to VY minus VX. VF is set to 0 when there's a borrow, and 1 when
     * there isn't.
     *
     * @param x register to set value of subtraction to as well as get value of
     * subtrahend.
     * @param y register to get value of minuend for subtraction.
     */
    private void opcode8XY7(int x, int y) {
        if (registerV[y] >= registerV[x]) {
            registerV[0xF] = 1;
            registerV[x] = registerV[y] - registerV[x];
        } else {
            registerV[0xF] = 0;
            registerV[x] = (int) (0xFF + (registerV[y] - registerV[x] + 1));
        }
    }

    /**
     * Shifts VX left by one. VF is set to the value of the most significant bit
     * of VX before the shift.
     *
     * @param x register to shift bits left by one.
     * @param y not used.
     */
    private void opcode8XYE(int x, int y) {
        registerV[0xF] = getBit(registerV[x], 7) ? 1 : 0;
        registerV[x] <<= 1;
        registerV[x] &= 0xFF;
    }

    /**
     * Skips the next instruction if VX doesn't equal VY.
     *
     * @param x register to check for equality.
     * @param y register to check for equality.
     */
    private void opcode9XY0(int x, int y) {
        if (registerV[x] != registerV[y]) {
            incrementProgramCounter();
        }
    }

    /**
     * Sets I to the address NNN.
     *
     * @param nnn value to set for I.
     */
    private void opcodeANNN(int nnn) {
        registerI = nnn;
    }

    /**
     * Jumps to the address NNN plus V0.
     *
     * @param nnn value to jump to plus value of register V0.
     */
    private void opcodeBNNN(int nnn) {
        programCounter = nnn + registerV[0];
    }

    /**
     * Sets VX to a random number and NN.
     *
     * @param x register to set value.
     * @param nn value to get bitwise AND with a random number for register VX.
     */
    private void opcodeCXNN(int x, int nn) {
        registerV[x] = rng.nextInt() & nn;
    }

    /**
     * Draws a sprite at coordinate (VX, VY) that has a width of 8 pixels and a
     * height of N pixels. Each row of 8 pixels is read as bit-coded (with the
     * most significant bit of each byte displayed on the left) starting from
     * memory location I; I value doesn't change after the execution of this
     * instruction. As described above, VF is set to 1 if any screen pixels are
     * flipped from set to unset when the sprite is drawn, and to 0 if that
     * doesn't happen.
     *
     * @param x register that holds X location to draw sprite.
     * @param y register that holds Y location to draw sprite.
     * @param n height of the sprite
     */
    private void opcodeDXYN(int x, int y, int n) {
        // Reset register VF
        registerV[0xF] = 0x0;
        // Loop through each row (represents Y coordinate)
        for (int i = 0; i < n; i++) {
            byte row = memory.getByte(registerI + i);
            // Loop through each bit to know how to draw it to
            // the screen (represents X coordinate)
            for (int j = 0; j < 8; j++) {
                // Boolean representing if the bit was set or not, we need
                // to read from MSB to LSB, so we invert the j index to
                // get the position we need.
                boolean drawPixel = getBit(row, 7 - j);
                if (drawPixel) {
                    // Get the coordinates to draw to
                    int drawX = registerV[x] + j;
                    int drawY = registerV[y] + i;
                    // If a pixel will be drawn off the screen it
                    // instead wraps around the screen
                    while (drawX >= Chip8.SCREEN_WIDTH) {
                        drawX -= Chip8.SCREEN_WIDTH;
                    }
                    while (drawY >= Chip8.SCREEN_HEIGHT) {
                        drawY -= Chip8.SCREEN_HEIGHT;
                    }
                    // If the pixel is set, then it will get unset and
                    // VF should be set to 1
                    if (screen.isPixelSet(drawX, drawY)) {
                        registerV[0xF] = 0x1;
                    }
                    // Draw the pixel.  Pixels  are XOR into the
                    // existing screen.
                    screen.drawPixel(drawX, drawY);
                }
            }
        }
        setChanged();
        notifyObservers();
    }

    /**
     * Skips the next instruction if the key stored in VX is pressed.
     *
     * @param x register that holds a value that will map to a key
     */
    private void opcodeEX9E(int x) {
        if (keyboard.isKeyPressed(registerV[x])) {
            incrementProgramCounter();
        }
    }

    /**
     * Skips the next instruction if the key stored in VX isn't pressed.
     *
     * @param x register that holds a value that will map to a key
     */
    private void opcodeEXA1(int x) {
        if (!keyboard.isKeyPressed(registerV[x])) {
            incrementProgramCounter();
        }
    }

    /**
     * Sets VX to the value of the delay timer.
     *
     * @param x register to set to value of delay timer.
     */
    private void opcodeFX07(int x) {
        registerV[x] = delayTimer;
    }

    /**
     * A key press is awaited, and then stored in VX.
     *
     * @param x register to store which key is pressed.
     */
    private void opcodeFX0A(int x) {
        registerV[x] = keyboard.waitForKeyPress();
    }

    /**
     * Sets the delay timer to VX.
     *
     * @param x register to set with the value of the delay timer.
     */
    private void opcodeFX15(int x) {
        delayTimer = registerV[x];
    }

    /**
     * Sets the sound timer to VX.
     *
     * @param x register to set with the value of the sound timer.
     */
    private void opcodeFX18(int x) {
        soundTimer = registerV[x];
    }

    /**
     * Adds VX to I.
     *
     * @param x register to add to I.
     */
    private void opcodeFX1E(int x) {
        registerI += registerV[x];
    }

    /**
     * Sets I to the location of the sprite for the character in VX. Characters
     * 0-F (in hexadecimal) are represented by a 4x5 font.
     *
     * @param x register to get value of the sprite for the character.
     */
    private void opcodeFX29(int x) {
        registerI = x * 5;
    }

    /**
     * Stores the Binary-coded decimal representation of VX, with the most
     * significant of three digits at the address in I, the middle digit at I
     * plus 1, and the least significant digit at I plus 2. (In other words,
     * take the decimal representation of VX, place the hundreds digit in memory
     * at location in I, the tens digit at location I+1, and the ones digit at
     * location I+2.)
     *
     * @param x register to get decimal value and store the binary-coded
     * representation.
     */
    private void opcodeFX33(int x) {
        int number = registerV[x];
        memory.setByte(registerI, (byte) (number / 100));
        memory.setByte(registerI + 1, (byte) ((number % 100) / 10));
        memory.setByte(registerI + 2, (byte) (number % 10));
    }

    /**
     * Stores V0 to VX in memory starting at address I.
     *
     * @param x last register to store in memory.
     */
    private void opcodeFX55(int x) {
        for (int i = 0x0; i <= x; i++) {
            memory.setByte(registerI + i, (byte) registerV[i]);
        }
    }

    /**
     * Fills V0 to VX with values from memory starting at address I.
     *
     * @param x last register to store from memory.
     */
    private void opcodeFX65(int x) {
        for (int i = 0x0; i <= x; i++) {
            registerV[i] = memory.getByte(registerI + i);
        }
    }

    private void incrementProgramCounter() {
        programCounter = programCounter + 2;
    }

    public int getRegisterV(int x) {
        return registerV[x];
    }

    public void setRegisterV(int x, int value) {
        this.registerV[x] = value;
    }

    public int getRegisterI() {
        return registerI;
    }

    public void setRegisterI(int registerI) {
        this.registerI = registerI;
    }

    public Stack<Integer> getStack() {
        return stack;
    }

    public void setStack(Stack<Integer> stack) {
        this.stack = stack;
    }

    public int getDelayTimer() {
        return delayTimer;
    }

    public void setDelayTimer(int delayTimer) {
        this.delayTimer = delayTimer;
    }

    public int getSoundTimer() {
        return soundTimer;
    }

    public void setSoundTimer(int soundTimer) {
        this.soundTimer = soundTimer;
    }

    public int getProgramCounter() {
        return programCounter;
    }

    public void setProgramCounter(int programCounter) {
        this.programCounter = programCounter;
    }

    public Keyboard getKeyboard() {
        return keyboard;
    }

    public void setKeyboard(Keyboard keyboard) {
        this.keyboard = keyboard;
    }

    public Screen getScreen() {
        return screen;
    }

    public void setScreen(Screen screen) {
        this.screen = screen;
    }

    public Memory getMemory() {
        return memory;
    }

    public void setMemory(Memory memory) {
        this.memory = memory;
    }

    public boolean isRunning() {
        return running;
    }

    public void setRunning(boolean running) {
        this.running = running;
    }
}


text:
坑位html

    <textarea class="pit-editor" id="htmlEditor"/>

坑位less

    <textarea class="pit-editor" id="lessEditor" />

页面配置

        坑位名称

          <input type="email" class="form-control" id="inputName" placeholder="不能用中文,建议拼音缩写加日期,例如:czh-20170115"/>

        <input type="file" id="pitImg"/>

保存和预览

      保存
      预览

坑位预览


text:
<?php
/**
 * Activity text strings.
 * Is used for all the text within activity logs & notifications.
 */
return [

    // Pages
    'page_create'                 => 'vytvořil/a stránku',
    'page_create_notification'    => 'Stránka byla úspěšně vytvořena',
    'page_update'                 => 'aktualizoval/a stránku',
    'page_update_notification'    => 'Stránka byla úspěšně aktualizována',
    'page_delete'                 => 'odstranil/a stránku',
    'page_delete_notification'    => 'Stránka byla úspěšně smazána',
    'page_restore'                => 'obnovil/a stránku',
    'page_restore_notification'   => 'Stránka byla úspěšně obnovena',
    'page_move'                   => 'přesunul/a stránku',

    // Chapters
    'chapter_create'              => 'vytvořil/a kapitolu',
    'chapter_create_notification' => 'Kapitola byla úspěšně vytvořena',
    'chapter_update'              => 'aktualizoval/a kapitolu',
    'chapter_update_notification' => 'Kapitola byla úspěšně aktualizována',
    'chapter_delete'              => 'odstranila/a kapitolu',
    'chapter_delete_notification' => 'Kapitola byla úspěšně odstraněna',
    'chapter_move'                => 'přesunul/a kapitolu',

    // Books
    'book_create'                 => 'vytvořil/a knihu',
    'book_create_notification'    => 'Kniha byla úspěšně vytvořena',
    'book_create_from_chapter'              => 'converted chapter to book',
    'book_create_from_chapter_notification' => 'Kapitola byla úspěšně převedena na knihu',
    'book_update'                 => 'aktualizoval/a knihu',
    'book_update_notification'    => 'Kniha byla úspěšně aktualizována',
    'book_delete'                 => 'odstranil/a knihu',
    'book_delete_notification'    => 'Kniha byla úspěšně odstraněna',
    'book_sort'                   => 'seřadil/a knihu',
    'book_sort_notification'      => 'Kniha byla úspěšně seřazena',

    // Bookshelves
    'bookshelf_create'            => 'created shelf',
    'bookshelf_create_notification'    => 'Shelf successfully created',
    'bookshelf_create_from_book'    => 'converted book to shelf',
    'bookshelf_create_from_book_notification'    => 'Book successfully converted to a shelf',
    'bookshelf_update'                 => 'updated shelf',
    'bookshelf_update_notification'    => 'Shelf successfully updated',
    'bookshelf_delete'                 => 'deleted shelf',
    'bookshelf_delete_notification'    => 'Shelf successfully deleted',

    // Favourites
    'favourite_add_notification' => '":name" byla přidána do Vašich oblíbených',
    'favourite_remove_notification' => '":name" byla odstraněna z Vašich oblíbených',

    // MFA
    'mfa_setup_method_notification' => 'Vícefaktorová metoda byla úspěšně nakonfigurována',
    'mfa_remove_method_notification' => 'Vícefaktorová metoda byla úspěšně odstraněna',

    // Webhooks
    'webhook_create' => 'vytvořil/a webhook',
    'webhook_create_notification' => 'Webhook byl úspěšně vytvořen',
    'webhook_update' => 'aktualizoval/a webhook',
    'webhook_update_notification' => 'Webhook byl úspěšně aktualizován',
    'webhook_delete' => 'odstranil/a webhook',
    'webhook_delete_notification' => 'Webhook byl úspěšně odstraněn',

    // Users
    'user_update_notification' => 'User successfully updated',
    'user_delete_notification' => 'User successfully removed',

    // Other
    'commented_on'                => 'okomentoval/a',
    'permissions_update'          => 'oprávnění upravena',
];


text:
function createToolPanel(renderer, scale){

   var STANDARD_DIMENSIONS = {width: 460, height:287};

   var width = STANDARD_DIMENSIONS.width * scale,
       height = STANDARD_DIMENSIONS.height * scale;

   var panel = createPanel(renderer, width, height, {foregroundGlow: true});

   var toolBGPlane,
       coverPlane,
       pointerPlane;

   var started = false;

   var menuPlanes = [];

   var menu = [
           ["Languages", ["Javascript", "C#", "Java", "Go"]],
           ["Editors", ["Vim", "IntelliJ", "Visual Studio"]],
           ["Platforms", ["Modern Web", "Android"]],
           ["OS", ["Linux", "Windows"]]
       ];

   function createBackground(){

        var material = new THREE.MeshBasicMaterial({transparent: false, color: 0x000000});
        var geometry = new THREE.PlaneBufferGeometry( width, height);

        var plane = new THREE.Mesh( geometry, material );
        plane.position.set(width/2, height/2, -1);
        panel.addToScene( plane );
   };

   function createCoverPlane(){

        var material = new THREE.MeshBasicMaterial({transparent: false, color: 0x000000});
        var geometry = new THREE.PlaneBufferGeometry( 256 * scale, 100 * scale);

        var plane = new THREE.Mesh( geometry, material );
        plane.position.set(200 * scale, 110 * scale,2);
        panel.addToScene( plane );

        return plane;

   }

   function createTextPlane(text, header, orange){

       var titleCanvas =  panel.renderToCanvas(512, 160, function(ctx){
           ctx.strokeStyle="#eac7df";

           ctx.fillStyle = '#eac7df';
           ctx.font = "18pt Roboto";
           if(header){
               ctx.font = "26pt Roboto";

               if(orange){
                   ctx.fillStyle = '#f15a24';
               } else {
                   ctx.fillStyle = '#12b7a7';
               }
           }

           ctx.fillText(text.toUpperCase(), 50, 35);

       });

        var titleTexture = new THREE.Texture(titleCanvas)
        titleTexture.needsUpdate = true;

        var titleMaterial = new THREE.MeshBasicMaterial({map: titleTexture, transparent: true});
        var titleGeometry = new THREE.PlaneBufferGeometry( 256 * scale, 80 * scale);

        var plane = new THREE.Mesh( titleGeometry, titleMaterial );
        return plane;

   };

    function init(){
        createBackground();
        var toolTexture = THREE.ImageUtils.loadTexture('images/tools-foreground.png', undefined, LOADSYNC.register() );
        var toolMaterial = new THREE.MeshBasicMaterial({map: toolTexture, transparent: true});
        var toolGeometry = new THREE.PlaneBufferGeometry( 350 * scale, 350 * scale);
        toolPlane = new THREE.Mesh( toolGeometry, toolMaterial );
        toolPlane.position.set(width/2 + 05 * scale, height/2 - 40 * scale, 3);
        toolPlane.scale.set(.5,.5,.5);

        panel.addToScene( toolPlane );

        var toolBGTexture = THREE.ImageUtils.loadTexture('images/tools-background.png', undefined, LOADSYNC.register() );
        var toolBGMaterial = new THREE.MeshBasicMaterial({map: toolBGTexture, transparent: true, opacity: .9});
        var toolBGGeometry = new THREE.PlaneBufferGeometry( 350 * scale, 350 * scale);
        toolBGPlane = new THREE.Mesh( toolBGGeometry, toolBGMaterial );
        toolBGPlane.position.set(width/2 + 05 * scale, height/2 - 40 * scale, 2);
        toolBGPlane.scale.set(.6,.6,.6);

        panel.addToScene( toolBGPlane );

        var headerTexture = THREE.ImageUtils.loadTexture("images/tools-header.png", undefined, LOADSYNC.register() );
        var headerMaterial = new THREE.MeshBasicMaterial({map: headerTexture, depthTest: false, transparent: true});
        var headerGeometry = new THREE.PlaneBufferGeometry( 134 * scale, 32 * scale);
        var headerPlane = new THREE.Mesh(headerGeometry, headerMaterial );
        headerPlane.position.set(108 * scale, height - 90 * scale,5);
        panel.addToScene(headerPlane);

        var selectorTexture = THREE.ImageUtils.loadTexture("images/tools-selector.png", undefined, LOADSYNC.register() );
        var selectorMaterial = new THREE.MeshBasicMaterial({map: selectorTexture, depthTest: false, transparent: true});
        var selectorGeometry = new THREE.PlaneBufferGeometry( 392 * scale, 156 * scale);
        var selectorPlane = new THREE.Mesh(selectorGeometry, selectorMaterial );
        selectorPlane.position.set(141 * scale, height/2 - 22 * scale,5);
        selectorPlane.scale.set(.5, .5, .5);
        panel.addToScene(selectorPlane);

        var pointerTexture = THREE.ImageUtils.loadTexture("images/tools-pointer.png", undefined, LOADSYNC.register() );
        var pointerMaterial = new THREE.MeshBasicMaterial({map: pointerTexture, depthTest: false, transparent: true});
        var pointerGeometry = new THREE.PlaneBufferGeometry( 26 * scale, 30 * scale);
        pointerPlane = new THREE.Mesh(pointerGeometry, pointerMaterial );
        pointerPlane.position.set(35 * scale, 115 * scale,15);
        pointerPlane.scale.set(.5, .5, .5);
        panel.addToScene(pointerPlane);

        var bottomTexture = THREE.ImageUtils.loadTexture("images/tools-bottom.png", undefined, LOADSYNC.register() );
        var bottomMaterial = new THREE.MeshBasicMaterial({map: bottomTexture, depthTest: false, transparent: true});
        var bottomGeometry = new THREE.PlaneBufferGeometry( 234 * scale, 45 * scale);
        var bottomPlane = new THREE.Mesh(bottomGeometry, bottomMaterial );
        bottomPlane.position.set(100 * scale, 55 * scale,5);
        bottomPlane.scale.set(.5, .5, .5);
        panel.addToScene(bottomPlane);

        var rightTexture = THREE.ImageUtils.loadTexture("images/tools-right.png", undefined, LOADSYNC.register() );
        rightTexture.minFilter = THREE.LinearFilter;
        var rightMaterial = new THREE.MeshBasicMaterial({map: rightTexture, depthTest: false, transparent: true});
        var rightGeometry = new THREE.PlaneBufferGeometry( 149 * scale, 270 * scale);
        var rightPlane = new THREE.Mesh(rightGeometry, rightMaterial );
        rightPlane.position.set(360 * scale, 125 * scale,5);
        rightPlane.scale.set(.5, .5, .5);
        panel.addToScene(rightPlane);

        for(var i =0; i< menu.length; i++){
            var title = createTextPlane(menu[i][0], true, i%2);
            title.position.set(( 25 + 256/2) * scale, 60 * scale,0);
            if(i != 0){
                title.position.x = -1000;
            }
            panel.addToScene(title);

            menuPlanes[i] = [];
            menuPlanes[i].push(title);
            for(var j = 0; j < menu[i][1].length; j++){
                var unhighlightedTitle = createTextPlane(menu[i][1][j], false);
                unhighlightedTitle.position.set(( 25 + 256/2) * scale, 88 * scale + 15*j * scale,0);

                if(i != 0){
                    unhighlightedTitle.position.x = -1000;
                }

                panel.addToScene(unhighlightedTitle);

                menuPlanes[i].push(unhighlightedTitle);
            }
        }

        coverPlane = createCoverPlane();

    }

    function render(time){
        if(!started){

            var rotation = [];
            var sliders = [];
            var pointers = [];
            var previous = "";
            var unpackedMenu = [];
            var subIndex = 0;

            for(var i = 0; i< menu.length; i++){
                for(var j = 0; j < menu[i][1].length; j++){
                    unpackedMenu.push([menu[i][0], menu[i][1][j], i, j]);
                }
            }

            for(var i = 0; i< unpackedMenu.length; i++){
                rotation.push(new TWEEN.Tween(toolPlane.rotation)
                   .delay(1000)
                   .easing(TWEEN.Easing.Cubic.InOut)
                   .to({z: (2 * (i + 1) * Math.PI / unpackedMenu.length ) % (1.9999 * Math.PI)}, 500));

                pointers.push(new TWEEN.Tween(pointerPlane.position)
                        .to({y: 115 * scale + 15 * unpackedMenu[i][3] * scale}, 500)
                        .easing(TWEEN.Easing.Cubic.InOut)
                        .delay(1000));

                if(previous != unpackedMenu[i][0]){
                    sliders.push(new TWEEN.Tween(coverPlane.position)
                            .to({x:500 * scale}, 750));
                    sliders.push(new TWEEN.Tween(coverPlane.position)
                            .delay(menu[(sliders.length-1) / 2][1].length * 1500 - 1500)
                            .onComplete(function(index){ return function(){
                                for(var layer = 0; layer<menuPlanes.length; layer++){
                                    for(var layerSub = 0; layerSub < menuPlanes[layer].length; layerSub++){
                                        if(layer === index){
                                            menuPlanes[layer][layerSub].position.x = (25 + 256/2) * scale;
                                        } else {
                                            menuPlanes[layer][layerSub].position.x = -1000;
                                        }

                                    }

                                }
                            }}((unpackedMenu[i][2] + 1) % menu.length))
                            .to({x:200 * scale}, 750));
                    if(sliders.length > 2){
                        sliders[sliders.length - 3].chain(sliders[sliders.length - 2]);
                    }

                    sliders[sliders.length - 2].chain(sliders[sliders.length - 1]);

                    previous = unpackedMenu[i][0];
                }

                if(i > 0){
                    rotation[i - 1].chain(rotation[i]);
                    pointers[i-1].chain(pointers[i]);
                }
            };

            // rotation.push(new TWEEN.Tween(toolPlane.rotation).delay(1000).easing(TWEEN.Easing.Cubic.InOut).to({z:0}, 500));
            // rotation[rotation.length - 2].chain(rotation[rotation.length - 1]);
            rotation[rotation.length - 1].chain(rotation[0]);
            pointers[pointers.length - 1].chain(pointers[0]);

            rotation[0].start();
            pointers[1].start();

            sliders[sliders.length - 1].chain(sliders[0]);
            sliders[0].start();

            started = true;

        }

        panel.render(time);

    }

    init();

    return Object.freeze({
        toString: function(){return "AboutPanel"},
        render: render,
        renderTarget: panel.renderTarget,
        width: width,
        height: height,
        quad: panel.quad,
        checkBounds: panel.checkBounds,
        setBlur: panel.setBlur,
        setPosition: panel.setPosition
    });
}


text:
import { AgPromise } from '../utils';
import { ValueService } from '../valueService/valueService';
import { ColumnController } from '../columnController/columnController';
import { ColumnApi } from '../columnController/columnApi';
import { RowNode } from '../entities/rowNode';
import { Column } from '../entities/column';
import { Autowired, Bean, PostConstruct, PreDestroy } from '../context/context';
import { IRowModel } from '../interfaces/iRowModel';
import { ColumnEventType, Events, FilterChangedEvent, FilterModifiedEvent, FilterOpenedEvent } from '../events';
import { IFilterComp, IFilterParams } from '../interfaces/iFilter';
import { ColDef, GetQuickFilterTextParams } from '../entities/colDef';
import { GridApi } from '../gridApi';
import { UserComponentFactory } from '../components/framework/userComponentFactory';
import { ModuleNames } from '../modules/moduleNames';
import { ModuleRegistry } from '../modules/moduleRegistry';
import { forEach, some, every } from '../utils/array';
import { BeanStub } from '../context/beanStub';
import { convertToSet } from '../utils/set';
import { exists } from '../utils/generic';
import { mergeDeep, cloneObject } from '../utils/object';
import { loadTemplate } from '../utils/dom';

export type FilterRequestSource = 'COLUMN_MENU' | 'TOOLBAR' | 'NO_UI';

@Bean('filterManager')
export class FilterManager extends BeanStub {

    @Autowired('$compile') private $compile: any;
    @Autowired('$scope') private $scope: any;
    @Autowired('valueService') private valueService: ValueService;
    @Autowired('columnController') private columnController: ColumnController;
    @Autowired('rowModel') private rowModel: IRowModel;
    @Autowired('columnApi') private columnApi: ColumnApi;
    @Autowired('gridApi') private gridApi: GridApi;
    @Autowired('userComponentFactory') private userComponentFactory: UserComponentFactory;

    public static QUICK_FILTER_SEPARATOR = '\n';

    private allAdvancedFilters = new Map<string, FilterWrapper>();
    private activeAdvancedFilters: IFilterComp[] = [];
    private quickFilter: string | null = null;
    private quickFilterParts: string[] | null = null;
    private externalFilterPresent: boolean;

    // this is true when the grid is processing the filter change. this is used by the cell comps, so that they
    // don't flash when data changes due to filter changes. there is no need to flash when filter changes as the
    // user is in control, so doesn't make sense to show flashing changes. for example, go to main demo where
    // this feature is turned off (hack code to always return false for isSuppressFlashingCellsBecauseFiltering(), put in)
    // 100,000 rows and group by country. then do some filtering. all the cells flash, which is silly.
    private processingFilterChange = false;
    private allowShowChangeAfterFilter: boolean;

    @PostConstruct
    public init(): void {
        this.addManagedListener(this.eventService, Events.EVENT_ROW_DATA_CHANGED, this.onNewRowsLoaded.bind(this));
        this.addManagedListener(this.eventService, Events.EVENT_NEW_COLUMNS_LOADED, this.onNewColumnsLoaded.bind(this));

        this.quickFilter = this.parseQuickFilter(this.gridOptionsWrapper.getQuickFilterText());
        this.setQuickFilterParts();

        this.allowShowChangeAfterFilter = this.gridOptionsWrapper.isAllowShowChangeAfterFilter();

        // check this here, in case there is a filter from the start
        this.checkExternalFilter();
    }

    private setQuickFilterParts(): void {
        this.quickFilterParts = this.quickFilter ? this.quickFilter.split(' ') : null;
    }

    public setFilterModel(model: { [key: string]: any; }): void {
        const allPromises: AgPromise<void>[] = [];

        if (model) {
            // mark the filters as we set them, so any active filters left over we stop
            const modelKeys = convertToSet(Object.keys(model));

            this.allAdvancedFilters.forEach((filterWrapper, colId) => {
                const newModel = model[colId];

                allPromises.push(this.setModelOnFilterWrapper(filterWrapper.filterPromise!, newModel));
                modelKeys.delete(colId);
            });

            // at this point, processedFields contains data for which we don't have a filter working yet
            modelKeys.forEach(colId => {
                const column = this.columnController.getPrimaryColumn(colId);

                if (!column) {
                    console.warn('Warning ag-grid setFilterModel - no column found for colId ' + colId);
                    return;
                }

                const filterWrapper = this.getOrCreateFilterWrapper(column, 'NO_UI');

                allPromises.push(this.setModelOnFilterWrapper(filterWrapper.filterPromise!, model[colId]));
            });
        } else {
            this.allAdvancedFilters.forEach(filterWrapper => {
                allPromises.push(this.setModelOnFilterWrapper(filterWrapper.filterPromise!, null));
            });
        }

        AgPromise.all(allPromises).then(() => this.onFilterChanged());
    }

    private setModelOnFilterWrapper(filterPromise: AgPromise<IFilterComp>, newModel: any): AgPromise<void> {
        return new AgPromise<void>(resolve => {
            filterPromise.then(filter => {
                if (typeof filter!.setModel !== 'function') {
                    console.warn('Warning ag-grid - filter missing setModel method, which is needed for setFilterModel');
                    resolve();
                }

                (filter!.setModel(newModel) || AgPromise.resolve()).then(() => resolve());
            });
        });
    }

    public getFilterModel(): { [key: string]: any; } {
        const result: { [key: string]: any; } = {};

        this.allAdvancedFilters.forEach((filterWrapper, key) => {
            // because user can provide filters, we provide useful error checking and messages
            const filterPromise = filterWrapper.filterPromise;
            const filter = filterPromise!.resolveNow(null, promiseFilter => promiseFilter);

            if (filter == null) { return null; }

            if (typeof filter.getModel !== 'function') {
                console.warn('Warning ag-grid - filter API missing getModel method, which is needed for getFilterModel');
                return;
            }

            const model = filter.getModel();

            if (exists(model)) {
                result[key] = model;
            }
        });

        return result;
    }

    // returns true if any advanced filter (ie not quick filter) active
    public isAdvancedFilterPresent(): boolean {
        return this.activeAdvancedFilters.length > 0;
    }

    // called by:
    // 1) onFilterChanged()
    // 2) onNewRowsLoaded()
    private updateActiveFilters(): void {
        this.activeAdvancedFilters.length = 0;

        this.allAdvancedFilters.forEach(filterWrapper => {
            if (filterWrapper.filterPromise!.resolveNow(false, filter => filter!.isFilterActive())) {
                const resolvedPromise = filterWrapper.filterPromise!.resolveNow(null, filter => filter);
                this.activeAdvancedFilters.push(resolvedPromise!);
            }
        });
    }

    private updateFilterFlagInColumns(source: ColumnEventType, additionalEventAttributes?: any): void {
        this.allAdvancedFilters.forEach(filterWrapper => {
            const isFilterActive = filterWrapper.filterPromise!.resolveNow(false, filter => filter!.isFilterActive());

            filterWrapper.column.setFilterActive(isFilterActive, source, additionalEventAttributes);
        });
    }

    public isAnyFilterPresent(): boolean {
        return this.isQuickFilterPresent() || this.isAdvancedFilterPresent() || this.externalFilterPresent;
    }

    private doAdvancedFiltersPass(node: RowNode, filterToSkip?: IFilterComp): boolean {
        const { data } = node;

        for (let i = 0; i < this.activeAdvancedFilters.length; i++) {
            const filter = this.activeAdvancedFilters[i];

            if (filter == null || filter === filterToSkip) { continue; }

            if (typeof filter.doesFilterPass !== 'function') {
                // because users can do custom filters, give nice error message
                throw new Error('Filter is missing method doesFilterPass');
            }

            if (!filter.doesFilterPass({ node, data })) {
                return false;
            }
        }

        return true;
    }

    private parseQuickFilter(newFilter?: string): string | null {
        if (!exists(newFilter)) {
            return null;
        }

        if (!this.gridOptionsWrapper.isRowModelDefault()) {
            console.warn('ag-grid: quick filtering only works with the Client-Side Row Model');
            return null;
        }

        return newFilter.toUpperCase();
    }

    public setQuickFilter(newFilter: any): void {
        const parsedFilter = this.parseQuickFilter(newFilter);

        if (this.quickFilter !== parsedFilter) {
            this.quickFilter = parsedFilter;
            this.setQuickFilterParts();
            this.onFilterChanged();
        }
    }

    private checkExternalFilter(): void {
        this.externalFilterPresent = this.gridOptionsWrapper.isExternalFilterPresent();
    }

    public onFilterChanged(filterInstance?: IFilterComp, additionalEventAttributes?: any): void {
        this.updateActiveFilters();
        this.updateFilterFlagInColumns('filterChanged', additionalEventAttributes);
        this.checkExternalFilter();

        this.allAdvancedFilters.forEach(filterWrapper => {
            filterWrapper.filterPromise!.then(filter => {
                if (filter !== filterInstance && filter!.onAnyFilterChanged) {
                    filter!.onAnyFilterChanged();
                }
            });
        });

        const filterChangedEvent: FilterChangedEvent = {
            type: Events.EVENT_FILTER_CHANGED,
            api: this.gridApi,
            columnApi: this.columnApi
        };

        if (additionalEventAttributes) {
            mergeDeep(filterChangedEvent, additionalEventAttributes);
        }

        // because internal events are not async in ag-grid, when the dispatchEvent
        // method comes back, we know all listeners have finished executing.
        this.processingFilterChange = true;

        this.eventService.dispatchEvent(filterChangedEvent);

        this.processingFilterChange = false;
    }

    public isSuppressFlashingCellsBecauseFiltering(): boolean {
        // if user has elected to always flash cell changes, then always return false, otherwise we suppress flashing
        // changes when filtering
        return !this.allowShowChangeAfterFilter && this.processingFilterChange;
    }

    public isQuickFilterPresent(): boolean {
        return this.quickFilter !== null;
    }

    public doesRowPassOtherFilters(filterToSkip: IFilterComp, node: any): boolean {
        return this.doesRowPassFilter({ rowNode: node, filterInstanceToSkip: filterToSkip });
    }

    private doesRowPassQuickFilterNoCache(node: RowNode, filterPart: string): boolean {
        const columns = this.columnController.getAllColumnsForQuickFilter();

        return some(columns, column => {
            const part = this.getQuickFilterTextForColumn(column, node);

            return exists(part) && part.indexOf(filterPart) >= 0;
        });
    }

    private doesRowPassQuickFilterCache(node: RowNode, filterPart: string): boolean {
        if (!node.quickFilterAggregateText) {
            this.aggregateRowForQuickFilter(node);
        }

        return node.quickFilterAggregateText!.indexOf(filterPart) >= 0;
    }

    private doesRowPassQuickFilter(node: RowNode): boolean {
        const usingCache = this.gridOptionsWrapper.isCacheQuickFilter();

        // each part must pass, if any fails, then the whole filter fails
        return every(this.quickFilterParts!, part =>
            usingCache ? this.doesRowPassQuickFilterCache(node, part) : this.doesRowPassQuickFilterNoCache(node, part)
        );
    }

    public doesRowPassFilter(params: {
        rowNode: RowNode,
        filterInstanceToSkip?: IFilterComp;
    }): boolean {
        // the row must pass ALL of the filters, so if any of them fail,
        // we return true. that means if a row passes the quick filter,
        // but fails the column filter, it fails overall

        // first up, check quick filter
        if (this.isQuickFilterPresent() && !this.doesRowPassQuickFilter(params.rowNode)) {
            return false;
        }

        // secondly, give the client a chance to reject this row
        if (this.externalFilterPresent && !this.gridOptionsWrapper.doesExternalFilterPass(params.rowNode)) {
            return false;
        }

        // lastly, check our internal advanced filter
        if (this.isAdvancedFilterPresent() && !this.doAdvancedFiltersPass(params.rowNode, params.filterInstanceToSkip)) {
            return false;
        }

        // got this far, all filters pass
        return true;
    }

    private getQuickFilterTextForColumn(column: Column, node: RowNode): string {
        let value = this.valueService.getValue(column, node, true);
        const colDef = column.getColDef();

        if (colDef.getQuickFilterText) {
            const params: GetQuickFilterTextParams = {
                value,
                node,
                data: node.data,
                column,
                colDef,
                context: this.gridOptionsWrapper.getContext()
            };

            value = colDef.getQuickFilterText(params);
        }

        return exists(value) ? value.toString().toUpperCase() : null;
    }

    private aggregateRowForQuickFilter(node: RowNode): void {
        const stringParts: string[] = [];
        const columns = this.columnController.getAllColumnsForQuickFilter();

        forEach(columns, column => {
            const part = this.getQuickFilterTextForColumn(column, node);

            if (exists(part)) {
                stringParts.push(part);
            }
        });

        node.quickFilterAggregateText = stringParts.join(FilterManager.QUICK_FILTER_SEPARATOR);
    }

    private onNewRowsLoaded(source: ColumnEventType): void {
        this.allAdvancedFilters.forEach(filterWrapper => {
            filterWrapper.filterPromise!.then(filter => {
                if (filter!.onNewRowsLoaded) {
                    filter!.onNewRowsLoaded();
                }
            });
        });

        this.updateFilterFlagInColumns(source);
        this.updateActiveFilters();
    }

    private createValueGetter(column: Column): (node: RowNode) => any {
        return node => this.valueService.getValue(column, node, true);
    }

    public getFilterComponent(column: Column, source: FilterRequestSource, createIfDoesNotExist = true): AgPromise<IFilterComp> | null {
        if (createIfDoesNotExist) {
            return this.getOrCreateFilterWrapper(column, source).filterPromise;
        }

        const filterWrapper = this.cachedFilter(column);

        return filterWrapper ? filterWrapper.filterPromise : null;
    }

    public isFilterActive(column: Column): boolean {
        const filterWrapper = this.cachedFilter(column);

        return !!filterWrapper && filterWrapper.filterPromise!.resolveNow(false, filter => filter!.isFilterActive());
    }

    public getOrCreateFilterWrapper(column: Column, source: FilterRequestSource): FilterWrapper {
        let filterWrapper = this.cachedFilter(column);

        if (!filterWrapper) {
            filterWrapper = this.createFilterWrapper(column, source);
            this.allAdvancedFilters.set(column.getColId(), filterWrapper);
        } else if (source !== 'NO_UI') {
            this.putIntoGui(filterWrapper, source);
        }

        return filterWrapper;
    }

    public cachedFilter(column: Column): FilterWrapper | undefined {
        return this.allAdvancedFilters.get(column.getColId());
    }

    private createFilterInstance(column: Column, $scope: any): AgPromise<IFilterComp> | null {
        const defaultFilter =
            ModuleRegistry.isRegistered(ModuleNames.SetFilterModule) ? 'agSetColumnFilter' : 'agTextColumnFilter';

        const colDef = column.getColDef();

        let filterInstance: IFilterComp;

        const params: IFilterParams = {
            ...this.createFilterParams(column, colDef, $scope),
            filterModifiedCallback: () => {
                const event: FilterModifiedEvent = {
                    type: Events.EVENT_FILTER_MODIFIED,
                    api: this.gridApi,
                    columnApi: this.columnApi,
                    column,
                    filterInstance
                };

                this.eventService.dispatchEvent(event);
            },
            filterChangedCallback: (additionalEventAttributes?: any) =>
                this.onFilterChanged(filterInstance, additionalEventAttributes),
            doesRowPassOtherFilter: node => this.doesRowPassOtherFilters(filterInstance, node),
        };

        const res = this.userComponentFactory.newFilterComponent(colDef, params, defaultFilter);

        if (res) {
            res.then(r => filterInstance = r!);
        }

        return res;
    }

    public createFilterParams(column: Column, colDef: ColDef, $scope: any = null): IFilterParams {
        const params: IFilterParams = {
            api: this.gridOptionsWrapper.getApi()!,
            column,
            colDef: cloneObject(colDef),
            rowModel: this.rowModel,
            filterChangedCallback: () => { },
            filterModifiedCallback: () => { },
            valueGetter: this.createValueGetter(column),
            context: this.gridOptionsWrapper.getContext(),
            doesRowPassOtherFilter: () => true,
        };

        // hack in scope if using AngularJS
        if ($scope) {
            (params as any).$scope = $scope;
        }

        return params;
    }

    private createFilterWrapper(column: Column, source: FilterRequestSource): FilterWrapper {
        const filterWrapper: FilterWrapper = {
            column: column,
            filterPromise: null,
            scope: null as any,
            compiledElement: null,
            guiPromise: AgPromise.resolve(null)
        };

        filterWrapper.scope = this.gridOptionsWrapper.isAngularCompileFilters() ? this.$scope.$new() : null;
        filterWrapper.filterPromise = this.createFilterInstance(column, filterWrapper.scope);

        if (filterWrapper.filterPromise) {
            this.putIntoGui(filterWrapper, source);
        }

        return filterWrapper;
    }

    private putIntoGui(filterWrapper: FilterWrapper, source: FilterRequestSource): void {
        const eFilterGui = document.createElement('div');

        eFilterGui.className = 'ag-filter';

        filterWrapper.guiPromise = new AgPromise<HTMLElement>(resolve => {
            filterWrapper.filterPromise!.then(filter => {
                let guiFromFilter = filter!.getGui();

                if (!exists(guiFromFilter)) {
                    console.warn(`getGui method from filter returned ${guiFromFilter}, it should be a DOM element or an HTML template string.`);
                }

                // for backwards compatibility with Angular 1 - we
                // used to allow providing back HTML from getGui().
                // once we move away from supporting Angular 1
                // directly, we can change this.
                if (typeof guiFromFilter === 'string') {
                    guiFromFilter = loadTemplate(guiFromFilter as string);
                }

                eFilterGui.appendChild(guiFromFilter);

                if (filterWrapper.scope) {
                    const compiledElement = this.$compile(eFilterGui)(filterWrapper.scope);
                    filterWrapper.compiledElement = compiledElement;
                    window.setTimeout(() => filterWrapper.scope.$apply(), 0);
                }

                resolve(eFilterGui);

                this.eventService.dispatchEvent({
                    type: Events.EVENT_FILTER_OPENED,
                    column: filterWrapper.column,
                    source,
                    eGui: eFilterGui,
                    api: this.gridApi,
                    columnApi: this.columnApi
                } as FilterOpenedEvent);
            });
        });
    }

    private onNewColumnsLoaded(): void {
        let atLeastOneFilterGone = false;

        this.allAdvancedFilters.forEach(filterWrapper => {
            const oldColumn = !this.columnController.getPrimaryColumn(filterWrapper.column);

            if (oldColumn) {
                atLeastOneFilterGone = true;
                this.disposeFilterWrapper(filterWrapper, 'filterDestroyed');
            }
        });

        if (atLeastOneFilterGone) {
            this.onFilterChanged();
        }
    }

    // destroys the filter, so it not longer takes part
    public destroyFilter(column: Column, source: ColumnEventType = 'api'): void {
        const filterWrapper = this.allAdvancedFilters.get(column.getColId());

        if (filterWrapper) {
            this.disposeFilterWrapper(filterWrapper, source);
            this.onFilterChanged();
        }
    }

    private disposeFilterWrapper(filterWrapper: FilterWrapper, source: ColumnEventType): void {
        filterWrapper.filterPromise!.then(filter => {
            (filter!.setModel(null) || AgPromise.resolve()).then(() => {
                this.getContext().destroyBean(filter);

                filterWrapper.column.setFilterActive(false, source);

                if (filterWrapper.scope) {
                    if (filterWrapper.compiledElement) {
                        filterWrapper.compiledElement.remove();
                    }

                    filterWrapper.scope.$destroy();
                }

                this.allAdvancedFilters.delete(filterWrapper.column.getColId());
            });
        });
    }

    @PreDestroy
    protected destroy() {
        super.destroy();
        this.allAdvancedFilters.forEach(filterWrapper => this.disposeFilterWrapper(filterWrapper, 'filterDestroyed'));
    }
}

export interface FilterWrapper {
    compiledElement: any;
    column: Column;
    filterPromise: AgPromise<IFilterComp> | null;
    scope: any;
    guiPromise: AgPromise<HTMLElement | null>;
}


text:
title: Rounded Square Roots
localeTitle: جذور مربعة دائرية
---
## مشكلة 255: جذور مربعة دائرية

هذا هو كعب. [ساعد مجتمعنا على توسيعه](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/project-euler/problem-255-rounded-square-roots/index.md) .

[سيساعدك دليل النمط السريع هذا على ضمان قبول طلب السحب](https://github.com/freecodecamp/guides/blob/master/README.md) .


text:
<?php
include ('../modSession.php')
?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="title" content="Sistema de Administración de Datos Univirtual">
    <meta name="description" content="">
    <meta name="author" content="Univirtual">

    <title>Gestión Usuario</title>

    <?php require("transversales/encabezado.php"); ?>

    <?php
    require ('funcionesUnivirtual.php');
    ?>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    Toggle navigation

                </button>
                Total HUB

                    <?php
                        include ('modMenuDerecha.php');
                    ?>

                    <?php
                        include ('modMenuPpal.php');
                    ?>

Administración de Usuarios

                <fieldset>
                <legend>Registrar Usuario</legend>

                        <form method="post" action="guardaUsuario.php" onsubmit="return validarDatos()">

                        Documento de Identidad
                        <input type="text" name="documentoUsuarioSolicitado" id="documentoUsuarioSolicitado" class="form-control">

                         País de Expedición del Documento
                        <select name="paisSolicitado" id="paisSolicitado" class='form-control estilo-select2' onchange="cargaDepartamento()">
                            <option></option>
                            <?php

                                    $total1 =new crudPais();
                                    $total1->conectarDB();
                                    $total1->selectPais();
                                ?>
                        </select>

                         Departamento de Expedición
                        <select name="departamentoSolicitado" id="departamentoSolicitado" class="form-control estilo-select2" onchange="cargaCiudad()">
                            <option></option>

                        </select>

                        Ciudad de Expedición del Documento
                        <select name="ciudadSolicitado" id="ciudadSolicitado" class="form-control estilo-select2">
                            <option></option>

                        </select>

                        Tipo de Documento
                        <select name="tipoDocumentoUsuarioSolicitado" id="tipoDocumentoUsuarioSolicitado" class="form-control estilo-select2">
                            <option></option>
                            <?php
                                    $total1 =new crudTipodocumento();
                                    $total1->conectarDB();
                                    $total1->selectTipodocumento();
                            ?>
                        </select>

                        Nombres Completos
                        <input type="text" name="nombresUsuarioSolicitado" id="nombresUsuarioSolicitado" class="form-control" >
                        Apellidos Completos
                        <input type="text" name="apellidoUsuarioSolicitado" id="apellidoUsuarioSolicitado"class="form-control" >

                        Correo Electrónico
                        <input type="text" name="mailUsuarioSolicitado" id="mailUsuarioSolicitado" class="form-control" >

                        Teléfono/Celular
                        <input type="text" name="telefonoUsuarioSolicitado" id="telefonoUsuarioSolicitado" class="form-control" >

                        Tipo de Usuario
                        <select name="tipoUsuarioSolicitado" id="tipoUsuarioSolicitado" class="form-control estilo-select2">
                            <option></option>
                            <?php
                                    $total1 =new crudTipousuario();
                                    $total1->conectarDB();
                                    $total1->selectTipousuario();
                            ?>
                        </select>
                        Estado
                        <select name="estadoUsuarioSolicitado" id="estadoUsuarioSolicitado" class="form-control estilo-select2">
                            <option></option>
                            <?php
                                    $total1 =new crudEstado();
                                    $total1->conectarDB();
                                    $total1->selectEstado();
                            ?>
                        </select>

                        Contraseña
                        <input type="password" name="contraseniaUsuarioSolicitado" id="contraseniaUsuarioSolicitado" class="form-control" >

                        <input type="submit" value="Guardar Usuario" class="btn btn-success" >
                        </form>

                </fieldset>

                            Tabla Usuarios

                                        Documento
                                        Nombres y Apellidos
                                        Mail
                                        Teléfono
                                        Tipo de Usuario
                                        Estado

                                        Fecha de Registro
                                        Fecha Última Actualización

                                    <?php
                                    $total1=new crudUsuario();
                                    $total1->conectarDB();
                                    $total1->listaUsuario();
                                    ?>

    <?php
    require("transversales/select2.php");
    require("transversales/foot.php");
    ?>


text:
"""This example creates a mobile display creative in a given advertiser or
campaign. If no campaign is specified then the creative is created in the
advertiser provided. To get assets file names, run create_html_asset.py and
create_image_asset.py. To get a size ID, run get_size.py. To get a creative
type ID, run get_creative_type.py.

Tags: creative.saveCreative
"""

__author__ = 'api.jdilallo@gmail.com (Joseph DiLallo)'

import os
import sys
sys.path.insert(0, os.path.join('..', '..', '..', '..'))

# Import appropriate classes from the client library.
from adspygoogle import DfaClient

CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE'
ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
CREATIVE_NAME = 'INSERT_CREATIVE_NAME_HERE'
MOBILE_ASSET_FILE_NAME = 'INSERT_MOBILE_ASSET_FILE_NAME_HERE'

def main(client, campaign_id, advertiser_id, creative_name,
         mobile_asset_file_name):
  # Initialize appropriate service.
  creative_service = client.GetCreativeService(
      'https://advertisersapitest.doubleclick.net', 'v1.20')

  # Construct and save mobile creative.
  mobile_creative = {
      'name': creative_name,
      'advertiserId': advertiser_id,
      'typeId': '30',
      'archived': 'false',
      'creativeAssets': [{
          'assetFilename': mobile_asset_file_name
      }]
  }

  # If you don't specify an xsi_type for a creative, the client library will try
  # to infer it from the typeId.
  result = creative_service.SaveCreative(mobile_creative, campaign_id)[0]

  # Display results.
  print 'Mobile creative with ID \'%s\' was created.' % result['id']

if __name__ == '__main__':
  # Initialize client object.
  client = DfaClient(path=os.path.join('..', '..', '..', '..'))
  main(client, CAMPAIGN_ID, ADVERTISER_ID, CREATIVE_NAME,
       MOBILE_ASSET_FILE_NAME)


text:
package org.apache.dubbo.echo;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.service.DemoService;
import org.apache.dubbo.service.DemoServiceImpl;

import com.alibaba.dubbo.rpc.service.EchoService;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class EchoServiceTest {

    @Test
    public void testEcho() {
        DemoService server = new DemoServiceImpl();
        ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
        Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
        URL url = URL.valueOf("dubbo://127.0.0.1:5342/" + DemoService.class.getName() + "?version=1.0.0");
        Exporter<DemoService> exporter = protocol.export(proxyFactory.getInvoker(server, DemoService.class, url));
        Invoker<DemoService> invoker = protocol.refer(DemoService.class, url);
        EchoService client = (EchoService) proxyFactory.getProxy(invoker);
        Object result = client.$echo("haha");
        Assertions.assertEquals("haha", result);

        org.apache.dubbo.rpc.service.EchoService newClient = (org.apache.dubbo.rpc.service.EchoService) proxyFactory.getProxy(invoker);
        Object res = newClient.$echo("hehe");
        Assertions.assertEquals("hehe", res);
        invoker.destroy();
        exporter.unexport();
    }
}


text:
A (beta) GUI for [Logging](https://github.com/TwP/logging) to set the log levels dynamically.

![screenshot](https://github.com/bukowskis/logging-hq/raw/master/doc/screenshot.png)

# Installation

```bash
gem install logging-hq  # This doesn't work yet, you'll have to fetch it from github
````

# Usage

To test it locally, just hit something like `bundle install && rackup`.

In Rails, you could use this:

```ruby
# routes.rb
require 'logging/hq/server'

# ...
mount Logging::HQ::Server.new, at: '/logging', as: :logging
# ...
````


text:
/**
 * Classe base para os parsers de linguagem
 * Metodos devem ser reescritos na classe herdeira
 */

/**
 * Recebe um JSON com um pattern da linguagem
 * @type {Parser}
 */
var Parser = new function (patternJSON) {
   this._Pattern = JSON.parse(patternJSON);
};

/**
 * Metodo para parse de 'Classes'
 * @param classJson
 */
Parser.prototype.parseClass = function (classJson) {
   console.log("Override this method in child class");
};

/**
 * Metodo para parse dos atributos de classe
 * @param attributesJson
 */
Parser.prototype.parseClassAttributes = function (attributesJson) {
   console.log("Override this method in child class");
};

/**
 * Metodo para parse de documentacao de Classe
 * @param classDocsJson
 */
Parser.prototype.parseClassDocs = function (classDocsJson) {
   console.log("Override this method in child class");
};

/**
 * Metodo para parse de 'Metodos'
 * @param methodJson
 */
Parser.prototype.parseMethod = function (methodJson) {
   console.log("Override this method in child class");
};

/**
 * Metodo para parse de documentacao de Metodo
 * @param methodDocsJson
 */
Parser.prototype.parseMethodDocs = function (methodDocsJson) {
   console.log("Override this method in child class");
};


text:
@interface PodsDummy_CHSlideSwitchView : NSObject
@end
@implementation PodsDummy_CHSlideSwitchView
@end


text:
package com.twitter.concurrent

import com.twitter.util._
import java.util.ArrayDeque
import java.util.concurrent.RejectedExecutionException
import scala.collection.JavaConverters._
import scala.util.control.NonFatal

/**
 * An AsyncSemaphore is a traditional semaphore but with asynchronous
 * execution.
 *
 * Grabbing a permit returns a `Future[Permit]`.
 *
 * Basic usage:
 * {{{
 *   val semaphore = new AsyncSemaphore(n)
 *   ...
 *   semaphore.acquireAndRun() {
 *     somethingThatReturnsFutureT()
 *   }
 * }}}
 *
 * Calls to acquire() and acquireAndRun are serialized, and tickets are
 * given out fairly (in order of arrival).
 *
 * @see [[AsyncMutex]] for a mutex version.
 */
class AsyncSemaphore protected (initialPermits: Int, maxWaiters: Option[Int]) { self =>
  import AsyncSemaphore._

  /**
   * Constructs a semaphore with no limit on the max number
   * of waiters for permits.
   *
   * @param initialPermits must be positive
   */
  def this(initialPermits: Int) = this(initialPermits, None)

  /**
   * Constructs a semaphore with `maxWaiters` as the limit on the
   * number of waiters for permits.
   *
   * @param initialPermits must be positive
   * @param maxWaiters must be non-negative
   */
  def this(initialPermits: Int, maxWaiters: Int) = this(initialPermits, Some(maxWaiters))

  require(maxWaiters.getOrElse(0) >= 0, s"maxWaiters must be non-negative: $maxWaiters")
  require(initialPermits > 0, s"initialPermits must be positive: $initialPermits")

  // access to `closed`, `waitq`, and `availablePermits` is synchronized
  // by locking on `self`
  private[this] var closed: Option[Throwable] = None
  private[this] val waitq = new ArrayDeque[Promise[Permit]]
  private[this] var availablePermits = initialPermits

  private[this] val semaphorePermit = new Permit {
    /**
     * Indicate that you are done with your Permit.
     */
    override def release(): Unit = self.synchronized {
      val next = waitq.pollFirst()
      if (next != null)
        next.setValue(this)
      else
        availablePermits += 1
    }
  }

  private[this] val futurePermit = Future.value(semaphorePermit)

  def numWaiters: Int = self.synchronized(waitq.size)
  def numInitialPermits: Int = initialPermits
  def numPermitsAvailable: Int = self.synchronized(availablePermits)

  /**
   * Fail the semaphore and stop it from distributing further permits. Subsequent
   * attempts to acquire a permit fail with `exc`. This semaphore's queued waiters
   * are also failed with `exc`.
   */
  def fail(exc: Throwable): Unit = self.synchronized {
    closed = Some(exc)
    val drained = waitq.asScala.toList
    // delegate dequeuing to the interrupt handler defined in #acquire
    drained.foreach(_.raise(exc))
  }

  /**
   * Acquire a [[Permit]], asynchronously. Be sure to `permit.release()` in a
   *
   * - `finally` block of your `onSuccess` callback
   * - `ensure` block of your future chain
   *
   * Interrupting this future is only advisory, and will not release the permit
   * if the future has already been satisfied.
   *
   * @note This method always return the same instance of [[Permit]].
   *
   * @return a `Future[Permit]` when the `Future` is satisfied, computation can proceed,
   *         or a Future.Exception[RejectedExecutionException]` if the configured maximum
   *         number of waiters would be exceeded.
   */
  def acquire(): Future[Permit] = self.synchronized {
    if (closed.isDefined)
      return Future.exception(closed.get)

    if (availablePermits > 0) {
      availablePermits -= 1
      futurePermit
    } else {
      maxWaiters match {
        case Some(max) if waitq.size >= max =>
          MaxWaitersExceededException
        case _ =>
          val promise = new Promise[Permit]
          promise.setInterruptHandler { case t: Throwable =>
            self.synchronized {
              if (promise.updateIfEmpty(Throw(t)))
                waitq.remove(promise)
            }
          }
          waitq.addLast(promise)
          promise
      }
    }
  }

  /**
   * Execute the function asynchronously when a permit becomes available.
   *
   * If the function throws a non-fatal exception, the exception is returned as part of the Future.
   * For all exceptions, the permit would be released before returning.
   *
   * @return a Future[T] equivalent to the return value of the input function. If the configured
   *         maximum value of waitq is reached, Future.Exception[RejectedExecutionException] is
   *         returned.
   */
  def acquireAndRun[T](func: => Future[T]): Future[T] =
    acquire().flatMap { permit =>
      val f = try func catch {
        case NonFatal(e) =>
          Future.exception(e)
        case e: Throwable =>
          permit.release()
          throw e
      }
      f.ensure {
        permit.release()
      }
    }

  /**
   * Execute the function when a permit becomes available.
   *
   * If the function throws an exception, the exception is returned as part of the Future.
   * For all exceptions, the permit would be released before returning.
   *
   * @return a Future[T] equivalent to the return value of the input function. If the configured
   *         maximum value of waitq is reached, Future.Exception[RejectedExecutionException] is
   *         returned.
   */
  def acquireAndRunSync[T](func: => T): Future[T] =
    acquire().flatMap { permit =>
      Future(func).ensure {
        permit.release()
      }
    }
  }

object AsyncSemaphore {
  private val MaxWaitersExceededException =
    Future.exception(new RejectedExecutionException("Max waiters exceeded"))
}


text:
<?php

namespace Admin\Entity;

use Core\Test\ModelTestCase;
use \Admin\Entity\Servico;
use \Admin\Provider\Add;

require_once __DIR__ . '/../Provider/Add.php';

/**
* @group Model
* @author Harold C. S. Becker
*/
class ServicoTest extends ModelTestCase
{
    use Add;

    /**
    *
    * @return \Zend\InputFilter\InputFilter
    */
    public function testGetInputFilter()
    {
        $servico = new Servico();
        $filtro = $servico->getInputFilter();
        $this->assertInstanceOf("Zend\InputFilter\InputFilter", $filtro);

        return $filtro;
    }

    /**
    * @depends testGetInputFilter
    * @param Zend\InputFilter\InputFilter $filtro
    */
    public function testInputFilterValid($filtro)
    {
        $this->assertEquals(4, $filtro->count());
        $this->assertTrue($filtro->has('id'));
        $this->assertTrue($filtro->has('hora'));
        $this->assertTrue($filtro->has('taxa'));
        $this->assertTrue($filtro->has('especificacao'));
    }

    /**
    * Teste de Inserção válida no banco
    *
    */
    public function testInsert()
    {
        $servico = $this->addServico();
        $this->assertEquals(1, $servico->getId());
        $this->assertEquals(10, $servico->getHora());
        $this->assertEquals(10.0, $servico->getTaxa());
        $this->assertEquals("ESPECIFICAÇÃO", $servico->getEspecificacao());
    }

    /**
    * Teste de atualização válido no banco de dados
    *
    */
    public function testUpdate()
    {
        $servico = $this->addServico();
        $servico->setHora(9);
        $servico->setTaxa(15.90);
        $servico->setEspecificacao("update data");
        $this->getEntityManager()->persist($servico);
        $this->getEntityManager()->flush();
        $this->assertEquals(9, $servico->getHora());
        $this->assertEquals(15.90, $servico->getTaxa());
        $this->assertEquals("UPDATE DATA", $servico->getEspecificacao());
    }

    /**
    * Teste de remoção válida no banco de dados
    *
    */
    public function testDelete()
    {
        $servico = $this->addServico();
        $query = $this->getEntityManager()
                ->createQuery("select s from Admin\Entity\Servico s");
        $result = $query->getResult();
        $this->assertEquals(1, count($result));
        $this->getEntityManager()->remove($servico);
        $this->getEntityManager()->flush();
        $query = $this->getEntityManager()
                ->createQuery("select s from Admin\Entity\Servico s");
        $result = $query->getResult();
        $this->assertEquals(0, count($result));
    }

    /**
    * Teste uma inserção inválida no banco de dados
    *
    * @expectedException Core\Model\EntityException
    */
    public function testInvalidInsert()
    {
        $servico = new Servico();
        $servico->setTaxa(null);
        $this->getEntityManager()->persist($servico);
        $this->getEntityManager()->flush();
    }

}


text:
package org.apache.dubbo.rpc.protocol.injvm;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.protocol.AbstractProtocol;
import org.apache.dubbo.rpc.support.ProtocolUtils;

import java.util.Map;

import static org.apache.dubbo.rpc.Constants.SCOPE_KEY;
import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL;
import static org.apache.dubbo.rpc.Constants.SCOPE_REMOTE;
import static org.apache.dubbo.rpc.Constants.GENERIC_KEY;
import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL;

/**
 * InjvmProtocol
 */
public class InjvmProtocol extends AbstractProtocol implements Protocol {

    public static final String NAME = LOCAL_PROTOCOL;

    public static final int DEFAULT_PORT = 0;
    private static InjvmProtocol INSTANCE;

    public InjvmProtocol() {
        INSTANCE = this;
    }

    public static InjvmProtocol getInjvmProtocol() {
        if (INSTANCE == null) {
            ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(InjvmProtocol.NAME); // load
        }
        return INSTANCE;
    }

    static Exporter<?> getExporter(Map<String, Exporter<?>> map, URL key) {
        Exporter<?> result = null;

        if (!key.getServiceKey().contains("*")) {
            result = map.get(key.getServiceKey());
        } else {
            if (CollectionUtils.isNotEmptyMap(map)) {
                for (Exporter<?> exporter : map.values()) {
                    if (UrlUtils.isServiceKeyMatch(key, exporter.getInvoker().getUrl())) {
                        result = exporter;
                        break;
                    }
                }
            }
        }

        if (result == null) {
            return null;
        } else if (ProtocolUtils.isGeneric(
                result.getInvoker().getUrl().getParameter(GENERIC_KEY))) {
            return null;
        } else {
            return result;
        }
    }

    @Override
    public int getDefaultPort() {
        return DEFAULT_PORT;
    }

    @Override
    public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException {
        return new InjvmExporter<T>(invoker, invoker.getUrl().getServiceKey(), exporterMap);
    }

    @Override
    public <T> Invoker<T> protocolBindingRefer(Class<T> serviceType, URL url) throws RpcException {
        return new InjvmInvoker<T>(serviceType, url, url.getServiceKey(), exporterMap);
    }

    public boolean isInjvmRefer(URL url) {
        String scope = url.getParameter(SCOPE_KEY);
        // Since injvm protocol is configured explicitly, we don't need to set any extra flag, use normal refer process.
        if (SCOPE_LOCAL.equals(scope) || (url.getParameter(LOCAL_PROTOCOL, false))) {
            // if it's declared as local reference
            // 'scope=local' is equivalent to 'injvm=true', injvm will be deprecated in the future release
            return true;
        } else if (SCOPE_REMOTE.equals(scope)) {
            // it's declared as remote reference
            return false;
        } else if (url.getParameter(GENERIC_KEY, false)) {
            // generic invocation is not local reference
            return false;
        } else if (getExporter(exporterMap, url) != null) {
            // by default, go through local reference if there's the service exposed locally
            return true;
        } else {
            return false;
        }
    }
}