text:
import atexit
import logging
import math
import os
import subprocess
import sys
import time

import ftdi1 as ftdi

import GPIO

logger = logging.getLogger(__name__)

FT232H_VID = 0x0403   # Default FTDI FT232H vendor ID
FT232H_PID = 0x6014   # Default FTDI FT232H product ID

MSBFIRST = 0
LSBFIRST = 1

_REPEAT_DELAY = 4

def _check_running_as_root():
    # NOTE: Checking for root with user ID 0 isn't very portable, perhaps
    # there's a better alternative?
    if os.geteuid() != 0:
        raise RuntimeError('Expected to be run by root user! Try running with sudo.')

def disable_FTDI_driver():
    """Disable the FTDI drivers for the current platform.  This is necessary
    because they will conflict with libftdi and accessing the FT232H.  Note you
    can enable the FTDI drivers again by calling enable_FTDI_driver.
    """
    logger.debug('Disabling FTDI driver.')
    if sys.platform == 'darwin':
        logger.debug('Detected Mac OSX')
        # Mac OS commands to disable FTDI driver.
        _check_running_as_root()
        subprocess.call('kextunload -b com.apple.driver.AppleUSBFTDI', shell=True)
        subprocess.call('kextunload /System/Library/Extensions/FTDIUSBSerialDriver.kext', shell=True)
    elif sys.platform.startswith('linux'):
        logger.debug('Detected Linux')
        # Linux commands to disable FTDI driver.
        _check_running_as_root()
        subprocess.call('modprobe -r -q ftdi_sio', shell=True)
        subprocess.call('modprobe -r -q usbserial', shell=True)
    # Note there is no need to disable FTDI drivers on Windows!

def enable_FTDI_driver():
    """Re-enable the FTDI drivers for the current platform."""
    logger.debug('Enabling FTDI driver.')
    if sys.platform == 'darwin':
        logger.debug('Detected Mac OSX')
        # Mac OS commands to enable FTDI driver.
        _check_running_as_root()
        subprocess.check_call('kextload -b com.apple.driver.AppleUSBFTDI', shell=True)
        subprocess.check_call('kextload /System/Library/Extensions/FTDIUSBSerialDriver.kext', shell=True)
    elif sys.platform.startswith('linux'):
        logger.debug('Detected Linux')
        # Linux commands to enable FTDI driver.
        _check_running_as_root()
        subprocess.check_call('modprobe -q ftdi_sio', shell=True)
        subprocess.check_call('modprobe -q usbserial', shell=True)

def use_FT232H():
    """Disable any built in FTDI drivers which will conflict and cause problems
    with libftdi (which is used to communicate with the FT232H).  Will register
    an exit function so the drivers are re-enabled on program exit.
    """
    disable_FTDI_driver()
    atexit.register(enable_FTDI_driver)

class FT232H(GPIO.BaseGPIO):
    # Make GPIO constants that match main GPIO class for compatibility.
    HIGH = GPIO.HIGH
    LOW  = GPIO.LOW
    IN   = GPIO.IN
    OUT  = GPIO.OUT

    def __init__(self, vid=FT232H_VID, pid=FT232H_PID):
        """Create a FT232H object.  Will search for the first available FT232H
        device with the specified USB vendor ID and product ID (defaults to
        FT232H default VID & PID).
        """
        # Initialize FTDI device connection.
        self._ctx = ftdi.new()
        if self._ctx == 0:
            raise RuntimeError('ftdi_new failed! Is libftdi1 installed?')
        # Register handler to close and cleanup FTDI context on program exit.
        atexit.register(self.close)
        # Open USB connection for specified VID and PID.
        self._check(ftdi.usb_open, vid, pid)
        # Reset device.
        self._check(ftdi.usb_reset)
        # Disable flow control. Commented out because it is unclear if this is necessary.
        #self._check(ftdi.setflowctrl, ftdi.SIO_DISABLE_FLOW_CTRL)
        # Change read & write buffers to maximum size, 65535 bytes.
        self._check(ftdi.read_data_set_chunksize, 65535)
        self._check(ftdi.write_data_set_chunksize, 65535)
        # Clear pending read data & write buffers.
        self._check(ftdi.usb_purge_buffers)
        # Enable MPSSE and syncronize communication with device.
        self._mpsse_enable()
        self._mpsse_sync()
        # Initialize all GPIO as inputs.
        self._write('\x80\x00\x00\x82\x00\x00')
        self._direction = 0x0000
        self._level = 0x0000

    def close(self):
        """Close the FTDI device.  Will be automatically called when the program ends."""
        if self._ctx is not None:
            ftdi.free(self._ctx)
        self._ctx = None

    def _write(self, string):
        """Helper function to call write_data on the provided FTDI device and
        verify it succeeds.
        """
        # Get modem status. Useful to enable for debugging.
        #ret, status = ftdi.poll_modem_status(self._ctx)
        #if ret == 0:
        #	logger.debug('Modem status {0:02X}'.format(status))
        #else:
        #	logger.debug('Modem status error {0}'.format(ret))
        length = len(string)
        ret = ftdi.write_data(self._ctx, string, length)
        # Log the string that was written in a python hex string format using a very
        # ugly one-liner list comprehension for brevity.
        #logger.debug('Wrote {0}'.format(''.join(['\\x{0:02X}'.format(ord(x)) for x in string])))
        if ret < 0:
            raise RuntimeError('ftdi_write_data failed with error {0}: {1}'.format(ret, ftdi.get_error_string(self._ctx)))
        if ret != length:
            raise RuntimeError('ftdi_write_data expected to write {0} bytes but actually wrote {1}!'.format(length, ret))

    def _check(self, command, *args):
        """Helper function to call the provided command on the FTDI device and
        verify the response matches the expected value.
        """
        ret = command(self._ctx, *args)
        logger.debug('Called ftdi_{0} and got response {1}.'.format(command.__name__, ret))
        if ret != 0:
            raise RuntimeError('ftdi_{0} failed with error {1}: {2}'.format(command.__name__, ret, ftdi.get_error_string(self._ctx)))

    def _poll_read(self, expected, timeout_s=5.0):
        """Helper function to continuously poll reads on the FTDI device until an
        expected number of bytes are returned.  Will throw a timeout error if no
        data is received within the specified number of timeout seconds.  Returns
        the read data as a string if successful, otherwise raises an execption.
        """
        start = time.time()
        # Start with an empty response buffer.
        response = bytearray(expected)
        index = 0
        # Loop calling read until the response buffer is full or a timeout occurs.
        while time.time() - start <= timeout_s:
            ret, data = ftdi.read_data(self._ctx, expected - index)
            # Fail if there was an error reading data.
            if ret < 0:
                raise RuntimeError('ftdi_read_data failed with error code {0}.'.format(ret))
            # Add returned data to the buffer.
            response[index:index+ret] = data[:ret]
            index += ret
            # Buffer is full, return the result data.
            if index >= expected:
                return str(response)
            time.sleep(0.01)
        raise RuntimeError('Timeout while polling ftdi_read_data for {0} bytes!'.format(expected))

    def _mpsse_enable(self):
        """Enable MPSSE mode on the FTDI device."""
        # Reset MPSSE by sending mask = 0 and mode = 0
        self._check(ftdi.set_bitmode, 0, 0)
        # Enable MPSSE by sending mask = 0 and mode = 2
        self._check(ftdi.set_bitmode, 0, 2)

    def _mpsse_sync(self, max_retries=10):
        """Synchronize buffers with MPSSE by sending bad opcode and reading expected
        error response.  Should be called once after enabling MPSSE."""
        # Send a bad/unknown command (0xAB), then read buffer until bad command
        # response is found.
        self._write('\xAB')
        # Keep reading until bad command response (0xFA 0xAB) is returned.
        # Fail if too many read attempts are made to prevent sticking in a loop.
        tries = 0
        sync = False
        while not sync:
            data = self._poll_read(2)
            if data == '\xFA\xAB':
                sync = True
            tries += 1
            if tries >= max_retries:
                raise RuntimeError('Could not synchronize with FT232H!')

    def mpsse_set_clock(self, clock_hz, adaptive=False, three_phase=False):
        """Set the clock speed of the MPSSE engine.  Can be any value from 450hz
        to 30mhz and will pick that speed or the closest speed below it.
        """
        # Disable clock divisor by 5 to enable faster speeds on FT232H.
        self._write('\x8A')
        # Turn on/off adaptive clocking.
        if adaptive:
            self._write('\x96')
        else:
            self._write('\x97')
        # Turn on/off three phase clock (needed for I2C).
        # Also adjust the frequency for three-phase clocking as specified in section 2.2.4
        # of this document:
        #   http://www.ftdichip.com/Support/Documents/AppNotes/AN_255_USB%20to%20I2C%20Example%20using%20the%20FT232H%20and%20FT201X%20devices.pdf
        if three_phase:
            self._write('\x8C')
        else:
            self._write('\x8D')
        # Compute divisor for requested clock.
        # Use equation from section 3.8.1 of:
        #  http://www.ftdichip.com/Support/Documents/AppNotes/AN_108_Command_Processor_for_MPSSE_and_MCU_Host_Bus_Emulation_Modes.pdf
        # Note equation is using 60mhz master clock instead of 12mhz.
        divisor = int(math.ceil((30000000.0-float(clock_hz))/float(clock_hz))) & 0xFFFF
        if three_phase:
            divisor = int(divisor*(2.0/3.0))
        logger.debug('Setting clockspeed with divisor value {0}'.format(divisor))
        # Send command to set divisor from low and high byte values.
        self._write(str(bytearray((0x86, divisor & 0xFF, (divisor >> 8) & 0xFF))))

    def mpsse_read_gpio(self):
        """Read both GPIO bus states and return a 16 bit value with their state.
        D0-D7 are the lower 8 bits and C0-C7 are the upper 8 bits.
        """
        # Send command to read low byte and high byte.
        self._write('\x81\x83')
        # Wait for 2 byte response.
        data = self._poll_read(2)
        # Assemble response into 16 bit value.
        low_byte = ord(data[0])
        high_byte = ord(data[1])
        logger.debug('Read MPSSE GPIO low byte = {0:02X} and high byte = {1:02X}'.format(low_byte, high_byte))
        return (high_byte << 8) | low_byte

    def mpsse_gpio(self):
        """Return command to update the MPSSE GPIO state to the current direction
        and level.
        """
        level_low  = chr(self._level & 0xFF)
        level_high = chr((self._level >> 8) & 0xFF)
        dir_low  = chr(self._direction & 0xFF)
        dir_high = chr((self._direction >> 8) & 0xFF)
        return str(bytearray((0x80, level_low, dir_low, 0x82, level_high, dir_high)))

    def mpsse_write_gpio(self):
        """Write the current MPSSE GPIO state to the FT232H chip."""
        self._write(self.mpsse_gpio())

    def get_i2c_device(self, address, **kwargs):
        """Return an I2CDevice instance using this FT232H object and the provided
        I2C address.  Meant to be passed as the i2c_provider parameter to objects
        which use the Adafruit_Python_GPIO library for I2C.
        """
        return I2CDevice(self, address, **kwargs)

    # GPIO functions below:

    def _setup_pin(self, pin, mode):
        if pin < 0 or pin > 15:
            raise ValueError('Pin must be between 0 and 15 (inclusive).')
        if mode not in (GPIO.IN, GPIO.OUT):
            raise ValueError('Mode must be GPIO.IN or GPIO.OUT.')
        if mode == GPIO.IN:
            # Set the direction and level of the pin to 0.
            self._direction &= ~(1 << pin) & 0xFFFF
            self._level     &= ~(1 << pin) & 0xFFFF
        else:
            # Set the direction of the pin to 1.
            self._direction |= (1 << pin) & 0xFFFF

    def setup(self, pin, mode):
        """Set the input or output mode for a specified pin.  Mode should be
        either OUT or IN."""
        self._setup_pin(pin, mode)
        self.mpsse_write_gpio()

    def setup_pins(self, pins, values={}, write=True):
        """Setup multiple pins as inputs or outputs at once.  Pins should be a
        dict of pin name to pin mode (IN or OUT).  Optional starting values of
        pins can be provided in the values dict (with pin name to pin value).
        """
        # General implementation that can be improved by subclasses.
        for pin, mode in pins.iteritems():
            self._setup_pin(pin, mode)
        for pin, value in values.iteritems():
            self._output_pin(pin, value)
        if write:
            self.mpsse_write_gpio()

    def _output_pin(self, pin, value):
        if value:
            self._level |= (1 << pin) & 0xFFFF
        else:
            self._level &= ~(1 << pin) & 0xFFFF

    def output(self, pin, value):
        """Set the specified pin the provided high/low value.  Value should be
        either HIGH/LOW or a boolean (true = high)."""
        if pin < 0 or pin > 15:
            raise ValueError('Pin must be between 0 and 15 (inclusive).')
        self._output_pin(pin, value)
        self.mpsse_write_gpio()

    def output_pins(self, pins, write=True):
        """Set multiple pins high or low at once.  Pins should be a dict of pin
        name to pin value (HIGH/True for 1, LOW/False for 0).  All provided pins
        will be set to the given values.
        """
        for pin, value in pins.iteritems():
            self._output_pin(pin, value)
        if write:
            self.mpsse_write_gpio()

    def input(self, pin):
        """Read the specified pin and return HIGH/true if the pin is pulled high,
        or LOW/false if pulled low."""
        if pin < 0 or pin > 15:
            raise ValueError('Pin must be between 0 and 15 (inclusive).')
        pins = self.mpsse_read_gpio()
        return ((pins >> pin) & 0x0001) == 1

