text:
import time
import sn3218
import RPi.GPIO as GPIO
from colorsys import hsv_to_rgb

__version__ = '0.0.1'

BUTTON_A = 0
BUTTON_B = 1
BUTTON_X = 2
BUTTON_Y = 3
NUM_BUTTONS = 4

# Underlighting LED locations
LIGHT_FRONT_RIGHT = 0
LIGHT_FRONT_LEFT = 1
LIGHT_MIDDLE_LEFT = 2
LIGHT_REAR_LEFT = 3
LIGHT_REAR_RIGHT = 4
LIGHT_MIDDLE_RIGHT = 5
NUM_UNDERLIGHTS = 6

# Useful underlighting groups
LIGHTS_LEFT = (LIGHT_FRONT_LEFT, LIGHT_MIDDLE_LEFT, LIGHT_REAR_LEFT)
LIGHTS_RIGHT = (LIGHT_FRONT_RIGHT, LIGHT_MIDDLE_RIGHT, LIGHT_REAR_RIGHT)
LIGHTS_FRONT = (LIGHT_FRONT_LEFT, LIGHT_FRONT_RIGHT)
LIGHTS_MIDDLE = (LIGHT_MIDDLE_LEFT, LIGHT_MIDDLE_RIGHT)
LIGHTS_REAR = (LIGHT_REAR_LEFT, LIGHT_REAR_RIGHT)
LIGHTS_LEFT_DIAGONAL = (LIGHT_FRONT_LEFT, LIGHT_REAR_RIGHT)
LIGHTS_RIGHT_DIAGONAL = (LIGHT_FRONT_RIGHT, LIGHT_REAR_LEFT)

# Motor names
MOTOR_LEFT = 0
MOTOR_RIGHT = 1
NUM_MOTORS = 2

