text:
<?php

use Behat\Behat\Context\Step;
use Behat\MinkExtension\Context\MinkContext;
use PHPUnit_Framework_Assert as Assert;

require_once(__DIR__ . '/../../../../../Flowpack.Behat/Tests/Behat/FlowContext.php');

/**
 * Features context for Roketi Panel Behat Tests
 */
class FeatureContext extends MinkContext {
	/**
	 * @var \TYPO3\Flow\Object\ObjectManagerInterface
	 */
	protected $objectManager;

	/**
	 * @var \Flowpack\Behat\Tests\Behat\FlowContext
	 */
	protected $flowContext;

	/**
	 * @var \TYPO3\Flow\Security\AccountRepository
	 */
	protected $accountRepository;

	/**
	 * Initializes the context
	 *
	 * @param array $parameters Context parameters (configured through behat.yml)
	 */
	public function __construct(array $parameters) {
		$this->useContext('flow', new \Flowpack\Behat\Tests\Behat\FlowContext($parameters));
		$this->flowContext = $this->getSubcontext('flow');
		$this->objectManager = $this->flowContext->getObjectManager();
		$this->accountRepository = $this->objectManager->get('TYPO3\Flow\Security\AccountRepository');
	}

	/**
	 * @Given /^I am not logged in$/
	 */
	public function iAmNotLoggedIn() {
		// Do nothing, every scenario has a new session
	}

	/**
	 * @Given /^I am logged in as "([^"]*)" with password "([^"]*)"$/
	 */
	public function iAmLoggedInAsUserWithPassword($username, $password) {
		$user = $this->accountRepository->findByAccountIdentifierAndAuthenticationProviderName($username, 'DefaultProvider');
		if (!$user) {
			$this->flowContext->iRunTheCommand('roketi.panel:setup:createadminuser --username ' . $username . ' --password ' . $password);
		}
		$this->visit('/');
		$this->fillField('username', $username);
		$this->fillField('password', $password);
		$this->pressButton('login');
	}

	/**
	 * @Then /^I should see a login form$/
	 */
	public function iShouldSeeALoginForm() {
		$this->assertSession()->fieldExists('username');
		$this->assertSession()->fieldExists('password');
	}
	/**
	 * @Given /^I should be logged in as "([^"]*)"$/
	 */
	public function iShouldBeLoggedInAs($name) {
		$this->assertSession()->pageTextContains('Signed in as ' . $name);
	}

	/**
	 * @Then /^I should not be logged in$/
	 */
	public function iShouldNotBeLoggedIn() {
		if ($this->getSession()->getPage()->findButton('logout')) {
			Assert::fail('"Logout" Button not expected');
		}
	}

	/**
	 * @Given /^there is a domain "([^"]*)"$/
	 */
	public function thereIsADomain($domainName) {
		return array(
			new Step\When('I go to "/domain/new"'),
			new Step\When('I fill in "' . $domainName . '" for "newDomainName"'),
			new Step\Then('I press "Create Domain"'),
		);
	}
}


text:
package org.vaadin.viritin.label;

import com.vaadin.shared.ui.label.ContentMode;
import com.vaadin.ui.Label;
import org.apache.commons.io.IOUtils;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;
import org.markdown4j.Markdown4jProcessor;

import java.io.IOException;
import java.io.InputStream;

/**
 * XSS safe rich text label with either Markdown syntax or raw html (sanitized
 * with Jsoup).
 *
 * By default jsoups Whitelist.relaxed is used for sanitizing. This can be
 * overridden by returning custom whitelist with getWhitelist method.
 */
public class RichText extends Label {

    transient private Whitelist whitelist;
    private String richText;

    public RichText() {
    }

    public RichText(String content) {
        setRichText(content);
    }