class SPI(object):
    def __init__(self, ft232h, cs=None, max_speed_hz=1000000, mode=0, bitorder=MSBFIRST):
        self._ft232h = ft232h
        # Initialize chip select pin if provided to output high.
        if cs is not None:
            ft232h.setup(cs, GPIO.OUT)
            ft232h.set_high(cs)
        self._cs = cs
        # Initialize clock, mode, and bit order.
        self.set_clock_hz(max_speed_hz)
        self.set_mode(mode)
        self.set_bit_order(bitorder)

    def _assert_cs(self):
        if self._cs is not None:
            self._ft232h.set_low(self._cs)

    def _deassert_cs(self):
        if self._cs is not None:
            self._ft232h.set_high(self._cs)

    def set_clock_hz(self, hz):
        """Set the speed of the SPI clock in hertz.  Note that not all speeds
        are supported and a lower speed might be chosen by the hardware.
        """
        self._ft232h.mpsse_set_clock(hz)

    def set_mode(self, mode):
        """Set SPI mode which controls clock polarity and phase.  Should be a
        numeric value 0, 1, 2, or 3.  See wikipedia page for details on meaning:
        http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
        """
        if mode < 0 or mode > 3:
            raise ValueError('Mode must be a value 0, 1, 2, or 3.')
        if mode == 0:
            # Mode 0 captures on rising clock, propagates on falling clock
            self.write_clock_ve = 1
            self.read_clock_ve  = 0
            # Clock base is low.
            clock_base = GPIO.LOW
        elif mode == 1:
            # Mode 1 capture of falling edge, propagate on rising clock
            self.write_clock_ve = 0
            self.read_clock_ve  = 1
            # Clock base is low.
            clock_base = GPIO.LOW
        elif mode == 2:
            # Mode 2 capture on rising clock, propagate on falling clock
            self.write_clock_ve = 1
            self.read_clock_ve  = 0
            # Clock base is high.
            clock_base = GPIO.HIGH
        elif mode == 3:
            # Mode 3 capture on falling edge, propagage on rising clock
            self.write_clock_ve = 0
            self.read_clock_ve  = 1
            # Clock base is high.
            clock_base = GPIO.HIGH
        # Set clock and DO as output, DI as input.  Also start clock at its base value.
        self._ft232h.setup_pins({0: GPIO.OUT, 1: GPIO.OUT, 2: GPIO.IN}, {0: clock_base})

    def set_bit_order(self, order):
        """Set order of bits to be read/written over serial lines.  Should be
        either MSBFIRST for most-significant first, or LSBFIRST for
        least-signifcant first.
        """
        if order == MSBFIRST:
            self.lsbfirst = 0
        elif order == LSBFIRST:
            self.lsbfirst = 1
        else:
            raise ValueError('Order must be MSBFIRST or LSBFIRST.')

    def write(self, data):
        """Half-duplex SPI write.  The specified array of bytes will be clocked
        out the MOSI line.
        """
        # Build command to write SPI data.
        command = 0x10 | (self.lsbfirst << 3) | self.write_clock_ve
        logger.debug('SPI write with command {0:2X}.'.format(command))
        # Compute length low and high bytes.
        # NOTE: Must actually send length minus one because the MPSSE engine
        # considers 0 a length of 1 and FFFF a length of 65536
        length = len(data)-1
        len_low  = length & 0xFF
        len_high = (length >> 8) & 0xFF
        self._assert_cs()
        # Send command and length.
        self._ft232h._write(str(bytearray((command, len_low, len_high))))
        # Send data.
        self._ft232h._write(str(bytearray(data)))
        self._deassert_cs()

    def read(self, length):
        """Half-duplex SPI read.  The specified length of bytes will be clocked
        in the MISO line and returned as a bytearray object.
        """
        # Build command to read SPI data.
        command = 0x20 | (self.lsbfirst << 3) | (self.read_clock_ve << 2)
        logger.debug('SPI read with command {0:2X}.'.format(command))
        # Compute length low and high bytes.
        # NOTE: Must actually send length minus one because the MPSSE engine
        # considers 0 a length of 1 and FFFF a length of 65536
        len_low  = (length-1) & 0xFF
        len_high = ((length-1) >> 8) & 0xFF
        self._assert_cs()
        # Send command and length.
        self._ft232h._write(str(bytearray((command, len_low, len_high, 0x87))))
        self._deassert_cs()
        # Read response bytes.
        return bytearray(self._ft232h._poll_read(length))

    def transfer(self, data):
        """Full-duplex SPI read and write.  The specified array of bytes will be
        clocked out the MOSI line, while simultaneously bytes will be read from
        the MISO line.  Read bytes will be returned as a bytearray object.
        """
        # Build command to read and write SPI data.
        command = 0x30 | (self.lsbfirst << 3) | (self.read_clock_ve << 2) | self.write_clock_ve
        logger.debug('SPI transfer with command {0:2X}.'.format(command))
        # Compute length low and high bytes.
        # NOTE: Must actually send length minus one because the MPSSE engine
        # considers 0 a length of 1 and FFFF a length of 65536
        length = len(data)
        len_low  = (length-1) & 0xFF
        len_high = ((length-1) >> 8) & 0xFF
        # Send command and length.
        self._assert_cs()
        self._ft232h._write(str(bytearray((command, len_low, len_high))))
        self._ft232h._write(str(bytearray(data)))
        self._ft232h._write('\x87')
        self._deassert_cs()
        # Read response bytes.
        return bytearray(self._ft232h._poll_read(length))

class I2CDevice(object):
    """Class for communicating with an I2C device using the smbus library.
    Allows reading and writing 8-bit, 16-bit, and byte array values to registers
    on the device."""
    # Note that most of the functions in this code are adapted from this app note:
    #  http://www.ftdichip.com/Support/Documents/AppNotes/AN_255_USB%20to%20I2C%20Example%20using%20the%20FT232H%20and%20FT201X%20devices.pdf
    def __init__(self, ft232h, address, clock_hz=100000):
        """Create an instance of the I2C device at the specified address on the
        specified I2C bus number."""
        self._address = address
        self._ft232h = ft232h
        # Enable clock with three phases for I2C.
        self._ft232h.mpsse_set_clock(clock_hz, three_phase=True)
        # Enable drive-zero mode to drive outputs low on 0 and tri-state on 1.
        # This matches the protocol for I2C communication so multiple devices can
        # share the I2C bus.
        self._ft232h._write('\x9E\x07\x00')
        self._idle()

    def _idle(self):
        """Put I2C lines into idle state."""
        # Put the I2C lines into an idle state with SCL and SDA high.
        self._ft232h.setup_pins({0: GPIO.OUT, 1: GPIO.OUT, 2: GPIO.IN},
                                {0: GPIO.HIGH, 1: GPIO.HIGH})

    def _transaction_start(self):
        """Start I2C transaction."""
        # Clear command buffer and expected response bytes.
        self._command = []
        self._expected = 0

    def _transaction_end(self):
        """End I2C transaction and get response bytes, including ACKs."""
        # Ask to return response bytes immediately.
        self._command.append('\x87')
        # Send the entire command to the MPSSE.
        self._ft232h._write(''.join(self._command))
        # Read response bytes and return them.
        return bytearray(self._ft232h._poll_read(self._expected))

    def _i2c_start(self):
        """Send I2C start signal. Must be called within a transaction start/end.
        """
        # Set SCL high and SDA low, repeat 4 times to stay in this state for a
        # short period of time.
        self._ft232h.output_pins({0: GPIO.HIGH, 1: GPIO.LOW}, write=False)
        self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)
        # Now drop SCL to low (again repeat 4 times for short delay).
        self._ft232h.output_pins({0: GPIO.LOW, 1: GPIO.LOW}, write=False)
        self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)

    def _i2c_idle(self):
        """Set I2C signals to idle state with SCL and SDA at a high value. Must
        be called within a transaction start/end.
        """
        self._ft232h.output_pins({0: GPIO.HIGH, 1: GPIO.HIGH}, write=False)
        self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)

    def _i2c_stop(self):
        """Send I2C stop signal. Must be called within a transaction start/end.
        """
        # Set SCL low and SDA low for a short period.
        self._ft232h.output_pins({0: GPIO.LOW, 1: GPIO.LOW}, write=False)
        self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)
        # Set SCL high and SDA low for a short period.
        self._ft232h.output_pins({0: GPIO.HIGH, 1: GPIO.LOW}, write=False)
        self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)
        # Finally set SCL high and SDA high for a short period.
        self._ft232h.output_pins({0: GPIO.HIGH, 1: GPIO.HIGH}, write=False)
        self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)

    def _i2c_read_bytes(self, length=1):
        """Read the specified number of bytes from the I2C bus.  Length is the
        number of bytes to read (must be 1 or more).
        """
        for i in range(length-1):
            # Read a byte and send ACK.
            self._command.append('\x20\x00\x00\x13\x00\x00')
            # Make sure pins are back in idle state with clock low and data high.
            self._ft232h.output_pins({0: GPIO.LOW, 1: GPIO.HIGH}, write=False)
            self._command.append(self._ft232h.mpsse_gpio())
        # Read last byte and send NAK.
        self._command.append('\x20\x00\x00\x13\x00\xFF')
        # Make sure pins are back in idle state with clock low and data high.
        self._ft232h.output_pins({0: GPIO.LOW, 1: GPIO.HIGH}, write=False)
        self._command.append(self._ft232h.mpsse_gpio())
        # Increase expected number of bytes.
        self._expected += length

    def _i2c_write_bytes(self, data):
        """Write the specified number of bytes to the chip."""
        for byte in data:
            # Write byte.
            self._command.append(str(bytearray((0x11, 0x00, 0x00, byte))))
            # Make sure pins are back in idle state with clock low and data high.
            self._ft232h.output_pins({0: GPIO.LOW, 1: GPIO.HIGH}, write=False)
            self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)
            # Read bit for ACK/NAK.
            self._command.append('\x22\x00')
        # Increase expected response bytes.
        self._expected += len(data)

    def _address_byte(self, read=True):
        """Return the address byte with the specified R/W bit set.  If read is
        True the R/W bit will be 1, otherwise the R/W bit will be 0.
        """
        if read:
            return (self._address << 1) | 0x01
        else:
            return self._address << 1

    def _verify_acks(self, response):
        """Check all the specified bytes have the ACK bit set.  Throws a
        RuntimeError exception if not all the ACKs are set.
        """
        for byte in response:
            if byte & 0x01 != 0x00:
                raise RuntimeError('Failed to find expected I2C ACK!')

    def ping(self):
        """Attempt to detect if a device at this address is present on the I2C
        bus.  Will send out the device's address for writing and verify an ACK
        is received.  Returns true if the ACK is received, and false if not.
        """
        self._idle()
        self._transaction_start()
        self._i2c_start()
        self._i2c_write_bytes([self._address_byte(False)])
        self._i2c_stop()
        response = self._transaction_end()
        if len(response) != 1:
            raise RuntimeError('Expected 1 response byte but received {0} byte(s).'.format(len(response)))
        return ((response[0] & 0x01) == 0x00)

    def writeRaw8(self, value):
        """Write an 8-bit value on the bus (without register)."""
        value = value & 0xFF
        self._idle()
        self._transaction_start()
        self._i2c_start()
        self._i2c_write_bytes([self._address_byte(False), value])
        self._i2c_stop()
        response = self._transaction_end()
        self._verify_acks(response)

    def write8(self, register, value):
        """Write an 8-bit value to the specified register."""
        value = value & 0xFF
        self._idle()
        self._transaction_start()
        self._i2c_start()
        self._i2c_write_bytes([self._address_byte(False), register, value])
        self._i2c_stop()
        response = self._transaction_end()
        self._verify_acks(response)

    def write16(self, register, value, little_endian=True):
        """Write a 16-bit value to the specified register."""
        value = value & 0xFFFF
        value_low  = value & 0xFF
        value_high = (value >> 8) & 0xFF
        if not little_endian:
            value_low, value_high = value_high, value_low
        self._idle()
        self._transaction_start()
        self._i2c_start()
        self._i2c_write_bytes([self._address_byte(False), register, value_low,
                                value_high])
        self._i2c_stop()
        response = self._transaction_end()
        self._verify_acks(response)

    def writeList(self, register, data):
        """Write bytes to the specified register."""
        self._idle()
        self._transaction_start()
        self._i2c_start()
        self._i2c_write_bytes([self._address_byte(False), register] + data)
        self._i2c_stop()
        response = self._transaction_end()
        self._verify_acks(response)

    def readList(self, register, length):
        """Read a length number of bytes from the specified register.  Results
        will be returned as a bytearray."""
        if length <= 0:
            raise ValueError("Length must be at least 1 byte.")
        self._idle()
        self._transaction_start()
        self._i2c_start()
        self._i2c_write_bytes([self._address_byte(True), register])
        self._i2c_stop()
        self._i2c_idle()
        self._i2c_start()
        self._i2c_read_bytes(length)
        self._i2c_stop()
        response = self._transaction_end()
        self._verify_acks(response[:-length])
        return response[-length:]

    def readRaw8(self):
        """Read an 8-bit value on the bus (without register)."""
        self._idle()
        self._transaction_start()
        self._i2c_start()
        self._i2c_write_bytes([self._address_byte(False)])
        self._i2c_stop()
        self._i2c_idle()
        self._i2c_start()
        self._i2c_write_bytes([self._address_byte(True)])
        self._i2c_read_bytes(1)
        self._i2c_stop()
        response = self._transaction_end()
        self._verify_acks(response[:-1])
        return response[-1]

    def readU8(self, register):
        """Read an unsigned byte from the specified register."""
        self._idle()
        self._transaction_start()
        self._i2c_start()
        self._i2c_write_bytes([self._address_byte(False), register])
        self._i2c_stop()
        self._i2c_idle()
        self._i2c_start()
        self._i2c_write_bytes([self._address_byte(True)])
        self._i2c_read_bytes(1)
        self._i2c_stop()
        response = self._transaction_end()
        self._verify_acks(response[:-1])
        return response[-1]

    def readS8(self, register):
        """Read a signed byte from the specified register."""
        result = self.readU8(register)
        if result > 127:
            result -= 256
        return result

    def readU16(self, register, little_endian=True):
        """Read an unsigned 16-bit value from the specified register, with the
        specified endianness (default little endian, or least significant byte
        first)."""
        self._idle()
        self._transaction_start()
        self._i2c_start()
        self._i2c_write_bytes([self._address_byte(False), register])
        self._i2c_stop()
        self._i2c_idle()
        self._i2c_start()
        self._i2c_write_bytes([self._address_byte(True)])
        self._i2c_read_bytes(2)
        self._i2c_stop()
        response = self._transaction_end()
        self._verify_acks(response[:-2])
        if little_endian:
            return (response[-1] << 8) | response[-2]
        else:
            return (response[-2] << 8) | response[-1]

    def readS16(self, register, little_endian=True):
        """Read a signed 16-bit value from the specified register, with the
        specified endianness (default little endian, or least significant byte
        first)."""
        result = self.readU16(register, little_endian)
        if result > 32767:
            result -= 65536
        return result

    def readU16LE(self, register):
        """Read an unsigned 16-bit value from the specified register, in little
        endian byte order."""
        return self.readU16(register, little_endian=True)

    def readU16BE(self, register):
        """Read an unsigned 16-bit value from the specified register, in big
        endian byte order."""
        return self.readU16(register, little_endian=False)

    def readS16LE(self, register):
        """Read a signed 16-bit value from the specified register, in little
        endian byte order."""
        return self.readS16(register, little_endian=True)

    def readS16BE(self, register):
        """Read a signed 16-bit value from the specified register, in big
        endian byte order."""
        return self.readS16(register, little_endian=False)