class Trilobot():
    # User button pins
    BUTTON_A_PIN = 5
    BUTTON_B_PIN = 6
    BUTTON_X_PIN = 16
    BUTTON_Y_PIN = 24

    # Onboard LEDs pins (next to each button)
    LED_A_PIN = 23
    LED_B_PIN = 22
    LED_X_PIN = 17
    LED_Y_PIN = 27

    # Motor driver pins, via DRV8833PWP Dual H-Bridge
    MOTOR_EN_PIN = 26
    MOTOR_LEFT_P = 8
    MOTOR_LEFT_N = 11
    MOTOR_RIGHT_P = 10
    MOTOR_RIGHT_N = 9

    # HC-SR04 Ultrasound pins
    ULTRA_TRIG_PIN = 13
    ULTRA_ECHO_PIN = 25

    # Servo / WS2812 pin
    SERVO_PIN = 12

    # SN3218 LED Driver pin
    UNDERLIGHTING_EN_PIN = 7

    # Speed of sound is 343m/s which we need in cm/ns for our distance measure
    SPEED_OF_SOUND_CM_NS = 343 * 100 / 1E9  # 0.0000343 cm / ns

    def __init__(self):
        """ Initialise trilobot's hardware functions
        """

        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)

        # Setup user buttons
        GPIO.setup(self.BUTTON_A_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.setup(self.BUTTON_B_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.setup(self.BUTTON_X_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.setup(self.BUTTON_Y_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        self.buttons = (self.BUTTON_A_PIN, self.BUTTON_B_PIN, self.BUTTON_X_PIN, self.BUTTON_Y_PIN)

        # Setup user LEDs
        GPIO.setup(self.LED_A_PIN, GPIO.OUT)
        GPIO.setup(self.LED_B_PIN, GPIO.OUT)
        GPIO.setup(self.LED_X_PIN, GPIO.OUT)
        GPIO.setup(self.LED_Y_PIN, GPIO.OUT)
        self.leds = (self.LED_A_PIN, self.LED_B_PIN, self.LED_X_PIN, self.LED_Y_PIN)

        led_a_pwm = GPIO.PWM(self.LED_A_PIN, 2000)
        led_a_pwm.start(0)

        led_b_pwm = GPIO.PWM(self.LED_B_PIN, 2000)
        led_b_pwm.start(0)

        led_x_pwm = GPIO.PWM(self.LED_X_PIN, 2000)
        led_x_pwm.start(0)

        led_y_pwm = GPIO.PWM(self.LED_Y_PIN, 2000)
        led_y_pwm.start(0)
        self.led_pwm_mapping = {self.LED_A_PIN: led_a_pwm,
                                self.LED_B_PIN: led_b_pwm,
                                self.LED_X_PIN: led_x_pwm,
                                self.LED_Y_PIN: led_y_pwm}

        # Setup motor driver
        GPIO.setup(self.MOTOR_EN_PIN, GPIO.OUT)
        GPIO.setup(self.MOTOR_LEFT_P, GPIO.OUT)
        GPIO.setup(self.MOTOR_LEFT_N, GPIO.OUT)
        GPIO.setup(self.MOTOR_RIGHT_P, GPIO.OUT)
        GPIO.setup(self.MOTOR_RIGHT_N, GPIO.OUT)

        motor_left_p_pwm = GPIO.PWM(self.MOTOR_LEFT_P, 100)
        motor_left_p_pwm.start(0)

        motor_left_n_pwm = GPIO.PWM(self.MOTOR_LEFT_N, 100)
        motor_left_n_pwm.start(0)

        motor_right_p_pwm = GPIO.PWM(self.MOTOR_RIGHT_P, 100)
        motor_right_p_pwm.start(0)

        motor_right_n_pwm = GPIO.PWM(self.MOTOR_RIGHT_N, 100)
        motor_right_n_pwm.start(0)
        self.motor_pwm_mapping = {self.MOTOR_LEFT_P: motor_left_p_pwm,
                                  self.MOTOR_LEFT_N: motor_left_n_pwm,
                                  self.MOTOR_RIGHT_P: motor_right_p_pwm,
                                  self.MOTOR_RIGHT_N: motor_right_n_pwm}

        sn3218.reset()

        self.underlight = [0 for i in range(18)]
        sn3218.output(self.underlight)
        sn3218.enable_leds(0b111111111111111111)
        sn3218.disable()

        # setup ultrasonic sensor pins
        GPIO.setup(self.ULTRA_TRIG_PIN, GPIO.OUT)
        GPIO.setup(self.ULTRA_ECHO_PIN, GPIO.IN)

        # setup the servo object to None, for later initialisation
        self.servo = None

    def __del__(self):
        """ Clean up GPIO and underlighting when the class is deleted.
        """
        sn3218.disable()
        GPIO.cleanup()

    ###########
    # Buttons #
    ###########
    def read_button(self, button):
        """ Return whether or not a given button is pressed.
        button: the ID of the button to read the state of
        Returns True for pressed, False for released
        """
        if type(button) is not int:
            raise TypeError("button must be an integer")

        if button not in range(NUM_BUTTONS):
            raise ValueError("""button must be an integer in the range 0 to 3. For convenience, use the constants:
                BUTTON_A (0), BUTTON_B (1), BUTTON_X (2), or BUTTON_Y (3)""")

        return not GPIO.input(self.buttons[button])

    ########
    # LEDs #
    ########
    def set_button_led(self, button_led, value):
        """ Turns the given button LED on or off, or to a brighness value.
        button_led: the ID of the button LED to set the state of
        value: either True for on, False for off, or a number between 0.0 and 1.0
        """
        if type(button_led) is not int:
            raise TypeError("led must be an integer")

        if button_led not in range(NUM_BUTTONS):
            raise ValueError("""button_led must be an integer in the range 0 to 3. For convenience, use the constants:
                BUTTON_A (0), BUTTON_B (1), BUTTON_X (2), or BUTTON_Y (3)""")

        pwm = self.led_pwm_mapping[self.leds[button_led]]
        if isinstance(value, bool):
            if value:
                pwm.ChangeDutyCycle(100)
            else:
                pwm.ChangeDutyCycle(0)
        elif value < 0.0 or value > 1.0:
            raise ValueError("value must be in the range 0.0 to 1.0")
        else:
            pwm.ChangeDutyCycle(value * 100)

    ##########
    # Motors #
    ##########
    def set_motor_speed(self, motor, speed):
        """ Sets the speed of the given motor.
        motor: the ID of the motor to set the state of
        speed: the motor speed, between -1.0 and 1.0
        """
        if type(motor) is not int:
            raise TypeError("motor must be an integer")

        if motor not in range(2):
            raise ValueError("""motor must be an integer in the range 0 to 1. For convenience, use the constants:
                MOTOR_LEFT (0), or MOTOR_RIGHT (1)""")

        # Limit the speed value rather than throw a value exception
        speed = max(min(speed, 1.0), -1.0)

        GPIO.output(self.MOTOR_EN_PIN, True)
        pwm_p = None
        pwm_n = None
        if motor == 0:
            # Left motor inverted so a positive speed drives forward
            pwm_p = self.motor_pwm_mapping[self.MOTOR_LEFT_N]
            pwm_n = self.motor_pwm_mapping[self.MOTOR_LEFT_P]
        else:
            pwm_p = self.motor_pwm_mapping[self.MOTOR_RIGHT_P]
            pwm_n = self.motor_pwm_mapping[self.MOTOR_RIGHT_N]

        if speed > 0.0:
            pwm_p.ChangeDutyCycle(100)
            pwm_n.ChangeDutyCycle(100 - (speed * 100))
        elif speed < 0.0:
            pwm_p.ChangeDutyCycle(100 - (-speed * 100))
            pwm_n.ChangeDutyCycle(100)
        else:
            pwm_p.ChangeDutyCycle(100)
            pwm_n.ChangeDutyCycle(100)

    def set_motor_speeds(self, l_speed, r_speed):
        """ Sets the speeds of both motors at once.
        l_speed: the left motor speed, between -1.0 and 1.0
        r_speed: the right motor speed, between -1.0 and 1.0
        """
        self.set_motor_speed(MOTOR_LEFT, l_speed)
        self.set_motor_speed(MOTOR_RIGHT, r_speed)

    def set_left_speed(self, speed):
        """ Sets the speed of the left motor only.
        speed: the speed, between -1.0 and 1.0
        """
        self.set_motor_speed(MOTOR_LEFT, speed)

    def set_right_speed(self, speed):
        """ Sets the speed of the right motor only.
        speed: the speed, between -1.0 and 1.0
        """
        self.set_motor_speed(MOTOR_RIGHT, speed)

    def disable_motors(self):
        """ Disables both motors, allowing them to spin freely.
        """
        GPIO.output(self.MOTOR_EN_PIN, False)
        self.motor_pwm_mapping[self.MOTOR_LEFT_P].ChangeDutyCycle(0)
        self.motor_pwm_mapping[self.MOTOR_LEFT_N].ChangeDutyCycle(0)
        self.motor_pwm_mapping[self.MOTOR_RIGHT_P].ChangeDutyCycle(0)
        self.motor_pwm_mapping[self.MOTOR_RIGHT_N].ChangeDutyCycle(0)

    #################
    # Motor Helpers #
    #################
    def forward(self, speed=1.0):
        """ Drives Trilobot forward.
        speed: the speed to drive at, between 0.0 and 1.0
        """
        self.set_motor_speeds(speed, speed)

    def backward(self, speed=1.0):
        """ Drives Trilobot backward.
        speed: the speed to drive at, between 0.0 and 1.0
        """
        self.set_motor_speeds(-speed, -speed)

    def turn_left(self, speed=1.0):
        """ Turns Trilobot left.
        speed: the speed to turn at, between 0.0 and 1.0
        """
        self.set_motor_speeds(-speed, speed)

    def turn_right(self, speed=1.0):
        """ Turns Trilobot right.
        speed: the speed to turn at, between 0.0 and 1.0
        """
        self.set_motor_speeds(speed, -speed)

    def curve_forward_left(self, speed=1.0):
        """ Drives Trilobot forward and to the left.
        speed: the speed to drive at, between 0.0 and 1.0
        """
        self.set_motor_speeds(0.0, speed)

    def curve_forward_right(self, speed=1.0):
        """ Drives Trilobot forward and to the right.
        speed: the speed to drive at, between 0.0 and 1.0
        """
        self.set_motor_speeds(speed, 0.0)

    def curve_backward_left(self, speed=1.0):
        """ Drives Trilobot backward and to the left.
        speed: the speed to drive at, between 0.0 and 1.0
        """
        self.set_motor_speeds(0.0, -speed)

    def curve_backward_right(self, speed=1.0):
        """ Drives Trilobot backward and to the right.
        speed: the speed to drive at, between 0.0 and 1.0
        """
        self.set_motor_speeds(-speed, 0.0)

    def stop(self):
        """ Stops Trilobot from driving, sharply.
        """
        self.set_motor_speeds(0.0, 0.0)

    def coast(self):
        """ Stops Trilobot from driving, slowly.
        """
        self.disable_motors()

    #################
    # Underlighting #
    #################
    def show_underlighting(self):
        """ Shows the previously stored colors on Trilobot's underlights.
        """
        sn3218.output(self.underlight)
        sn3218.enable()

    def disable_underlighting(self):
        """ Disables Trilobot's underlighting, preserving the last set colors.
        """
        sn3218.disable()

    def set_underlight(self, light, r_color, g=None, b=None, show=True):
        """ Sets a single underlight to a given RGB color.
        light: the ID of the light to set the color of
        r_color: the red component of the color (from 0 to 255), or a list/tuple containing all three color components.
        g: the green component of the color (from 0 to 255), if r_color was not given a list/tuple
        b: the blue component of the color (from 0 to 255), if r_color was not given a list/tuple
        show: whether or not to show the new color immediately
        """
        if type(light) is not int:
            raise TypeError("light must be an integer")

        if light not in range(NUM_UNDERLIGHTS):
            raise ValueError("""light must be an integer in the range 0 to 5. For convenience, use the constants:
                LIGHT_FRONT_RIGHT (0), LIGHT_FRONT_LEFT (1), LIGHT_MIDDLE_LEFT (2), LIGHT_REAR_LEFT (3), LIGHT_REAR_RIGHT (4), or LIGHT_MIDDLE_RIGHT (5)""")

        if g is None and b is None:
            # Treat r_color as a colour

            if isinstance(r_color, str):
                value = r_color.strip('#')
                r_color = list(int(value[i:i + 2], 16) for i in (0, 2, 4))

            if isinstance(r_color, list) or isinstance(r_color, tuple):
                if len(r_color) != 3 or \
                        (r_color[0] < 0 or r_color[0] > 255) or \
                        (r_color[1] < 0 or r_color[1] > 255) or \
                        (r_color[2] < 0 or r_color[2] > 255):
                    raise ValueError("color must either be a color hex code, or a list/tuple of 3 numbers between 0 and 255")

                self.underlight[(light * 3)] = int(r_color[0])
                self.underlight[(light * 3) + 1] = int(r_color[1])
                self.underlight[(light * 3) + 2] = int(r_color[2])
            else:
                raise ValueError("color must either be a color hex code, or a list/tuple of 3 numbers between 0 and 255")

        else:
            if r_color < 0 or r_color > 255:
                raise ValueError("r must be in the range 0 to 255")

            if g is None or g < 0 or g > 255:
                raise ValueError("g must be in the range 0 to 255")

            if b is None or b < 0 or b > 255:
                raise ValueError("b must be in the range 0 to 255")

            self.underlight[(light * 3)] = int(r_color)
            self.underlight[(light * 3) + 1] = int(g)
            self.underlight[(light * 3) + 2] = int(b)

        if show:
            self.show_underlighting()

    def set_underlight_hsv(self, light, h, s=1, v=1, show=True):
        """ Sets a single underlight to a given HSV color.
        light: the ID of the light to set the color of
        h: the hue of the color (from 0.0 to 1.0)
        s: the saturation of the color (from 0.0 to 1.0)
        v: the value of the color (from 0.0 to 1.0)
        show: whether or not to show the new color immediately
        """
        color = [i * 255 for i in hsv_to_rgb(h, s, v)]
        self.set_underlight(light, color, show=show)

    def fill_underlighting(self, r_color, g=None, b=None, show=True):
        """ Fill all the underlights with a given RGB color.
        light: the ID of the light to set the color of
        r_color: the red component of the color (from 0 to 255), or a list/tuple containing all three color components.
        g: the green component of the color (from 0 to 255), if r_color was not given a list/tuple
        b: the blue component of the color (from 0 to 255), if r_color was not given a list/tuple
        show: whether or not to show the new color immediately
        """
        for i in range(0, NUM_UNDERLIGHTS):
            self.set_underlight(i, r_color, g, b, show=False)
        if show:
            self.show_underlighting()

    def fill_underlighting_hsv(self, h, s=1, v=1, show=True):
        """ Fill all the underlights with a given HSV color.
        h: the hue of the color (from 0.0 to 1.0)
        s: the saturation of the color (from 0.0 to 1.0)
        v: the value of the color (from 0.0 to 1.0)
        show: whether or not to show the new color immediately
        """
        color = [i * 255 for i in hsv_to_rgb(h, s, v)]
        for i in range(0, NUM_UNDERLIGHTS):
            self.set_underlight(i, color, show=False)
        if show:
            self.show_underlighting()

    def clear_underlight(self, light, show=True):
        """ Clear the color of a single underlight. This has the effect of turning it off.
        light: the ID of the light to clear
        show: whether or not to show the new color immediately
        """
        self.set_underlight(light, 0, 0, 0, show=show)

    def clear_underlighting(self, show=True):
        """ Clear the color of all underlights. This has the effect of turning them off.
        show: whether or not to show the new color immediately
        """
        self.fill_underlighting(0, 0, 0, show=show)

    #########################
    # Underlighting Helpers #
    #########################
    def set_underlights(self, lights, r_color, g=None, b=None, show=True):
        """ Sets a group of underlights to a given RGB color.
        lights: a list/tuple containing the IDs of the lights to set the color of
        r_color: the red component of the color (from 0 to 255), or a list/tuple containing all three color components.
        g: the green component of the color (from 0 to 255), if r_color was not given a list/tuple
        b: the blue component of the color (from 0 to 255), if r_color was not given a list/tuple
        show: whether or not to show the new color immediately
        """
        if type(lights) != list and type(lights) != tuple:
            raise TypeError("lights must be a list or tuple containing the numbers for the underlights to set (from 0 to 5)")

        light_count = len(lights)
        if light_count > NUM_UNDERLIGHTS:
            raise ValueError("lights contains more values than the number of underlights available")
        if light_count == 0:
            raise ValueError("lights cannot be empty")

        if light_count > 1:
            for i in range(0, light_count - 1):
                self.set_underlight(lights[i], r_color, g, b, show=False)

        self.set_underlight(lights[light_count - 1], r_color, g, b, show=show)

    def set_underlights_hsv(self, lights, h, s=1, v=1, show=True):
        """ Sets a group of underlights to a single HSV color.
        lights: a list/tuple containing the IDs of the lights to set the color of
        h: the hue of the color (from 0.0 to 1.0)
        s: the saturation of the color (from 0.0 to 1.0)
        v: the value of the color (from 0.0 to 1.0)
        show: whether or not to show the new color immediately
        """
        color = [i * 255 for i in hsv_to_rgb(h, s, v)]
        self.set_underlights(lights, color, show=show)

    def clear_underlights(self, lights, show=True):
        """ Clear the color of a group of underlights. This has the effect of turning them off.
        lights: a list/tuple containing the IDs of the lights to set the color of
        show: whether or not to show the new color immediately
        """
        self.set_underlights(lights, 0, 0, 0, show=show)

    ##############
    # Ultrasound #
    ##############
    def read_distance(self, timeout=50, samples=3, offset=190000):
        """ Return a distance in cm from the ultrasound sensor.
        timeout: total time in ms to try to get distance reading
        samples: determines how many readings to average
        offset: Time in ns the measurement takes (prevents over estimates)
        The default offset here is about right for a Raspberry Pi 4.
        Returns the measured distance in centimetres as a float.

        To give more stable readings, this method will attempt to take several
        readings and return the average distance. You can set the maximum time
        you want it to take before returning a result so you have control over
        how long this method ties up your program. It takes as many readings
        up to the requested number of samples set as it can before the timeout
        total is reached. It then returns the average distance measured. Any
        readings where the single reading takes more than the timeout is
        ignored so these do not distort the average distance measured. If no
        valid readings are taken before the timeout then it returns zero.

        You can choose parameters to get faster but less accurate readings or
        take longer to get more samples to average before it returns. The
        timeout effectively limits the maximum distance the sensor can measure
        because if the sound pusle takes longer to return over the distance
        than the timeout set then this method returns zero rather than waiting.
        So to extend the distance that can be measured, use a larger timeout.
        """

        # Start timing
        start_time = time.perf_counter_ns()
        time_elapsed = 0
        count = 0  # Track now many samples taken
        total_pulse_durations = 0
        distance = -999

        # Loop until the timeout is exceeded or all samples have been taken
        while (count < samples) and (time_elapsed < timeout * 1000000):
            # Trigger
            GPIO.output(self.ULTRA_TRIG_PIN, 1)
            time.sleep(.00001)  # 10 microseconds
            GPIO.output(self.ULTRA_TRIG_PIN, 0)

            # Wait for the ECHO pin to go high
            # wait for the pulse rise
            GPIO.wait_for_edge(self.ULTRA_ECHO_PIN, GPIO.RISING, timeout=timeout)
            pulse_start = time.perf_counter_ns()

            # And wait for it to fall
            GPIO.wait_for_edge(self.ULTRA_ECHO_PIN, GPIO.FALLING, timeout=timeout)
            pulse_end = time.perf_counter_ns()

            # get the duration
            pulse_duration = pulse_end - pulse_start - offset
            if pulse_duration < 0:
                pulse_duration = 0  # Prevent negative readings when offset was too high

            # Only count reading if achieved in less than timeout total time
            if pulse_duration < timeout * 1000000:
                # Convert to distance and add to total
                total_pulse_durations += pulse_duration
                count += 1

            time_elapsed = time.perf_counter_ns() - start_time

        # Calculate average distance in cm if any successful reading were made
        if count > 0:
            # Calculate distance using speed of sound divided by number of samples and half
            # that as sound pulse travels from robot to obstacle and back (twice the distance)
            distance = total_pulse_durations * self.SPEED_OF_SOUND_CM_NS / (2 * count)

        return distance

    #########
    # Servo #
    #########
    def initialise_servo(self, min_angle=-90, max_angle=90, min_pulse_us=500, max_pulse_us=2500):
        if self.servo is not None:
            raise RuntimeError("Servo is already initialised.")

        # if not exists /var/run/pigpio.pid:
        #    stop now
        import os
        import sys
        if not os.path.isfile('/var/run/pigpio.pid'):
            print('Trilobot uses pigpio for Servo control.')
            print('If it is not already installed, please install it with "sudo apt install pigpio"')
            print('Then run "sudo pigpiod" to enable it until the next boot, \
and "sudo systemctl enable pigpiod" to have it auto-start on every boot')
            sys.exit()

        # set up servo control
        from gpiozero.pins.pigpio import PiGPIOFactory
        from gpiozero import AngularServo
        self.servo = AngularServo(self.SERVO_PIN, initial_angle=None,
                                  min_angle=min_angle,
                                  max_angle=max_angle,
                                  min_pulse_width=min_pulse_us / 1000000,
                                  max_pulse_width=max_pulse_us / 1000000,
                                  pin_factory=PiGPIOFactory())

    def set_servo_value(self, value):
        """ Sets the servo to a given value between its minimum and maximum angles.
        value: a number between -1.0 and 1.0
        """
        if self.servo is None:
            self.initialise_servo()
        self.servo.value = value

    def set_servo_angle(self, angle):
        """ Sets the servo to a given angle.
        angle: an angle in degrees between -90 and +90
        """
        if self.servo is None:
            self.initialise_servo()
        self.servo.angle = angle

    def disable_servo(self):
        """ Disables the servo, allowing it to be turned freely.
        """
        if self.servo is not None:
            self.servo.value = None

    #########################
    # Servo Helpers #
    #########################
    def servo_to_center(self):
        """ Moves the servo to its center angle.
        """
        if self.servo is None:
            self.initialise_servo()
        self.servo.mid()

    def servo_to_min(self):
        """ Moves the servo to its minimum angle.
        """
        if self.servo is None:
            self.initialise_servo()
        self.servo.min()

    def servo_to_max(self):
        """ Moves the servo to its maximum angle.
        """
        if self.servo is None:
            self.initialise_servo()
        self.servo.max()

    def servo_to_percent(self, value, value_min=0, value_max=1, angle_min=-90, angle_max=+90):
        """ Moves the servo to an angle between the given minimum and maximums.
        Useful for having a sensor that outputs between two values move the servo between two particular angles.
        By default this will convert a percentage value between 0.0 and 1.0 to servo angles of -90 and +90 degrees.
        value: the value to be applied to the servo
        value_min: the minimum value expected
        value_max: the maximum value expected
        angle_min: the angle that corresponds to value_min
        angle_max: the angle that corresponds to value_max
        """
        if self.servo is None:
            self.initialise_servo()
        # Map the value from its range to an angle range
        angle = (value - value_min) * (angle_max - angle_min) / (value_max - value_min) + angle_min
        self.set_servo_angle(angle)

if __name__ == "__main__":
    tbot = Trilobot()

    print("Trilobot Function Test")

    time.sleep(2.0)
    tbot.fill_underlighting(127, 127, 127, show=False)
    for i in range(0, 10):
        print(i)
        tbot.show_underlighting()
        time.sleep(0.1)
        tbot.disable_underlighting()
        time.sleep(0.5)

    for led in range(NUM_UNDERLIGHTS):
        tbot.clear_underlighting(show=False)
        tbot.set_underlight(led, 255, 0, 0)
        time.sleep(0.1)
        tbot.clear_underlighting(show=False)
        tbot.set_underlight(led, 0, 255, 0)
        time.sleep(0.1)
        tbot.clear_underlighting(show=False)
        tbot.set_underlight(led, 0, 0, 255)
        time.sleep(0.1)

    tbot.clear_underlighting()

    h = 0
    v = 0
    spacing = 1.0 / NUM_UNDERLIGHTS

    a = 0
    b = 0
    x = 0
    y = 0
    while True:
        for led in range(NUM_UNDERLIGHTS):
            led_h = h + (led * spacing)
            if led_h >= 1.0:
                led_h -= 1.0
            tbot.set_underlight_hsv(led, led_h, 1, 1, show=False)

        tbot.show_underlighting()
        h += 0.5 / 360
        if h >= 1.0:
            h -= 1.0

        if tbot.read_button(BUTTON_A):
            a = min(a + 0.01, 1.0)
        else:
            a = max(a - 0.01, 0.0)
        tbot.set_button_led(BUTTON_A, a)

        if tbot.read_button(BUTTON_B):
            b = min(b + 0.01, 1.0)
        else:
            b = max(b - 0.01, 0.0)
        tbot.set_button_led(BUTTON_B, b)

        if tbot.read_button(BUTTON_X):
            x = min(x + 0.01, 1.0)
        else:
            x = max(x - 0.01, 0.0)
        tbot.set_button_led(BUTTON_X, x)

        if tbot.read_button(BUTTON_Y):
            y = min(y + 0.01, 1.0)
        else:
            y = max(y - 0.01, 0.0)
        tbot.set_button_led(BUTTON_Y, y)

        tbot.set_left_speed(a - b)
        tbot.set_right_speed(x - y)
        time.sleep(0.01)


text:
package org.market.tool.ui;

import org.market.tool.R;
import org.market.tool.bean.OriginTaskBean;
import org.market.tool.bean.User;
import org.market.tool.util.ProgressUtil;

import cn.bmob.v3.listener.UpdateListener;

import com.bmob.pay.tool.BmobPay;
import com.bmob.pay.tool.PayListener;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class RechargeActivity extends BaseActivity {
	private Button btSubmit;
	private EditText etRechargeFund;
	private double fund;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_recharge);

		initViews();
		setListeners();

		initTopBarForLeft("³äÖµ");
	}

	private void initViews(){
		btSubmit=(Button) findViewById(R.id.submit);
		etRechargeFund=(EditText) findViewById(R.id.et_recharge_fund);
	}

	private void setListeners(){
		btSubmit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				String etFund=etRechargeFund.getText().toString();
				if(TextUtils.isEmpty(etFund)){
					ShowToast("ÊäÈëΪ¿Õ");
					return;
				}
				fund=new Double(etFund);
				new BmobPay(RechargeActivity.this).pay(fund, "¹ºÂò½ð±Ò", new PayListener() {

					@Override
					public void unknow() {

					}

					@Override
					public void succeed() {
						ShowToast("³äֵʧ°Ü");
						updateFund();

					}

					@Override
					public void orderId(String arg0) {

					}

					@Override
					public void fail(int arg0, String arg1) {
						ShowToast("³äֵʧ°Ü");

					}
				});
			}
		});
	}

	/**
	 * ¸üжÔÏó
	 */
	private void updateFund() {
		ProgressUtil.showProgress(this, "");
		final User u = new User();
		u.setFund(fund);
		u.update(this, user.getObjectId(), new UpdateListener() {

			@Override
			public void onSuccess() {
				ShowLog("success");
				ProgressUtil.closeProgress();
			}

			@Override
			public void onFailure(int code, String msg) {
				ShowLog("¸üÐÂʧ°Ü£º" + msg);
				ProgressUtil.closeProgress();
			}
		});

	}

}