    public RichText withMarkDown(String markdown) {
        try {
            return setRichText(new Markdown4jProcessor().process(markdown));
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    public RichText withMarkDown(InputStream markdown) {
        try {
            return setRichText(new Markdown4jProcessor().process(markdown));
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    public RichText withSafeHtml(String html) {
        return setRichText(html);
    }

    public RichText withSafeHtml(InputStream markdown) {
        try {
            return setRichText(IOUtils.toString(markdown, "UTF-8"));
        } catch (IOException ex) {
            throw new RuntimeException("Input stream coulnd't be read!", ex);
        }
    }

    /**
     * Only replaces all new line characters with
, but no Markdown
     * processing.
     *
     * @param text the text value to be displayed
     * @return the object itself for further configuration
     */
    public RichText withNewLines(String text) {
        return setRichText(text.replaceAll("(\\r|\\n|\\r\\n)+", "
"));
    }

    public Whitelist getWhitelist() {
        if (whitelist == null) {
            return Whitelist.relaxed();
        }
        return whitelist;
    }

    /**
     *
     * @param whitelist the whitelist used for sanitizing the rich text content
     * @return the object itself for further configuration
     * @deprecated Whitelist is not serializable. Override getWhitelist instead
     * if you need to support serialiazation
     */
    @Deprecated
    public RichText setWhitelist(Whitelist whitelist) {
        this.whitelist = whitelist;
        markAsDirty();
        return this;
    }

    @Override
    public void setValue(String newStringValue) {
        setRichText(newStringValue);
    }

    public String getText() {
        return richText;
    }

    public RichText setRichText(String text) {
        this.richText = text;
        markAsDirty();
        return this;
    }

    @Override
    public void beforeClientResponse(boolean initial) {
        setContentMode(ContentMode.HTML);
        super.setValue(Jsoup.clean(richText, getWhitelist()));
        super.beforeClientResponse(initial);
    }

    public RichText withMarkDownResource(String resourceName) {
        return withMarkDown(getClass().getResourceAsStream(resourceName));
    }

    public RichText withSafeHtmlResource(String resourceName) {
        return withSafeHtml(getClass().getResourceAsStream(resourceName));
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * Created by hajarboulhdir on 02/10/2016.
 */
public abstract class Shape2D extends Shape implements Translatable2D{
    public  Point2D refPoint;
    public abstract double perimeter();

    public Point2D getRefPoint() {
        return refPoint;
    }
}


text:
"""
@package mi.instrument.noaa.ooicore.driver
@file marine-integrations/mi/instrument/noaa/ooicore/driver.py
@author Pete Cable
@brief BOTPT
Release notes:
"""

import re
import time
import datetime

import ntplib
from mi.core.driver_scheduler import DriverSchedulerConfigKey, TriggerType
from mi.core.instrument.data_particle import DataParticleKey, DataParticleValue
from mi.core.instrument.protocol_param_dict import ParameterDictVisibility, ParameterDictType
from mi.core.common import BaseEnum, Units, Prefixes
from mi.core.instrument.chunker import StringChunker
from mi.core.instrument.instrument_fsm import ThreadSafeFSM
from mi.core.instrument.instrument_protocol import CommandResponseInstrumentProtocol, InitializationType
from mi.core.instrument.instrument_driver import DriverEvent
from mi.core.instrument.instrument_driver import SingleConnectionInstrumentDriver
from mi.core.instrument.instrument_driver import DriverParameter
from mi.core.instrument.instrument_driver import DriverConfigKey
from mi.core.instrument.instrument_driver import DriverAsyncEvent
from mi.core.instrument.instrument_driver import DriverProtocolState
from mi.core.exceptions import InstrumentParameterException
from mi.core.exceptions import InstrumentProtocolException
from mi.core.exceptions import InstrumentDataException
from mi.core.instrument.driver_dict import DriverDictKey
import mi.instrument.noaa.botpt.ooicore.particles as particles
import mi.core.log

__author__ = 'Pete Cable'
__license__ = 'Apache 2.0'

log = mi.core.log.get_logger()
META_LOGGER = mi.core.log.get_logging_metaclass('trace')

###
#    Driver Constant Definitions
###

NEWLINE = '\n'

LILY_STRING = 'LILY,'
NANO_STRING = 'NANO,'
IRIS_STRING = 'IRIS,'
SYST_STRING = 'SYST,'

LILY_COMMAND = '*9900XY'
IRIS_COMMAND = LILY_COMMAND
NANO_COMMAND = '*0100'

NANO_RATE_RESPONSE = '*0001TH'

MAX_BUFFER_SIZE = 2 ** 16

STATUS_TIMEOUT = 30

class ScheduledJob(BaseEnum):
    """
    Instrument scheduled jobs
    """
    LEVELING_TIMEOUT = 'botpt_leveling_timeout'
    NANO_TIME_SYNC = 'botpt_nano_time_sync'
    ACQUIRE_STATUS = 'botpt_acquire_status'

class ProtocolState(BaseEnum):
    """
    Instrument protocol states
    """
    UNKNOWN = DriverProtocolState.UNKNOWN

    # BOTPT initiates sampling at discovery. However, the UI commands still need to be available for execution
    # as BOTPT can handle commands while sampling. As such, even though sampling is started, the state will
    # remain COMMAND so that the UI will allow command execution. There is currently a tracking issue against the UI
    # (Redmine 10283) to allow the driver to control what capabilities are available. When that issue is resolved,
    # this will need to be changed from DriverProtocolState.COMMAND to DriverProtocolState.AUTOSAMPLE. Currently,
    # this just allows us to fake out the UI
    AUTOSAMPLE = DriverProtocolState.COMMAND

    DIRECT_ACCESS = DriverProtocolState.DIRECT_ACCESS

class ProtocolEvent(BaseEnum):
    """
    Protocol events
    """
    ENTER = DriverEvent.ENTER
    EXIT = DriverEvent.EXIT
    START_AUTOSAMPLE = DriverEvent.START_AUTOSAMPLE
    GET = DriverEvent.GET
    SET = DriverEvent.SET
    DISCOVER = DriverEvent.DISCOVER
    ACQUIRE_STATUS = DriverEvent.ACQUIRE_STATUS
    START_DIRECT = DriverEvent.START_DIRECT
    EXECUTE_DIRECT = DriverEvent.EXECUTE_DIRECT
    STOP_DIRECT = DriverEvent.STOP_DIRECT
    START_LEVELING = 'PROTOCOL_EVENT_START_LEVELING'
    STOP_LEVELING = 'PROTOCOL_EVENT_STOP_LEVELING'
    NANO_TIME_SYNC = 'PROTOCOL_EVENT_NANO_TIME_SYNC'
    LEVELING_TIMEOUT = 'PROTOCOL_EVENT_LEVELING_TIMEOUT'

class Capability(BaseEnum):
    """
    Protocol events that should be exposed to users (subset of above).
    """
    START_DIRECT = ProtocolEvent.START_DIRECT
    STOP_DIRECT = ProtocolEvent.STOP_DIRECT
    GET = ProtocolEvent.GET
    SET = ProtocolEvent.SET
    ACQUIRE_STATUS = ProtocolEvent.ACQUIRE_STATUS
    START_LEVELING = ProtocolEvent.START_LEVELING
    STOP_LEVELING = ProtocolEvent.STOP_LEVELING
    DISCOVER = ProtocolEvent.DISCOVER

class Parameter(DriverParameter):
    """
    Device specific parameters.
    """
    AUTO_RELEVEL = 'auto_relevel'  # Auto-relevel mode
    XTILT_TRIGGER = 'xtilt_relevel_trigger'
    YTILT_TRIGGER = 'ytilt_relevel_trigger'
    LEVELING_TIMEOUT = 'relevel_timeout'
    LEVELING_FAILED = 'leveling_failed'
    OUTPUT_RATE = 'output_rate_hz'
    LILY_LEVELING = 'lily_leveling'

    @classmethod
    def reverse_dict(cls):
        return dict((v, k) for k, v in cls.dict().iteritems())

class ParameterConstraint(BaseEnum):
    """
    Constraints for parameters
    (type, min, max)
    """
    XTILT_TRIGGER = (float, 0, 330)
    YTILT_TRIGGER = (float, 0, 330)
    LEVELING_TIMEOUT = (int, 60, 6000)
    OUTPUT_RATE = (int, 1, 40)
    AUTO_RELEVEL = (bool, None, None)

class InstrumentCommands(BaseEnum):
    """
    Instrument Commands
    """
    LILY_ON = LILY_STRING + LILY_COMMAND + 'C2'  # turns on continuous data
    LILY_OFF = LILY_STRING + LILY_COMMAND + 'C-OFF'  # turns off continuous data
    LILY_DUMP1 = LILY_STRING + LILY_COMMAND + '-DUMP-SETTINGS'  # outputs current settings
    LILY_DUMP2 = LILY_STRING + LILY_COMMAND + '-DUMP2'  # outputs current extended settings
    LILY_START_LEVELING = LILY_STRING + LILY_COMMAND + '-LEVEL,1'  # starts leveling
    LILY_STOP_LEVELING = LILY_STRING + LILY_COMMAND + '-LEVEL,0'  # stops leveling
    NANO_ON = NANO_STRING + NANO_COMMAND + 'E4'  # turns on continuous data
    NANO_OFF = NANO_STRING + NANO_COMMAND + 'E3'  # turns off continuous data
    NANO_DUMP1 = NANO_STRING + NANO_COMMAND + 'IF'  # outputs current settings
    NANO_SET_TIME = NANO_STRING + 'TS'  # requests the SBC to update the NANO time
    NANO_SET_RATE = NANO_STRING + '*0100EW*0100TH='  # sets the sample rate in Hz
    IRIS_ON = IRIS_STRING + IRIS_COMMAND + 'C2'  # turns on continuous data
    IRIS_OFF = IRIS_STRING + IRIS_COMMAND + 'C-OFF'  # turns off continuous data
    IRIS_DUMP1 = IRIS_STRING + IRIS_COMMAND + '-DUMP-SETTINGS'  # outputs current settings
    IRIS_DUMP2 = IRIS_STRING + IRIS_COMMAND + '-DUMP2'  # outputs current extended settings
    SYST_DUMP1 = SYST_STRING + '1'

class InstrumentCommandNames(BaseEnum):
    """
    Instrument Commands
    """
    LILY_ON = 'Lily On'
    LILY_OFF = 'Lily Off'
    LILY_DUMP1 = 'Lily Settings'
    LILY_DUMP2 = 'Lily Extended Settings'
    LILY_START_LEVELING = 'Start Leveling'
    LILY_STOP_LEVELING = 'Stop Leveling'
    NANO_ON = 'Nano On'
    NANO_OFF = 'Nano Off'
    NANO_DUMP1 = 'Nano Settings'
    NANO_SET_TIME = 'Set Time>'
    NANO_SET_RATE = 'Set Rate>'
    IRIS_ON = 'Iris On'
    IRIS_OFF = 'Iris Off'
    IRIS_DUMP1 = 'Iris Settings'
    IRIS_DUMP2 = 'Iris Extended Settings'
    SYST_DUMP1 = 'System Settings'

class Prompt(BaseEnum):
    """
    Instrument responses (basic)
    """
    LILY_ON = LILY_COMMAND + 'C2'
    LILY_OFF = LILY_COMMAND + 'C-OFF'
    IRIS_ON = IRIS_COMMAND + 'C2'
    IRIS_OFF = IRIS_COMMAND + 'C-OFF'
    LILY_START_LEVELING = LILY_COMMAND + '-LEVEL,1'
    LILY_STOP_LEVELING = LILY_COMMAND + '-LEVEL,0'

###############################################################################
# Driver
###############################################################################

# noinspection PyMethodMayBeStatic
class InstrumentDriver(SingleConnectionInstrumentDriver):
    """
    InstrumentDriver subclass
    Subclasses SingleConnectionInstrumentDriver with connection state machine.
    """

    ########################################################################
    # Superclass overrides for resource query.
    ########################################################################
    def get_resource_params(self):
        """
        Return list of device parameters available.
        @return List of parameters
        """
        return Parameter.list()

    def _build_protocol(self):
        """
        Construct the driver protocol state machine.
        """
        self._protocol = Protocol(BaseEnum, NEWLINE, self._driver_event)

###########################################################################
# Protocol
###########################################################################

# noinspection PyUnusedLocal,PyMethodMayBeStatic
class Protocol(CommandResponseInstrumentProtocol):
    """
    Instrument protocol class
    Subclasses CommandResponseInstrumentProtocol
    """
    __metaclass__ = META_LOGGER

    def __init__(self, prompts, newline, driver_event):
        """
        Protocol constructor.
        @param prompts A BaseEnum class containing instrument prompts.
        @param newline The newline.
        @param driver_event Driver process event callback.
        """
        # Construct protocol superclass.
        CommandResponseInstrumentProtocol.__init__(self, prompts, newline, driver_event)

        # Build protocol state machine.
        self._protocol_fsm = ThreadSafeFSM(ProtocolState, ProtocolEvent, ProtocolEvent.ENTER, ProtocolEvent.EXIT)

        # Add event handlers for protocol state machine.
        handlers = {
            ProtocolState.UNKNOWN: [
                (ProtocolEvent.ENTER, self._handler_generic_enter),
                (ProtocolEvent.EXIT, self._handler_generic_exit),
                (ProtocolEvent.DISCOVER, self._handler_unknown_discover),
            ],
            ProtocolState.AUTOSAMPLE: [
                (ProtocolEvent.ENTER, self._handler_autosample_enter),
                (ProtocolEvent.EXIT, self._handler_generic_exit),
                (ProtocolEvent.GET, self._handler_autosample_get),
                (ProtocolEvent.SET, self._handler_autosample_set),
                (ProtocolEvent.START_AUTOSAMPLE, self._handler_start_autosample),
                (ProtocolEvent.ACQUIRE_STATUS, self._handler_acquire_status),
                (ProtocolEvent.START_LEVELING, self._handler_start_leveling),
                (ProtocolEvent.STOP_LEVELING, self._handler_stop_leveling),
                (ProtocolEvent.START_DIRECT, self._handler_autosample_start_direct),
                (ProtocolEvent.NANO_TIME_SYNC, self._handler_time_sync),
                (ProtocolEvent.LEVELING_TIMEOUT, self._handler_leveling_timeout),
            ],
            ProtocolState.DIRECT_ACCESS: [
                (ProtocolEvent.ENTER, self._handler_direct_access_enter),
                (ProtocolEvent.EXIT, self._handler_generic_exit),
                (ProtocolEvent.EXECUTE_DIRECT, self._handler_direct_access_execute_direct),
                (ProtocolEvent.STOP_DIRECT, self._handler_direct_access_stop_direct),
            ],
        }

        for state in handlers:
            for event, handler in handlers[state]:
                self._protocol_fsm.add_handler(state, event, handler)

        # Construct the metadata dictionaries
        self._build_param_dict()
        self._build_command_dict()
        self._build_driver_dict()

        # Add build handlers for device commands.
        for command in InstrumentCommands.list():
            if command in [InstrumentCommands.NANO_SET_RATE]:
                self._add_build_handler(command, self._build_command_with_value)
            else:
                self._add_build_handler(command, self._build_simple_command)

        # # Add response handlers for device commands.
        for command in InstrumentCommands.list():
            self._add_response_handler(command, self._generic_response_handler)

        # Start state machine in UNKNOWN state.
        self._protocol_fsm.start(ProtocolState.UNKNOWN)

        # commands sent to device to be filtered in responses for telnet DA
        self._sent_cmds = []

        # create chunker
        self._chunker = StringChunker(Protocol.sieve_function)

        self._last_data_timestamp = 0
        self.has_pps = True

        # set up scheduled event handling
        self.initialize_scheduler()
        self._add_scheduler_event(ScheduledJob.ACQUIRE_STATUS, ProtocolEvent.ACQUIRE_STATUS)
        self._add_scheduler_event(ScheduledJob.NANO_TIME_SYNC, ProtocolEvent.NANO_TIME_SYNC)

        self._direct_commands['Wakeup'] = NEWLINE
        self._direct_commands['Newline'] = NEWLINE
        self._direct_commands['Heater Duration>']='HEAT,'
        command_dict = InstrumentCommands.dict()
        label_dict = InstrumentCommandNames.dict()
        for key in command_dict:
            label = label_dict.get(key)
            command = command_dict[key]
            builder = self._build_handlers.get(command, None)
            if builder in [self._build_simple_command]:
                command = builder(command)
                self._direct_commands[label] = command

    @staticmethod
    def sieve_function(raw_data):
        """
        Sort data in the chunker...
        @param raw_data: Data to be searched for samples
        @return: list of (start,end) tuples
        """
        matchers = []
        return_list = []

        matchers.append(particles.HeatSampleParticle.regex_compiled())
        matchers.append(particles.IrisSampleParticle.regex_compiled())
        matchers.append(particles.NanoSampleParticle.regex_compiled())
        matchers.append(particles.LilySampleParticle.regex_compiled())
        matchers.append(particles.LilyLevelingParticle.regex_compiled())

        for matcher in matchers:
            for match in matcher.finditer(raw_data):
                return_list.append((match.start(), match.end()))

        return return_list

    def _got_chunk(self, chunk, ts):
        """
        Process chunk output by the chunker.  Generate samples and (possibly) react
        @param chunk: data
        @param ts: ntp timestamp
        @return sample
        @throws InstrumentProtocolException
        """
        possible_particles = [
            (particles.LilySampleParticle, self._check_for_autolevel),
            (particles.LilyLevelingParticle, self._check_completed_leveling),
            (particles.HeatSampleParticle, None),
            (particles.IrisSampleParticle, None),
            (particles.NanoSampleParticle, self._check_pps_sync),
        ]

        for particle_type, func in possible_particles:
            sample = self._extract_sample(particle_type, particle_type.regex_compiled(), chunk, ts)
            if sample:
                if func and self.get_current_state() != ProtocolState.UNKNOWN:
                    func(sample)
                return sample

        raise InstrumentProtocolException(u'unhandled chunk received by _got_chunk: [{0!r:s}]'.format(chunk))

    def _extract_sample(self, particle_class, regex, line, timestamp, publish=True):
        """
        Overridden to set the quality flag for LILY particles that are out of range.
        @param particle_class: Class type for particle
        @param regex: regular expression to verify data
        @param line: data
        @param timestamp: ntp timestamp
        @param publish: boolean to indicate if sample should be published
        @return: extracted sample
        """
        if regex.match(line):
            if particle_class == particles.LilySampleParticle and self._param_dict.get(Parameter.LEVELING_FAILED):
                particle = particle_class(line, port_timestamp=timestamp, quality_flag=DataParticleValue.OUT_OF_RANGE)
            else:
                particle = particle_class(line, port_timestamp=timestamp)
            parsed_sample = particle.generate()

            # Add an entry to the particle dictionary, with the particle class as the key
            self._particle_dict[particle.data_particle_type()] = parsed_sample

            if publish and self._driver_event:
                self._driver_event(DriverAsyncEvent.SAMPLE, parsed_sample)

            return parsed_sample

    def _filter_capabilities(self, events):
        """
        Filter a list of events to only include valid capabilities
        @param events: list of events to be filtered
        @return: list of filtered events
        """
        leveling = self._param_dict.get(Parameter.LILY_LEVELING)

        capabilities = []
        for x in events:
            if Capability.has(x):
                if x is Capability.START_LEVELING and leveling:
                    continue
                if x is Capability.STOP_LEVELING and not leveling:
                    continue
                capabilities.append(x)
        return capabilities

    def _build_command_dict(self):
        """
        Populate the command dictionary with commands.
        """
        self._cmd_dict.add(Capability.ACQUIRE_STATUS, display_name="Acquire Status")
        self._cmd_dict.add(Capability.START_LEVELING, display_name="Start LILY Leveling")
        self._cmd_dict.add(Capability.STOP_LEVELING, display_name="Stop LILY Leveling")
        self._cmd_dict.add(Capability.DISCOVER, display_name='Discover')

    def _build_param_dict(self):
        """
        Populate the parameter dictionary with parameters.
        For each parameter key, add match string, match lambda function,
        and value formatting function for set commands.
        """
        my_regex = 'Not used'
        ro, rw = ParameterDictVisibility.READ_ONLY, ParameterDictVisibility.READ_WRITE
        _bool, _float, _int = ParameterDictType.BOOL, ParameterDictType.FLOAT, ParameterDictType.INT

        parameters = {
            Parameter.AUTO_RELEVEL: {
                'type': _bool,
                'display_name': 'Automatic Releveling Enabled',
                'description': 'Enable LILY re-leveling automatically: (true | false)',
                'range': {'True': True, 'False': False},
                'visibility': rw,
                'startup_param': True,
            },
            Parameter.XTILT_TRIGGER: {
                'type': _float,
                'display_name': 'X-tilt Releveling Trigger',
                'description': 'The X-tilt value that must be exceeded before LILY auto releveling occurs: (1-330)',
                'range': (1, 330),
                'units': Prefixes.MICRO + Units.RADIAN,
                'visibility': rw,
                'startup_param': True,
            },
            Parameter.YTILT_TRIGGER: {
                'type': _float,
                'display_name': 'Y-tilt Releveling Trigger',
                'description': 'The Y-tilt value that must be exceeded before LILY auto releveling occurs: (1-330)',
                'range': (1, 330),
                'units': Prefixes.MICRO + Units.RADIAN,
                'visibility': rw,
                'startup_param': True,
            },
            Parameter.LEVELING_TIMEOUT: {
                'type': _int,
                'display_name': 'LILY Leveling Timeout',
                'description': 'Leveling timeout: (1-32767)',
                'range': (60, 6000),
                'units': Units.SECOND,
                'visibility': rw,
                'startup_param': True,
            },
            Parameter.OUTPUT_RATE: {
                'type': _int,
                'display_name': 'NANO Output Rate',
                'description': 'Sample rate: (1, 40)',
                'range': (1, 40),
                'units': Units.HERTZ,
                'visibility': rw,
                'startup_param': True,
            },
            Parameter.LILY_LEVELING: {
                'type': _bool,
                'display_name': 'Lily Leveling',
                'description': 'Indicates if LILY leveling is occurring: (true | false)',
                'range': {'True': True, 'False': False},
                'value': False,
                'visibility': ro,
            },
            Parameter.LEVELING_FAILED: {
                'type': _bool,
                'display_name': 'LILY Leveling Failed',
                'description': 'Indicates if LILY leveling failed: (true | false)',
                'range': {'True': True, 'False': False},
                'value': False,
                'visibility': ro,
            },
        }
        for param in parameters:
            self._param_dict.add(param, my_regex, None, None, **parameters[param])

    def _build_driver_dict(self):
        """
        Populate the driver dictionary with options
        """
        self._driver_dict.add(DriverDictKey.VENDOR_SW_COMPATIBLE, False)

    def _build_command_with_value(self, cmd, value):
        """
        Build a simple command with one value specified
        @param cmd: instrument command
        @param value: value to be sent
        @return: command string
        """
        return '%s%d%s' % (cmd, value, NEWLINE)

    def _verify_set_values(self, params):
        """
        Verify supplied values are in range, if applicable
        @param params: Dictionary of Parameter:value pairs to be verified
        @throws InstrumentParameterException
        """
        constraints = ParameterConstraint.dict()
        parameters = Parameter.reverse_dict()

        # step through the list of parameters
        for key, val in params.iteritems():
            # verify this parameter exists
            if not Parameter.has(key):
                raise InstrumentParameterException('Received invalid parameter in SET: %s' % key)
            # if constraint exists, verify we have not violated it
            constraint_key = parameters.get(key)
            if constraint_key in constraints:
                var_type, minimum, maximum = constraints[constraint_key]
                constraint_string = 'Parameter: %s Value: %s Type: %s Minimum: %s Maximum: %s' % \
                                    (key, val, var_type, minimum, maximum)
                log.debug('SET CONSTRAINT: %s', constraint_string)

                # attempt to cast val to target type
                try:
                    val = var_type(val)
                except ValueError:
                    raise InstrumentParameterException('Type mismatch: %s' % constraint_string)

                # now, verify we are within min/max
                if not var_type == bool:
                    if val < minimum or val > maximum:
                        raise InstrumentParameterException('Out of range: %s' % constraint_string)

    def _set_params(self, *args, **kwargs):
        """
        Issue commands to the instrument to set various parameters
        @param args: arglist, should contain a dictionary of parameters/values to be set
        """
        try:
            params = args[0]
        except IndexError:
            raise InstrumentParameterException('Set command requires a parameter dict.')

        self._verify_set_values(params)
        self._verify_not_readonly(*args, **kwargs)

        # if setting the output rate, get the current rate from the instrument first...
        if Parameter.OUTPUT_RATE in params:
            self._update_params()

        old_config = self._param_dict.get_config()

        # all constraints met or no constraints exist, set the values
        for key, value in params.iteritems():
            self._param_dict.set_value(key, value)

        new_config = self._param_dict.get_config()

        if not old_config == new_config:
            log.debug('Config change: %r %r', old_config, new_config)
            if old_config[Parameter.OUTPUT_RATE] is not None:
                if int(old_config[Parameter.OUTPUT_RATE]) != int(new_config[Parameter.OUTPUT_RATE]):
                    self._do_cmd_no_resp(InstrumentCommands.NANO_SET_RATE, int(new_config[Parameter.OUTPUT_RATE]))
            self._driver_event(DriverAsyncEvent.CONFIG_CHANGE)

    def _update_params(self, *args, **kwargs):
        """
        Update the param dictionary based on instrument response
        """
        result, _ = self._do_cmd_resp(InstrumentCommands.NANO_DUMP1,
                                      response_regex=particles.NanoStatusParticle.regex_compiled())
        rate = int(re.search(r'NANO,\*TH:(\d+)', result).group(1))
        self._param_dict.set_value(Parameter.OUTPUT_RATE, rate)

    def _wakeup(self, timeout, delay=1):
        """
        Overriding _wakeup; does not apply to this instrument
        """

    def add_to_buffer(self, data):
        """
        Overriding base class to reduce logging due to NANO high data rate
        @param data: data to be added to buffers
        """
        # Update the line and prompt buffers.
        self._linebuf += data
        self._promptbuf += data
        self._last_data_timestamp = time.time()

        # If our buffer exceeds the max allowable size then drop the leading
        # characters on the floor.
        max_size = self._max_buffer_size()
        if len(self._linebuf) > max_size:
            self._linebuf = self._linebuf[max_size * -1:]

        # If our buffer exceeds the max allowable size then drop the leading
        # characters on the floor.
        if len(self._promptbuf) > max_size:
            self._promptbuf = self._linebuf[max_size * -1:]

    def _max_buffer_size(self):
        """
        Overriding base class to increase max buffer size
        @return int max_buffer_size
        """
        return MAX_BUFFER_SIZE

    def _remove_leveling_timeout(self):
        """
        Clean up the leveling timer
        """
        try:
            self._remove_scheduler(ScheduledJob.LEVELING_TIMEOUT)
        except KeyError:
            log.debug('Unable to remove LEVELING_TIMEOUT scheduled job, job does not exist.')

    def _schedule_leveling_timeout(self):
        """
        Set up a leveling timer to make sure we don't stay in leveling state forever if something goes wrong
        """
        self._remove_leveling_timeout()
        dt = datetime.datetime.now() + datetime.timedelta(seconds=self._param_dict.get(Parameter.LEVELING_TIMEOUT))
        job_name = ScheduledJob.LEVELING_TIMEOUT
        config = {
            DriverConfigKey.SCHEDULER: {
                job_name: {
                    DriverSchedulerConfigKey.TRIGGER: {
                        DriverSchedulerConfigKey.TRIGGER_TYPE: TriggerType.ABSOLUTE,
                        DriverSchedulerConfigKey.DATE: dt
                    },
                }
            }
        }

        self.set_init_params(config)
        self._add_scheduler_event(ScheduledJob.LEVELING_TIMEOUT, ProtocolEvent.LEVELING_TIMEOUT)

    def _generic_response_handler(self, resp, prompt):
        """
        Pass through response handler
        @param resp: response
        @param prompt: prompt
        @return: (response, prompt)
        """
        return resp, prompt

    def _particle_to_dict(self, sample):
        """
        Convert a particle to a dictionary of value_id:value
        @param sample: particle to be parsed
        @return: dictionary representing the particle
        """
        sample_dict = {}
        values = sample.get(DataParticleKey.VALUES, [])
        for each in values:
            sample_dict[each[DataParticleKey.VALUE_ID]] = each[DataParticleKey.VALUE]
        return sample_dict

    def _check_for_autolevel(self, sample):
        """
        Check this sample, kick off a leveling event if out of range
        @param sample: sample to be checked
        """
        if self._param_dict.get(Parameter.AUTO_RELEVEL) and self.get_current_state() == ProtocolState.AUTOSAMPLE:
            # Find the current X and Y tilt values
            # If they exceed the trigger parameters, begin autolevel
            relevel = False
            sample = self._particle_to_dict(sample)
            x_tilt = abs(sample[particles.LilySampleParticleKey.X_TILT])
            y_tilt = abs(sample[particles.LilySampleParticleKey.Y_TILT])
            x_trig = int(self._param_dict.get(Parameter.XTILT_TRIGGER))
            y_trig = int(self._param_dict.get(Parameter.YTILT_TRIGGER))
            if x_tilt > x_trig or y_tilt > y_trig:
                self._async_raise_fsm_event(ProtocolEvent.START_LEVELING)

    def _failed_leveling(self, axis):
        """
        Handle a failed leveling event.  Set the failed flag, disable auto relevel and notify the operator
        @param axis: Axis which failed leveling
        """
        log.error('Detected leveling error in %s axis!', axis)
        # Read only parameter, must be set outside of handler
        self._param_dict.set_value(Parameter.LEVELING_FAILED, True)
        # Use the handler to disable auto relevel to raise a config change event if needed.
        self._handler_autosample_set({Parameter.AUTO_RELEVEL: False})
        raise InstrumentDataException('LILY Leveling (%s) Failed.  Disabling auto relevel' % axis)

    def _check_completed_leveling(self, sample):
        """
        Check this sample if leveling is complete or failed
        @param sample: Sample to be checked
        """
        sample = self._particle_to_dict(sample)
        status = sample[particles.LilyLevelingParticleKey.STATUS]
        if status is not None:
            # Leveling status update received
            # If leveling complete, send STOP_LEVELING, set the _leveling_failed flag to False
            if 'Leveled' in status:
                if self._param_dict.get(Parameter.LEVELING_FAILED):
                    self._handler_autosample_set({Parameter.LEVELING_FAILED: False})
                self._async_raise_fsm_event(ProtocolEvent.STOP_LEVELING)
            # Leveling X failed!  Set the flag and raise an exception to notify the operator
            # and disable auto leveling. Let the instrument attempt to level
            # in the Y axis.
            elif 'X Axis out of range' in status:
                self._failed_leveling('X')
            # Leveling X failed!  Set the flag and raise an exception to notify the operator
            # and disable auto leveling. Send STOP_LEVELING
            elif 'Y Axis out of range' in status:
                self._async_raise_fsm_event(ProtocolEvent.STOP_LEVELING)
                self._failed_leveling('Y')

    def _check_pps_sync(self, sample):
        """
        Check if PPS sync status has changed.  Update driver flag and, if appropriate, trigger a time sync
        @param sample: sample to be checked
        """
        sample = self._particle_to_dict(sample)
        pps_sync = sample[particles.NanoSampleParticleKey.PPS_SYNC] == 'P'
        if pps_sync:
            if not self.has_pps:
                # pps sync regained, sync the time
                self.has_pps = True
                if self.get_current_state() == ProtocolState.AUTOSAMPLE:
                    self._async_raise_fsm_event(ProtocolEvent.NANO_TIME_SYNC)
        else:
            self.has_pps = False

    ########################################################################
    # Unknown handlers.
    ########################################################################

    def _handler_unknown_discover(self, *args, **kwargs):
        """
        Process discover event
        @return next_state, (next_state, result)
        """
        next_state = ProtocolState.AUTOSAMPLE

        result = []

        return next_state, (next_state, result)

    ########################################################################
    # Autosample handlers.
    ########################################################################

    def _handler_autosample_enter(self, *args, **kwargs):
        """
        Enter autosample state.
        """
        # key off the initialization flag to determine if we should sync the time
        if self._init_type == InitializationType.STARTUP:
            self._handler_time_sync()

        self._init_params()
        self._driver_event(DriverAsyncEvent.STATE_CHANGE)

        # Since BOTPT is to discover into the Autosample state without a command execution, and remain that
        # way permanently, we make the call to start autosampling here
        self._handler_start_autosample()

    def _handler_autosample_get(self, *args, **kwargs):
        """
        Process GET event
        """
        return self._handler_get(*args, **kwargs)

    def _handler_autosample_set(self, *args, **kwargs):
        """
        Perform a set command.
        @param args[0] parameter : value dict.
        @return next_state, (next_state, result)
        @throws InstrumentParameterException
        """
        next_state = None
        result = []
        startup = False

        if len(args) < 1:
            raise InstrumentParameterException('Set command requires a parameter dict.')
        params = args[0]
        if len(args) > 1:
            startup = args[1]

        if not isinstance(params, dict):
            raise InstrumentParameterException('Set parameters not a dict.')
        if not isinstance(startup, bool):
            raise InstrumentParameterException('Startup not a bool.')

        self._set_params(params, startup)
        return next_state, result

    def _handler_autosample_start_direct(self):
        """
        Start direct access
        @return next_state, (next_state, result)
        """
        next_state = ProtocolState.DIRECT_ACCESS
        result = []
        return next_state, (next_state, result)

    def _handler_start_autosample(self):
        """
        Start autosample
        @return next_state, (next_state, result)
        """
        next_state = ProtocolState.AUTOSAMPLE
        result = []
        self._do_cmd_resp(InstrumentCommands.LILY_ON, expected_prompt=Prompt.LILY_ON)
        self._do_cmd_resp(InstrumentCommands.NANO_ON, expected_prompt=NANO_STRING)
        self._do_cmd_resp(InstrumentCommands.IRIS_ON, expected_prompt=Prompt.IRIS_ON)
        return next_state, (next_state, result)

    ########################################################################
    # Direct access handlers.
    ########################################################################

    def _handler_direct_access_enter(self, *args, **kwargs):
        """
        Enter direct access state.
        """
        # Tell driver superclass to send a state change event.
        # Superclass will query the state.
        self._driver_event(DriverAsyncEvent.STATE_CHANGE)
        self._sent_cmds = []

    def _handler_direct_access_execute_direct(self, data):
        """
        Execute direct access command
        @return next_state, (next_state, result)
        """
        next_state = None
        result = []
        self._do_cmd_direct(data)
        self._sent_cmds.append(data)
        return next_state, (next_state, result)

    def _handler_direct_access_stop_direct(self):
        """
        Stop direct access
        @return next_state, (next_state, result)
        """
        next_state, (_, result) = self._handler_unknown_discover()

        return next_state, (next_state, result)

    ########################################################################
    # Generic handlers.
    ########################################################################

    def _handler_generic_enter(self, *args, **kwargs):
        """
        Generic enter state handler
        """
        # Tell driver superclass to send a state change event.
        # Superclass will query the state.
        self._driver_event(DriverAsyncEvent.STATE_CHANGE)

    def _handler_generic_exit(self, *args, **kwargs):
        """
        Generic exit state handler
        """

    def _handler_acquire_status(self, *args, **kwargs):
        """
        We generate these particles here to avoid the chunker.  This allows us to process status
        messages with embedded messages from the other parts of the instrument.
        @return next_state, (next_state, result)
        """
        next_state = None
        timeout = time.time() + STATUS_TIMEOUT

        ts = ntplib.system_to_ntp_time(time.time())
        parts = []

        for command, particle_class in [
            (InstrumentCommands.SYST_DUMP1, particles.SystStatusParticle),
            (InstrumentCommands.LILY_DUMP1, particles.LilyStatusParticle1),
            (InstrumentCommands.LILY_DUMP2, particles.LilyStatusParticle2),
            (InstrumentCommands.IRIS_DUMP1, particles.IrisStatusParticle1),
            (InstrumentCommands.IRIS_DUMP2, particles.IrisStatusParticle2),
            (InstrumentCommands.NANO_DUMP1, particles.NanoStatusParticle),
        ]:
            result, _ = self._do_cmd_resp(command, response_regex=particle_class.regex_compiled())
            parts.append(result)
        sample = self._extract_sample(particles.BotptStatusParticle,
                                      particles.BotptStatusParticle.regex_compiled(),
                                      NEWLINE.join(parts), ts)

        if self.get_current_state() == ProtocolState.AUTOSAMPLE:
            # acquiring status stops NANO output, restart it
            self._do_cmd_resp(InstrumentCommands.NANO_ON, expected_prompt=NANO_STRING)

        data_particles = self.wait_for_particles([particles.DataParticleType.BOTPT_STATUS], timeout)

        if not sample:
            raise InstrumentProtocolException('Failed to generate status particle')
        return next_state, (next_state, data_particles)

    def _handler_time_sync(self, *args, **kwargs):
        """
        Syncing time starts autosample...
        @return next_state, (next_state, result)
        """
        next_state = None
        result = self._do_cmd_resp(InstrumentCommands.NANO_SET_TIME, expected_prompt=NANO_STRING)
        return next_state, (next_state, result)

    def _handler_start_leveling(self):
        """
        Send the start leveling command
        @return next_state, (next_state, result)
        """
        next_state = None
        result = None
        if not self._param_dict.get(Parameter.LILY_LEVELING):
            self._schedule_leveling_timeout()
            result = self._do_cmd_resp(InstrumentCommands.LILY_START_LEVELING,
                                       expected_prompt=Prompt.LILY_START_LEVELING)
            self._param_dict.set_value(Parameter.LILY_LEVELING, True)
            self._driver_event(DriverAsyncEvent.CONFIG_CHANGE)
        return next_state, (next_state, result)

    def _handler_stop_leveling(self):
        """
        Send the stop leveling command
        @return next_state, (next_state, result)
        """
        next_state = None
        result = []
        if self._param_dict.get(Parameter.LILY_LEVELING):
            self._remove_leveling_timeout()

            next_state = self._do_cmd_resp(InstrumentCommands.LILY_STOP_LEVELING,
                                           expected_prompt=Prompt.LILY_STOP_LEVELING)
            self._param_dict.set_value(Parameter.LILY_LEVELING, False)

            if self.get_current_state() == ProtocolState.AUTOSAMPLE:
                self._do_cmd_resp(InstrumentCommands.LILY_ON, expected_prompt=Prompt.LILY_ON)

            self._driver_event(DriverAsyncEvent.CONFIG_CHANGE)

        return next_state, (next_state, result)

    def _handler_leveling_timeout(self):
        """
        Leveling has timed out, disable auto-relevel and mark leveling as failed.
        handler_stop_leveling will raise the config change event.
        @throws InstrumentProtocolException
        """
        self._param_dict.set_value(Parameter.AUTO_RELEVEL, False)
        self._param_dict.set_value(Parameter.LEVELING_FAILED, True)
        self._handler_stop_leveling()
        raise InstrumentProtocolException('Leveling failed to complete within timeout, disabling auto-relevel')

def create_playback_protocol(callback):
    return Protocol(None, None, callback)


text:
require "etsiest/version"
require "pry"
require "etsiest/etsysearch"
require "sinatra/base"

require 'etsy'
Etsy.api_key = ENV['ETSY_KEY']

module Etsiest
  class App < Sinatra::Base
    set :logging, true

    get "/" do
      whiskey = EtsySearch.new
      results = whiskey.find_listings('whiskey')
      # ['title'],
      # image 170x135 => 225 x 179, ['Images']['url_170x135']
      # ['shop']['shop_name'],
      # ['price']
      # ['currency_code']
      erb :index, locals: { results: results }
    end

    run! if app_file == $0
  end
end


text:
require 'simplecov'
require 'coveralls'

SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[
  SimpleCov::Formatter::HTMLFormatter,
  Coveralls::SimpleCov::Formatter
]
SimpleCov.start

Dir['./spec/support/**/*.rb'].each {|f| require f}

RSpec.configure do |config|
  config.order = 'random'
  config.run_all_when_everything_filtered = false
end

class User
  require 'active_model'
  require 'active_support/all'

  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :name

  def initialize(attributes = {})
    @name = attributes[:name]
  end

  def persisted?
    false
  end
end

require 'action_view'
include ActionView::Helpers::FormOptionsHelper
if defined?(ActionView::VERSION) # only defined in ActionView >=4
  include ActionView::RecordIdentifier
else
  include ActionController::RecordIdentifier
end
I18n.enforce_available_locales = true


text:
package org.apache.hadoop.security.ssl;

import org.apache.hadoop.thirdparty.com.google.common.annotations.VisibleForTesting;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.TrustManager;
import java.io.IOException;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.text.MessageFormat;
import java.util.Timer;

/**
 * {@link KeyStoresFactory} implementation that reads the certificates from
 * keystore files.
 *

 * If either the truststore or the keystore certificates file changes, it
 * would be refreshed under the corresponding wrapper implementation -
 * {@link ReloadingX509KeystoreManager} or {@link ReloadingX509TrustManager}.
 *

 */
@InterfaceAudience.Private
@InterfaceStability.Evolving
public class FileBasedKeyStoresFactory implements KeyStoresFactory {

  private static final Logger LOG =
      LoggerFactory.getLogger(FileBasedKeyStoresFactory.class);

  /**
   * The name of the timer thread monitoring file changes.
   */
  public static final String SSL_MONITORING_THREAD_NAME = "SSL Certificates Store Monitor";

  /**
   * The refresh interval used to check if either of the truststore or keystore
   * certificate file has changed.
   */
  public static final String SSL_STORES_RELOAD_INTERVAL_TPL_KEY =
    "ssl.{0}.stores.reload.interval";

  public static final String SSL_KEYSTORE_LOCATION_TPL_KEY =
    "ssl.{0}.keystore.location";
  public static final String SSL_KEYSTORE_PASSWORD_TPL_KEY =
    "ssl.{0}.keystore.password";
  public static final String SSL_KEYSTORE_KEYPASSWORD_TPL_KEY =
    "ssl.{0}.keystore.keypassword";
  public static final String SSL_KEYSTORE_TYPE_TPL_KEY =
    "ssl.{0}.keystore.type";

  public static final String SSL_TRUSTSTORE_RELOAD_INTERVAL_TPL_KEY =
    "ssl.{0}.truststore.reload.interval";
  public static final String SSL_TRUSTSTORE_LOCATION_TPL_KEY =
    "ssl.{0}.truststore.location";
  public static final String SSL_TRUSTSTORE_PASSWORD_TPL_KEY =
    "ssl.{0}.truststore.password";
  public static final String SSL_TRUSTSTORE_TYPE_TPL_KEY =
    "ssl.{0}.truststore.type";
  public static final String SSL_EXCLUDE_CIPHER_LIST =
      "ssl.{0}.exclude.cipher.list";

  /**
   * Default format of the keystore files.
   */
  public static final String DEFAULT_KEYSTORE_TYPE = "jks";

  /**
   * The default time interval in milliseconds used to check if either
   * of the truststore or keystore certificates file has changed and needs reloading.
   */
  public static final int DEFAULT_SSL_STORES_RELOAD_INTERVAL = 10000;

  private Configuration conf;
  private KeyManager[] keyManagers;
  private TrustManager[] trustManagers;
  private ReloadingX509TrustManager trustManager;
  private Timer fileMonitoringTimer;

  private void createTrustManagersFromConfiguration(SSLFactory.Mode mode,
                                                    String truststoreType,
                                                    String truststoreLocation,
                                                    long storesReloadInterval)
      throws IOException, GeneralSecurityException {
    String passwordProperty = resolvePropertyName(mode,
        SSL_TRUSTSTORE_PASSWORD_TPL_KEY);
    String truststorePassword = getPassword(conf, passwordProperty, "");
    if (truststorePassword.isEmpty()) {
      // An empty trust store password is legal; the trust store password
      // is only required when writing to a trust store. Otherwise it's
      // an optional integrity check.
      truststorePassword = null;
    }

    // Check if obsolete truststore specific reload interval is present for backward compatible
    long truststoreReloadInterval =
        conf.getLong(
            resolvePropertyName(mode, SSL_TRUSTSTORE_RELOAD_INTERVAL_TPL_KEY),
            storesReloadInterval);

    if (LOG.isDebugEnabled()) {
      LOG.debug(mode.toString() + " TrustStore: " + truststoreLocation +
          ", reloading at " + truststoreReloadInterval + " millis.");
    }

    trustManager = new ReloadingX509TrustManager(
        truststoreType,
        truststoreLocation,
        truststorePassword);

    if (truststoreReloadInterval > 0) {
      fileMonitoringTimer.schedule(
          new FileMonitoringTimerTask(
              Paths.get(truststoreLocation),
              path -> trustManager.loadFrom(path),
              exception -> LOG.error(ReloadingX509TrustManager.RELOAD_ERROR_MESSAGE, exception)),
          truststoreReloadInterval,
          truststoreReloadInterval);
    }

    if (LOG.isDebugEnabled()) {
      LOG.debug(mode.toString() + " Loaded TrustStore: " + truststoreLocation);
    }
    trustManagers = new TrustManager[]{trustManager};
  }

  /**
   * Implements logic of initializing the KeyManagers with the options
   * to reload keystores.
   * @param mode client or server
   * @param keystoreType The keystore type.
   * @param storesReloadInterval The interval to check if the keystore certificates
   *                             file has changed.
   */
  private void createKeyManagersFromConfiguration(SSLFactory.Mode mode,
                                                  String keystoreType, long storesReloadInterval)
      throws GeneralSecurityException, IOException {
    String locationProperty =
        resolvePropertyName(mode, SSL_KEYSTORE_LOCATION_TPL_KEY);
    String keystoreLocation = conf.get(locationProperty, "");
    if (keystoreLocation.isEmpty()) {
      throw new GeneralSecurityException("The property '" + locationProperty +
          "' has not been set in the ssl configuration file.");
    }
    String passwordProperty =
        resolvePropertyName(mode, SSL_KEYSTORE_PASSWORD_TPL_KEY);
    String keystorePassword = getPassword(conf, passwordProperty, "");
    if (keystorePassword.isEmpty()) {
      throw new GeneralSecurityException("The property '" + passwordProperty +
          "' has not been set in the ssl configuration file.");
    }
    String keyPasswordProperty =
        resolvePropertyName(mode, SSL_KEYSTORE_KEYPASSWORD_TPL_KEY);
    // Key password defaults to the same value as store password for
    // compatibility with legacy configurations that did not use a separate
    // configuration property for key password.
    String keystoreKeyPassword = getPassword(
        conf, keyPasswordProperty, keystorePassword);
    if (LOG.isDebugEnabled()) {
      LOG.debug(mode.toString() + " KeyStore: " + keystoreLocation);
    }

    ReloadingX509KeystoreManager keystoreManager =  new ReloadingX509KeystoreManager(
        keystoreType,
        keystoreLocation,
        keystorePassword,
        keystoreKeyPassword);

    if (storesReloadInterval > 0) {
      fileMonitoringTimer.schedule(
          new FileMonitoringTimerTask(
              Paths.get(keystoreLocation),
              path -> keystoreManager.loadFrom(path),
              exception -> LOG.error(ReloadingX509KeystoreManager.RELOAD_ERROR_MESSAGE, exception)),
          storesReloadInterval,
          storesReloadInterval);
    }

    keyManagers = new KeyManager[] { keystoreManager };
  }

  /**
   * Resolves a property name to its client/server version if applicable.
   *

   * NOTE: This method is public for testing purposes.
   *
   * @param mode client/server mode.
   * @param template property name template.
   * @return the resolved property name.
   */
  @VisibleForTesting
  public static String resolvePropertyName(SSLFactory.Mode mode,
                                           String template) {
    return MessageFormat.format(
        template, StringUtils.toLowerCase(mode.toString()));
  }

  /**
   * Sets the configuration for the factory.
   *
   * @param conf the configuration for the factory.
   */
  @Override
  public void setConf(Configuration conf) {
    this.conf = conf;
  }

  /**
   * Returns the configuration of the factory.
   *
   * @return the configuration of the factory.
   */
  @Override
  public Configuration getConf() {
    return conf;
  }

  /**
   * Initializes the keystores of the factory.
   *
   * @param mode if the keystores are to be used in client or server mode.
   * @throws IOException thrown if the keystores could not be initialized due
   * to an IO error.
   * @throws GeneralSecurityException thrown if the keystores could not be
   * initialized due to a security error.
   */
  @Override
  public void init(SSLFactory.Mode mode)
    throws IOException, GeneralSecurityException {

    boolean requireClientCert =
      conf.getBoolean(SSLFactory.SSL_REQUIRE_CLIENT_CERT_KEY,
          SSLFactory.SSL_REQUIRE_CLIENT_CERT_DEFAULT);

    long storesReloadInterval = conf.getLong(
        resolvePropertyName(mode, SSL_STORES_RELOAD_INTERVAL_TPL_KEY),
        DEFAULT_SSL_STORES_RELOAD_INTERVAL);

    fileMonitoringTimer = new Timer(SSL_MONITORING_THREAD_NAME, true);

    // certificate store
    String keystoreType =
        conf.get(resolvePropertyName(mode, SSL_KEYSTORE_TYPE_TPL_KEY),
                 DEFAULT_KEYSTORE_TYPE);

    if (requireClientCert || mode == SSLFactory.Mode.SERVER) {
      createKeyManagersFromConfiguration(mode, keystoreType, storesReloadInterval);
    } else {
      KeyStore keystore = KeyStore.getInstance(keystoreType);
      keystore.load(null, null);
      KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance(
          SSLFactory.KEY_MANAGER_SSLCERTIFICATE);

      keyMgrFactory.init(keystore, null);
      keyManagers = keyMgrFactory.getKeyManagers();
    }

    //trust store
    String truststoreType =
      conf.get(resolvePropertyName(mode, SSL_TRUSTSTORE_TYPE_TPL_KEY),
               DEFAULT_KEYSTORE_TYPE);

    String locationProperty =
      resolvePropertyName(mode, SSL_TRUSTSTORE_LOCATION_TPL_KEY);
    String truststoreLocation = conf.get(locationProperty, "");
    if (!truststoreLocation.isEmpty()) {
      createTrustManagersFromConfiguration(mode, truststoreType, truststoreLocation, storesReloadInterval);
    } else {
      if (LOG.isDebugEnabled()) {
        LOG.debug("The property '" + locationProperty + "' has not been set, " +
            "no TrustStore will be loaded");
      }
      trustManagers = null;
    }
  }

  String getPassword(Configuration conf, String alias, String defaultPass) {
    String password = defaultPass;
    try {
      char[] passchars = conf.getPassword(alias);
      if (passchars != null) {
        password = new String(passchars);
      }
    }
    catch (IOException ioe) {
      LOG.warn("Exception while trying to get password for alias " + alias +
          ": " + ioe.getMessage());
    }
    return password;
  }

  /**
   * Releases any resources being used.
   */
  @Override
  public synchronized void destroy() {
    if (trustManager != null) {
      fileMonitoringTimer.cancel();
      trustManager = null;
      keyManagers = null;
      trustManagers = null;
    }
  }

  /**
   * Returns the keymanagers for owned certificates.
   *
   * @return the keymanagers for owned certificates.
   */
  @Override
  public KeyManager[] getKeyManagers() {
    return keyManagers;
  }

  /**
   * Returns the trustmanagers for trusted certificates.
   *
   * @return the trustmanagers for trusted certificates.
   */
  @Override
  public TrustManager[] getTrustManagers() {
    return trustManagers;
  }

}


text:
package engine

import (
	"adexchange/lib"
	m "adexchange/models"
	//"bytes"
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/franela/goreq"
	"net/url"
	"time"
)

func invokeMH(demand *Demand) {

	adRequest := demand.AdRequest
	beego.Debug("Start Invoke MH,did:" + demand.Did)
	item := url.Values{}

	//item.Set("bid", lib.GenerateBid(demand.AdspaceKey))
	item.Set("bid", demand.Did)
	item.Set("adspaceid", demand.RealAdspaceKey)
	//hard code 2 to request MH as hero app
	item.Set("adtype", "2")

	if len(demand.PkgName) > 0 {
		item.Set("pkgname", demand.PkgName)
	} else {
		item.Set("pkgname", adRequest.Pkgname)
	}

	if len(demand.PkgName) > 0 {
		item.Set("appname", demand.AppName)
	} else {
		item.Set("appname", adRequest.Appname)
	}

	if len(demand.PkgName) > 0 {
		item.Set("pcat", lib.ConvertIntToString(demand.Pcat))
	} else {
		item.Set("pcat", adRequest.Pcat)
	}

	if len(demand.PkgName) > 0 {
		item.Set("ua", demand.Ua)
	} else {
		item.Set("ua", adRequest.Ua)
	}
	if len(adRequest.Conn) > 0 {
		item.Set("conn", adRequest.Conn)
	} else {
		item.Set("conn", "1")
	}

	if len(adRequest.Carrier) > 0 {
		item.Set("carrier", adRequest.Carrier)
	} else {
		item.Set("Carrier", "1")
	}

	//hard code 2 to return json response
	//hard code 4 to return json response with display titile and text
	item.Set("apitype", "4")
	item.Set("os", lib.ConvertIntToString(adRequest.Os))
	item.Set("osv", adRequest.Osv)
	item.Set("imei", adRequest.Imei)
	item.Set("wma", adRequest.Wma)
	item.Set("aid", adRequest.Aid)
	item.Set("aaid", adRequest.Aaid)
	item.Set("idfa", adRequest.Idfa)
	item.Set("oid", adRequest.Oid)
	item.Set("uid", adRequest.Uid)
	item.Set("device", adRequest.Device)

	item.Set("ip", adRequest.Ip)
	item.Set("width", lib.ConvertIntToString(adRequest.Width))
	item.Set("height", lib.ConvertIntToString(adRequest.Height))
	item.Set("density", adRequest.Density)
	item.Set("lon", lib.ConvertFloatToString(adRequest.Lon))
	item.Set("lat", lib.ConvertFloatToString(adRequest.Lat))

	beego.Debug(demand.Timeout)
	res, err := goreq.Request{
		Uri:         demand.URL,
		QueryString: item,
		//ShowDebug:   true,
		Timeout: time.Duration(demand.Timeout) * time.Millisecond,
	}.Do()

	adResponse := initAdResponse(demand)

	var strResponse string
	if serr, ok := err.(*goreq.Error); ok {

		if serr.Timeout() {
			//adResponse = generateErrorResponse(adRequest, demand.AdspaceKey, lib.ERROR_TIMEOUT_ERROR)
			adResponse.StatusCode = lib.ERROR_TIMEOUT_ERROR
		} else {
			//adResponse = generateErrorResponse(adRequest, demand.AdspaceKey, lib.ERROR_MHSERVER_ERROR)
			adResponse.StatusCode = lib.ERROR_MHSERVER_ERROR
			beego.Critical(err.Error())
		}

	} else {
		var resultMap map[string]*m.MHAdUnit

		//flg, _ := beego.AppConfig.Bool("log_demand_body")
		//var err error
		//if flg {
		//	strResponse, _ = res.Body.ToString()
		//	err = json.Unmarshal([]byte(strResponse), &resultMap)

		//} else {
		//	err = res.Body.FromJsonTo(&resultMap)
		//}
		strResponse, _ = res.Body.ToString()
		err = json.Unmarshal(lib.EscapeCtrl([]byte(strResponse)), &resultMap)
		defer res.Body.Close()

		if err != nil {
			beego.Critical(err.Error())
			//adResponse = generateErrorResponse(adRequest, demand.AdspaceKey, lib.ERROR_MAP_ERROR)
			adResponse.StatusCode = lib.ERROR_MAP_ERROR
			//demand.Result <- adResponse
		} else {
			if resultMap != nil {
				for _, v := range resultMap {
					mapMHResult(adResponse, v)
					//adResponse.Bid = adRequest.Bid
					//adResponse.SetDemandAdspaceKey(demand.AdspaceKey)
					//demand.Result <- adResponse
					break
				}
			} else {
				//adResponse = generateErrorResponse(adRequest, demand.AdspaceKey, lib.ERROR_MAP_ERROR)
				//demand.Result <- adResponse
				adResponse.StatusCode = lib.ERROR_MAP_ERROR
			}
		}
	}

	if adResponse.StatusCode != lib.STATUS_SUCCESS {
		adResponse.ResBody = strResponse
	}

	go SendDemandLog(adResponse)

	demand.Result <- adResponse
}

func mapMHResult(adResponse *m.AdResponse, mhAdunit *m.MHAdUnit) {

	adResponse.StatusCode = mhAdunit.Returncode
	adResponse.Did = mhAdunit.Bid

	if adResponse.StatusCode == 200 {
		adUnit := new(m.AdUnit)
		adResponse.Adunit = adUnit
		adUnit.Cid = mhAdunit.Cid
		adUnit.ClickUrl = mhAdunit.Clickurl
		//todo hardcode 3 for MH, only support picture ad
		//adUnit.CreativeType = 3
		adUnit.CreativeUrls = []string{mhAdunit.Imgurl}
		adUnit.ImpTrackingUrls = mhAdunit.Imgtracking
		adUnit.ClkTrackingUrls = mhAdunit.Thclkurl
		adUnit.AdWidth = mhAdunit.Adwidth
		adUnit.AdHeight = mhAdunit.Adheight
		adUnit.DisplayTitle = mhAdunit.Displaytitle
		adUnit.DisplayText = mhAdunit.Displaytext

		adResponse.ClickUrlCacheKey = lib.GetMd5String(mhAdunit.Imgurl)
	}

	//return adResponse
}


text:
from app import application

if __name__ == '__main__':
    application.run(debug=True)

 #curl http://localhost:5000/gateways/001/sensors/data/2015-12-20T13:40:15+1000 -d "data={\"voltage\":12}" -X PUT


text:
using System;
using System.Linq.Expressions;
using System.Reflection;

namespace Reposify.Testing
{
    public class Builder
    {
        /// <summary>
        ///  Utility method to create objects with protected constructor
        ///  e.g., Apple apple = ObjectBuilder.Create<Apple>();
        /// </summary>
        public static T Create<T>()
        {
            return Create<T>(false);
        }

        public static T Create<T>(bool allowPublicConstructor)
        {
            var flags = allowPublicConstructor
                ? BindingFlags.Instance | BindingFlags.Public
                : BindingFlags.Instance | BindingFlags.NonPublic;

            var constructors = typeof(T).GetConstructors(flags);

            if ((constructors == null) || (constructors.Length == 0))
            {
                var message = allowPublicConstructor
                    ? "Couldn't find default constructor on type " + typeof(T).Name
                    : "Couldn't find non-public default constructor on type " + typeof(T).Name;

                throw new System.Exception(message);
            }

            return (T)constructors[0].Invoke(null);
        }

        public static Builder<T> Modify<T>(T instance)
        {
            return new Builder<T>(instance);
        }

        protected static PropertyInfo GetPropertyInfo(Expression body)
        {
            MemberExpression me;

            if (body is UnaryExpression)
                body = (body as UnaryExpression).Operand;

            me = (MemberExpression)body;
            return (PropertyInfo)me.Member;
        }

        public static string GetPropertyName(Expression body)
        {
            return GetPropertyInfo(body).Name;
        }

        public static void SetField(object instance, string fieldName, object value)
        {
            var field = instance.GetType().GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
            field.SetValue(instance, value);
        }

        public static object GetField(object instance, string fieldName)
        {
            var field = instance.GetType().GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
            var value = field.GetValue(instance);
            return value;
        }
    }

    public class Builder<T> : Builder
    {
        protected T     _instance;
        protected bool  _allowPublicMutators;

        public Builder() : this(Create<T>()) { }

        public Builder(T instance, bool allowPublicMutators = false)
        {
            if (instance == null)
                throw new ArgumentNullException("Cannot have null instance when constructing " + GetType());

            _instance = instance;
            _allowPublicMutators = allowPublicMutators;
        }

        public Builder<T> With<U>(Expression<Func<T, U>> propertyFunction, U value)
        {
            PropertyInfo propertyInfo = GetPropertyInfo(propertyFunction.Body);

            if (!_allowPublicMutators && propertyInfo.GetSetMethod() != null)
                throw new System.Exception("Property '" + propertyInfo.Name + "' is not protected on " + _instance.GetType());

            if (!propertyInfo.CanWrite)
                throw new System.Exception("Property '" + propertyInfo.Name + "' does not have a mutator on " + _instance.GetType());

            propertyInfo.SetValue(_instance, value, null);
            return this;
        }

        public Builder<T> WithField(string fieldName, object value)
        {
            SetField(_instance, fieldName, value);
            return this;
        }

        public T Value()
        {
            return _instance;
        }
    }
}


text:
<html>
<body>
Reports about unused construct names.
</body>
</html>


text:
package ca.polymtl.lol.expressions;

import java.util.Vector;

import ca.polymtl.lol.Context;
import ca.polymtl.lol.FunctionsScope;
import ca.polymtl.lol.exceptions.LOLRuntimeEx;
import ca.polymtl.lol.types.NullValue;
import ca.polymtl.lol.types.Value;
import static ca.polymtl.lol.Utils.tabs;

public class Function extends FunctionsScope implements Expression {
	Vector<String> parameters;
	Vector<Expression> expressions = new Vector<Expression>();
	String name;

	public void setName(String name) {
		this.name = name;
	}

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

	public Function(FunctionsScope parentFunctionsScope) {
		super(parentFunctionsScope);
	}

	public Vector<Expression> getExpressions() {
		return expressions;
	}

	public void addExpression(Expression e) {
		assert(e != null);
		expressions.add(e);
	}

	public int getNbParameters() {
		return parameters.size();
	}

	public void setParameters(Vector<String> parameters) {
		this.parameters = parameters;
	}

	public String getParameter(int i) {
		return parameters.get(i);
	}

	public Vector<String> getParameters() {
		return parameters;
	}

	@Override
	public Value evaluate(Context context) throws LOLRuntimeEx {
		System.err.println("Evaluating function " + name);

		/* If no return expression is found, the function returns a NullValue */
		Value ret = new NullValue();
		context.pushScope();

		for (Expression e : expressions) {
			Value expRet = e.evaluate(context);

			if (context.isReturning()) {
				context.setReturning(false);

				ret = context.getReturnValue();

				break;
			}

			if (context.isBreaking()) {
				throw new LOLRuntimeEx("Can't break out of a function");
			}

			/* If the expression returned something, put it in the IT variable. */
			if (expRet != null) {
				context.getCurrentScope().defineVariable("IT", expRet);
			}
		}

		context.popScope();

		return ret;
	}

	@Override
	public void debugPrint(int indent) {
		tabs(indent);
		System.err.println("Function " + name);
	}
}


text:
<?php
//
//  Copyright (C) 2014 Bastien Clément <g@ledric.me>
//
//  Permission is hereby granted, free of charge, to any person obtaining
//  a copy of this software and associated documentation files (the
//  "Software"), to deal in the Software without restriction, including
//  without limitation the rights to use, copy, modify, merge, publish,
//  distribute, sublicense, and/or sell copies of the Software, and to
//  permit persons to whom the Software is furnished to do so, subject to
//  the following conditions:
//
//  The above copyright notice and this permission notice shall be included
//  in all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
//  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
//  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
//  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

namespace XBBC;

class Exception extends \Exception {};

require "context.php";
require "stack.php";
require "tags.php";

//
// Parsing flags
//
const PARSE_META = 1;   // Only extract the meta-data array and return it
const PARSE_LEAD = 2;   // Only parse lead paragraph if available

const NO_CODE    = 4;   // Disable XBBCode parsing
const NO_SMILIES = 8;   // Disable Smilies parsing
const NO_HTMLESC = 16;  // Disable HTML escaping (only if NO_CODE is not set)

const SMILIES_OPTIMIZER = 32;  // Enable the optional smilies optimizer
const PLAIN_TEXT = 64;  // Produce plain-text output

//
// Regex used for parsing
//
const REGEX_TAG_NAME = '/[\w\-\*]/i';
const REGEX_XARGS = '/[ \t]+(\w+)(?:[=:](?|"((?:\\.|[^"])*)"|([^ \t]*)))?/';
const REGEX_TAG = <<<END
/^
	\\[
		(?|
			# Close tag
			(\\/)  ([\w\-\*]+)
		|
			# Open tag
			()    ([\\w\\-\\*]+)  (?:[=:](?|"((?:\\.|[^"])*)"|([^ \t]*)))?  ((?:  [ \\t]+\w+(?:[=:](?|"(?:\\\\.|[^"])*"|[^ \\t]*))?  )*)
		)
	\\]
$/x
END;

// =============================================================================

//
// The main XBBC Parser class.
//
class Parser {
	// Parser flags
	private $flags = 0;
	private $used = false;

	// Tag names for special tags
	private $halt_tag_name = "halt";
	private $lead_tag_name = "more";
	private $meta_tag_name = "meta";

	// Tag definition for main tags
	private $main_tag;
	private $root_tag;

	// Tags and smilies list
	private $tags    = array();

	private $smilies = array();
	private $smilies_prefix = '';

	// Results from last parsing
	private $last_meta = null;
	private $last_has_lead = null;

	// A custom reducer function
	private $custom_reducer = null;

	public function __construct($flags = 0) {
		$this->flags = $flags;

		$this->main_tag = new MainTag;
		$this->root_tag = new RootTag;
	}

	private function CheckUsed() {
		if($this->used) {
			throw new Exception("Once a parser is used, it cannot be modified");
		}
	}

	// === Flags functions ======================================================

	//
	// Enable a specific flag
	//
	public function SetFlag($flag) {
		$this->flags = $this->flags | $flag;
		return $this;
	}

	//
	// Disable a specific flag
	//
	public function UnsetFlag($flag) {
		$this->flags = $this->flags & ~$flag;
		return $this;
	}

	//
	// Check if a given flag is enabled
	//
	public function HasFlag($flag) {
		return (bool) ($this->flags & $flag);
	}

	//
	// Set and retrieves all parses flags at once
	//
	public function Flags($flags = null) {
		if($flags === null):
			return $this->flags;
		endif;

		$this->flags = (int) $flags;
		return $this;
	}

	// === Tag functions =======================================================

	//
	// Set and retrieve the special halt tag name
	//
	public function HaltTagName($tag = null) {
		if($tag === null)
			return $this->halt_tag_name;

		$this->CheckUsed();
		$this->halt_tag_name = $this->ValidateTagName($tag, true);
		return $this;
	}

	//
	// Set and retrieve the special lead tag name
	//
	public function LeadTagName($tag = null) {
		if($tag === null)
			return $this->lead_tag_name;

		$this->CheckUsed();
		$this->lead_tag_name = $this->ValidateTagName($tag, true);
		return $this;
	}

	//
	// Set and retrieve the special meta tag name
	//
	public function MetaTagName($tag = null) {
		if($tag === null)
			return $this->meta_tag_name;

		$this->CheckUsed();
		$this->meta_tag_name = $this->ValidateTagName($tag, true);
		return $this;
	}

	//
	// Set the main text tag definition (typically a <p>)
	//
	public function MainTag(TagDefinition $mainTag = null) {
		if($mainTag === null)
			return $this->main_tag;

		$this->CheckUsed();
		$this->main_tag = $mainTag;
		return $this;
	}

	//
	// Set the root tag definition
	//
	public function RootTag(TagDefinition $rootTag = null) {
		if($rootTag === null)
			return $this->root_tag;

		$this->CheckUsed();
		$this->root_tag = $rootTag;
		return $this;
	}

	//
	// Define a new tag for this parser
	//
	public function DefineTag($tag_name, TagDefinition $tag_def) {
		$this->CheckUsed();

		$tag_name = $this->ValidateTagName($tag_name, true);
		$this->tags[$tag_name] = $tag_def;

		return $this;
	}

	//
	// Remove a tag from the parser tags-table
	//
	public function RemoveTag($tag_name) {
		$this->CheckUsed();
		unset($this->tags[$tag_name]);
		return $this;
	}

	//
	// Check if a given tag is defined, optionally including specials tags
	//
	public function TagDefined($tag, $include_specials = false) {
		// Check standards tags
		if(isset($this->tags[$tag]))
			return true;

		// Check special tags
		if($include_specials &&
			($tag == $this->halt_tag_name
			|| $tag == $this->lead_tag_name
			|| $tag == $this->meta_tag_name)) {
			return true;
		}

		return false;
	}

	//
	// Return the TagDefinition for a previously defined tag
	//
	public function TagDefinition($tag) {
		return isset($this->tags[$tag]) ? $this->tags[$tag] : null;
	}

	//
	// Check if a tag name matches the TAG_NAME regex
	//
	public function IsValidTagName($tag) {
		return (bool) preg_match(REGEX_TAG_NAME, $tag);
	}

	//
	// Check and sanitize a tag name
	//
	private function ValidateTagName($tag, $check_defined = false) {
		if(!$this->IsValidTagName($tag))
			throw new Exception("Invalid tag name: [$tag]");

		// If required, check that the given tag name is not already defined
		if($check_defined && $this->TagDefined($tag, true))
			throw new Exception("Tag [$tag] is already defined");

		return strtolower($tag);
	}

	// === Smilies functions ===================================================

	//
	// Define a single smiley or replace an already existing one
	//
	public function DefineSmiley($code, $img) {
		$this->CheckUsed();
		$this->smilies[$code] = $img;
	}

	//
	// Remove a single smiley from the parser smilies table
	//
	public function RemoveSmiley($code) {
		$this->CheckUsed();
		unset($this->smilies[$code]);
	}

	//
	// Clean the smilies table, removing all defined smilies
	//
	public function RemoveAllSmilies() {
		$this->CheckUsed();
		$this->smilies = array();
	}

	//
	// Set and retrieve the smilies prefix
	//
	public function SmiliesPrefix($prefix = null) {
		if($prefix === null)
			return $this->smilies_prefix;

		$this->CheckUsed();
		$this->smilies_prefix = $prefix;
		return $this;
	}

	// === Main parsing functions ==============================================

	//
	// Set and retrieve the special meta tag name
	//
	public function CustomReducer($fn = false) {
		if($fn === false) {
			return $this->custom_reducer;
		}

		$this->CheckUsed();
		if($fn === null) {
			$this->custom_reducer = null;
		} else if(is_callable($fn)) {
			$this->custom_reducer = $fn;
		}

		return $this;
	}

	//
	// Main parsing function, take XBBCode as input and outputs HTML
	//
	public function Parse($code) {
		$this->used = true;

		// Line-breaks normalization
		$code = str_replace(array("\n\r", "\r\n", "\n", "\r"), "\n", $code);

		// Handle halt parser
		if($this->halt_tag_name && ($halt_offset = stripos($code, "[$this->halt_tag_name]")) !== false)
			$code = substr($code, 0, $halt_offset);

		// Extract meta data
		if($this->meta_tag_name) {
			$meta = array();

			$meta_callback = function($matches) use (&$meta) {
				$meta[strtolower($matches[1])] = $matches[2];
				return ""; // Delete the meta from the code
			};

			$meta_regex = "/\[$this->meta_tag_name\s*(\w+)\s*\](.*?)\[\/$this->meta_tag_name\]/is";
			$code = preg_replace_callback($meta_regex, $meta_callback, $code);

			if($this->HasFlag(PARSE_META))
				return $meta;
			else
				$this->last_meta = $meta;
		} else {
			$this->last_meta = null;
		}

		// Handle lead parsing
		if($this->lead_tag_name && ($lead_offset = stripos($code, "[$this->lead_tag_name]")) !== false) {
			$this->last_has_lead = true;
			if($this->HasFlag(PARSE_LEAD))
				$code = substr($code, 0, $lead_offset);
			else
				$code = substr($code, 0, $lead_offset).substr($code, $lead_offset + strlen($this->lead_tag_name) + 2);
		} else {
			$this->last_has_lead = false;
		}

		// Parse XBBCode if not disabled
		if(!$this->HasFlag(NO_CODE)) {
			// Lexer
			list($tokens, $t_count) = $this->SplitTokens($code);

			// Parser
			$ctx = new Context($this);

			foreach($tokens as $token) {
				// Reading a tag
				if($token[0] == '[' && preg_match(REGEX_TAG, $token, $matches)) {
					@list(, $closing, $el, $arg, $xargs) = $matches;

					// Check if this tag is defined
					if($this->TagDefined($el)) {
						if($closing) {
							// Reduced successfully
							if($ctx->Reduce($el)) {
								continue;
							}
						} else if($ctx->stack->Head()->AllowChilds()) {
							$arg   = (!empty($arg)) ? stripcslashes($arg) : null;
							$xargs = (!empty($xargs) && ($xargs[0] == ' ' || $xargs[0] == "\t"))
								? $this->ParseXArgs($xargs)
								: null;

							$tag = $this->TagDefinition($el)->create($ctx, $el, $arg, $xargs);

							// Shifted successfully
							if($tag && $ctx->Shift($tag)) {
								continue;
							}
						}
					}
				}

				// Not reading a tag
				if($ctx->stack->Head()->AllowText())
					$ctx->stack->Head()->Bufferize($token);
			}

			// Compile and generate HTML from the stack
			$html = $ctx->ReduceAll();

			if($this->HasFlag(PLAIN_TEXT) && !$this->HasFlag(NO_HTMLESC)) {
				$html = htmlspecialchars($html);
			}
		} else {
			$html = $this->HasFlag(NO_HTMLESC) ? $code : htmlspecialchars($code);

			// Parse smilies if not disabled
			if(!$this->HasFlag(NO_SMILIES))
				$html = $this->ParseSmilies($html);
		}

		return $html;
	}

	//
	// Metadata from last parsing
	//
	public function LastMeta() {
		return $this->last_meta;
	}

	//
	// Does the last string parsed used the [more] tag ?
	//
	public function LastHasLead() {
		return $this->last_has_lead;
	}

	//
	// Split the XBBC document into tokens
	//
	private function SplitTokens($code) {
		$tokens = preg_split('/(\[.+?\])/', trim($code), null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
		return array($tokens, count($tokens));
	}

	//
	// Parse the extended-arguments string
	//
	private function ParseXArgs($xargs) {
		preg_match_all(REGEX_XARGS, $xargs, $matches, PREG_SET_ORDER);

		$xargs = array();
		foreach($matches as $match)
			$xargs[strtolower($match[1])] = isset($match[2]) ? stripcslashes($match[2]) : true;

		return $xargs;
	}

	//
	// Parse and replace smilies in the XBBC document
	//
	public function ParseSmilies($text, $escaped = false) {
		// Check if we need to handle smilies
		if($this->HasFlag(NO_SMILIES) || empty($this->smilies))
			return $text;

		// Flag the parser as used
		$this->used = true;

		// The replacer function
		$smilies_replacer = function($matches) use ($escaped) {
			// Decode the smiley if the input was htmlspecialchars'd
			$smiley = $escaped ? htmlspecialchars_decode($matches[0]) : $matches[0];

			if(isset($this->smilies[$smiley])) {
				$url = $this->smilies_prefix.$this->smilies[$smiley];
				return '<img src="'.$url.'" alt="'.htmlspecialchars($smiley).'" class="smiley" />';
			} else {
				return $matches[0];
			}
		};

		// Regex cache & compiler
		static $regex, $e_regex, $smilies_identifiers;
		if(!$regex) {
			$regex = $e_regex = '/(?<=\s|<br \/>)(?:';

			foreach($this->smilies as $smiley => $_) {
				$regex   .= preg_quote($smiley, '/').'|';
				$e_regex .= preg_quote(htmlspecialchars($smiley), '/').'|';
			}

			$regex   = substr($regex, 0, -1).')(?=\s|<br \/>)/im';
			$e_regex = substr($e_regex, 0, -1).')(?=\s|<br \/>)/im';

			// --- Smilies optimizer ---
			if($this->HasFlag(SMILIES_OPTIMIZER)) {
				$smilies_identifiers = array();
				$buckets = array();

				foreach($this->smilies as $smiley => $_) {
					// Split smiliey to chars and put them in buckets
					foreach(str_split($smiley) as $char) {
						if(!isset($buckets[$char]))
							$buckets[$char] = array();

						$buckets[$char][] = $smiley;
					}
				}

				// Move the biggest bucket first
				uasort($buckets, function($a, $b) {
					return count($b) - count($a);
				});

				// Keep trace of already encountered smiley
				$smilies_identified = array();

				// Clean up buckets a bit
				foreach($buckets as $char => &$bucket) {
					// Remove duplicated smilies already encountered
					$bucket = array_filter($bucket, function($smiley) use (&$smilies_identified) {
						if(isset($smilies_identified[$smiley])) {
							return false;
						} else {
							$smilies_identified[$smiley] = true;
							return true;
						}
					});

					// Bucket is not empty, so its char-key is useful for smilies detection
					if(count($bucket) > 0) {
						$smilies_identifiers[] = $char;
					}
				}
			}
		}

		// Smilies replacing

		if($this->HasFlag(SMILIES_OPTIMIZER)) {
			$found = false;
			foreach($smilies_identifiers as $char) {
				// Assuming most text nodes doesn't contains smilies, strpos
				// fails faster than a useless preg_replace.
				if(strpos($text, $char) !== false) {
					$found = true;
					break;
				}
			}
		} else {
			$found = true;
		}

		if($found) {
			$text = preg_replace_callback($escaped ? $e_regex : $regex, $smilies_replacer, " $text ");
			return substr($text, 1, -1);
		} else {
			return $text;
		}
	}
}


text:
using System;
using NewEngine.Engine.Core;
using NewEngine.Engine.Rendering;
using NewEngine.Engine.Rendering.Shading;
using OpenTK;
using OpenTK.Graphics.OpenGL;

namespace NewEngine.Engine.components {
    public class SpotLight : PointLight {
        public SpotLight(Vector3 color, float intensity, Attenuation attenuation, float viewAngle, int shadowMapSizeAsPowerOf2 = 0,
            float shadowSoftness = 1.0f, float lightBleedReductionAmount = 0.2f, float minVariance = 0.00002f)
            : base(color, intensity, attenuation) {

            Cutoff = (float)Math.Cos(viewAngle / 2);

            if (shadowMapSizeAsPowerOf2 != 0) {
                ShadowInfo = new ShadowInfo(Matrix4.CreatePerspectiveFieldOfView(viewAngle, 1.0f, 0.1f, Range), false, shadowMapSizeAsPowerOf2, shadowSoftness, lightBleedReductionAmount, minVariance);
                int shadowMapSize = 1 << (shadowMapSizeAsPowerOf2 + 1);
                ShadowInfo.ShadowMap = Texture.GetTexture(IntPtr.Zero, shadowMapSize, shadowMapSize, TextureMinFilter.Linear, PixelInternalFormat.Rg32f, PixelFormat.Rgba, true);
                ShadowInfo.TempShadowMap = Texture.GetTexture(IntPtr.Zero, shadowMapSize, shadowMapSize, TextureMinFilter.Linear, PixelInternalFormat.Rg32f, PixelFormat.Rgba, true);
            }
        }

        public float Cutoff { get; set; }

        public Vector3 Direction => Transform.Forward;
    }
}


text:
package org.wso2.siddhi.core.util;

import org.wso2.siddhi.core.event.SessionComplexEventChunk;
import org.wso2.siddhi.core.event.stream.StreamEvent;

import java.io.Serializable;

/**
 * This keeps the information of a session key. i.e. current session and the previous session
 */
public class SessionContainer implements Serializable {

    private String key;
    private SessionComplexEventChunk<StreamEvent> currentSession;
    private SessionComplexEventChunk<StreamEvent> previousSession;

    public SessionContainer(String key) {
        currentSession = new SessionComplexEventChunk<>(key);
        previousSession = new SessionComplexEventChunk<>(key);
        this.key = key;
    }

    public SessionContainer() {
        currentSession = new SessionComplexEventChunk<>();
        previousSession = new SessionComplexEventChunk<>();
    }

    public long getCurrentSessionEndTimestamp() {
        if (currentSession.getFirst() != null) {
            return currentSession.getEndTimestamp();
        } else {
            return -1;
        }
    }

    public long getPreviousSessionEndTimestamp() {
        if (previousSession.getFirst() != null) {
            return previousSession.getEndTimestamp();
        } else {
            return -1;
        }
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public SessionComplexEventChunk<StreamEvent> getCurrentSession() {
        return currentSession;
    }

    public SessionComplexEventChunk<StreamEvent> getPreviousSession() {
        return previousSession;
    }
}


text:
<?php declare(strict_types = 1);

namespace PHPStan\PhpDoc;

use PHPStan\Broker\Broker;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\Php\PhpMethodReflection;
use PHPStan\Reflection\Php\PhpPropertyReflection;

class PhpDocBlock
{

	/** @var string */
	private $docComment;

	/** @var string */
	private $file;

	/** @var string */
	private $class;

	private function __construct(
		string $docComment,
		string $file,
		string $class
	)
	{
		$this->docComment = $docComment;
		$this->file = $file;
		$this->class = $class;
	}

	public function getDocComment(): string
	{
		return $this->docComment;
	}

	public function getFile(): string
	{
		return $this->file;
	}

	public function getClass(): string
	{
		return $this->class;
	}

	public static function resolvePhpDocBlockForProperty(
		Broker $broker,
		string $docComment,
		string $class,
		string $propertyName,
		string $file
	): self
	{
		return self::resolvePhpDocBlock(
			$broker,
			$docComment,
			$class,
			$propertyName,
			$file,
			'hasNativeProperty',
			'getNativeProperty',
			__FUNCTION__
		);
	}

	public static function resolvePhpDocBlockForMethod(
		Broker $broker,
		string $docComment,
		string $class,
		string $methodName,
		string $file
	): self
	{
		return self::resolvePhpDocBlock(
			$broker,
			$docComment,
			$class,
			$methodName,
			$file,
			'hasNativeMethod',
			'getNativeMethod',
			__FUNCTION__
		);
	}

	private static function resolvePhpDocBlock(
		Broker $broker,
		string $docComment,
		string $class,
		string $name,
		string $file,
		string $hasMethodName,
		string $getMethodName,
		string $resolveMethodName
	): self
	{
		if (
			preg_match('#\{@inheritdoc\}#i', $docComment) > 0
			&& $broker->hasClass($class)
		) {
			$classReflection = $broker->getClass($class);
			if ($classReflection->getParentClass() !== false) {
				$parentClassReflection = $classReflection->getParentClass();
				$phpDocBlockFromClass = self::resolvePhpDocBlockFromClass(
					$broker,
					$parentClassReflection,
					$name,
					$hasMethodName,
					$getMethodName,
					$resolveMethodName
				);
				if ($phpDocBlockFromClass !== null) {
					return $phpDocBlockFromClass;
				}
			}

			foreach ($classReflection->getInterfaces() as $interface) {
				$phpDocBlockFromClass = self::resolvePhpDocBlockFromClass(
					$broker,
					$interface,
					$name,
					$hasMethodName,
					$getMethodName,
					$resolveMethodName
				);
				if ($phpDocBlockFromClass !== null) {
					return $phpDocBlockFromClass;
				}
			}
		}

		return new self($docComment, $file, $class);
	}

	private static function resolvePhpDocBlockFromClass(
		Broker $broker,
		ClassReflection $classReflection,
		string $name,
		string $hasMethodName,
		string $getMethodName,
		string $resolveMethodName
	): ?self
	{
		if ($classReflection->getFileName() !== false && $classReflection->$hasMethodName($name)) {
			/** @var \PHPStan\Reflection\PropertyReflection|\PHPStan\Reflection\MethodReflection $parentReflection */
			$parentReflection = $classReflection->$getMethodName($name);
			if (
				!$parentReflection instanceof PhpPropertyReflection
				&& !$parentReflection instanceof PhpMethodReflection
			) {
				return null;
			}
			if ($parentReflection->getDocComment() !== false) {
				return self::$resolveMethodName(
					$broker,
					$parentReflection->getDocComment(),
					$classReflection->getName(),
					$name,
					$classReflection->getFileName()
				);
			}
		}

		return null;
	}

}


text:
@interface MFViewController ()

@end

@implementation MFViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.

    MFAction *action1 = [MFAction action:@"Say Hello" block:^{
        [MFAlert alert:@"Message" message:@"Hello there!"];
    }];

    MFAction *action2 = [MFAction action:@"Say Bye" block:^{
        [MFAlert alert:@"Message" message:@"Bye Now!"];
    }];

    MFAction *cancel = [MFAction action:@"Cancel" block:nil];

    [MFActionSheet selectAction:@[action1,action2]
                          title:@"Select an Option"
                         cancel:cancel];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
/* Expand width of fields for the module and courses tables to ensure they can handle
 * the full possible width of a Learn course code.
 */

ALTER TABLE MODULE
  MODIFY LEARN_COURSE_CODE VARCHAR2(106);

ALTER TABLE MODULE_COURSE
  MODIFY LEARN_COURSE_CODE VARCHAR2(106);


text:
namespace content {

class WebUI;

// Implements the mojo endpoint for the Conversion WebUI which proxies calls to
// the ConversionManager to get information about stored conversion data. Owned
// by ConversionInternalsUI.
class ConversionInternalsHandlerImpl
    : public ::mojom::ConversionInternalsHandler {
 public:
  ConversionInternalsHandlerImpl(
      WebUI* web_ui,
      mojo::PendingReceiver<::mojom::ConversionInternalsHandler> receiver);
  ~ConversionInternalsHandlerImpl() override;

  // mojom::ConversionInternalsHandler overrides:
  void IsMeasurementEnabled(
      ::mojom::ConversionInternalsHandler::IsMeasurementEnabledCallback
          callback) override;
  void GetActiveImpressions(
      ::mojom::ConversionInternalsHandler::GetActiveImpressionsCallback
          callback) override;
  void GetPendingReports(
      ::mojom::ConversionInternalsHandler::GetPendingReportsCallback callback)
      override;
  void SendPendingReports(
      ::mojom::ConversionInternalsHandler::SendPendingReportsCallback callback)
      override;
  void ClearStorage(::mojom::ConversionInternalsHandler::ClearStorageCallback
                        callback) override;

  void SetConversionManagerProviderForTesting(
      std::unique_ptr<ConversionManager::Provider> manager_provider);

 private:
  WebUI* web_ui_;
  std::unique_ptr<ConversionManager::Provider> manager_provider_;

  mojo::Receiver<::mojom::ConversionInternalsHandler> receiver_;
};

}  // namespace content

#endif  // CONTENT_BROWSER_CONVERSIONS_CONVERSION_INTERNALS_HANDLER_IMPL_H_


text:
package com.auth0.jwt.impl;

import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.Claim;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * The JsonNodeClaim retrieves a claim value from a JsonNode object.
 */
class JsonNodeClaim implements Claim {

    private final JsonNode data;

    private JsonNodeClaim(JsonNode node) {
        this.data = node;
    }

    @Override
    public Boolean asBoolean() {
        return !data.isBoolean() ? null : data.asBoolean();
    }

    @Override
    public Integer asInt() {
        return !data.isNumber() ? null : data.asInt();
    }

    @Override
    public Long asLong() { return !data.isNumber() ? null : data.asLong(); }

    @Override
    public Double asDouble() {
        return !data.isNumber() ? null : data.asDouble();
    }

    @Override
    public String asString() {
        return !data.isTextual() ? null : data.asText();
    }

    @Override
    public Date asDate() {
        if (!data.canConvertToLong()) {
            return null;
        }
        long seconds = data.asLong();
        return new Date(seconds * 1000);
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> T[] asArray(Class<T> tClazz) throws JWTDecodeException {
        if (!data.isArray()) {
            return null;
        }

        ObjectMapper mapper = new ObjectMapper();
        T[] arr = (T[]) Array.newInstance(tClazz, data.size());
        for (int i = 0; i < data.size(); i++) {
            try {
                arr[i] = mapper.treeToValue(data.get(i), tClazz);
            } catch (JsonProcessingException e) {
                throw new JWTDecodeException("Couldn't map the Claim's array contents to " + tClazz.getSimpleName(), e);
            }
        }
        return arr;
    }

    @Override
    public <T> List<T> asList(Class<T> tClazz) throws JWTDecodeException {
        if (!data.isArray()) {
            return null;
        }

        ObjectMapper mapper = new ObjectMapper();
        List<T> list = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            try {
                list.add(mapper.treeToValue(data.get(i), tClazz));
            } catch (JsonProcessingException e) {
                throw new JWTDecodeException("Couldn't map the Claim's array contents to " + tClazz.getSimpleName(), e);
            }
        }
        return list;
    }

    @Override
    public Map<String, Object> asMap() throws JWTDecodeException {
        if (!data.isObject()) {
            return null;
        }

        ObjectMapper mapper = new ObjectMapper();
        try {
            TypeReference<Map<String, Object>> mapType = new TypeReference<Map<String, Object>>() {
            };
            return mapper.treeAsTokens(data).readValueAs(mapType);
        } catch (IOException e) {
            throw new JWTDecodeException("Couldn't map the Claim value to Map", e);
        }
    }

    @Override
    public <T> T as(Class<T> tClazz) throws JWTDecodeException {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.treeAsTokens(data).readValueAs(tClazz);
        } catch (IOException e) {
            throw new JWTDecodeException("Couldn't map the Claim value to " + tClazz.getSimpleName(), e);
        }
    }

    @Override
    public boolean isNull() {
        return false;
    }

    /**
     * Helper method to extract a Claim from the given JsonNode tree.
     *
     * @param claimName the Claim to search for.
     * @param tree      the JsonNode tree to search the Claim in.
     * @return a valid non-null Claim.
     */
    static Claim extractClaim(String claimName, Map<String, JsonNode> tree) {
        JsonNode node = tree.get(claimName);
        return claimFromNode(node);
    }

    /**
     * Helper method to create a Claim representation from the given JsonNode.
     *
     * @param node the JsonNode to convert into a Claim.
     * @return a valid Claim instance. If the node is null or missing, a NullClaim will be returned.
     */
    static Claim claimFromNode(JsonNode node) {
        if (node == null || node.isNull() || node.isMissingNode()) {
            return new NullClaim();
        }
        return new JsonNodeClaim(node);
    }
}


text:
<ion-header>
  <ion-navbar>
    <ion-buttons begin>
      <button ion-button (click)="nav.pop()">
      <ion-icon name="back"></ion-icon>
    </button>
    </ion-buttons>
    <ion-title>View Poster</ion-title>
  </ion-navbar>
</ion-header>

<ion-content>

</ion-content>