text:
namespace swift {

class FunctionSignaturePartialSpecializer;
class SILOptFunctionBuilder;

namespace OptRemark {
class Emitter;
} // namespace OptRemark

/// Tries to specialize an \p Apply of a generic function. It can be a full
/// apply site or a partial apply.
/// Replaced and now dead instructions are returned in \p DeadApplies.
/// New created functions, like the specialized callee and thunks, are returned
/// in \p NewFunctions.
///
/// This is the top-level entry point for specializing an existing call site.
void trySpecializeApplyOfGeneric(
    SILOptFunctionBuilder &FunctionBuilder,
    ApplySite Apply, DeadInstructionSet &DeadApplies,
    llvm::SmallVectorImpl<SILFunction *> &NewFunctions,
    OptRemark::Emitter &ORE,
    bool isMandatory);

/// Helper class to describe re-abstraction of function parameters done during
/// specialization.
///
/// Specifically, it contains information which formal parameters and returns
/// are changed from indirect values to direct values.
class ReabstractionInfo {
  /// A 1-bit means that this argument (= either indirect return value or
  /// parameter) is converted from indirect to direct.
  SmallBitVector Conversions;

  /// For each bit set in Conversions, there is a bit set in TrivialArgs if the
  /// argument has a trivial type.
  SmallBitVector TrivialArgs;

  /// Set to true if the function has a re-abstracted (= converted from
  /// indirect to direct) resilient argument or return type. This can happen if
  /// the function is compiled within the type's resilience domain, i.e. in
  /// its module (where the type is loadable).
  /// In this case we need to generate a different mangled name for the
  /// function to distinguish it from functions in other modules, which cannot
  /// re-abstract this resilient type.
  /// Fortunately, a flag is sufficient to describe this: either a function has
  /// re-abstracted resilient types or not. It cannot happen that two
  /// functions have two different subsets of re-abstracted resilient parameter
  /// types.
  bool hasConvertedResilientParams = false;

  /// If set, indirect to direct conversions should be performed by the generic
  /// specializer.
  bool ConvertIndirectToDirect;

  /// The first NumResults bits in Conversions refer to formal indirect
  /// out-parameters.
  unsigned NumFormalIndirectResults;

  /// The function type after applying the substitutions used to call the
  /// specialized function.
  CanSILFunctionType SubstitutedType;

  /// The function type after applying the re-abstractions on the
  /// SubstitutedType.
  CanSILFunctionType SpecializedType;

  /// The generic environment to be used by the specialization.
  GenericEnvironment *SpecializedGenericEnv;

  /// The generic signature of the specialization.
  /// It is nullptr if the specialization is not polymorphic.
  GenericSignature SpecializedGenericSig;

  // Set of substitutions from callee's invocation before
  // any transformations performed by the generic specializer.
  //
  // Maps callee's generic parameters to caller's archetypes.
  SubstitutionMap CalleeParamSubMap;

  // Set of substitutions to be used to invoke a specialized function.
  //
  // Maps generic parameters of the specialized callee function to caller's
  // archetypes.
  SubstitutionMap CallerParamSubMap;

  // Replaces archetypes of the original callee with archetypes
  // or concrete types, if they were made concrete) of the specialized
  // callee.
  SubstitutionMap ClonerParamSubMap;

  // Reference to the original generic non-specialized callee function.
  SILFunction *Callee;

  // The module the specialization is created in.
  ModuleDecl *TargetModule = nullptr;

  bool isWholeModule = false;

  // The apply site which invokes the generic function.
  ApplySite Apply;

  // Set if a specialized function has unbound generic parameters.
  bool HasUnboundGenericParams;

  // Substitutions to be used for creating a new function type
  // for the specialized function.
  //
  // Maps original callee's generic parameters to specialized callee's
  // generic parameters.
  // It uses interface types.
  SubstitutionMap CallerInterfaceSubs;

  bool isPrespecialization = false;

  // Is the generated specialization going to be serialized?
  IsSerialized_t Serialized;

  enum TypeCategory {
    NotLoadable,
    Loadable,
    LoadableAndTrivial
  };

  unsigned param2ArgIndex(unsigned ParamIdx) const  {
    return ParamIdx + NumFormalIndirectResults;
  }

  // Create a new substituted type with the updated signature.
  CanSILFunctionType createSubstitutedType(SILFunction *OrigF,
                                           SubstitutionMap SubstMap,
                                           bool HasUnboundGenericParams);

  void createSubstitutedAndSpecializedTypes();

  TypeCategory getReturnTypeCategory(const SILResultInfo &RI,
                                     const SILFunctionConventions &substConv,
                                     TypeExpansionContext typeExpansion);

  TypeCategory getParamTypeCategory(const SILParameterInfo &PI,
                                    const SILFunctionConventions &substConv,
                                    TypeExpansionContext typeExpansion);

  bool prepareAndCheck(ApplySite Apply, SILFunction *Callee,
                       SubstitutionMap ParamSubs,
                       OptRemark::Emitter *ORE = nullptr);
  void performFullSpecializationPreparation(SILFunction *Callee,
                                            SubstitutionMap ParamSubs);
  void performPartialSpecializationPreparation(SILFunction *Caller,
                                               SILFunction *Callee,
                                               SubstitutionMap ParamSubs);
  void finishPartialSpecializationPreparation(
      FunctionSignaturePartialSpecializer &FSPS);

public:
  ReabstractionInfo() {}

  /// Constructs the ReabstractionInfo for generic function \p Callee with
  /// substitutions \p ParamSubs.
  /// If specialization is not possible getSpecializedType() will return an
  /// invalid type.
  ReabstractionInfo(ModuleDecl *targetModule,
                    bool isModuleWholeModule,
                    ApplySite Apply, SILFunction *Callee,
                    SubstitutionMap ParamSubs,
                    IsSerialized_t Serialized,
                    bool ConvertIndirectToDirect = true,
                    OptRemark::Emitter *ORE = nullptr);

  /// Constructs the ReabstractionInfo for generic function \p Callee with
  /// a specialization signature.
  ReabstractionInfo(ModuleDecl *targetModule, bool isModuleWholeModule,
                    SILFunction *Callee, GenericSignature SpecializedSig,
                    bool isPrespecialization = false);

  bool isPrespecialized() const { return isPrespecialization; }

  IsSerialized_t isSerialized() const {
    return Serialized;
  }

  /// Returns true if the specialized function needs an alternative mangling.
  /// See hasConvertedResilientParams.
  bool needAlternativeMangling() const {
    return hasConvertedResilientParams;
  }

  TypeExpansionContext getResilienceExpansion() const {
    auto resilience = (Serialized ? ResilienceExpansion::Minimal
                                  : ResilienceExpansion::Maximal);
    return TypeExpansionContext(resilience, TargetModule, isWholeModule);
  }

  /// Returns true if the \p ParamIdx'th (non-result) formal parameter is
  /// converted from indirect to direct.
  bool isParamConverted(unsigned ParamIdx) const {
    return ConvertIndirectToDirect && isArgConverted(param2ArgIndex(ParamIdx));
  }

  /// Returns true if the \p ResultIdx'th formal result is converted from
  /// indirect to direct.
  bool isFormalResultConverted(unsigned ResultIdx) const {
    assert(ResultIdx < NumFormalIndirectResults);
    return ConvertIndirectToDirect && Conversions.test(ResultIdx);
  }