redpajama_set_name: RedPajamaGithub


text:
var searchData=
[
  ['kernel_20information_20and_20control',['Kernel Information and Control',['../group___c_m_s_i_s___r_t_o_s___kernel_ctrl.html',1,'']]]
];


text:
<?php

namespace Zend\Mvc\Controller\Plugin;

use Zend\Stdlib\DispatchableInterface as Dispatchable;

interface PluginInterface
{
    /**
     * Set the current controller instance
     *
     * @param  Dispatchable $controller
     * @return void
     */
    public function setController(Dispatchable $controller);

    /**
     * Get the current controller instance
     *
     * @return null|Dispatchable
     */
    public function getController();
}


text:
!function(d, w, c, u){'use strict'

	/*
		// USAGE:

		// Setup to-be parent element as extendable (Must have at least one child)
		var productList = new DomExtension({
			parent: document.querySelector('#productList')
		})

		// Create new elements if needed
		productList.total(10)
		// Populate/modify the newly created elements if needed
		// Show elements when done
		productList.show(10)

	*/

	var proto = {
		deep: true,
		showEl: function(el){
			el.style.display = 'block'
		},
		hideEl: function(el){
			el.style.display = 'none'
		},
		onExtend: noop,
		onContract: noop,

		// Extend/contract element list to new total
		total: function(n){
			if(this.showing < n){
				return this.extendChildren(n)
			}
			return this
		},

		// Increment total by n
		incrementTotal: function(n){
			return this.total(this.showing + n)
		},

		// Increment show by n
		incrementShow: function(n){
			return this.show(this.showing + n)
		},

		// Extend number of elements to n
		extendChildren: function(n){

			var deficit = n - this.children.length
			if(deficit > 0){
				while(deficit--){
					var el = this.orig.cloneNode(this.deep)
					this.parent.appendChild(el)
				}
			}

			return this
		},

		// Resets dom extension
		reset: function(){
			this.show(0)
		},

		// Expand/contract to n
		show: function(n){
			while(this.showing > n){
				this.showing--
				this.hideEl(this.children[this.showing])
				this.onContract()
			}
			while(this.showing < n){
				this.showing++
				this.showEl(this.children[this.showing - 1])
				this.onExtend()
			}
			return this
		},

	}

	function DomExtension(config){

		for(var i in config){
			this[i] = config[i]
		}

		this.children = this.parent.children
		if(this.children.length){
			this.orig = this.children[0].cloneNode(this.deep)
			this.orig.style.display = 'none'
		}
		this.showing = this.children.length

		return this
	}
	DomExtension.prototype = proto

	function noop(){}

	c.DomExtension = DomExtension

}(document, window, c)