  /// Gets the total number of original function arguments.
  unsigned getNumArguments() const { return Conversions.size(); }

  /// Returns true if the \p ArgIdx'th argument is converted from an
  /// indirect
  /// result or parameter to a direct result or parameter.
  bool isArgConverted(unsigned ArgIdx) const {
    return Conversions.test(ArgIdx);
  }

  /// Returns true if there are any conversions from indirect to direct values.
  bool hasConversions() const { return Conversions.any(); }

  /// Remove the arguments of a partial apply, leaving the arguments for the
  /// partial apply result function.
  void prunePartialApplyArgs(unsigned numPartialApplyArgs) {
    assert(numPartialApplyArgs <= SubstitutedType->getNumParameters());
    assert(numPartialApplyArgs <= Conversions.size());
    Conversions.resize(Conversions.size() - numPartialApplyArgs);
  }

  /// Returns the index of the first argument of an apply site, which may be
  /// > 0 in case of a partial_apply.
  unsigned getIndexOfFirstArg(ApplySite Apply) const {
    unsigned numArgs = Apply.getNumArguments();
    assert(numArgs == Conversions.size() ||
           (numArgs < Conversions.size() && isa<PartialApplyInst>(Apply)));
    return Conversions.size() - numArgs;
  }

  /// Get the function type after applying the substitutions to the original
  /// generic function.
  CanSILFunctionType getSubstitutedType() const { return SubstitutedType; }

  /// Get the function type after applying the re-abstractions on the
  /// substituted type. Returns an invalid type if specialization is not
  /// possible.
  CanSILFunctionType getSpecializedType() const { return SpecializedType; }

  GenericEnvironment *getSpecializedGenericEnvironment() const {
    return SpecializedGenericEnv;
  }

  GenericSignature getSpecializedGenericSignature() const {
    return SpecializedGenericSig;
  }

  SubstitutionMap getCallerParamSubstitutionMap() const {
    return CallerParamSubMap;
  }

  SubstitutionMap getClonerParamSubstitutionMap() const {
    return ClonerParamSubMap;
  }

  SubstitutionMap getCalleeParamSubstitutionMap() const {
    return CalleeParamSubMap;
  }

  /// Create a specialized function type for a specific substituted type \p
  /// SubstFTy by applying the re-abstractions.
  CanSILFunctionType createSpecializedType(CanSILFunctionType SubstFTy,
                                           SILModule &M) const;

  SILFunction *getNonSpecializedFunction() const { return Callee; }

  /// Map type into a context of the specialized function.
  Type mapTypeIntoContext(Type type) const;

  /// Map SIL type into a context of the specialized function.
  SILType mapTypeIntoContext(SILType type) const;

  SILModule &getModule() const { return Callee->getModule(); }

  /// Returns true if generic specialization is possible.
  bool canBeSpecialized() const;

  /// Returns true if it is a full generic specialization.
  bool isFullSpecialization() const;

  /// Returns true if it is a partial generic specialization.
  bool isPartialSpecialization() const;

  /// Returns true if a given apply can be specialized.
  static bool canBeSpecialized(ApplySite Apply, SILFunction *Callee,
                               SubstitutionMap ParamSubs);

  /// Returns the apply site for the current generic specialization.
  ApplySite getApply() const {
    return Apply;
  }

  void verify() const;
};

/// Helper class for specializing a generic function given a list of
/// substitutions.
class GenericFuncSpecializer {
  SILOptFunctionBuilder &FuncBuilder;
  SILModule &M;
  SILFunction *GenericFunc;
  SubstitutionMap ParamSubs;
  const ReabstractionInfo &ReInfo;

  SubstitutionMap ContextSubs;
  std::string ClonedName;

  bool isMandatory;

public:
  GenericFuncSpecializer(SILOptFunctionBuilder &FuncBuilder,
                         SILFunction *GenericFunc,
                         SubstitutionMap ParamSubs,
                         const ReabstractionInfo &ReInfo,
                         bool isMandatory = false);

  /// If we already have this specialization, reuse it.
  SILFunction *lookupSpecialization();

  /// Return a newly created specialized function.
  SILFunction *tryCreateSpecialization(bool forcePrespecialization = false);

  /// Try to specialize GenericFunc given a list of ParamSubs.
  /// Returns either a new or existing specialized function, or nullptr.
  SILFunction *trySpecialization(bool forcePrespecialization = false) {
    if (!ReInfo.getSpecializedType())
      return nullptr;

    SILFunction *SpecializedF = lookupSpecialization();
    if (!SpecializedF)
      SpecializedF = tryCreateSpecialization(forcePrespecialization);

    return SpecializedF;
  }

  StringRef getClonedName() {
    return ClonedName;
  }
};

// =============================================================================
// Prespecialized symbol lookup.
// =============================================================================

/// Checks if a given mangled name could be a name of a known
/// prespecialization for -Onone support.
bool isKnownPrespecialization(StringRef SpecName);

/// Checks if all OnoneSupport pre-specializations are included in the module
/// as public functions.
///
/// Issues errors for all missing functions.
void checkCompletenessOfPrespecializations(SILModule &M);

/// Create a new apply based on an old one, but with a different
/// function being applied.
ApplySite replaceWithSpecializedFunction(ApplySite AI, SILFunction *NewF,
                                         const ReabstractionInfo &ReInfo);

/// Returns a SILFunction for the symbol specified by FunctioName if it is
/// visible to the current SILModule. This is used to link call sites to
/// externally defined specialization and should only be used when the function
/// body is not required for further optimization or inlining (-Onone).
SILFunction *lookupPrespecializedSymbol(SILModule &M, StringRef FunctionName);

} // end namespace swift

#endif

redpajama_set_name: RedPajamaGithub


text:
const path = require("path");
// eslint-disable-next-line node/no-unpublished-require
const CLI = require("../../../packages/webpack-cli/lib/webpack-cli");

const utilsDirectory = {
  cli: "../../../packages/webpack-cli/lib/utils",
  generators: "../../../packages/generators/src/utils",
};

jest.mock(path.join(utilsDirectory.generators, "scaffold-utils"), () => ({
  List: jest.fn(),
}));

const { getInstaller, getTemplate, toKebabCase, toUpperCamelCase } = require(path.join(
  utilsDirectory.generators,
  "helpers",
));
const { List } = require(path.join(utilsDirectory.generators, "scaffold-utils"));

describe("helpers", () => {
  let cli;
  let getDefaultPackageManagerSpy;
  let context;

  beforeEach(() => {
    cli = new CLI();
    context = {
      prompt: () => {},
      supportedTemplates: ["default"],
      cli: cli,
    };
    getDefaultPackageManagerSpy = jest.spyOn(cli, "getDefaultPackageManager");
  });

  afterEach(() => {
    jest.clearAllMocks();

    getDefaultPackageManagerSpy.mockRestore();
  });

  it("toKebabCase() returns kebab case", () => {
    const kebabValue = toKebabCase("HtmlMinimizerPlugin");

    expect(kebabValue).toBe("html-minimizer-plugin");
  });

  it("toUpperCamelCase() returns camel case strings", () => {
    const camelCaseString = toUpperCamelCase("html-minimizer-webpack-plugin");

    expect(camelCaseString).toBe("HtmlMinimizerWebpackPlugin");
  });

  it("getInstaller() returns the available installer", async () => {
    // Multiple installers are not available
    getDefaultPackageManagerSpy.mockReturnValue(["npm"]);

    // User chose "pnpm"
    List.mockReturnValue({ packager: "npm" });

    // Invoke the helper function
    const installer = await getInstaller.call(context);

    expect(installer).toBe("npm");
  });

  it("getInstaller() invokes a List prompt if multiple installers are available", async () => {
    // Multiple installers are available
    getDefaultPackageManagerSpy.mockReturnValue(["npm", "yarn", "pnpm"]);

    // User chose "pnpm"
    List.mockReturnValue({ packager: "pnpm" });

    // Invoke the helper function
    const installer = await getInstaller.call(context);
    expect(installer).toBe("pnpm");
  });

  it("getTemplate() returns with the valid template", async () => {
    context.template = "default";

    // Invoke the helper function
    const template = await getTemplate.call(context);

    expect(template).toBe("default");
  });

  it("getTemplate() invokes a List prompt on supplying an invalid template", async () => {
    context.template = "unknown";

    // User chose "default"
    List.mockReturnValue({ selectedTemplate: "default" });

    const { logger } = cli;
    const loggerMock = jest.spyOn(logger, "warn").mockImplementation(() => {});
    // Invoke the helper function`
    const template = await getTemplate.call(context);

    expect(template).toBe("default");
    expect(loggerMock).toHaveBeenCalled();
  });
});


text:
from openturns import *

TESTPREAMBLE()

try:

    # Dimension of test
    dimension = 2

    # function
    function = NumericalMathFunction("x", "sin(x)")

    # Init of the function
    myFunction = TrendEvaluationImplementation(function)
    myFunction.setName("myTrendFunction")

    # We check that for a NumericalPoint with same values, the function is
    # done by component
    inPoint = NumericalPoint(dimension, 30.0)

    # result point of the function
    outPoint = myFunction(inPoint)
    print "myFunction=", myFunction
    print myFunction.getName(), "( ", inPoint, " ) = ", outPoint

    # Creation of a NumericalSample
    size = 10
    inSample = NumericalSample(size, dimension)
    for index in range(size):
        inSample[index] = NumericalPoint(dimension, index + 1)

    # result of the function
    outSample = myFunction(inSample)
    print myFunction.getName(), "( ", repr(inSample), " ) = ", repr(outSample)

except:
    import sys
    print "t__TrendEvaluationImplementation_std.py", sys.exc_type, sys.exc_value


text:
package godo

import (
	"context"
	"net/http"
	"path"
)

const certificatesBasePath = "/v2/certificates"

// CertificatesService is an interface for managing certificates with the DigitalOcean API.
// See: https://docs.digitalocean.com/reference/api/api-reference/#tag/Certificates
type CertificatesService interface {
	Get(context.Context, string) (*Certificate, *Response, error)
	List(context.Context, *ListOptions) ([]Certificate, *Response, error)
	Create(context.Context, *CertificateRequest) (*Certificate, *Response, error)
	Delete(context.Context, string) (*Response, error)
}

// Certificate represents a DigitalOcean certificate configuration.
type Certificate struct {
	ID              string   `json:"id,omitempty"`
	Name            string   `json:"name,omitempty"`
	DNSNames        []string `json:"dns_names,omitempty"`
	NotAfter        string   `json:"not_after,omitempty"`
	SHA1Fingerprint string   `json:"sha1_fingerprint,omitempty"`
	Created         string   `json:"created_at,omitempty"`
	State           string   `json:"state,omitempty"`
	Type            string   `json:"type,omitempty"`
}

// CertificateRequest represents configuration for a new certificate.
type CertificateRequest struct {
	Name             string   `json:"name,omitempty"`
	DNSNames         []string `json:"dns_names,omitempty"`
	PrivateKey       string   `json:"private_key,omitempty"`
	LeafCertificate  string   `json:"leaf_certificate,omitempty"`
	CertificateChain string   `json:"certificate_chain,omitempty"`
	Type             string   `json:"type,omitempty"`
}

type certificateRoot struct {
	Certificate *Certificate `json:"certificate"`
}

type certificatesRoot struct {
	Certificates []Certificate `json:"certificates"`
	Links        *Links        `json:"links"`
	Meta         *Meta         `json:"meta"`
}

// CertificatesServiceOp handles communication with certificates methods of the DigitalOcean API.
type CertificatesServiceOp struct {
	client *Client
}

var _ CertificatesService = &CertificatesServiceOp{}

// Get an existing certificate by its identifier.
func (c *CertificatesServiceOp) Get(ctx context.Context, cID string) (*Certificate, *Response, error) {
	urlStr := path.Join(certificatesBasePath, cID)

	req, err := c.client.NewRequest(ctx, http.MethodGet, urlStr, nil)
	if err != nil {
		return nil, nil, err
	}

	root := new(certificateRoot)
	resp, err := c.client.Do(ctx, req, root)
	if err != nil {
		return nil, resp, err
	}

	return root.Certificate, resp, nil
}