text:
package org.arabidopsis.ahocorasick;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.arabidopsis.ahocorasick.wildcard.WildcardAhoCorasickTree;
import org.junit.Test;

import com.google.common.io.Files;

public class TestUnicode {
    @Test
    public void testUnicode() {
        AhoCorasick tree = new AhoCorasick();

        tree.add("hsro", "hsro");
        tree.add("sra", "sra");
        tree.add("马超", "马超");

        tree.prepare();

        Iterator<SearchResult> it = tree.search("马刺今年必须亚军!=1".toCharArray());
        while (it.hasNext()) {
            SearchResult sr = it.next();
            System.out.println(sr.getLastIndex());
            System.out.println(new String(sr.chars).substring(sr.getLastIndex()));

            Set<String> outputs = sr.getOutputs();

            // for(Object s : outputs)
            // System.out.println(new String((char[]) s));
        }
    }

    @Test
    public void testUnicode2() throws IOException {

        Set<String> dict = getStopWord();
        long date1 = System.currentTimeMillis();
        printMem();
        AhoCorasick tree = new AhoCorasick();
        for (String e : dict) {
            tree.add(e, e);
        }
        tree.prepare();
        printMem();

        List<String> tests = loadTest();
        long date2 = System.currentTimeMillis();

        int i = 0;
        for (int j = 0; j < 10; j++) {

            for (String t : tests) {
                Iterator<SearchResult> iter = tree.search(t.toCharArray());
                if (iter.hasNext()) {
                    i++;
                    // String tmp = iter.next().getOutputs().iterator().next();
                    // System.out.println(tmp + ":" + t);
                }
            }
        }

        long date3 = System.currentTimeMillis();
        System.out.println("ac建模用时:" + (date2 - date1));
        System.out.println("ac测试用时:" + (date3 - date2));
        System.out.println(i);
    }

    @Test
    public void testsearchOne() throws Exception {
        Set<String> dict = getStopWord();
        long date1 = System.currentTimeMillis();
        printMem();
        WildcardAhoCorasickTree tree = new WildcardAhoCorasickTree(dict);
        printMem();
        List<String> tests = loadTest();
        System.out.println(tests.size());
        long date2 = System.currentTimeMillis();

        // Thread.sleep(10000);
        int i = 0;
        for (int j = 0; j < 10; j++) {
            for (String t : tests) {
                String rs = tree.searchOne(t);
                if (rs != null)
                    i++;
                // System.out.println(t);
            }
        }

        long date3 = System.currentTimeMillis();
        System.out.println("wcac建模用时:" + (date2 - date1));

        System.out.println("wcac测试用时:" + (date3 - date2));

        System.out.println(i);

    }

    private static List<String> loadTest() throws IOException {
        return Files.readLines(new File("E:\\commentForTest.txt"), Charset.forName("utf8"));
    }

    private static Set<String> getStopWord() throws IOException {
        Set<String> ret = new HashSet<String>(Files.readLines(new File("E:\\wsgs6.txt"), Charset.forName("utf8")));
        return ret;
    }

    private static void printMem() {
        System.gc();
        Runtime rt = Runtime.getRuntime();
        System.out.println("Total Memory= " + rt.totalMemory() +
                " Free Memory = " + rt.freeMemory() + " Used Memory=" + (rt.totalMemory() - rt.freeMemory()));
    }