// List all certificates.
func (c *CertificatesServiceOp) List(ctx context.Context, opt *ListOptions) ([]Certificate, *Response, error) {
	urlStr, err := addOptions(certificatesBasePath, opt)
	if err != nil {
		return nil, nil, err
	}

	req, err := c.client.NewRequest(ctx, http.MethodGet, urlStr, nil)
	if err != nil {
		return nil, nil, err
	}

	root := new(certificatesRoot)
	resp, err := c.client.Do(ctx, req, root)
	if err != nil {
		return nil, resp, err
	}
	if l := root.Links; l != nil {
		resp.Links = l
	}
	if m := root.Meta; m != nil {
		resp.Meta = m
	}

	return root.Certificates, resp, nil
}

// Create a new certificate with provided configuration.
func (c *CertificatesServiceOp) Create(ctx context.Context, cr *CertificateRequest) (*Certificate, *Response, error) {
	req, err := c.client.NewRequest(ctx, http.MethodPost, certificatesBasePath, cr)
	if err != nil {
		return nil, nil, err
	}

	root := new(certificateRoot)
	resp, err := c.client.Do(ctx, req, root)
	if err != nil {
		return nil, resp, err
	}

	return root.Certificate, resp, nil
}

// Delete a certificate by its identifier.
func (c *CertificatesServiceOp) Delete(ctx context.Context, cID string) (*Response, error) {
	urlStr := path.Join(certificatesBasePath, cID)

	req, err := c.client.NewRequest(ctx, http.MethodDelete, urlStr, nil)
	if err != nil {
		return nil, err
	}

	return c.client.Do(ctx, req, nil)
}


text:
from collections import defaultdict

class PlotStore(object):
    def __init__(self):
        self._plots = defaultdict(dict)

    @property
    def empty(self):
        return len(self._plots) == 0

    def add_plot(self, dt, series_name, value):
        self._plots[series_name][dt] = value

    def get_plots(self):
        return self._plots


text:
using Premotion.Mansion.Core.Nucleus;

namespace Premotion.Mansion.Core.Security
{
	/// <summary>
	/// Registers the <see cref="DotNetCryptoEncryptionService"/>.
	/// </summary>
	public class DotNetCryptoEncryptionServiceApplicationBootstrapper : ApplicationBootstrapper
	{
		#region Constructors
		/// <summary></summary>
		public DotNetCryptoEncryptionServiceApplicationBootstrapper() : base(50)
		{
		}
		#endregion
		#region Overrides of ApplicationBootstrapper
		/// <summary>
		/// Registers all the services used by the application in the <paramref name="nucleus"/>.
		/// </summary>
		/// <param name="nucleus">The <see cref="IConfigurableNucleus"/> in which to register the services used by the application.</param>
		protected override void DoBootstrap(IConfigurableNucleus nucleus)
		{
			nucleus.Register<IEncryptionService>(resolver => DotNetCryptoEncryptionService.Create());
		}
		#endregion
	}
}


text:
<?php

namespace PHPExiftool\Driver\Tag\QuickTime;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class AudioInputBufferSize extends AbstractTag
{

    protected $Id = 'tbuf';

    protected $Name = 'AudioInputBufferSize';

    protected $FullName = 'QuickTime::EncodingParams';

    protected $GroupName = 'QuickTime';

    protected $g0 = 'QuickTime';

    protected $g1 = 'QuickTime';

    protected $g2 = 'Audio';

    protected $Type = '?';

    protected $Writable = false;

    protected $Description = 'Audio Input Buffer Size';

}


text:
#include "pbm.h"
#include "shhopt.h"
#include "mallocvar.h"
#include <string.h>
#include <assert.h>

static char *rowBuffer, *prevRowBuffer, *packBuffer, *deltaBuffer;
static int rowBufferSize, rowBufferIndex, prevRowBufferIndex;
static int packBufferSize, packBufferIndex;
static int deltaBufferSize, deltaBufferIndex;

static int item, bitsperitem, bitshift;

struct cmdlineInfo {
    /* All the information the user supplied in the command line,
       in a form easy for the program to use.
    */
    const char *inputFilename;
    unsigned int dpi;
    unsigned int copies;     /* number of copies */
    unsigned int floating;   /* suppress the ``ESC & l 0 E'' ? */
    unsigned int noreset;
    unsigned int pack;       /* use TIFF packbits compression */
    unsigned int delta;      /* use row-delta compression */
};

static void
parseCommandLine(int argc, char ** argv,
                 struct cmdlineInfo * const cmdlineP) {
/*----------------------------------------------------------------------------
   Note that the file spec array we return is stored in the storage that
   was passed to us as the argv array.
-----------------------------------------------------------------------------*/
    optEntry *option_def;
        /* Instructions to OptParseOptions3 on how to parse our options.
         */
    optStruct3 opt;

    unsigned int option_def_index;
    unsigned int dpiSpec, copiesSpec, compressSpec;

    MALLOCARRAY(option_def, 100);

    option_def_index = 0;   /* incremented by OPTENTRY */
    OPTENT3(0,   "resolution",  OPT_UINT, &cmdlineP->dpi,
            &dpiSpec, 0);
    OPTENT3(0,   "copies",      OPT_UINT, &cmdlineP->copies,
            &copiesSpec, 0);
    OPTENT3(0,   "float",       OPT_FLAG, NULL,
            &cmdlineP->floating, 0);
    OPTENT3(0,   "noreset",     OPT_FLAG, NULL,
            &cmdlineP->noreset, 0);
    OPTENT3(0,   "packbits",    OPT_FLAG, NULL,
            &cmdlineP->pack, 0);
    OPTENT3(0,   "delta",       OPT_FLAG, NULL,
            &cmdlineP->delta, 0);
    OPTENT3(0,   "compress",    OPT_FLAG, NULL,
            &compressSpec, 0);

    opt.opt_table = option_def;
    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
    opt.allowNegNum = FALSE;  /* We may have parms that are negative numbers */

    optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
        /* Uses and sets argc, argv, and some of *cmdlineP and others. */

    if (argc-1 == 0)
        cmdlineP->inputFilename = "-";
    else if (argc-1 != 1)
        pm_error("Program takes zero or one argument (filename).  You "
                 "specified %d", argc-1);
    else
        cmdlineP->inputFilename = argv[1];

    if (!dpiSpec)
        cmdlineP->dpi = 75;
    if (!copiesSpec)
        cmdlineP->copies = 1;
    if (compressSpec) {
        cmdlineP->pack = 1;
        cmdlineP->delta = 1;
    }
}

static void
allocateBuffers(unsigned int const cols) {

    rowBufferSize = (cols + 7) / 8;
    packBufferSize = rowBufferSize + (rowBufferSize + 127) / 128 + 1;
    deltaBufferSize = rowBufferSize + rowBufferSize / 8 + 10;

    MALLOCARRAY_NOFAIL(prevRowBuffer, rowBufferSize);
    MALLOCARRAY_NOFAIL(rowBuffer, rowBufferSize);
    MALLOCARRAY_NOFAIL(packBuffer, packBufferSize);
    MALLOCARRAY_NOFAIL(deltaBuffer, deltaBufferSize);
}

static void
freeBuffers(void) {

    free(deltaBuffer);
    free(packBuffer);
    free(rowBuffer);
    free(prevRowBuffer);
}

static void
putinit(struct cmdlineInfo const cmdline) {
    if (!cmdline.noreset) {
        /* Printer reset. */
        printf("\033E");
    }

    if (cmdline.copies > 1) {
        /* number of copies */
        printf("\033&l%dX", cmdline.copies);
    }
    if (!cmdline.floating) {
        /* Ensure top margin is zero */
        printf("\033&l0E");
    }

    /* Set raster graphics resolution */
    printf("\033*t%dR", cmdline.dpi);

    /* Start raster graphics, relative adressing */
    printf("\033*r1A");

    bitsperitem = 1;
    item = 0;
    bitshift = 7;
}

static void
putitem(void) {
    assert(rowBufferIndex < rowBufferSize);
    rowBuffer[rowBufferIndex++] = item;
    bitsperitem = 0;
    item = 0;
}

static void
putbit(bit const b) {

    if (b == PBM_BLACK)
        item += 1 << bitshift;

    --bitshift;

    if (bitsperitem == 8) {
        putitem();
        bitshift = 7;
    }
    ++bitsperitem;
}

static void
putflush(void) {
    if (bitsperitem > 1)
        putitem();
}

static void
putrest(bool const reset) {
    /* end raster graphics */
    printf("\033*rB");

    if (reset) {
        /* Printer reset. */
        printf("\033E");
    }
}

static void
packbits(void) {
    int ptr, litStart, runStart, thisByte, startByte, chew, spit;
    packBufferIndex = 0;
    ptr = 0;
    while (ptr < rowBufferIndex) {
        litStart = ptr;
        runStart = ptr;
        startByte = rowBuffer[ptr];
        ++ptr;
        while (ptr < rowBufferIndex) {
            thisByte = rowBuffer[ptr];
            if (thisByte != startByte) {
                if (ptr - runStart > 3) {
                    /* found literal after nontrivial run */
                    break;
                }
                startByte = thisByte;
                runStart = ptr;
            }
            ++ptr;
        }
        /*
          We drop out here after having found a [possibly empty]
          literal, followed by a [possibly degenerate] run of repeated
          bytes.  Degenerate runs can occur at the end of the scan line...
          there may be a "repeat" of 1 byte (which can't actually be
          represented as a repeat) so we simply fold it into the previous
          literal.
        */
        if (runStart == rowBufferIndex - 1) {
            runStart = rowBufferIndex;
        }
        /*
          Spit out the leading literal if it isn't empty
        */
        chew = runStart - litStart;
        while (chew > 0) {
            spit = (chew > 127) ? 127 : chew;
            packBuffer[packBufferIndex++] = (char) (spit - 1);
            memcpy(packBuffer+packBufferIndex, rowBuffer+litStart, spit);
            packBufferIndex += spit;
            litStart += spit;
            chew -= spit;
        }
        /*
          Spit out the repeat, if it isn't empty
        */
        chew = ptr - runStart;
        while (chew > 0) {
            spit = (chew > 128) ? 128 : chew;
            if (chew == spit + 1) {
                spit--; /* don't leave a degenerate run at the end */
            }
            if (spit == 1) {
                fprintf(stderr, "packbits created a degenerate run!\n");
            }
            packBuffer[packBufferIndex++] = (char) -(spit - 1);
            packBuffer[packBufferIndex++] = startByte;
            chew -= spit;
        }
    }
}

static void
deltarow(void) {
    int burstStart, burstEnd, burstCode, mustBurst, ptr, skip, skipped, code;
    deltaBufferIndex = 0;
    if (memcmp(rowBuffer, prevRowBuffer, rowBufferIndex) == 0) {
        return; /* exact match, no deltas required */
    }
    ptr = 0;
    skipped = 0;
    burstStart = -1;
    burstEnd = -1;
    mustBurst = 0;
    while (ptr < rowBufferIndex) {
        skip = 0;
        if (ptr == 0 || skipped == 30 || rowBuffer[ptr] != prevRowBuffer[ptr]
            || (burstStart != -1 && ptr == rowBufferIndex - 1)) {
            /* we want to output this byte... */
            if (burstStart == -1) {
                burstStart = ptr;
            }
            if (ptr - burstStart == 7 || ptr == rowBufferIndex - 1) {
                /* we have to output it now... */
                burstEnd = ptr;
                mustBurst = 1;
            }
        } else {
            /* duplicate byte, we can skip it */
            if (burstStart != -1) {
                burstEnd = ptr - 1;
                mustBurst = 1;
            }
            skip = 1;
        }
        if (mustBurst) {
            burstCode = burstEnd - burstStart;
                /* 0-7, means 1-8 bytes follow */
            code = (burstCode << 5) | skipped;
            deltaBuffer[deltaBufferIndex++] = (char) code;
            memcpy(deltaBuffer+deltaBufferIndex, rowBuffer+burstStart,
                   burstCode + 1);
            deltaBufferIndex += burstCode + 1;
            burstStart = -1;
            burstEnd = -1;
            mustBurst = 0;
            skipped = 0;
        }
        if (skip) {
            ++skipped;
        }
        ++ptr;
    }
}