    public static void main(String[] args) throws Exception {
        TestUnicode t = new TestUnicode();
        t.testsearchOne();
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<toolkitInfoModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.ibm.com/xmlns/prod/streams/spl/toolkitInfo" xsi:schemaLocation="http://www.ibm.com/xmlns/prod/streams/spl/toolkitInfo toolkitInfoModel.xsd">
  <identity>
    <name>com.ibm.streamsx.topology</name>
    <description>
Toolkit providing mechanisms to build IBM Streams
applications in other programming languages, with Java, Scala and Python support.

# Java
*Java Application API* - A library that allows the definition
and execution of streaming applications implemented in Java.
Applications use Java code to process tuples and tuples are Java objects.

See the documentation under `doc/javadoc/index.html` for details.
# Scala
*Scala Support* - The Java Application API supports applications written in Scala.

See the documentation under `doc/scaladoc/index.html` for details.

# SPL
*Topic based* [com.ibm.streamsx.topology.topic::Publish|Publish] and
[com.ibm.streamsx.topology.topic::Subscribe|Subscribe] operators
provide the mechanism to exchange streams between applications
regardles of the thier implementation language.
[compilationunit:com.ibm.streamsx.topology::types.spl|SPL types] are
provided that allow interchange with applications implemented
in other languages.

# Python

*Python Application API* - A module that allows the definition
and execution of streaming applications implemented in Python.
Applications use Python code to process tuples and tuples are Python objects.

*Python functions as SPL operators* - A Python function can be simply turned into an SPL operator to allow
tuple processing using Python.

See the documentation under [namespace:com.ibm.streamsx.topology.python|com.ibm.streamsx.topology.python] for details.

    </description>
    <version>2.2.0</version>
    <requiredProductVersion>4.2</requiredProductVersion>
    </identity>
  <dependencies/>
  <resources>
    <messageSet name="TopologySplpyResource">
      <lang default="true">en_US/TopologySplpyResource.xlf</lang>
      <lang>de_DE/TopologySplpyResource.xlf</lang>
      <lang>es_ES/TopologySplpyResource.xlf</lang>
      <lang>fr_FR/TopologySplpyResource.xlf</lang>
      <lang>it_IT/TopologySplpyResource.xlf</lang>
      <lang>ja_JP/TopologySplpyResource.xlf</lang>
      <lang>ko_KR/TopologySplpyResource.xlf</lang>
      <lang>pt_BR/TopologySplpyResource.xlf</lang>
      <lang>ru_RU/TopologySplpyResource.xlf</lang>
      <lang>zh_CN/TopologySplpyResource.xlf</lang>
      <lang>zh_TW/TopologySplpyResource.xlf</lang>
    </messageSet>
  </resources>
  <sabFiles>
    <exclude path="opt/client/**"/>
    <exclude path="opt/icons/**"/>
    <exclude path="opt/python/codegen/**"/>
    <exclude path="opt/python/include/**"/>
    <exclude path="opt/python/templates/**"/>
    <exclude path="opt/python/packages/**/__pycache__/**"/>
    <exclude path="opt/python/packages/**/*.pyi"/>
    <exclude path="opt/python/packages/.mypy_cache/**"/>
  </sabFiles>
</toolkitInfoModel>


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Beih. Bot. Centralbl. , Abt. 2, 34:264. 1916

#### Original name
null

### Remarks
null


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W29606_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">GAS CAPTURE PLAN AFFIDAVIT

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">STATE OF TEXAS

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">COUNTY OF HARRIS

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Robert Eason, being duly sworn, states as follows:

    <p class="styleSans12.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">1. He is employed by Oasis Petroleum North America LLC ("Oasis") as Marketing
Manager, is over the age of 21 and has personal knowledge of the matters set forth in this affidavit.

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">2. This affidavit is submitted in conjunction with the Application for Permit to Drill for the Lydell 6192 12-27B well, with a surface location in the NW NW of Section 27, Township 161 North, Range 92 West, Burke County, North Dakota (the "Well").

    <p class="styleSans12.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">3. Oasis currently does not have a contractual arrangement with any gatherer for the gas to be produced from the Well, however, we have had initial discussions with Oneok Rockies Midstream, L.L.C. and Bison Midstream, LLC (the "Gathering Companies") to determine their level of interest. Oasis has advised the Gathering Companies of its intent to drill the Well and has advised the Gathering Companies that it currently anticipates that the Well will be completed in March 2015, with an initial gas production rate of approximately 400 mcf/day.

    <p class="styleSans20.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">@wAa
Robert H. Eason Marketing Manager

    <p class="styleSans20.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Subscribed and sworn to before me this&_' day of AM, 2014.

    <p class="styleSans30.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">\J
W Notary Public in and for the State of Texas My Commission expires: [I - 6 . 13

    <p class="styleSans49.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">ARMANDINA BARRON Notary Public. State of taxes
My Commisslon Expires June 05. 2018

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">003

    <p class="styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">


text:
package main.tree;

/*

https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/

It can be reduced to O(n) time and O(n) space;
Optimaztion 2 passes

1 pass find depth of all nodes

2nd pass finds the node with all deepest nodes

 */
public class SmallestSubtreeWithAllDeepestNodes {

    public TreeNode subtreeWithAllDeepest(TreeNode root) {
        if (root == null) return root;
        int left = maxHeight(root.left);
        int right = maxHeight(root.right);

        if (left == right) return root;

        if (left > right) return subtreeWithAllDeepest(root.left);
        return subtreeWithAllDeepest(root.right);
    }

    int maxHeight(TreeNode node) {
        if (node == null) return 0;
        int left = maxHeight(node.left);
        int right = maxHeight(node.right);
        return left > right ? left + 1 : right + 1;
    }
}


text:
/*
 * InputEventHander.h
 *
 *  Created on: 2015-4-17
 *      Author: manson
 */

#ifndef INPUTEVENTHANDER_H_
#define INPUTEVENTHANDER_H_

#include <string>

namespace matchstick {

struct input_event {
	struct timeval time;
	unsigned short type;
	unsigned short code;
	unsigned int value;
};

class InputEventHandler {
public:
	virtual ~InputEventHandler();

	static InputEventHandler * getInstance();

private:
	InputEventHandler();
	int sendEventInternal(unsigned short type, unsigned short code,
			unsigned int value);

public:
	int sendEvent(unsigned short type, unsigned short code, unsigned int value);

private:
	int fd_;
};

}

#endif /* INPUTEVENTHANDER_H_ */


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- space -->
    <dimen name="space_4dp">4dp</dimen>
    <dimen name="space_8dp">8dp</dimen>
    <dimen name="space_12dp">12dp</dimen>
    <dimen name="space_16dp">16dp</dimen>
    <dimen name="space_24dp">24dp</dimen>
    <dimen name="space_32dp">32dp</dimen>
    <dimen name="space_minus_4dp">-4dp</dimen>

    <dimen name="icon_space_4dp">4dp</dimen>
    <dimen name="icon_space_8dp">8dp</dimen>

    <dimen name="line_space_1dp">1dp</dimen>
    <dimen name="line_space_2dp">2dp</dimen>

    <!-- Text -->
    <dimen name="text_12sp">12sp</dimen>
    <dimen name="text_14sp">14sp</dimen>
    <dimen name="text_16sp">16sp</dimen>
    <dimen name="text_20sp">20sp</dimen>
    <dimen name="text_24sp">24sp</dimen>
    <dimen name="text_drawable_12dp">12dp</dimen>

    <!-- Line -->
    <dimen name="line_1dp">1dp</dimen>
    <dimen name="line_2dp">2dp</dimen>

    <!-- Border -->
    <dimen name="border_1dp">1dp</dimen>

    <!-- Elevation -->
    <dimen name="elevation_2dp">2dp</dimen>
    <dimen name="elevation_4dp">4dp</dimen>
    <dimen name="elevation_6dp">6dp</dimen>

    <!-- Radius -->
    <dimen name="radius_4dp">4dp</dimen>

    <!-- Component -->
    <dimen name="user_image">36dp</dimen>
    <dimen name="user_image_large">48dp</dimen>
    <dimen name="bottom_nav_height">56dp</dimen>

    <dimen name="tag_radius">4dp</dimen>
    <dimen name="tag_padding_horizontal">8dp</dimen>
    <dimen name="tag_padding_vertical">4dp</dimen>
    <dimen name="tag_border_width">1dp</dimen>

    <!-- Session -->
    <dimen name="session_table_header_row_height">36dp</dimen>
    <dimen name="session_table_cell_text_margin">2dp</dimen>
    <dimen name="session_table_border_width">1dp</dimen>
    <dimen name="session_table_cell_title_text_size">10sp</dimen>
    <dimen name="session_table_min_width">670dp</dimen>
    <dimen name="user_image_border">1dp</dimen>

    <dimen name="detail_header_height">200dp</dimen>

    <!-- Feedback -->
    <dimen name="feedback_ranking_size">48dp</dimen>

    <!-- Information -->
    <dimen name="info_logo_width">240dp</dimen>
    <dimen name="info_social_icon_margin">@dimen/space_16dp</dimen>
    <dimen name="info_social_icon_size">36dp</dimen>

    <!-- Contributor -->
    <dimen name="contributor_image">60dp</dimen>
    <dimen name="contributor_image_margin">@dimen/space_16dp</dimen>
    <dimen name="contributor_image_margin_bottom">@dimen/space_8dp</dimen>
    <dimen name="contributor_cell_margin_bottom">@dimen/space_16dp</dimen>

    <!-- Sponsor -->
    <dimen name="sponsor_image_height">80dp</dimen>
    <dimen name="sponsor_image_margin">@dimen/space_8dp</dimen>
    <dimen name="sponsor_image_border">2dp</dimen>
</resources>


text:
namespace base {
namespace trace_event {
class TracedValue;
}  // namespace trace_event
}  // namespace base

namespace cc {

struct CC_EXPORT ScrollNode {
  ScrollNode();
  ScrollNode(const ScrollNode& other);

  // The node index of this node in the scroll tree node vector.
  int id;
  // The node index of the parent node in the scroll tree node vector.
  int parent_id;

  // The layer id that corresponds to the layer contents that are scrolled.
  // Unlike |id|, this id is stable across frames that don't change the
  // composited layer list.
  int owning_layer_id;

  // This is used for subtrees that should not be scrolled independently. For
  // example, when there is a layer that is not scrollable itself but is inside
  // a scrolling layer.
  bool scrollable;

  uint32_t main_thread_scrolling_reasons;
  bool contains_non_fast_scrollable_region;

  // Size of the clipped area, not including non-overlay scrollbars. Overlay
  // scrollbars do not affect the clipped area.
  gfx::Size scroll_clip_layer_bounds;

  // Bounds of the overflow scrolling area.
  gfx::Size bounds;

  bool max_scroll_offset_affected_by_page_scale;
  bool is_inner_viewport_scroll_layer;
  bool is_outer_viewport_scroll_layer;

  // This offset is used when |scrollable| is false and there isn't a transform
  // node already present that covers this offset.
  gfx::Vector2dF offset_to_transform_parent;

  bool should_flatten;
  bool user_scrollable_horizontal;
  bool user_scrollable_vertical;
  ElementId element_id;
  int transform_id;

  bool operator==(const ScrollNode& other) const;
  void AsValueInto(base::trace_event::TracedValue* value) const;
};

}  // namespace cc

#endif  // CC_TREES_SCROLL_NODE_H_


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

#ifndef __EMBREE_BRUSHED_METAL_H__
#define __EMBREE_BRUSHED_METAL_H__

#include "../materials/material.h"
#include "../brdfs/conductor.h"
#include "../brdfs/microfacet.h"

namespace embree
{
  /*! Implements a brushed metal material. The metal is modelled by a
   *  microfacet BRDF with a fresnel term for metals and a power
   *  cosine distribution for different roughness of the material. */
  class BrushedMetal : public Material
  {
    typedef Microfacet<FresnelConductor,AnisotropicPowerCosineDistribution > MicrofacetMetal1;
    typedef Microfacet<FresnelConductor,AnisotropicBeckmannDistribution > MicrofacetMetal2;

  public:

    /*! Construction from parameters. */
    BrushedMetal (const Parms& parms) {
      reflectance  = parms.getColor("reflectance",one);
      eta          = parms.getColor("eta",Color(1.4f));
      k            = parms.getColor("k",Color(0.0f));
      roughnessX   = parms.getFloat("roughnessX",0.01f);
      roughnessY   = parms.getFloat("roughnessY",0.01f);
      rcpRoughnessX = rcp(roughnessX);
      rcpRoughnessY = rcp(roughnessY);
    }

    void shade(const Ray& ray, const Medium& currentMedium, const DifferentialGeometry& dg, CompositedBRDF& brdfs) const
    {
      /*! handle the special case of a specular metal through a special BRDF */
      if (unlikely(roughnessX == 0.0f || roughnessY == 0.0f)) {
        brdfs.add(NEW_BRDF(Conductor)(reflectance, eta, k));
        return;
      }

      brdfs.add(NEW_BRDF(MicrofacetMetal1)(reflectance, FresnelConductor(eta,k), AnisotropicPowerCosineDistribution(dg.Tx,rcpRoughnessX,dg.Ty,rcpRoughnessY,dg.Ns)));
      //brdfs.add(NEW_BRDF(MicrofacetMetal2)(reflectance, FresnelConductor(eta,k), AnisotropicBeckmannDistribution(dx,roughnessX,dy,inf,dz)));
    }

  private:
    Color reflectance;   //!< Reflectivity of the metal
    Color eta;           //!< Real part of refraction index
    Color k;             //!< Imaginary part of refraction index
    float roughnessX;    //!< Roughness parameter in X direction. The range goes from 0 (specular) to 1 (diffuse).
    float roughnessY;    //!< Roughness parameter in Y direction. The range goes from 0 (specular) to 1 (diffuse).
    float rcpRoughnessX; //!< Reciprocal roughness parameter in X direction.
    float rcpRoughnessY; //!< Reciprocal roughness parameter in Y direction.
  };
}

#endif


text:
import * as React from 'react'
import onClickOutside from 'react-onclickoutside'

interface Props {
    closePanel: () => void
}

class ExtraButtonsPanel extends React.PureComponent<Props> {
    handleClickOutside() {
        this.props.closePanel()
    }

    render() {
        return <div>{this.props.children}</div>
    }
}

export default onClickOutside(ExtraButtonsPanel)


text:
namespace lly {

	class VertexDescription
	{
		struct Description
		{
			VertexAttribPosition position;
			unsigned int size;
			DataType type;
			bool normalized;
			int stride;
			int offset;
		};

	public:
		VertexDescription(DrawType mode, int size) : _mode(mode), _size(size) {}
		virtual ~VertexDescription() {}

		virtual void bind() const;

		DrawType get_draw_type() const { return _mode; }
		int get_size() const { return _size; }

		void add(VertexAttribPosition position, unsigned int size, DataType type, bool normalized, int stride, int offset);

	private:
		DrawType _mode;
		int _size;

		std::vector<Description> _descriptions;
	};
}

#endif //VERTEXDESCRIPTION_H_


text:
#if !GOOGLE_CUDA
#error This file must only be included when building with Cuda support
#endif

#ifndef TENSORFLOW_CORE_KERNELS_MAXPOOLING_OP_GPU_H_
#define TENSORFLOW_CORE_KERNELS_MAXPOOLING_OP_GPU_H_

#define EIGEN_USE_GPU

#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/tensor_format.h"

namespace tensorflow {

namespace functor {
// Run the forward pass of max pooling, optionally writing the argmax indices to
// the mask array, if it is not nullptr. If mask is passed in as nullptr, the
// argmax indices are not written.
template <typename T>
struct MaxPoolForwardWithOptionalArgmax {
  bool operator()(const T* bottom_data, const int batch, const int height,
                  const int width, const int channels, const int pooled_height,
                  const int pooled_width, const int kernel_h,
                  const int kernel_w, const int stride_h, const int stride_w,
                  const int pad_t, const int pad_l, T* top_data, int64* mask,
                  const Eigen::GpuDevice& d);
};

template <typename T>
struct MaxPoolBackwardWithArgmax {
  bool operator()(const int output_size, const int input_size,
                  const T* top_diff, const int64* mask, const int top_offset,
                  const int bottom_offset, T* bottom_diff,
                  const Eigen::GpuDevice& d);
};

template <typename T>
struct MaxPoolBackwardNoMask {
  bool operator()(const T* bottom_data, const int batch, const int height,
                  const int width, const int channels, const int pooled_height,
                  const int pooled_width, const int kernel_h,
                  const int kernel_w, const int stride_h, const int stride_w,
                  const int pad_t, const int pad_l, const T* top_diff,
                  T* bottom_diff, const Eigen::GpuDevice& d);
};

template <typename T>
struct MaxPoolGradBackwardWithArgmax {
  bool operator()(const int output_size, const int input_size,
                  const T* top_diff, const int64* mask, const int top_offset,
                  const int bottom_offset, T* bottom_diff,
                  const Eigen::GpuDevice& d);
};

template <typename T>
struct MaxPoolGradBackwardNoMask {
  bool operator()(TensorFormat data_format, const T* bottom_data,
                  const T* output_data, const int batch,
                  const int pooled_height, const int pooled_width,
                  const int channels, const int height, const int width,
                  const int kernel_h, const int kernel_w, const int stride_h,
                  const int stride_w, const int pad_t, const int pad_l,
                  const T* top_diff, T* bottom_diff, const Eigen::GpuDevice& d);
};

}  // namespace functor

}  // namespace tensorflow

#endif  // TENSORFLOW_CORE_KERNELS_MAXPOOLING_OP_GPU_H_


text:
package net.sf.relish;

import static net.sf.relish.matcher.RelishMatchers.*;
import static org.hamcrest.CoreMatchers.*;

import java.util.Collection;

import org.hamcrest.Matcher;

/**
 * Each enumerated value is a different algorithm used to match tables in the DSL.
 */
public enum TableMatcher {

	/**
	 * All the rows in the actual table must exist in the expected table and vice-versa and they must be in the same order.
	 */
	EQUAL,

	/**
	 * All the rows in the actual table must exist in the expected table and vice-versa but their order does not have to match.
	 */
	BE,

	/**
	 * All the entries in the expected table must be in the actual table but there may be entries in the actual table that are not in the expected table.
	 */
	INCLUDE;

	public <T> Matcher<Collection<T>> newMatcher(Collection<T> expected) {

		if (expected == null) {
			return equalTo(expected);
		}

		switch (this) {
		case EQUAL:
			return equalTo(expected);
		case BE:
			return containsExactly(expected);
		case INCLUDE:
			return contains(expected);
		default:
			throw new RelishException("Unknown enum value %s. THIS IS A BUG!!", this);
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright © 2016 ESUP-Portail (https://www.esup-portail.org/)

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

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

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

-->
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd"
         updateCheck="true" monitoring="autodetect" dynamicConfig="true">

  <diskStore path="java.io.tmpdir" />

  <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" overflowToOffHeap="false" diskPersistent="false"/>

  <cache name="flashinfos"
         eternal="false"
         maxEntriesLocalHeap="1000"
         diskPersistent="false"
         timeToIdleSeconds="3600"
         timeToLiveSeconds="14400"
         memoryStoreEvictionPolicy="LFU">
  </cache>
</ehcache>


text:
'use strict';

/**
* Group values according to an indicator function and return group counts.
*
* @module @stdlib/utils/async/count-by
*
* @example
* var readFile = require( '@stdlib/fs/read-file' );
* var countByAsync = require( '@stdlib/utils/async/count-by' );
*
* var files = [
*     './beep.js',
*     './boop.js'
* ];
*
* function done( error, result ) {
*     if ( error ) {
*         throw error;
*     }
*     console.log( result );
* }
*
* function indicator( file, next ) {
*     var opts = {
*         'encoding': 'utf8'
*     };
*     readFile( file, opts, onFile );
*
*     function onFile( error ) {
*         if ( error ) {
*             return next( null, 'nonreadable' );
*         }
*         next( null, 'readable' );
*     }
* }
*
* countByAsync( files, indicator, done );
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var main = require( './main.js' );
var factory = require( './factory.js' );

// MAIN //

setReadOnly( main, 'factory', factory );

// EXPORTS //

module.exports = main;


text:
package com.lambdaworks.redis.protocol;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author Mark Paluch
 */
class EmptyFuture implements ChannelFuture {

    @Override
    public Channel channel() {
        return null;
    }

    @Override
    public ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener) {
        return null;
    }

    @Override
    public ChannelFuture addListeners(GenericFutureListener<? extends Future<? super Void>>... listeners) {
        return null;
    }

    @Override
    public ChannelFuture removeListener(GenericFutureListener<? extends Future<? super Void>> listener) {
        return null;
    }

    @Override
    public ChannelFuture removeListeners(GenericFutureListener<? extends Future<? super Void>>... listeners) {
        return null;
    }

    @Override
    public ChannelFuture sync() throws InterruptedException {
        return null;
    }

    @Override
    public ChannelFuture syncUninterruptibly() {
        return null;
    }

    @Override
    public ChannelFuture await() throws InterruptedException {
        return null;
    }

    @Override
    public ChannelFuture awaitUninterruptibly() {
        return null;
    }

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

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

    @Override
    public Throwable cause() {
        return null;
    }

    @Override
    public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public boolean await(long timeoutMillis) throws InterruptedException {
        return false;
    }

    @Override
    public boolean awaitUninterruptibly(long timeout, TimeUnit unit) {
        return false;
    }

    @Override
    public boolean awaitUninterruptibly(long timeoutMillis) {
        return false;
    }

    @Override
    public Void getNow() {
        return null;
    }

    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        return false;
    }

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

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

    @Override
    public Void get() throws InterruptedException, ExecutionException {
        return null;
    }

    @Override
    public Void get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        return null;
    }
}


text:
using NUnit.Framework;
using Photon.LoadBalancing.UnifiedClient.AuthenticationSchemes;
using Photon.LoadBalancing.UnitTests.TestsImpl;
using Photon.LoadBalancing.UnitTests.UnifiedServer.Policy;

namespace Photon.LoadBalancing.UnitTests.Offline
{
    [TestFixture]
    public class AsyncJoinOfflineTests : LBAsyncJoinTestImpl
    {
        public AsyncJoinOfflineTests()
            : base(new OfflineConnectPolicy(new TokenAuthenticationScheme(), "AsyncJoinConfig.config"))
        {
        }
    }
}


text:
<?php

namespace SecucardConnect\Product\Payment\Model;

/**
 * Class TransferAccount
 * @package SecucardConnect\Product\Payment\Model
 */
class TransferAccount
{
    /**
     * @var string
     */
    public $account_owner;

    /**
     * @var string
     */
    public $accountnumber;

    /**
     * @var string
     */
    public $iban;

    /**
     * @var string
     */
    public $bic;

    /**
     * @var string
     */
    public $bankcode;

}


text:
Listado de usuarios

                    <a href="<?php echo site_url('user/add'); ?>" class="btn btn-success btn-sm">

    						Id User
                            Nombre
                            Apellidos
                            Email
                            Usuario
                            Perfil
                            Acciones

                        <?php foreach($users as $u): ?>

    						<?php echo $u['id_user']; ?>
                            <?php echo $u['name']; ?>
                            <?php echo $u['lastname']; ?>
    						<?php echo $u['email']; ?>
                            <?php echo $u['username']; ?>

                                <?php
                                    $profile = $this->Profile_model->get_profile($u['profile_id']);
                                    echo $profile['name'];
                                ?>

                                <a href="<?php echo site_url('user/edit/'.$u['id_user']); ?>" class="btn btn-info btn-xs">
                                     Editar

                                <a href="<?php echo site_url('user/remove/'.$u['id_user']); ?>" class="btn btn-danger btn-xs">
                                     Eliminar

                        <?php endforeach; ?>

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.4.1/css/buttons.bootstrap.min.css">


text:
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item
    android:state_enabled="false"
    android:drawable="@drawable/title_bar_button_background_disabled"
  />
  <item
    android:state_pressed="true"
    android:drawable="@drawable/title_bar_button_background_pressed"
  />
  <item
    android:state_focused="true"
    android:drawable="@drawable/title_bar_button_background_selected"
  />
  <item android:drawable="@android:color/transparent"/>
</selector>