static void
findRightmostBlackCol(const bit *    const bitrow,
                      unsigned int   const cols,
                      bool *         const allWhiteP,
                      unsigned int * const blackColP) {

    int i;

    for (i = cols - 1; i >= 0 && bitrow[i] == PBM_WHITE; --i);

    if (i < 0)
        *allWhiteP = TRUE;
    else {
        *allWhiteP = FALSE;
        *blackColP = i;
    }
}

static void
convertRow(const bit *    const bitrow,
           unsigned int   const cols,
           bool           const pack,
           bool           const delta,
           bool *         const rowIsBlankP) {

    unsigned int rightmostBlackCol;

    findRightmostBlackCol(bitrow, cols, rowIsBlankP, &rightmostBlackCol);

    if (!*rowIsBlankP) {
        unsigned int const nzcol = rightmostBlackCol + 1;
            /* Number of columns excluding white right margin */
        unsigned int const rucols = ((nzcol + 7) / 8) * 8;
            /* 'nzcol' rounded up to nearest multiple of 8 */

        unsigned int col;

        memset(rowBuffer, 0, rowBufferSize);

        rowBufferIndex = 0;

        /* Generate the unpacked data */

        for (col = 0; col < nzcol; ++col)
            putbit(bitrow[col]);

        /* Pad out to a full byte with white */
        for (col = nzcol; col < rucols; ++col)
            putbit(0);

        putflush();

        /* Try optional compression algorithms */

        if (pack)
            packbits();
        else
            packBufferIndex = rowBufferIndex + 999;

        if (delta) {
            /* May need to temporarily bump the row buffer index up to
               whatever the previous line's was - if this line is shorter
               than the previous would otherwise leave dangling cruft.
            */
            unsigned int const savedRowBufferIndex = rowBufferIndex;

            if (rowBufferIndex < prevRowBufferIndex)
                rowBufferIndex = prevRowBufferIndex;

            deltarow();

            rowBufferIndex = savedRowBufferIndex;
        } else
            deltaBufferIndex = packBufferIndex + 999;
    }
}

static void
printBlankRows(unsigned int const count) {

    if (count > 0) {
        unsigned int x;
        /* The code used to be this, but Charles Howes reports that
           this escape sequence does not exist on his HP Laserjet IIP
           plus, so we use the following less elegant code instead.

           printf("\033*b%dY", (*blankRowsP));
        */
        for (x = 0; x < count; ++x)
            printf("\033*b0W");

        memset(prevRowBuffer, 0, rowBufferSize);
    }
}

static void
establishMode(int const newMode) {

    static int mode = -1;

    if (mode != newMode) {
        printf("\033*b%uM", newMode);
        mode = newMode;
    }
}

static void
printRow(void) {

    if (deltaBufferIndex < packBufferIndex &&
        deltaBufferIndex < rowBufferIndex) {
        assert(deltaBufferIndex <= deltaBufferSize);
        /*
          It's smallest when delta'ed
        */
        establishMode(3);

        printf("\033*b%dW", deltaBufferIndex);
        fwrite(deltaBuffer, 1, deltaBufferIndex, stdout);
    } else if (rowBufferIndex <= packBufferIndex) {
        assert (rowBufferIndex <= rowBufferSize);
        /*
          It didn't pack - send it unpacked
        */
        establishMode(0);

        printf("\033*b%dW", rowBufferIndex);
        fwrite(rowBuffer, 1, rowBufferIndex, stdout);
    } else {
        assert (packBufferIndex <= packBufferSize);
        /*
          It's smaller when packed
        */
        establishMode(2);

        printf("\033*b%dW", packBufferIndex);
        fwrite(packBuffer, 1, packBufferIndex, stdout);
    }
    memcpy(prevRowBuffer, rowBuffer, rowBufferSize);
    prevRowBufferIndex = rowBufferIndex;
}

static void
doPage(FILE *             const ifP,
       struct cmdlineInfo const cmdline) {

    bit * bitrow;
    int rows, cols, format, row;
    unsigned int blankRows;
    bool rowIsBlank;

    pbm_readpbminit(ifP, &cols, &rows, &format);

    bitrow = pbm_allocrow(cols);

    allocateBuffers(cols);

    putinit(cmdline);

    blankRows = 0;
    prevRowBufferIndex = 0;
    memset(prevRowBuffer, 0, rowBufferSize);

    for (row = 0; row < rows; ++row) {
        pbm_readpbmrow(ifP, bitrow, cols, format);

        convertRow(bitrow, cols, cmdline.pack, cmdline.delta,
                   &rowIsBlank);

        if (rowIsBlank)
            ++blankRows;
        else {
            printBlankRows(blankRows);
            blankRows = 0;

            printRow();
        }
    }
    printBlankRows(blankRows);
    blankRows = 0;

    putrest(!cmdline.noreset);

    freeBuffers();
    pbm_freerow(bitrow);
}

int
main(int argc, char * argv[]) {

    struct cmdlineInfo cmdline;
    FILE * ifP;
    bool eof;

    pbm_init(&argc, argv);

    parseCommandLine(argc, argv, &cmdline);

    ifP = pm_openr(cmdline.inputFilename);

    eof = FALSE;
    while (!eof) {
        doPage(ifP, cmdline);
        pbm_nextimage(ifP, &eof);
    }

    pm_close(ifP);

    return 0;
}


text:
package net.hydromatic.optiq;

import org.eigenbase.reltype.RelDataType;

import java.util.Map;

/**
 * Factory for {@link Table} objects.
 *
 *
A table factory allows you to include custom tables in a model file.
 * For example, here is a model that contains a custom table that generates
 * a range of integers.

 *
 *
{@code
 * {
 *   version: '1.0',
 *   defaultSchema: 'MATH',
 *   schemas: [
 *     {
 *       name: 'MATH',
 *       tables: [
 *         {
 *           name: 'INTEGERS',
 *           type: 'custom',
 *           factory: 'com.acme.IntegerTable',
 *           operand: {
 *             start: 3,
 *             end: 7,
 *             column: 'N'
 *           }
 *         }
 *       ]
 *     }
 *   ]
 * }
 * }
 *

 *
 *
Given that schema, the query

 *
 *
{@code SELECT * FROM math.integers}

 *
 *
returns

 *
 *
{@code
 * +---+
 * | N |
 * +---+
 * | 3 |
 * | 4 |
 * | 5 |
 * | 6 |
 * +---+
 * }

 *
 *
A class that implements TableFactory specified in a schema must have a
 * public default constructor.

 *
 * @param <T> Sub-type of table created by this factory
 */
public interface TableFactory<T extends Table> {
  /** Creates a Table.
   *
   * @param schema Schema this table belongs to
   * @param name Name of this table
   * @param operand The "operand" JSON property
   * @param rowType Row type. Specified if the "columns" JSON property.
   */
  T create(
      SchemaPlus schema,
      String name,
      Map<String, Object> operand,
      RelDataType rowType);
}

// End TableFactory.java


text:
package com.opengamma.analytics.financial.model.option.pricing.analytic.twoasset;

import java.util.Set;

import org.apache.commons.lang.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opengamma.analytics.financial.greeks.Greek;
import com.opengamma.analytics.financial.greeks.GreekResultCollection;
import com.opengamma.analytics.financial.model.option.definition.OptionDefinition;
import com.opengamma.analytics.financial.model.option.definition.twoasset.StandardTwoAssetOptionDataBundle;
import com.opengamma.analytics.financial.model.option.pricing.OptionModel;
import com.opengamma.analytics.math.function.Function1D;

/**
 * Base class for the analytic pricing of two-asset options.
 * @param <T> Type of the option definition
 * @param <U> Type of the two asset data bundle
 */
public abstract class TwoAssetAnalyticOptionModel<T extends OptionDefinition, U extends StandardTwoAssetOptionDataBundle> implements OptionModel<T, U> {
  private static final Logger LOGGER = LoggerFactory.getLogger(TwoAssetAnalyticOptionModel.class);

  /**
   *
   * @param definition The option definition
   * @return A function that prices the option given a {@link StandardTwoAssetOptionDataBundle} or descendant class
   */
  public abstract Function1D<U, Double> getPricingFunction(T definition);

  /**
   * Note that currently the only greek that can be calculated is the fair price. If other greeks are requested a warning is given and
   * nothing is added to the result
   * @param definition The option definition
   * @param data The type of the data
   * @param requiredGreeks The greeks that are to be calculated
   * @return A {@link GreekResultCollection} containing the results
   * @throws IllegalArgumentException If any of the arguments are null, or if the set of required greeks is empty
   */
  @Override
  public GreekResultCollection getGreeks(final T definition, final U data, final Set<Greek> requiredGreeks) {
    Validate.notNull(definition, "definition");
    Validate.notNull(data, "data");
    Validate.notNull(requiredGreeks, "required greeks");
    Validate.notEmpty(requiredGreeks, "required greeks");
    final Function1D<U, Double> pricingFunction = getPricingFunction(definition);
    final GreekResultCollection results = new GreekResultCollection();
    for (final Greek greek : requiredGreeks) {
      if (greek != Greek.FAIR_PRICE) {
        LOGGER.warn("Can only calculate price for two-asset options, not calculating " + greek);
      } else {
        results.put(greek, pricingFunction.evaluate(data));
      }
    }
    return results;
  }

}


text:
using System;
using IdentityServer4.Stores;
using Microsoft.Extensions.DependencyInjection;
using QrF.Core.IdentityServer4.Dapper.Interfaces;

namespace QrF.Core.IdentityServer4.Dapper.SqlServer
{
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        ///
        /// </summary>
        public static IIdentityServerBuilder UseSqlServer(this IIdentityServerBuilder builder)
        {
            builder.Services.AddTransient<IClientStore, Stores.ClientStore>();
            builder.Services.AddTransient<IResourceStore, Stores.ResourceStore>();
            builder.Services.AddTransient<IPersistedGrantStore, Stores.PersistedGrantStore>();
            builder.Services.AddTransient<IPersistedGrants, Stores.PersistedGrants>();
            return builder;
        }
    }
}


text:
package routing

import (
	"context"
	"errors"
	"fmt"
	"net"
	"strconv"
	"strings"
	"time"

	"github.com/cloudnativelabs/kube-router/pkg/metrics"
	"github.com/cloudnativelabs/kube-router/pkg/options"
	"github.com/cloudnativelabs/kube-router/pkg/utils"
	gobgpapi "github.com/osrg/gobgp/v3/api"
	gobgp "github.com/osrg/gobgp/v3/pkg/server"
	v1core "k8s.io/api/core/v1"
	"k8s.io/client-go/tools/cache"
	"k8s.io/klog/v2"
)

// Refresh the peer relationship with rest of the nodes in the cluster (iBGP peers). Node add/remove
// events should ensure peer relationship with only currently active nodes. In case
// we miss any events from API server this method which is called periodically
// ensures peer relationship with removed nodes is deleted.
func (nrc *NetworkRoutingController) syncInternalPeers() {
	nrc.mu.Lock()
	defer nrc.mu.Unlock()

	start := time.Now()
	defer func() {
		endTime := time.Since(start)
		if nrc.MetricsEnabled {
			metrics.ControllerBGPInternalPeersSyncTime.Observe(endTime.Seconds())
		}
		klog.V(2).Infof("Syncing BGP peers for the node took %v", endTime)
	}()

	// get the current list of the nodes from API server
	nodes := nrc.nodeLister.List()

	if nrc.MetricsEnabled {
		metrics.ControllerBPGpeers.Set(float64(len(nodes)))
	}
	// establish peer and add Pod CIDRs with current set of nodes
	currentNodes := make([]string, 0)
	for _, obj := range nodes {
		node := obj.(*v1core.Node)
		nodeIP, err := utils.GetNodeIP(node)
		if err != nil {
			klog.Errorf("Failed to find a node IP and therefore cannot sync internal BGP Peer: %v", err)
			continue
		}

		// skip self
		if nodeIP.String() == nrc.nodeIP.String() {
			continue
		}

		// we are rr-client peer only with rr-server
		if nrc.bgpRRClient {
			if _, ok := node.ObjectMeta.Annotations[rrServerAnnotation]; !ok {
				continue
			}
		}

		// if node full mesh is not requested then just peer with nodes with same ASN
		// (run iBGP among same ASN peers)
		if !nrc.bgpFullMeshMode {
			nodeasn, ok := node.ObjectMeta.Annotations[nodeASNAnnotation]
			if !ok {
				klog.Infof("Not peering with the Node %s as ASN number of the node is unknown.",
					nodeIP.String())
				continue
			}

			asnNo, err := strconv.ParseUint(nodeasn, 0, asnMaxBitSize)
			if err != nil {
				klog.Infof("Not peering with the Node %s as ASN number of the node is invalid.",
					nodeIP.String())
				continue
			}

			// if the nodes ASN number is different from ASN number of current node skip peering
			if nrc.nodeAsnNumber != uint32(asnNo) {
				klog.Infof("Not peering with the Node %s as ASN number of the node is different.",
					nodeIP.String())
				continue
			}
		}

		currentNodes = append(currentNodes, nodeIP.String())
		nrc.activeNodes[nodeIP.String()] = true
		// explicitly set neighbors.transport.config.local-address with nodeIP which is configured
		// as their neighbor address at the remote peers.
		// this prevents the controller from initiating connection to its peers with a different IP address
		// when multiple L3 interfaces are active.
		n := &gobgpapi.Peer{
			Conf: &gobgpapi.PeerConf{
				NeighborAddress: nodeIP.String(),
				PeerAsn:         nrc.nodeAsnNumber,
			},
			Transport: &gobgpapi.Transport{
				LocalAddress: nrc.nodeIP.String(),
				RemotePort:   nrc.bgpPort,
			},
		}

		if nrc.bgpGracefulRestart {
			n.GracefulRestart = &gobgpapi.GracefulRestart{
				Enabled:         true,
				RestartTime:     uint32(nrc.bgpGracefulRestartTime.Seconds()),
				DeferralTime:    uint32(nrc.bgpGracefulRestartDeferralTime.Seconds()),
				LocalRestarting: true,
			}

			if nrc.isIpv6 {
				n.AfiSafis = []*gobgpapi.AfiSafi{
					{
						Config: &gobgpapi.AfiSafiConfig{
							Family:  &gobgpapi.Family{Afi: gobgpapi.Family_AFI_IP6, Safi: gobgpapi.Family_SAFI_UNICAST},
							Enabled: true,
						},
						MpGracefulRestart: &gobgpapi.MpGracefulRestart{
							Config: &gobgpapi.MpGracefulRestartConfig{
								Enabled: true,
							},
							State: &gobgpapi.MpGracefulRestartState{},
						},
					},
				}
			} else {
				n.AfiSafis = []*gobgpapi.AfiSafi{
					{
						Config: &gobgpapi.AfiSafiConfig{
							Family:  &gobgpapi.Family{Afi: gobgpapi.Family_AFI_IP, Safi: gobgpapi.Family_SAFI_UNICAST},
							Enabled: true,
						},
						MpGracefulRestart: &gobgpapi.MpGracefulRestart{
							Config: &gobgpapi.MpGracefulRestartConfig{
								Enabled: true,
							},
							State: &gobgpapi.MpGracefulRestartState{},
						},
					},
				}
			}
		}

		// we are rr-server peer with other rr-client with reflection enabled
		if nrc.bgpRRServer {
			if _, ok := node.ObjectMeta.Annotations[rrClientAnnotation]; ok {
				// add rr options with clusterId
				n.RouteReflector = &gobgpapi.RouteReflector{
					RouteReflectorClient:    true,
					RouteReflectorClusterId: fmt.Sprint(nrc.bgpClusterID),
				}
			}
		}

		// TODO: check if a node is already added as neighbor in a better way than add and catch error
		if err := nrc.bgpServer.AddPeer(context.Background(), &gobgpapi.AddPeerRequest{
			Peer: n,
		}); err != nil {
			if !strings.Contains(err.Error(), "can't overwrite the existing peer") {
				klog.Errorf("Failed to add node %s as peer due to %s", nodeIP.String(), err)
			}
		}
	}

	// find the list of the node removed, from the last known list of active nodes
	removedNodes := make([]string, 0)
	for ip := range nrc.activeNodes {
		stillActive := false
		for _, node := range currentNodes {
			if ip == node {
				stillActive = true
				break
			}
		}
		if !stillActive {
			removedNodes = append(removedNodes, ip)
		}
	}

	// delete the neighbor for the nodes that are removed
	for _, ip := range removedNodes {
		if err := nrc.bgpServer.DeletePeer(context.Background(), &gobgpapi.DeletePeerRequest{Address: ip}); err != nil {
			klog.Errorf("Failed to remove node %s as peer due to %s", ip, err)
		}
		delete(nrc.activeNodes, ip)
	}
}

// connectToExternalBGPPeers adds all the configured eBGP peers (global or node specific) as neighbours
func (nrc *NetworkRoutingController) connectToExternalBGPPeers(server *gobgp.BgpServer, peerNeighbors []*gobgpapi.Peer,
	bgpGracefulRestart bool, bgpGracefulRestartDeferralTime time.Duration, bgpGracefulRestartTime time.Duration,
	peerMultihopTTL uint8) error {
	for _, n := range peerNeighbors {

		if bgpGracefulRestart {
			n.GracefulRestart = &gobgpapi.GracefulRestart{
				Enabled:         true,
				RestartTime:     uint32(bgpGracefulRestartTime.Seconds()),
				DeferralTime:    uint32(bgpGracefulRestartDeferralTime.Seconds()),
				LocalRestarting: true,
			}

			if nrc.isIpv6 {
				n.AfiSafis = []*gobgpapi.AfiSafi{
					{
						Config: &gobgpapi.AfiSafiConfig{
							Family:  &gobgpapi.Family{Afi: gobgpapi.Family_AFI_IP6, Safi: gobgpapi.Family_SAFI_UNICAST},
							Enabled: true,
						},
						MpGracefulRestart: &gobgpapi.MpGracefulRestart{
							Config: &gobgpapi.MpGracefulRestartConfig{
								Enabled: true,
							},
						},
					},
				}
			} else {
				n.AfiSafis = []*gobgpapi.AfiSafi{
					{
						Config: &gobgpapi.AfiSafiConfig{
							Family:  &gobgpapi.Family{Afi: gobgpapi.Family_AFI_IP, Safi: gobgpapi.Family_SAFI_UNICAST},
							Enabled: true,
						},
						MpGracefulRestart: &gobgpapi.MpGracefulRestart{
							Config: &gobgpapi.MpGracefulRestartConfig{
								Enabled: true,
							},
						},
					},
				}
			}
		}
		if peerMultihopTTL > 1 {
			n.EbgpMultihop = &gobgpapi.EbgpMultihop{
				Enabled:     true,
				MultihopTtl: uint32(peerMultihopTTL),
			}
		}
		err := server.AddPeer(context.Background(), &gobgpapi.AddPeerRequest{Peer: n})
		if err != nil {
			return fmt.Errorf("error peering with peer router "+
				"%q due to: %s", n.Conf.NeighborAddress, err)
		}
		klog.V(2).Infof("Successfully configured %s in ASN %v as BGP peer to the node",
			n.Conf.NeighborAddress, n.Conf.PeerAsn)
	}
	return nil
}

// Does validation and returns neighbor configs
func newGlobalPeers(ips []net.IP, ports []uint32, asns []uint32, passwords []string, localips []string,
	holdtime float64, localAddress string) ([]*gobgpapi.Peer, error) {
	peers := make([]*gobgpapi.Peer, 0)

	// Validations
	if len(ips) != len(asns) {
		return nil, errors.New("invalid peer router config, the number of IPs and ASN numbers must be equal")
	}

	if len(ips) != len(passwords) && len(passwords) != 0 {
		return nil, errors.New("invalid peer router config. The number of passwords should either be zero, or " +
			"one per peer router. Use blank items if a router doesn't expect a password. Example: \"pass,,pass\" " +
			"OR [\"pass\",\"\",\"pass\"]")
	}

	if len(ips) != len(ports) && len(ports) != 0 {
		return nil, fmt.Errorf("invalid peer router config. The number of ports should either be zero, or "+
			"one per peer router. If blank items are used, it will default to standard BGP port, %s. "+
			"Example: \"port,,port\" OR [\"port\",\"\",\"port\"]", strconv.Itoa(options.DefaultBgpPort))
	}

	if len(ips) != len(localips) && len(localips) != 0 {
		return nil, fmt.Errorf("invalid peer router config. The number of localIPs should either be zero, or "+
			"one per peer router. If blank items are used, it will default to nodeIP, %s. "+
			"Example: \"10.1.1.1,,10.1.1.2\" OR [\"10.1.1.1\",\"\",\"10.1.1.2\"]", localAddress)
	}

	for i := 0; i < len(ips); i++ {
		if !((asns[i] >= 1 && asns[i] <= 23455) ||
			(asns[i] >= 23457 && asns[i] <= 63999) ||
			(asns[i] >= 64512 && asns[i] <= 65534) ||
			(asns[i] >= 131072 && asns[i] <= 4199999999) ||
			(asns[i] >= 4200000000 && asns[i] <= 4294967294)) {
			return nil, fmt.Errorf("reserved ASN number \"%d\" for global BGP peer",
				asns[i])
		}

		// explicitly set neighbors.transport.config.local-address
		// this prevents the controller from initiating connection to its peers with a different IP address
		// when multiple L3 interfaces are active.
		peer := &gobgpapi.Peer{
			Conf: &gobgpapi.PeerConf{
				NeighborAddress: ips[i].String(),
				PeerAsn:         asns[i],
			},
			Timers: &gobgpapi.Timers{Config: &gobgpapi.TimersConfig{HoldTime: uint64(holdtime)}},
			Transport: &gobgpapi.Transport{
				LocalAddress: localAddress,
				RemotePort:   options.DefaultBgpPort,
			},
		}

		if len(ports) != 0 {
			peer.Transport.RemotePort = ports[i]
		}

		if len(passwords) != 0 {
			peer.Conf.AuthPassword = passwords[i]
		}

		if len(localips) != 0 && localips[i] != "" {
			peer.Transport.LocalAddress = localips[i]
		}

		peers = append(peers, peer)
	}

	return peers, nil
}

func (nrc *NetworkRoutingController) newNodeEventHandler() cache.ResourceEventHandler {
	return cache.ResourceEventHandlerFuncs{
		AddFunc: func(obj interface{}) {
			node := obj.(*v1core.Node)
			nodeIP, err := utils.GetNodeIP(node)
			if err != nil {
				klog.Errorf(
					"New node received, but we were unable to add it as we were couldn't find its node IP: %v", err)
				return
			}

			klog.V(2).Infof("Received node %s added update from watch API so peer with new node", nodeIP)
			nrc.OnNodeUpdate(obj)
		},
		UpdateFunc: func(oldObj, newObj interface{}) {
			// we are only interested in node add/delete, so skip update
		},
		DeleteFunc: func(obj interface{}) {
			node, ok := obj.(*v1core.Node)
			if !ok {
				tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
				if !ok {
					klog.Errorf("unexpected object type: %v", obj)
					return
				}
				if node, ok = tombstone.Obj.(*v1core.Node); !ok {
					klog.Errorf("unexpected object type: %v", obj)
					return
				}
			}
			nodeIP, err := utils.GetNodeIP(node)
			// In this case even if we can't get the NodeIP that's alright as the node is being removed anyway and
			// future node lister operations that happen in OnNodeUpdate won't be affected as the node won't be returned
			if err == nil {
				klog.Infof("Received node %s removed update from watch API, so remove node from peer", nodeIP)
			} else {
				klog.Infof("Received node (IP unavailable) removed update from watch API, so remove node " +
					"from peer")
			}

			nrc.OnNodeUpdate(obj)
		},
	}
}

// OnNodeUpdate Handle updates from Node watcher. Node watcher calls this method whenever there is
// new node is added or old node is deleted. So peer up with new node and drop peering
// from old node
func (nrc *NetworkRoutingController) OnNodeUpdate(_ interface{}) {
	if !nrc.bgpServerStarted {
		return
	}

	// update export policies so that NeighborSet gets updated with new set of nodes
	err := nrc.AddPolicies()
	if err != nil {
		klog.Errorf("Error adding BGP policies: %s", err.Error())
	}

	if nrc.bgpEnableInternal {
		nrc.syncInternalPeers()
	}

	// skip if first round of disableSourceDestinationCheck() is not done yet, this is to prevent
	// all the nodes for all the node add update trying to perfrom disableSourceDestinationCheck
	if nrc.disableSrcDstCheck && nrc.initSrcDstCheckDone && nrc.ec2IamAuthorized {
		nrc.disableSourceDestinationCheck()
	}
}


text:
declare var i18n;

export interface FormatResult {
    number: string;
    valid: boolean;
}

export enum Mode {
    E164, National
}

export class Util {
    static trimNumber(value: string) {
        if (angular.isString(value)) {
            return value.replace(/[\+\s\-\(\)]/g, '');
        } else {
            return value;
        }
    }
}

export function telephoneFilter() {

    return function (input: string, mode: string, defaultAreaCode: string, returnObject: boolean) {

        var trimmedNumber, defaultGeneratedNumber, number;
        var filter = new TelephoneFilter();
        mode = mode ? mode : 'e164';
        trimmedNumber = Util.trimNumber(input);

        number = filter.formatNumber(trimmedNumber, mode);
        if (number) {
            return filter.wrapResult(input, number, returnObject);
        }

        if (defaultAreaCode && defaultAreaCode !== '') {
            defaultGeneratedNumber = defaultAreaCode + '' + trimmedNumber;
            number = filter.formatNumber(defaultGeneratedNumber, mode);
            if (number) {
                return filter.wrapResult(input, number, returnObject);
            }
        }

        return filter.wrapResult(input, number, returnObject);

    };

}

class TelephoneFilter {
    countryCodes = i18n.phonenumbers.metadata.countryCodeToRegionCodeMap;
    countryMetaData = i18n.phonenumbers.metadata.countryToMetadata;
    validRangeMap = {
        2: 'fixedLine',
        3: 'mobile',
        4: 'tollFree',
        5: 'premiumRate',
        6: 'sharedCost',
        7: 'personalNumber',
        8: 'voip',
        21: 'pager',
        24: 'noInternationalDialing',
        25: 'uan',
        28: 'voiceMail'
    };

    private regionsFromNumber(e164: string): Object[] {
        let regions: Object[], key, value;
        for (key in this.countryCodes) {
            value = this.countryCodes[key];
            var reg = new RegExp('^' + key),
                ok;

            ok = reg.exec(e164);

            if (ok) {
                regions = value;
                break;
            }
        }

        return regions;
    }

    private formatNumberForRegion(region: string, nationalNumber: string, mode: Mode, mainRegion: string): string {
        var metaData = this.countryMetaData[region],
            metaDataMain = this.countryMetaData[mainRegion],
            countryCode = metaData[10],
            nationalPrefix = metaData[12],
            nationalFormats = metaDataMain[19],
            internationalFormats = metaDataMain[20],
            number, international = (mode === Mode.E164),
            numberFormats = international && internationalFormats ? internationalFormats : nationalFormats,
            entry, i, matchNumber, matchLeadingDigits, validRange = false, range;

        if (numberFormats) {

            if (nationalPrefix && nationalNumber.substr(0, nationalPrefix.length) === nationalPrefix) {
                nationalNumber = nationalNumber.substr(nationalPrefix.length);
            }

            for (var key in this.validRangeMap) {
                entry = metaData[key];
                if (new RegExp('^(' + entry[2] + ')$').exec(nationalNumber)) {
                    validRange = true;
                    range = this.validRangeMap[key];
                    break;
                }
            }

            if (validRange) {
                for (i = 0; i < numberFormats.length; i++) {
                    entry = numberFormats[i];
                    matchNumber = new RegExp('^(' + entry[1] + ')$').exec(nationalNumber);

                    if (!angular.isDefined(entry[3])) {
                        matchLeadingDigits = true;
                    } else if (angular.isString(entry[3])) {
                        matchLeadingDigits = new RegExp('^(' + entry[3] + ')').exec(nationalNumber);
                    } else if (angular.isArray(entry[3])) {
                        angular.forEach(entry[3], function (lead) {
                            var result = new RegExp('^(' + lead + ')').exec(nationalNumber);
                            if (result) {
                                matchLeadingDigits = true;
                            }
                        });
                    }

                    if (matchNumber && matchLeadingDigits) {
                        var format = entry[2];
                        if (international) {
                            number = nationalNumber;
                            number = number.replace(new RegExp(entry[1]), format);
                            number = '+' + countryCode + ' ' + number;
                        } else {
                            number = nationalNumber;
                            number = number.replace(new RegExp(entry[1]), format);

                            if (nationalPrefix) {
                                number = nationalPrefix + '' + number;
                            }

                        }
                        break;
                    }
                }
            }
        }
        return number;
    }

    public formatNumber(number: string, mode: Mode | string): string {
        let regions = this.regionsFromNumber(number), region, i, countryCode, nationalPrefix, nationalNumber, result, mainRegion;
        let finalMode: Mode;

        if (typeof mode === 'string') {
            finalMode = mode === 'e164' ? Mode.E164 : Mode.National;
        } else {
            finalMode = mode;
        }

        if (angular.isNumber(number)) {
            number = number.toString();
        }

        if (regions && regions.length > 0) {
            mainRegion = regions[0];

            for (i = 0; i < regions.length; i++) {
                region = regions[i];
                if (this.countryMetaData[region]) {
                    countryCode = this.countryMetaData[region][10];
                    nationalPrefix = this.countryMetaData[region][12];
                    nationalNumber = number.substr(countryCode.toString().length);
                    if (nationalPrefix && nationalNumber.substr(0, nationalPrefix.length) !== nationalPrefix) {
                        nationalNumber = nationalPrefix + '' + nationalNumber;
                    }
                    result = this.formatNumberForRegion(region, nationalNumber, finalMode, mainRegion);
                    if (result) {
                        break;
                    }
                }
            }
        }
        return result;
    };

    public wrapResult(input: string, number: string, returnObject: boolean): string | FormatResult {
        var result: string | FormatResult;

        if (returnObject) {
            if (!number) {
                result = {
                    number: input,
                    valid: false
                };
            } else {
                result = {
                    number: number,
                    valid: true
                };
            }
        } else {
            if (!number) {
                result = input;
            } else {
                result = number;
            }
        }
        return result;
    };
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syst. mycol. (Lundae) 1: 320 (1821)

#### Original name
Cantharellus cinereus f. cinereus

### Remarks
null


text:
package middleware

import "net/http"

type Cors struct{}

func (c Cors) Handle(w http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
	headers := w.Header()
	if headers.Get("Access-Control-Allow-Origin") == "" {
		headers.Add("Access-Control-Allow-Origin", "*")
	}
	if headers.Get("Access-Control-Allow-Methods") == "" {
		headers.Add("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE")
	}
	if headers.Get("Access-Control-Allow-Headers") == "" {
		headers.Add("Access-Control-Allow-Headers", "x-auth, content-type, Access-Control-Request-Headers, Authorization, x-app-api-key")
	}
	if req.Method != "OPTIONS" {
		next(w, req)
		return
	}
}


text:
#import "NSObject.h"

@class NSCalendar, NSObject<OS_dispatch_semaphore>;

// Not exported
@interface TSCECalendar : NSObject
{
    NSCalendar *mCalendar;
    NSObject<OS_dispatch_semaphore> *mSem;
}

- (void)dealloc;
- (id)components:(unsigned long long)arg1 fromDate:(id)arg2 toDate:(id)arg3 options:(unsigned long long)arg4;
- (id)dateByAddingComponents:(id)arg1 toDate:(id)arg2 options:(unsigned long long)arg3;
- (id)components:(unsigned long long)arg1 fromDate:(id)arg2;
- (id)dateFromComponents:(id)arg1;
- (void)setTimeZone:(id)arg1;
- (id)initWithCalendarIdentifier:(id)arg1;
- (id)init;

@end


text:
- Original: [Release electron v10.4.3 - electron/electron](https://github.com/electron/electron/releases/tag/v10.4.3)

## Fixes

- Fixed an issue where the thumbar disappeared after `win.hide()` on Windows. [#28388](https://github.com/electron/electron/pull/28388) (Also in [11](https://github.com/electron/electron/pull/28391), [12](https://github.com/electron/electron/pull/28389), [13](https://github.com/electron/electron/pull/28390))
  - Windows にて `win.hide()` の後にサムネイル ツールバー表示が消える問題を修正しました
  - Windows のタスクバーにおけるアプリ ウィンドウの縮小表示が消える問題 [#28319](https://github.com/electron/electron/issues/28319) を修正、ウィンドウを隠した場合は自前でサムネイルを再設定する必要があるので処理を追加することにより対応

## Other Changes

- Security: backported fix for chromium:1196683. [#28640](https://github.com/electron/electron/pull/28640)
- Securty: Backported fix to CVE-2021-21174. [#28234](https://github.com/electron/electron/pull/28234)


text:
require_relative 'base'

module Pliny::Commands
  class Generator
    class Mediator < Base
      def create
        mediator = "./lib/mediators/#{field_name}.rb"
        write_template('mediator.erb', mediator,
                        singular_class_name: singular_class_name)
        display "created mediator file #{mediator}"
      end

      def create_test
        test = "./spec/mediators/#{field_name}_spec.rb"
        write_template('mediator_test.erb', test,
                        singular_class_name: singular_class_name)
        display "created test #{test}"
      end
    end
  end
end


text:
"""Types used in the Google BigQuery DB-API.

See `PEP-249`_ for details.

.. _PEP-249:
    https://www.python.org/dev/peps/pep-0249/#type-objects-and-constructors
"""

import datetime

Date = datetime.date
Time = datetime.time
Timestamp = datetime.datetime
DateFromTicks = datetime.date.fromtimestamp
TimestampFromTicks = datetime.datetime.fromtimestamp

def Binary(string):
    """Contruct a DB-API binary value.

    :type string: str
    :param string: A string to encode as a binary value.

    :rtype: bytes
    :returns: The UTF-8 encoded bytes representing the string.
    """
    return string.encode('utf-8')

def TimeFromTicks(ticks, tz=None):
    """Construct a DB-API time value from the given ticks value.

    :type ticks: float
    :param ticks:
        a number of seconds since the epoch; see the documentation of the
        standard Python time module for details.

    :type tz: :class:`datetime.tzinfo`
    :param tz: (Optional) time zone to use for conversion

    :rtype: :class:`datetime.time`
    :returns: time represented by ticks.
    """
    dt = datetime.datetime.fromtimestamp(ticks, tz=tz)
    return dt.timetz()

class _DBAPITypeObject(object):
    """DB-API type object which compares equal to many different strings.

    See `PEP-249`_ for details.

    .. _PEP-249:
        https://www.python.org/dev/peps/pep-0249/#implementation-hints-for-module-authors
    """

    def __init__(self, *values):
        self.values = values

    def __eq__(self, other):
        return other in self.values

STRING = 'STRING'
BINARY = _DBAPITypeObject('BYTES', 'RECORD', 'STRUCT')
NUMBER = _DBAPITypeObject(
    'INTEGER', 'INT64', 'FLOAT', 'FLOAT64', 'BOOLEAN', 'BOOL')
DATETIME = _DBAPITypeObject('TIMESTAMP', 'DATE', 'TIME', 'DATETIME')
ROWID = 'ROWID'


text:
/* Automatically generated by shapeshifter. Do not modify! */
/* eslint-disable */
/* @flow */

import Schema from 'shapeshifter';

export const multipleChildrenSchema = new Schema('multiple-children', 'uuid');

export const singleChildSchema = new Schema('single-child');

export const parentSchema = new Schema('parents');

multipleChildrenSchema
  .addAttributes([
    'uuid',
  ]);

singleChildSchema
  .hasOne({
    self: singleChildSchema,
  })
  .addAttributes([
    'id',
    'active',
    'self',
  ]);

parentSchema
  .morphTo({
    Single: singleChildSchema,
    'Model::Multiple': multipleChildrenSchema,
  }, 'polymorph', '_type', '_fk')
  .belongsToMany({
    children: multipleChildrenSchema,
  })
  .hasOne({
    orphan: singleChildSchema,
  })
  .addAttributes([
    'id',
    'name',
    'children',
    'orphan',
    'polymorph',
    'polymorph_fk',
    'polymorph_type',
  ]);