text:
from __future__ import division

import sys
import warnings
from time import sleep, time
from threading import Event
from inspect import getfullargspec

from .btcomm import BluetoothServer
from .threads import WrapThread
from .constants import PROTOCOL_VERSION, CHECK_PROTOCOL_TIMEOUT
from .interactions import BlueDotInteraction, BlueDotPosition, BlueDotRotation, BlueDotSwipe
from .colors import parse_color, BLUE
from .exceptions import ButtonDoesNotExist

class Dot:
    """
    The internal base class for the implementation of a "button" or "buttons".
    """
    def __init__(self, color, square, border, visible):
        self._color = color
        self._square = square
        self._border = border
        self._visible = visible

        self._is_pressed_event = Event()
        self._is_released_event = Event()
        self._is_moved_event = Event()
        self._is_swiped_event = Event()
        self._is_double_pressed_event = Event()

        self._when_pressed = None
        self._when_pressed_background = False
        self._when_double_pressed = None
        self._when_double_pressed_background = False
        self._when_released = None
        self._when_released_background = False
        self._when_moved = None
        self._when_moved_background = False
        self._when_swiped = None
        self._when_swiped_background = False
        self._when_rotated = None
        self._when_rotated_background = False

        self._is_pressed = False
        self._position = None
        self._double_press_time = 0.3
        self._rotation_segments = 8

    @property
    def is_pressed(self):
        """
        Returns ``True`` if the button is pressed (or held).
        """
        return self._is_pressed

    @property
    def value(self):
        """
        Returns a 1 if ``.is_pressed``, 0 if not.
        """
        return 1 if self.is_pressed else 0

    @property
    def values(self):
        """
        Returns an infinite generator constantly yielding the current value.
        """
        while True:
            yield self.value

    @property
    def position(self):
        """
        Returns an instance of :class:`BlueDotPosition` representing the
        current or last position the button was pressed, held or
        released.

        .. note::

            If the button is released (and inactive), :attr:`position` will
            return the position where it was released, until it is pressed
            again. If the button has never been pressed :attr:`position` will
            return ``None``.
        """
        return self._position

    @property
    def when_pressed(self):
        """
        Sets or returns the function which is called when the button is pressed.

        The function should accept 0 or 1 parameters, if the function accepts 1 parameter an
        instance of :class:`BlueDotPosition` will be returned representing where the button was pressed.

        The following example will print a message to the screen when the button is pressed::

            from bluedot import BlueDot

            def dot_was_pressed():
                print("The button was pressed")

            bd = BlueDot()
            bd.when_pressed = dot_was_pressed

        This example shows how the position of where the button was pressed can be obtained::

            from bluedot import BlueDot

            def dot_was_pressed(pos):
                print("The button was pressed at pos x={} y={}".format(pos.x, pos.y))

            bd = BlueDot()
            bd.when_pressed = dot_was_pressed

        The function will be run in the same thread and block, to run in a separate
        thread use `set_when_pressed(function, background=True)`
        """
        return self._when_pressed

    @when_pressed.setter
    def when_pressed(self, value):
        self.set_when_pressed(value)

    def set_when_pressed(self, callback, background=False):
        """
        Sets the function which is called when the button is pressed.

        :param Callable callback:
            The function to call, setting to `None` will stop the callback.

        :param bool background:
            If set to `True` the function will be run in a separate thread
            and it will return immediately. The default is `False`.
        """
        self._when_pressed = callback
        self._when_pressed_background = background

    @property
    def when_double_pressed(self):
        """
        Sets or returns the function which is called when the button is double pressed.

        The function should accept 0 or 1 parameters, if the function accepts 1 parameter an
        instance of :class:`BlueDotPosition` will be returned representing where the button was
        pressed the second time.

        The function will be run in the same thread and block, to run in a separate
        thread use `set_when_double_pressed(function, background=True)`

        .. note::
            The double press event is fired before the 2nd press event e.g. events would be
            appear in the order, pressed, released, double pressed, pressed.
        """
        return self._when_double_pressed

    @when_double_pressed.setter
    def when_double_pressed(self, value):
        self.set_when_double_pressed(value)

    def set_when_double_pressed(self, callback, background=False):
        """
        Sets the function which is called when the button is double pressed.

        :param Callable callback:
            The function to call, setting to `None` will stop the callback.

        :param bool background:
            If set to `True` the function will be run in a separate thread
            and it will return immediately. The default is `False`.
        """
        self._when_double_pressed = callback
        self._when_double_pressed_background = background

    @property
    def double_press_time(self):
        """
        Sets or returns the time threshold in seconds for a double press. Defaults to 0.3.
        """
        return self._double_press_time

    @double_press_time.setter
    def double_press_time(self, value):
        self._double_press_time = value

    @property
    def when_released(self):
        """
        Sets or returns the function which is called when the button is released.

        The function should accept 0 or 1 parameters, if the function accepts 1 parameter an
        instance of :class:`BlueDotPosition` will be returned representing where the button was held
        when it was released.

        The function will be run in the same thread and block, to run in a separate
        thread use `set_when_released(function, background=True)`
        """
        return self._when_released

    @when_released.setter
    def when_released(self, value):
        self.set_when_released(value)

    def set_when_released(self, callback, background=False):
        """
        Sets the function which is called when the button is released.

        :param Callable callback:
            The function to call, setting to `None` will stop the callback.

        :param bool background:
            If set to `True` the function will be run in a separate thread
            and it will return immediately. The default is `False`.
        """
        self._when_released = callback
        self._when_released_background = background

    @property
    def when_moved(self):
        """
        Sets or returns the function which is called when the position the button is pressed is moved.

        The function should accept 0 or 1 parameters, if the function accepts 1 parameter an
        instance of :class:`BlueDotPosition` will be returned representing the new position of where the
        Blue Dot is held.

        The function will be run in the same thread and block, to run in a separate
        thread use `set_when_moved(function, background=True)`
        """
        return self._when_moved

    @when_moved.setter
    def when_moved(self, value):
        self.set_when_moved(value)

    def set_when_moved(self, callback, background=False):
        """
        Sets the function which is called when the position the button is pressed is moved.

        :param Callable callback:
            The function to call, setting to `None` will stop the callback.

        :param bool background:
            If set to `True` the function will be run in a separate thread
            and it will return immediately. The default is `False`.
        """
        self._when_moved = callback
        self._when_moved_background = background

    @property
    def when_swiped(self):
        """
        Sets or returns the function which is called when the button is swiped.

        The function should accept 0 or 1 parameters, if the function accepts 1 parameter an
        instance of :class:`BlueDotSwipe` will be returned representing the how the button was
        swiped.

        The function will be run in the same thread and block, to run in a separate
        thread use `set_when_swiped(function, background=True)`
        """
        return self._when_swiped

    @when_swiped.setter
    def when_swiped(self, value):
        self.set_when_swiped(value)

    def set_when_swiped(self, callback, background=False):
        """
        Sets the function which is called when the position the button is swiped.

        :param Callable callback:
            The function to call, setting to `None` will stop the callback.

        :param bool background:
            If set to `True` the function will be run in a separate thread
            and it will return immediately. The default is `False`.
        """
        self._when_swiped = callback
        self._when_swiped_background = background

    @property
    def rotation_segments(self):
        """
        Sets or returns the number of virtual segments the button is split into for rotating.
        Defaults to 8.
        """
        return self._rotation_segments

    @rotation_segments.setter
    def rotation_segments(self, value):
        self._rotation_segments = value

    @property
    def when_rotated(self):
        """
        Sets or returns the function which is called when the button is rotated (like an
        iPod clock wheel).

        The function should accept 0 or 1 parameters, if the function accepts 1 parameter an
        instance of :class:`BlueDotRotation` will be returned representing how the button was
        rotated.

        The function will be run in the same thread and block, to run in a separate
        thread use `set_when_rotated(function, background=True)`
        """
        return self._when_rotated

    @when_rotated.setter
    def when_rotated(self, value):
        self.set_when_rotated(value)

    def set_when_rotated(self, callback, background=False):
        """
        Sets the function which is called when the position the button is rotated (like an
        iPod clock wheel).

        :param Callable callback:
            The function to call, setting to `None` will stop the callback.

        :param bool background:
            If set to `True` the function will be run in a separate thread
            and it will return immediately. The default is `False`.
        """
        self._when_rotated = callback
        self._when_rotated_background = background

    @property
    def color(self):
        """
        Sets or returns the color of the dot. Defaults to BLUE.

        An instance of :class:`.colors.Color` is returned.

        Value can be set as a :class:`.colors.Color` object, a hex color value
        in the format `#rrggbb` or `#rrggbbaa`, a tuple of `(red, green, blue)`
        or `(red, green, blue, alpha)` values between `0` & `255` or a text
        description of the color, e.g. "red".

        A dictionary of available colors can be obtained from `bluedot.COLORS`.
        """
        return self._color

    @color.setter
    def color(self, value):
        self._color = parse_color(value)

    @property
    def square(self):
        """
        When set to `True` the 'dot' is made square. Default is `False`.
        """
        return self._square

    @square.setter
    def square(self, value):
        self._square = value

    @property
    def border(self):
        """
        When set to `True` adds a border to the dot. Default is `False`.
        """
        return self._border

    @border.setter
    def border(self, value):
        self._border = value

    @property
    def visible(self):
        """
        When set to `False` the dot will be hidden. Default is `True`.

        .. note::

            Events (press, release, moved) are still sent from the dot
            when it is not visible.
        """
        return self._visible

    @visible.setter
    def visible(self, value):
        self._visible = value

    def wait_for_press(self, timeout = None):
        """
        Waits until a Blue Dot is pressed.
        Returns ``True`` if the button was pressed.

        :param float timeout:
            Number of seconds to wait for a Blue Dot to be pressed, if ``None``
            (the default), it will wait indefinetly.
        """
        return self._is_pressed_event.wait(timeout)

    def wait_for_double_press(self, timeout = None):
        """
        Waits until a Blue Dot is double pressed.
        Returns ``True`` if the button was double pressed.

        :param float timeout:
            Number of seconds to wait for a Blue Dot to be double pressed, if ``None``
            (the default), it will wait indefinetly.
        """
        return self._is_double_pressed_event.wait(timeout)

    def wait_for_release(self, timeout = None):
        """
        Waits until a Blue Dot is released.
        Returns ``True`` if the button was released.

        :param float timeout:
            Number of seconds to wait for a Blue Dot to be released, if ``None``
            (the default), it will wait indefinetly.
        """
        return self._is_released_event.wait(timeout)

    def wait_for_move(self, timeout = None):
        """
        Waits until the position where the button is pressed is moved.
        Returns ``True`` if the position pressed on the button was moved.

        :param float timeout:
            Number of seconds to wait for the position that the button
            is pressed to move, if ``None`` (the default), it will wait indefinetly.
        """
        return self._is_moved_event.wait(timeout)

    def wait_for_swipe(self, timeout = None):
        """
        Waits until the button is swiped.
        Returns ``True`` if the button was swiped.

        :param float timeout:
            Number of seconds to wait for the button to be swiped, if ``None``
            (the default), it will wait indefinetly.
        """
        return self._is_swiped_event.wait(timeout)

    def press(self, position):
        """
        Processes any "pressed" events associated with this dot.

        :param BlueDotPosition position:
            The BlueDotPosition where the dot was pressed.
        """
        self._position = position
        self._is_pressed = True
        self._is_pressed_event.set()
        self._is_pressed_event.clear()

        self._process_callback(self.when_pressed, position, self._when_pressed_background)

    def release(self, position):
        """
        Processes any "released" events associated with this dot.

        :param BlueDotPosition position:
            The BlueDotPosition where the Dot was pressed.
        """
        self._position = position
        self._is_pressed = False
        self._is_released_event.set()
        self._is_released_event.clear()

        self._process_callback(self.when_released, position, self._when_released_background)

    def move(self, position):
        """
        Processes any "released" events associated with this dot.

        :param BlueDotPosition position:
            The BlueDotPosition where the Dot was pressed.
        """
        self._is_moved_event.set()
        self._is_moved_event.clear()

        self._process_callback(self.when_moved, position, self._when_moved_background)

    def double_press(self, position):
        """
        Processes any "double press" events associated with this dot.

        :param BlueDotPosition position:
            The BlueDotPosition where the Dot was pressed.
        """
        self._is_double_pressed_event.set()
        self._is_double_pressed_event.clear()

        self._process_callback(self.when_double_pressed, position, self._when_double_pressed_background)

    def swipe(self, swipe):
        """
        Processes any "swipe" events associated with this dot.

        :param BlueDotSwipe swipe:
            The BlueDotSwipe representing how the dot was swiped.
        """
        self._is_swiped_event.set()
        self._is_swiped_event.clear()

        self._process_callback(self.when_swiped, swipe, self._when_swiped_background)

    def rotate(self, rotation):
        """
        Processes any "rotation" events associated with this dot.

        :param BlueDotRotation rotation:
            The BlueDotRotation representing how the dot was rotated.
        """
        # print("rotating - when_rotated {}")
        self._process_callback(self.when_rotated, rotation, self._when_rotated_background)

    def _process_callback(self, callback, arg, background):
        if callback:
            args_expected = getfullargspec(callback).args
            no_args_expected = len(args_expected)
            if len(args_expected) > 0:
                # if someone names the first arg of a class function to something
                # other than self, this will fail! or if they name the first argument
                # of a non class function to self this will fail!
                if args_expected[0] == "self":
                    no_args_expected -= 1

            if no_args_expected == 0:
                call_back_t = WrapThread(target=callback)
            else:
                call_back_t = WrapThread(target=callback, args=(arg, ))
            call_back_t.start()

            # if this callback is not running in the background wait for it
            if not background:
                call_back_t.join()

class BlueDotButton(Dot):
    """
    Represents a single button on the button client applications. It keeps
    tracks of when and where the button has been pressed and processes any
    events.

    This class is intended for use via :class:`BlueDot` and should not be
    instantiated "manually".

    A button can be interacted with individually via :class:`BlueDot` by
    stating its position in the grid e.g. ::

        from bluedot import BlueDot
        bd = BlueDot()

        first_button = bd[0,0].wait_for_press

        first_button.wait_for_press()
        print("The first button was pressed")

    :param BlueDot bd:
        The BlueDot object this button belongs too.

    :param int col:
        The column position for this button in the grid.

    :param int col:
        The row position for this button in the grid.

    :param string color
        The color of the button.

        Can be set as a :class:`.colors.Color` object, a hex color value
        in the format `#rrggbb` or `#rrggbbaa`, a tuple of `(red, green, blue)`
        or `(red, green, blue, alpha)` values between `0` & `255` or a text
        description of the color, e.g. "red".

        A dictionary of available colors can be obtained from `bluedot.COLORS`.

    :param bool square:
        When set to `True` the button is made square.

    :param bool border:
        When set to `True` adds a border to the button.

    :param bool visible:
        When set to `False` the button will be hidden.
    """
    def __init__(self, bd, col, row, color, square, border, visible):
        self._bd = bd
        self.col = col
        self.row = row

        self._interaction = None

        # setup the "dot"
        super().__init__(color, square, border, visible)

    @property
    def color(self):
        return super(BlueDotButton, self.__class__).color.fget(self)

    @color.setter
    def color(self, value):
        super(BlueDotButton, self.__class__).color.fset(self, value)
        self._send_config()

    @property
    def square(self):
        return super(BlueDotButton, self.__class__).square.fget(self)

    @square.setter
    def square(self, value):
        super(BlueDotButton, self.__class__).square.fset(self, value)
        self._send_config()

    @property
    def border(self):
        return super(BlueDotButton, self.__class__).border.fget(self)

    @border.setter
    def border(self, value):
        super(BlueDotButton, self.__class__).border.fset(self, value)
        self._send_config()

    @property
    def visible(self):
        return super(BlueDotButton, self.__class__).visible.fget(self)

    @visible.setter
    def visible(self, value):
        super(BlueDotButton, self.__class__).visible.fset(self, value)
        self._send_config()

    @property
    def modified(self):
        """
        Returns `True` if the button's appearance has been modified [is
        different] from the default.
        """
        return not (
            self.color == self._bd.color and
            self.visible == self._bd.visible and
            self.border == self._bd.border and
            self.square == self._bd.square
            )

    @property
    def interaction(self):
        """
        Returns an instance of :class:`BlueDotInteraction` representing the
        current or last interaction with the button.

        .. note::

            If the button is released (and inactive), :attr:`interaction`
            will return the interaction when it was released, until it is
            pressed again.  If the button has never been pressed
            :attr:`interaction` will return ``None``.
        """
        return self._interaction

    def press(self, position):
        """
        Processes any "pressed" events associated with this button.

        :param BlueDotPosition position:
            The BlueDotPosition where the dot was pressed.
        """
        super().press(position)

        # create new interaction
        self._interaction = BlueDotInteraction(position)

    def release(self, position):
        """
        Processes any "released" events associated with this button.

        :param BlueDotPosition position:
            The BlueDotPosition where the Dot was pressed.
        """
        super().release(position)

        self._interaction.released(position)

    def move(self, position):
        """
        Processes any "released" events associated with this button.

        :param BlueDotPosition position:
            The BlueDotPosition where the Dot was pressed.
        """
        super().move(position)

        self._interaction.moved(position)

    def is_double_press(self, position):
        """
        Returns True if the position passed represents a double press.

        i.e. The last interaction was the button was to release it, and
        the time to press is less than the double_press_time.

        :param BlueDotPosition position:
            The BlueDotPosition where the Dot was pressed.
        """
        double_press = False
        #was there a previous interaction
        if self._interaction:
            # was the previous interaction complete (i.e. had it been released)
            if not self._interaction.active:
                # was it less than the time threshold (0.3 seconds)
                if self._interaction.duration < self._double_press_time:
                    #was the dot pressed again in less than the threshold
                    if time() - self._interaction.released_position.time < self._double_press_time:
                        double_press = True

        return double_press

    def get_swipe(self):
        """
        Returns an instance of :class:`BlueDotSwipe` if the last interaction
        with the button was a swipe. Returns `None` if the button was not
        swiped.
        """
        swipe = BlueDotSwipe(self.interaction)
        if swipe.valid:
            return swipe

    def get_rotation(self):
        """
        Returns an instance of :class:`BlueDotRotation` if the last interaction
        with the button was a rotation. Returns `None` if the button was not
        rotated.
        """
        # only bother checking to see if its a rotation if `when_rotated`
        # as been set. Performance thang!
        if self.when_rotated or self._bd.when_rotated:
            rotation = BlueDotRotation(self._interaction, self._rotation_segments)
            if rotation.valid:
                return rotation

    def _build_config_msg(self):
        return "5,{},{},{},{},{},{}\n".format(
                    self.color,
                    int(self.square),
                    int(self.border),
                    int(self.visible),
                    self.col,
                    self.row
                    )

    def _send_config(self):
        if self._bd.is_connected:
            self._bd._server.send(self._build_config_msg())

class BlueDot(Dot):
    """
    Interacts with a Blue Dot client application, communicating when and where a
    button has been pressed, released or held.

    This class starts an instance of :class:`.btcomm.BluetoothServer`
    which manages the connection with the Blue Dot client.

    This class is intended for use with a Blue Dot client application.

    The following example will print a message when the Blue Dot button is pressed::

        from bluedot import BlueDot
        bd = BlueDot()
        bd.wait_for_press()
        print("The button was pressed")

    Multiple buttons can be created, by changing the number of columns and rows. Each button can be referenced using its [col, row]::

        bd = BlueDot(cols=2, rows=2)
        bd[0,0].wait_for_press()
        print("Top left button pressed")
        bd[1,1].wait_for_press()
        print("Bottom right button pressed")

    :param str device:
        The Bluetooth device the server should use, the default is "hci0", if
        your device only has 1 Bluetooth adapter this shouldn't need to be changed.

    :param int port:
        The Bluetooth port the server should use, the default is 1, and under
        normal use this should never need to change.

    :param bool auto_start_server:
        If ``True`` (the default), the Bluetooth server will be automatically
        started on initialisation; if ``False``, the method :meth:`start` will
        need to be called before connections will be accepted.

    :param bool power_up_device:
        If ``True``, the Bluetooth device will be powered up (if required) when the
        server starts. The default is ``False``.

        Depending on how Bluetooth has been powered down, you may need to use :command:`rfkill`
        to unblock Bluetooth to give permission to bluez to power on Bluetooth::

            sudo rfkill unblock bluetooth

    :param bool print_messages:
        If ``True`` (the default), server status messages will be printed stating
        when the server has started and when clients connect / disconnect.

    :param int cols:
        The number of columns in the grid of buttons. Defaults to ``1``.

    :param int rows:
        The number of rows in the grid of buttons. Defaults to ``1``.

    """
    def __init__(self,
        device = "hci0",
        port = 1,
        auto_start_server = True,
        power_up_device = False,
        print_messages = True,
        cols = 1,
        rows = 1):

        self._data_buffer = ""
        self._device = device
        self._port = port
        self._power_up_device = power_up_device
        self._print_messages = print_messages

        self._check_protocol_event = Event()
        self._is_connected_event = Event()
        self._when_client_connects = None
        self._when_client_connects_background = False
        self._when_client_disconnects = None
        self._when_client_disconnects_background = False

        # setup the main "dot"
        super().__init__(BLUE, False, False, True)

        # setup the grid
        self._buttons = {}
        self.resize(cols, rows)

        self._create_server()

        if auto_start_server:
            self.start()

    @property
    def buttons(self):
        """
        A list of :class:`BlueDotButton` objects in the "grid".
        """
        return self._buttons.values()

    @property
    def cols(self):
        """
        Sets or returns the number of columns in the grid of buttons.
        """
        return self._cols

    @cols.setter
    def cols(self, value):
        self.resize(value, self._rows)

    @property
    def rows(self):
        """
        Sets or returns the number of rows in the grid of buttons.
        """
        return self._rows

    @rows.setter
    def rows(self, value):
        self.resize(self._cols, value)

    @property
    def device(self):
        """
        The Bluetooth device the server is using. This defaults to "hci0".
        """
        return self._device

    @property
    def port(self):
        """
        The port the server is using. This defaults to 1.
        """
        return self._port

    @property
    def server(self):
        """
        The :class:`.btcomm.BluetoothServer` instance that is being used to communicate
        with clients.
        """
        return self._server

    @property
    def adapter(self):
        """
        The :class:`.btcomm.BluetoothAdapter` instance that is being used.
        """
        return self._server.adapter

    @property
    def paired_devices(self):
        """
        Returns a sequence of devices paired with this adapter
        :code:`[(mac_address, name), (mac_address, name), ...]`::

            bd = BlueDot()
            devices = bd.paired_devices
            for d in devices:
                device_address = d[0]
                device_name = d[1]
        """
        return self._server.adapter.paired_devices

    @property
    def print_messages(self):
        """
        When set to ``True`` messages relating to the status of the Bluetooth server
        will be printed.
        """
        return self._print_messages

    @print_messages.setter
    def print_messages(self, value):
        self._print_messages = value

    @property
    def running(self):
        """
        Returns a ``True`` if the server is running.
        """
        return self._server.running

    @property
    def is_connected(self):
        """
        Returns ``True`` if a Blue Dot client is connected.
        """
        return self._is_connected_event.is_set()

    @property
    def is_pressed(self):
        """
        Returns ``True`` if the button is pressed (or held).

        .. note::

            If there are multiple buttons, if any button is pressed, `True`
            will be returned.
        """
        for button in self.buttons:
            if button._is_pressed:
                return True

        return False

    @property
    def interaction(self):
        """
        Returns an instance of :class:`BlueDotInteraction` representing the
        current or last interaction with the Blue Dot.

        .. note::

            If the Blue Dot is released (and inactive), :attr:`interaction`
            will return the interaction when it was released, until it is
            pressed again.  If the Blue Dot has never been pressed
            :attr:`interaction` will return ``None``.

            If there are multiple buttons, the interaction will only be
            returned for button [0,0]

        .. deprecated:: 2.0.0

        """
        return self._get_button((0,0)).interaction

    @property
    def rotation_segments(self):
        """
        Sets or returns the number of virtual segments the button is split into for rotating.
        Defaults to 8.

        .. note::

            If there are multiple buttons in the grid, the 'default' value
            will be returned and when set all buttons will be updated.
        """
        return super(BlueDot, self.__class__).rotation_segments.fget(self)

    @rotation_segments.setter
    def rotation_segments(self, value):
        super(BlueDot, self.__class__).rotation_segments.fset(self, value)
        for button in self.buttons:
            button.rotation_segments = value

    @property
    def double_press_time(self):
        """
        Sets or returns the time threshold in seconds for a double press. Defaults to 0.3.

        .. note::

            If there are multiple buttons in the grid, the 'default' value
            will be returned and when set all buttons will be updated.
        """
        return super(BlueDot, self.__class__).double_press_time.fget(self)

    @double_press_time.setter
    def double_press_time(self, value):
        super(BlueDot, self.__class__).double_press_time.fset(self, value)
        for button in self.buttons:
            button.double_press_time = value

    @property
    def color(self):
        """
        Sets or returns the color of the button. Defaults to BLUE.

        An instance of :class:`.colors.Color` is returned.

        Value can be set as a :class:`.colors.Color` object, a hex color value
        in the format `#rrggbb` or `#rrggbbaa`, a tuple of `(red, green, blue)`
        or `(red, green, blue, alpha)` values between `0` & `255` or a text
        description of the color, e.g. "red".

        A dictionary of available colors can be obtained from `bluedot.COLORS`.

        .. note::

            If there are multiple buttons in the grid, the 'default' value
            will be returned and when set all buttons will be updated.
        """
        return super(BlueDot, self.__class__).color.fget(self)

    @color.setter
    def color(self, value):
        super(BlueDot, self.__class__).color.fset(self, value)
        for button in self.buttons:
            button.color = value

    @property
    def square(self):
        """
        When set to `True` the 'dot' is made square. Default is `False`.

        .. note::

            If there are multiple buttons in the grid, the 'default' value
            will be returned and when set all buttons will be updated.
        """
        return super(BlueDot, self.__class__).square.fget(self)

    @square.setter
    def square(self, value):
        super(BlueDot, self.__class__).square.fset(self, value)
        for button in self.buttons:
            button.square = value

    @property
    def border(self):
        """
        When set to `True` adds a border to the dot. Default is `False`.

        .. note::

            If there are multiple buttons in the grid, the 'default' value
            will be returned and when set all buttons will be updated.
        """
        return super(BlueDot, self.__class__).border.fget(self)

    @border.setter
    def border(self, value):
        super(BlueDot, self.__class__).border.fset(self, value)
        for button in self.buttons:
            button.border = value

    @property
    def visible(self):
        """
        When set to `False` the dot will be hidden. Default is `True`.

        .. note::

            Events (press, release, moved) are still sent from the dot
            when it is not visible.

            If there are multiple buttons in the grid, the 'default' value
            will be returned and when set all buttons will be updated.
        """
        return super(BlueDot, self.__class__).visible.fget(self)

    @visible.setter
    def visible(self, value):
        super(BlueDot, self.__class__).visible.fset(self, value)
        for button in self.buttons:
            button.visible = value

    @property
    def when_client_connects(self):
        """
        Sets or returns the function which is called when a Blue Dot
        application connects.

        The function will be run in the same thread and block, to run in a separate
        thread use `set_when_client_connects(function, background=True)`
        """
        return self._when_client_connects

    @when_client_connects.setter
    def when_client_connects(self, value):
        self.set_when_client_connects(value)

    def set_when_client_connects(self, callback, background=False):
        """
        Sets the function which is called when a Blue Dot connects.

        :param Callable callback:
            The function to call, setting to `None` will stop the callback.

        :param bool background:
            If set to `True` the function will be run in a separate thread
            and it will return immediately. The default is `False`.
        """
        self._when_client_connects = callback
        self._when_client_connects_background = background

    @property
    def when_client_disconnects(self):
        """
        Sets or returns the function which is called when a Blue Dot disconnects.

        The function will be run in the same thread and block, to run in a separate
        thread use `set_when_client_disconnects(function, background=True)`
        """
        return self._when_client_disconnects

    @when_client_disconnects.setter
    def when_client_disconnects(self, value):
        self.set_when_client_disconnects(value)

    def set_when_client_disconnects(self, callback, background=False):
        """
        Sets the function which is called when a Blue Dot disconnects.

        :param Callable callback:
            The function to call, setting to `None` will stop the callback.

        :param bool background:
            If set to `True` the function will be run in a separate thread
            and it will return immediately. The default is `False`.
        """
        self._when_client_disconnects = callback
        self._when_client_disconnects_background = background

    def wait_for_connection(self, timeout = None):
        """
        Waits until a Blue Dot client connects.
        Returns ``True`` if a client connects.

        :param float timeout:
            Number of seconds to wait for a wait connections, if ``None`` (the default),
            it will wait indefinetly for a connection from a Blue Dot client.
        """
        return self._is_connected_event.wait(timeout)

    def start(self):
        """
        Start the :class:`.btcomm.BluetoothServer` if it is not already
        running. By default the server is started at initialisation.
        """
        self._server.start()
        self._print_message("Server started {}".format(self.server.server_address))
        self._print_message("Waiting for connection")

    def _create_server(self):
        self._server = BluetoothServer(
                self._data_received,
                when_client_connects = self._client_connected,
                when_client_disconnects = self._client_disconnected,
                device = self.device,
                port = self.port,
                power_up_device = self._power_up_device,
                auto_start = False)

    def stop(self):
        """
        Stop the Bluetooth server.
        """
        self._server.stop()

    def allow_pairing(self, timeout = 60):
        """
        Allow a Bluetooth device to pair with your Raspberry Pi by putting
        the adapter into discoverable and pairable mode.

        :param int timeout:
            The time in seconds the adapter will remain pairable. If set to ``None``
            the device will be discoverable and pairable indefinetly.
        """
        self.server.adapter.allow_pairing(timeout = timeout)

    def resize(self, cols, rows):
        """
        Resizes the grid of buttons.

        :param int cols:
            The number of columns in the grid of buttons.

        :param int rows:
            The number of rows in the grid of buttons.

        .. note::
            Existing buttons will retain their state (color, border, etc) when
            resized. New buttons will be created with the default values set
            by the :class:`BlueDot`.
        """
        self._cols = cols
        self._rows = rows

        # create new buttons
        new_buttons = {}

        for c in range(cols):
            for r in range(rows):
                # if button already exist, reuse it
                if (c,r) in self._buttons.keys():
                    new_buttons[c,r] = self._buttons[c,r]
                else:
                    new_buttons[c,r] = BlueDotButton(self, c, r, self._color, self._square, self._border, self._visible)

        self._buttons = new_buttons

        self._send_bluedot_config()

    def _get_button(self, key):
        try:
            return self._buttons[key]
        except KeyError:
            raise ButtonDoesNotExist("The button `{}` does not exist".format(key))

    def _client_connected(self):
        self._is_connected_event.set()
        self._print_message("Client connected {}".format(self.server.client_address))
        self._send_bluedot_config()
        if self.when_client_connects:
            self._process_callback(self.when_client_connects, None, self._when_client_connects_background)

        # wait for the protocol version to be checked.
        if not self._check_protocol_event.wait(CHECK_PROTOCOL_TIMEOUT):
            self._print_message("Protocol version not received from client - do you need to update the client to the latest version?")
            self._server.disconnect_client()

    def _client_disconnected(self):
        self._is_connected_event.clear()
        self._check_protocol_event.clear()
        self._print_message("Client disconnected")
        if self.when_client_disconnects:
            self._process_callback(self.when_client_disconnects, None, self._when_client_disconnects_background)

    def _data_received(self, data):
        #add the data received to the buffer
        self._data_buffer += data

        #get any full commands ended by \n
        last_command = self._data_buffer.rfind("\n")
        if last_command != -1:
            commands = self._data_buffer[:last_command].split("\n")
            #remove the processed commands from the buffer
            self._data_buffer = self._data_buffer[last_command + 1:]
            self._process_commands(commands)

    def _process_commands(self, commands):
        for command in commands:
            # debug - print each command
            # print(command)

            operation = command.split(",")[0]
            params = command.split(",")[1:]

            # dot change operation?
            if operation in ["0", "1", "2"]:

                position = None
                try:
                    button, position = self._parse_interaction_msg(operation, params)
                    self._position = position
                except ValueError:
                    # warn about the occasional corrupt command
                    warnings.warn("Data received which could not be parsed.\n{}".format(command))
                except ButtonDoesNotExist:
                    # data received for a button which could not be found
                    warnings.warn("Data received for a button which does not exist.\n{}".format(command))
                else:
                    # dot released
                    if operation == "0":
                        self._process_release(button, position)

                    # dot pressed
                    elif operation == "1":
                        self._process_press(button, position)

                    # dot pressed position moved
                    elif operation == "2":
                        self._process_move(button, position)

            # protocol check
            elif operation == "3":
                self._check_protocol_version(params[0], params[1])

            else:
                # operation not identified...
                warnings.warn("Data received for an unknown operation.\n{}".format(command))

    def _parse_interaction_msg(self, operation, params):
        """
        Parses an interaction (press, move, release) message and returns
        the component parts
        """
        # parse message
        col = int(params[0])
        row = int(params[1])
        position = BlueDotPosition(col, row, params[2], params[3])
        button = self._get_button((col, row))

        return button, position

    def _process_press(self, button, position):
        # was the button double pressed?
        if button.is_double_press(position):
            self.double_press(position)
            button.double_press(position)

        # set the blue dot and button as pressed
        self.press(position)
        button.press(position)

    def _process_move(self, button, position):
        # set the blue dot as moved
        self.move(position)
        # set the button as moved
        button.move(position)
        # was it a rotation
        rotation = button.get_rotation()
        if rotation is not None:
            self.rotate(rotation)
            button.rotate(rotation)

    def _process_release(self, button, position):
        # set the blue dot as released
        self.release(position)
        # set the button as released
        button.release(position)

        # was it a swipe?
        swipe = button.get_swipe()
        if swipe is not None:
            self.swipe(swipe)
            button.swipe(swipe)

    def _check_protocol_version(self, protocol_version, client_name):
        try:
            version_no = int(protocol_version)
        except ValueError:
            raise ValueError("protocol version number must be numeric, received {}.".format(protocol_version))
        self._check_protocol_event.set()

        if version_no != PROTOCOL_VERSION:
            msg = "Client '{}' was using protocol version {}, bluedot python library is using version {}. "
            if version_no > PROTOCOL_VERSION:
                msg += "Update the bluedot python library, using 'sudo pip3 --upgrade install bluedot'."
                msg = msg.format(client_name, protocol_version, PROTOCOL_VERSION)
            else:
                msg += "Update the {}."
                msg = msg.format(client_name, protocol_version, PROTOCOL_VERSION, client_name)
            self._server.disconnect_client()
            print(msg)

    # called whenever the BlueDot configuration is changed or a client connects
    def _send_bluedot_config(self):
        if self.is_connected:
            self._server.send(
                "4,{},{},{},{},{},{}\n".format(
                    self._color.str_rgba,
                    int(self._square),
                    int(self._border),
                    int(self._visible),
                    self._cols,
                    self._rows
                    )
                )

            # send the configuration for the individual buttons
            button_config_msg = ""
            for button in self.buttons:
                if button.modified:
                    button_config_msg += button._build_config_msg()

            if button_config_msg != "":
                self._server.send(button_config_msg)

    def _print_message(self, message):
        if self.print_messages:
            print(message)

    def __getitem__(self, key):
        return self._get_button(key)


text:
namespace MVCHoldem.Web
{
    using System.Data.Entity;
    using System.Reflection;
    using System.Web.Mvc;
    using System.Web.Optimization;
    using System.Web.Routing;
    using MVCHoldem.Data;
    using MVCHoldem.Data.Migrations;
    using MVCHoldem.Web.App_Start;

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<EfDbContext, Configuration>());

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new RazorViewEngine());

            AutoMapperConfig.Execute(Assembly.GetExecutingAssembly());
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<html>
<body></body>
This file exists to test that one resource get loaded in Chrome inspector.
</html>


text:
import time

# external libraries
from numpy import hstack, ones, pi, linspace, array, zeros, zeros_like
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from pydy.models import n_link_pendulum_on_cart
from sympy import symbols

def run_benchmark(max_num_links, num_time_steps=1000):
    """Runs the n link pendulum derivation, code generation, and integration
    for each n up to the max number provided and generates a plot of the
    results."""

    methods = ['lambdify', 'theano', 'cython']

    link_numbers = range(1, max_num_links + 1)

    derivation_times = zeros(len(link_numbers))
    integration_times = zeros((max_num_links, len(methods)))
    code_generation_times = zeros_like(integration_times)

    for j, n in enumerate(link_numbers):

        title = "Pendulum with {} links.".format(n)
        print(title)
        print('=' * len(title))

        start = time.time()
        sys = n_link_pendulum_on_cart(n, cart_force=False)

        m = symbols('m:{}'.format(n + 1))
        l = symbols('l:{}'.format(n))
        g = symbols('g')

        derivation_times[j] = time.time() - start
        print('The derivation took {:1.5f} seconds.\n'.format(derivation_times[j]))

        # Define the numerical values: parameters, time, and initial conditions
        arm_length = 1. / n
        bob_mass = 0.01 / n
        parameter_vals = [9.81, 0.01 / n]
        for i in range(n):
            parameter_vals += [arm_length, bob_mass]

        times = linspace(0, 10, num_time_steps)
        sys.times = times

        x0 = hstack(
            (0,
             pi / 2 * ones(len(sys.coordinates) - 1),
             1e-3 * ones(len(sys.speeds))))
        sys.initial_conditions = dict(zip(sys.states, x0))

        constants = [g, m[0]]
        for i in range(n):
            constants += [l[i], m[i + 1]]

        sys.constants = dict(zip(constants, array(parameter_vals)))

        for k, method in enumerate(methods):

            subtitle = "Generating with {} method.".format(method)
            print(subtitle)
            print('-' * len(subtitle))
            start = time.time()
            sys.generate_ode_function(generator=method)
            code_generation_times[j, k] = time.time() - start
            print('The code generation took {:1.5f} seconds.'.format(
                code_generation_times[j, k]))

            start = time.time()
            sys.integrate()
            integration_times[j, k] = time.time() - start
            print('ODE integration took {:1.5f} seconds.\n'.format(
                integration_times[j, k]))

        del sys

    # plot the results
    fig, ax = plt.subplots(3, 1, sharex=True)

    ax[0].plot(link_numbers, derivation_times)
    ax[0].set_title('Symbolic Derivation Time')

    ax[1].plot(link_numbers, code_generation_times)
    ax[1].set_title('Code Generation Time')
    ax[1].legend(methods, loc=2)

    ax[2].plot(link_numbers, integration_times)
    ax[2].set_title('Integration Time')
    ax[2].legend(methods, loc=2)

    for a in ax.flatten():
        a.set_ylabel('Time [s]')

    ax[-1].set_xlabel('Number of links')

    plt.tight_layout()

    fig.savefig('benchmark-results.png')

if __name__ == "__main__":

    import argparse

    parser = argparse.ArgumentParser(
        description='Run the n link pendulum benchmark.')

    parser.add_argument('max_num_links', type=int,
        help="The maximum number of links to compute.")

    parser.add_argument('num_time_steps', type=int,
        help="The number of integration time steps.")

    args = parser.parse_args()

    run_benchmark(args.max_num_links, args.num_time_steps)


text:
#include "runtime.h"
#include "interface.h"

/* Compare a non-empty interface value with an empty interface value.
   Return 0 for equal, not zero for not equal (return value is like
   strcmp).  */

int
__go_interface_empty_compare (struct __go_interface left,
			      struct __go_empty_interface right)
{
  const struct __go_type_descriptor *left_descriptor;

  if (((uintptr_t) right.__type_descriptor & reflectFlags) != 0)
    runtime_panicstring ("invalid interface value");
  if (left.__methods == NULL && right.__type_descriptor == NULL)
    return 0;
  if (left.__methods == NULL || right.__type_descriptor == NULL)
    return 1;
  left_descriptor = left.__methods[0];
  if (!__go_type_descriptors_equal (left_descriptor, right.__type_descriptor))
    return 1;
  if (__go_is_pointer_type (left_descriptor))
    return left.__object == right.__object ? 0 : 1;
  if (!left_descriptor->__equalfn (left.__object, right.__object,
				   left_descriptor->__size))
    return 1;
  return 0;
}


text:
package eu.cyfronoid.core.file;

import java.io.InputStream;

public interface NamedInputStream {
    String getName();
    InputStream getInputStream();
    void close();
}


text:
package distuv

import (
	"math"

	"golang.org/x/exp/rand"

	"gonum.org/v1/gonum/floats"
	"gonum.org/v1/gonum/mathext"
	"gonum.org/v1/gonum/stat"
)

// UnitNormal is an instantiation of the normal distribution with Mu = 0 and Sigma = 1.
var UnitNormal = Normal{Mu: 0, Sigma: 1}

// Normal respresents a normal (Gaussian) distribution (https://en.wikipedia.org/wiki/Normal_distribution).
type Normal struct {
	Mu    float64 // Mean of the normal distribution
	Sigma float64 // Standard deviation of the normal distribution
	Src   rand.Source

	// Needs to be Mu and Sigma and not Mean and StdDev because Normal has functions
	// Mean and StdDev
}

// CDF computes the value of the cumulative density function at x.
func (n Normal) CDF(x float64) float64 {
	return 0.5 * math.Erfc(-(x-n.Mu)/(n.Sigma*math.Sqrt2))
}

// ConjugateUpdate updates the parameters of the distribution from the sufficient
// statistics of a set of samples. The sufficient statistics, suffStat, have been
// observed with nSamples observations. The prior values of the distribution are those
// currently in the distribution, and have been observed with priorStrength samples.
//
// For the normal distribution, the sufficient statistics are the mean and
// uncorrected standard deviation of the samples.
// The prior is having seen strength[0] samples with mean Normal.Mu
// and strength[1] samples with standard deviation Normal.Sigma. As a result of
// this function, Normal.Mu and Normal.Sigma are updated based on the weighted
// samples, and strength is modified to include the new number of samples observed.
//
// This function panics if len(suffStat) != 2 or len(priorStrength) != 2.
func (n *Normal) ConjugateUpdate(suffStat []float64, nSamples float64, priorStrength []float64) {
	// TODO: Support prior strength with math.Inf(1) to allow updating with
	// a known mean/standard deviation

	totalMeanSamples := nSamples + priorStrength[0]
	totalSum := suffStat[0]*nSamples + n.Mu*priorStrength[0]

	totalVarianceSamples := nSamples + priorStrength[1]
	// sample variance
	totalVariance := nSamples * suffStat[1] * suffStat[1]
	// add prior variance
	totalVariance += priorStrength[1] * n.Sigma * n.Sigma
	// add cross variance from the difference of the means
	meanDiff := (suffStat[0] - n.Mu)
	totalVariance += priorStrength[0] * nSamples * meanDiff * meanDiff / totalMeanSamples

	n.Mu = totalSum / totalMeanSamples
	n.Sigma = math.Sqrt(totalVariance / totalVarianceSamples)
	floats.AddConst(nSamples, priorStrength)
}

// Entropy returns the differential entropy of the distribution.
func (n Normal) Entropy() float64 {
	return 0.5 * (log2Pi + 1 + 2*math.Log(n.Sigma))
}

// ExKurtosis returns the excess kurtosis of the distribution.
func (Normal) ExKurtosis() float64 {
	return 0
}

// Fit sets the parameters of the probability distribution from the
// data samples x with relative weights w. If weights is nil, then all the weights
// are 1. If weights is not nil, then the len(weights) must equal len(samples).
func (n *Normal) Fit(samples, weights []float64) {
	suffStat := make([]float64, n.NumSuffStat())
	nSamples := n.SuffStat(suffStat, samples, weights)
	n.ConjugateUpdate(suffStat, nSamples, make([]float64, n.NumSuffStat()))
}

// LogProb computes the natural logarithm of the value of the probability density function at x.
func (n Normal) LogProb(x float64) float64 {
	return negLogRoot2Pi - math.Log(n.Sigma) - (x-n.Mu)*(x-n.Mu)/(2*n.Sigma*n.Sigma)
}

// Mean returns the mean of the probability distribution.
func (n Normal) Mean() float64 {
	return n.Mu
}

// Median returns the median of the normal distribution.
func (n Normal) Median() float64 {
	return n.Mu
}

// Mode returns the mode of the normal distribution.
func (n Normal) Mode() float64 {
	return n.Mu
}

// NumParameters returns the number of parameters in the distribution.
func (Normal) NumParameters() int {
	return 2
}

// NumSuffStat returns the number of sufficient statistics for the distribution.
func (Normal) NumSuffStat() int {
	return 2
}

// Prob computes the value of the probability density function at x.
func (n Normal) Prob(x float64) float64 {
	return math.Exp(n.LogProb(x))
}

// Quantile returns the inverse of the cumulative probability distribution.
func (n Normal) Quantile(p float64) float64 {
	if p < 0 || p > 1 {
		panic(badPercentile)
	}
	return n.Mu + n.Sigma*mathext.NormalQuantile(p)
}

// Rand returns a random sample drawn from the distribution.
func (n Normal) Rand() float64 {
	var rnd float64
	if n.Src == nil {
		rnd = rand.NormFloat64()
	} else {
		rnd = rand.New(n.Src).NormFloat64()
	}
	return rnd*n.Sigma + n.Mu
}

// Score returns the score function with respect to the parameters of the
// distribution at the input location x. The score function is the derivative
// of the log-likelihood at x with respect to the parameters
//  (∂/∂θ) log(p(x;θ))
// If deriv is non-nil, len(deriv) must equal the number of parameters otherwise
// Score will panic, and the derivative is stored in-place into deriv. If deriv
// is nil a new slice will be allocated and returned.
//
// The order is [∂LogProb / ∂Mu, ∂LogProb / ∂Sigma].
//
// For more information, see https://en.wikipedia.org/wiki/Score_%28statistics%29.
func (n Normal) Score(deriv []float64, x float64) []float64 {
	if deriv == nil {
		deriv = make([]float64, n.NumParameters())
	}
	if len(deriv) != n.NumParameters() {
		panic(badLength)
	}
	deriv[0] = (x - n.Mu) / (n.Sigma * n.Sigma)
	deriv[1] = 1 / n.Sigma * (-1 + ((x-n.Mu)/n.Sigma)*((x-n.Mu)/n.Sigma))
	return deriv
}

// ScoreInput returns the score function with respect to the input of the
// distribution at the input location specified by x. The score function is the
// derivative of the log-likelihood
//  (d/dx) log(p(x)) .
func (n Normal) ScoreInput(x float64) float64 {
	return -(1 / (2 * n.Sigma * n.Sigma)) * 2 * (x - n.Mu)
}

// Skewness returns the skewness of the distribution.
func (Normal) Skewness() float64 {
	return 0
}

// StdDev returns the standard deviation of the probability distribution.
func (n Normal) StdDev() float64 {
	return n.Sigma
}

// SuffStat computes the sufficient statistics of a set of samples to update
// the distribution. The sufficient statistics are stored in place, and the
// effective number of samples are returned.
//
// The normal distribution has two sufficient statistics, the mean of the samples
// and the standard deviation of the samples.
//
// If weights is nil, the weights are assumed to be 1, otherwise panics if
// len(samples) != len(weights). Panics if len(suffStat) != NumSuffStat().
func (Normal) SuffStat(suffStat, samples, weights []float64) (nSamples float64) {
	lenSamp := len(samples)
	if len(weights) != 0 && len(samples) != len(weights) {
		panic(badLength)
	}
	if len(suffStat) != (Normal{}).NumSuffStat() {
		panic(badSuffStat)
	}

	if len(weights) == 0 {
		nSamples = float64(lenSamp)
	} else {
		nSamples = floats.Sum(weights)
	}

	mean := stat.Mean(samples, weights)
	suffStat[0] = mean

	// Use Moment and not StdDev because we want it to be uncorrected
	variance := stat.MomentAbout(2, samples, mean, weights)
	suffStat[1] = math.Sqrt(variance)
	return nSamples
}

// Survival returns the survival function (complementary CDF) at x.
func (n Normal) Survival(x float64) float64 {
	return 0.5 * (1 - math.Erf((x-n.Mu)/(n.Sigma*math.Sqrt2)))
}

// setParameters modifies the parameters of the distribution.
func (n *Normal) setParameters(p []Parameter) {
	if len(p) != n.NumParameters() {
		panic("normal: incorrect number of parameters to set")
	}
	if p[0].Name != "Mu" {
		panic("normal: " + panicNameMismatch)
	}
	if p[1].Name != "Sigma" {
		panic("normal: " + panicNameMismatch)
	}
	n.Mu = p[0].Value
	n.Sigma = p[1].Value
}

// Variance returns the variance of the probability distribution.
func (n Normal) Variance() float64 {
	return n.Sigma * n.Sigma
}

// parameters returns the parameters of the distribution.
func (n Normal) parameters(p []Parameter) []Parameter {
	nParam := n.NumParameters()
	if p == nil {
		p = make([]Parameter, nParam)
	} else if len(p) != nParam {
		panic("normal: improper parameter length")
	}
	p[0].Name = "Mu"
	p[0].Value = n.Mu
	p[1].Name = "Sigma"
	p[1].Value = n.Sigma
	return p
}


text:
import math
import random
import time
import threading
from mince import Colour

# Easing Functions
def linear(edge0, edge1, weight):
    ''' Linear interpolation '''
    if weight < 0:
        weight = 0.0
    elif weight > 1:
        weight = 1.0
    return edge0 + ((edge1 - edge0) * float(weight))

def smooth_step(edge0, edge1, weight):
    ''' Interpolation with smoother end points '''
    tmp = float(weight - edge0) / float(edge1 - edge0)
    if tmp < 0:
        tmp = 0.0
    elif tmp > 1:
        tmp = 1.0
    return math.pow(tmp, 2)*(3 - 2*tmp)

def smoother_step(edge0, edge1, weight):
    ''' Perlin's Smoother Step '''
    tmp = float(weight - edge0) / float(edge1 - edge0)
    if tmp < 0:
        tmp = 0.0
    elif tmp > 1:
        tmp = 1.0
    return math.pow(tmp, 3)*(tmp*(tmp*6 - 15)+10)

class FXRunner:
    ''' Runs effects on a string of lights '''
    def __init__(self, lights, colours=None):
        self.lights = lights
        self.num_lights = lights.num_lights
        if colours is None:
            self.colours = [Colour(0, 0, 0)] * 50
        else:
            self.colours = colours
        self.__thread = None
        self.__stop_event = None

    def run(self, fxclass, *args, **kwargs):
        # Another task is running, stop it
        if self.is_running() and not self.__stop_event.is_set():
            self.stop()

        # Wait until the last thread stops
        while self.is_running() and self.__stop_event.is_set():
            pass

        # Event for stopping thread
        self.__stop_event = threading.Event()

        # Create effects instance
        fxinstance = fxclass(self, *args, **kwargs)

        # Create wrapper for thread
        def wrap(event, *w_args, **k_wargs):
            last_time = time.time()
            delta_time = 0

            while not event.is_set():
                fxinstance.run(delta_time)
                now = time.time()
                delta_time = now - last_time
                last_time = now

        self.__thread = threading.Thread(target=wrap, args=(self.__stop_event,))
        self.__thread.daemon = True
        self.__thread.start()

    def stop(self):
        if self.__stop_event is not None:
            self.__stop_event.set()

    def is_running(self):
        return (self.__thread is not None and self.__thread.is_alive())

class StaticFX(object):
    def __init__(self, runner):
        self.runner = runner

    def _output_lights(self):
        # Update lights
        self.runner.lights.set_lights(self.runner.colours)
        self.runner.lights.write()

    def run(self, delta):
        # Constantly display lights
        self._output_lights()


text:
class VERGEClient
  class HTTPError < StandardError

    attr_accessor :object, :message

    def initialize(object)
      @object = object
      @message = "Expected NET::HTTPOK but got: #{object.class}"
    end

  end
end


text:
#pragma once

#include <stdexcept>
#include <chrono>
#include <ctime>
#include <system_error>
#include <codecvt>
#include <locale>
#include <type_traits>
#include <cstdlib>
#include <algorithm>

#ifdef _WIN32
#include <Windows.h>
#define SLASH "\\"
#define WSLASH L"\\"
#else
#include <sys/stat.h>
#define SLASH "/"
#define WSLASH L"/"
#endif // _WIN32

#ifdef _MSC_VER
#pragma warning(disable: 4996)
#define TINY_CHAR16_T unsigned short
#define TINY_CHAR32_T unsigned int

#else
#define TINY_CHAR16_T char16_t
#define TINY_CHAR32_T char32_t
#endif // _MSC_VER

#ifdef _WIN32
#define IS_DIR_SEPARATOR(c) (c=='\\')
#define IS_DIR_SEPARATORW(c) (c==L'\\')
#else
#define IS_DIR_SEPARATOR(c) (c=='/')
#endif

namespace tinydircpp
{
    namespace fs {

        using file_time_type = std::chrono::time_point<std::chrono::system_clock>;
        using space_info = struct {
            std::uintmax_t available;
            std::uintmax_t capacity;
            std::uintmax_t free;
        };
        template<typename T>
        using str_t = std::basic_string<T, std::char_traits<T>>;

        class path {
        public:
            using value_type = wchar_t;
            using string_type = str_t<value_type>;
        public:

            path() = default;
            ~path() = default;
            path( path && p ) : pathname_{ std::move( p.pathname_ ) } {}
            path( path const & p ) : pathname_{ p.pathname_ } {}

            explicit path( std::wstring const & pathname );
            explicit path( std::string const & pathname );
            explicit path( std::u16string const & pathname );
            explicit path( std::u32string const & pathname );
            explicit path( wchar_t const * pathname );
            explicit path( char const * pathname );

            template<typename InputIterator>
            path( InputIterator begin, InputIterator end );

            path& operator=( path const & p );
            path& operator=( path && p );
            template<typename Source>
            path& operator=( Source const & source )
            {
                *this = path{ source };
                return *this;
            }

            template<typename Source>
            path& assign( Source const & source )
            {
                *this = source;
                return *this;
            }

            template<typename InputIterator>
            path& assign( InputIterator beg, InputIterator end )
            {
                *this = path{ beg, end };
                return *this;
            }
            void clear() noexcept
            {
                pathname_.clear();
            }

            friend path operator/( path const & p, path const & rel_path );
            path& operator/=( path const & p );
            bool operator<( path const & p ) const
            {
                return pathname_ < p.pathname_;
            }
            bool operator>( path const & p ) const
            {
                return pathname_ > p.pathname_;
            }

            bool operator<=( path const & p ) const
            {
                return pathname_ <= p.pathname_;
            }
            bool operator>=( path const & p ) const
            {
                return pathname_ >= p.pathname_;
            }
            /*
            path& operator +=( std::string const & str );
            path& operator+=( path const & p );
            path& operator+=( char p );
            path& remove_filename();
            path& replace_filename_with( path const & new_filename );
            path& replace_extension( path const & );
            int compare( path const & ) const noexcept;
            int compare( std::string const & ) const noexcept;
            path root_name() const;
            path root_directory() const;
            path relative_path() const;
            */
            path extension() const;
            path filename() const;

            operator string_type()
            {
                return pathname_;
            }

            std::u32string u32string() const;
            std::u16string u16string() const;
            std::wstring wstring() const;
            std::string string() const;

            bool empty() const
            {
                return pathname_.empty();
            }

            string_type const & native() const noexcept
            {
                return pathname_;
            }
            value_type const * c_str() const noexcept
            {
                return pathname_.c_str();
            }
            operator string_type() const
            {
                return pathname_;
            }
            /*
            bool has_root_name() const;
            bool has_root_directory() const;
            bool has_filename() const;
            bool is_absolute() const;
            bool is_relative() const; */
        private:
            str_t<value_type> pathname_ {}; // basic-string
        };

        enum class filesystem_error_codes
        {
            directory_name_unobtainable = 0x80,
            unknown_io_error,
            handle_not_opened,
            could_not_obtain_size,
            could_not_obtain_time,
            hardlink_count_error,
            invalid_set_file_pointer,
            set_filetime_error,
            no_link,
            operation_cancelled
        };

        std::error_code make_error_code( filesystem_error_codes code );

        namespace details {
            struct invalid_filename : public std::runtime_error {
                invalid_filename( char const * error_message ) : std::runtime_error{ error_message }{}
            };
            struct name_too_long : public std::runtime_error {
                name_too_long( char const * error_message ) : std::runtime_error{ error_message }{}
            };

            struct smart_handle {
                smart_handle( HANDLE h ) : h_{ h } {}
                smart_handle( smart_handle const & ) = delete;
                smart_handle( smart_handle && ) = delete;
                smart_handle& operator=( smart_handle const & ) = delete;
                smart_handle& operator=( smart_handle && ) = delete;

                ~smart_handle()
                {
                    if ( h_ != INVALID_HANDLE_VALUE ) CloseHandle( h_ );
                }
                operator bool()
                {
                    return h_ != INVALID_HANDLE_VALUE;
                }
                operator HANDLE() { return h_; }
            private:
                HANDLE h_;
            };

            std::string get_windows_error( DWORD error_code );

            file_time_type Win32FiletimeToChronoTime( FILETIME const &pFiletime );
            FILETIME ChronoTimeToWin32Filetime( file_time_type const & ftt );

            template<typename T>
            bool is_filename( str_t<T> const & str )
            {
                std::locale locale_{};
                return std::all_of( std::begin( str ), std::end( str ), [&]( T const & ch ) {
                    return std::isalnum( ch, locale_ ) || ( T( '.' ) == ch ) || ( T( '_' ) == ch ) || ( T( '-' ) == ch );
                } );
            }

            void convert_to( str_t<wchar_t> const & from, str_t<char32_t> & to );
            void convert_to( str_t<char32_t> const & from, str_t<wchar_t> & to );
            void convert_to( str_t<wchar_t> const & from, str_t<char> & to );
            void convert_to( str_t<char16_t> const & from, str_t<char> & to );
            void convert_to( str_t<char32_t> const & from, str_t<char> & to );
            void convert_to( str_t<char> const & from, str_t<char16_t> & to );
            void convert_to( str_t<char> const & from, str_t<char32_t> & to );
            void convert_to( str_t<char> const &from, str_t<char> & to );
            void convert_to( str_t<char> const & from, str_t<wchar_t> & to );

        }
        template<typename InputIterator>
        path::path( InputIterator begin, InputIterator end ) : // we delegate the task to a ctor taking a string type
            path{ str_t<typename std::iterator_traits<InputIterator>::value_type>{ begin, end } }
        {
        }

        class filesystem_error : public std::system_error {
        public:
            filesystem_error( std::string const & what, std::error_code ec ) : filesystem_error{ what, {}, ec } {}
            filesystem_error( std::string const & what, path const & p, std::error_code ec ) :
                filesystem_error{ what, p, {}, ec }
            {
            }
            filesystem_error( std::string const & what, path const & p1, path const & p2, std::error_code ec ) :
                std::system_error{ ec, what }, first_path{ p1 }, second_path{ p2 }{}

            path const & path1() const { return first_path; }
            path const & path2() const { return second_path; }
            using std::system_error::what;

        private:
            path const first_path;
            path const second_path;
        };

        enum class file_type : int {
            none = 0,
            not_found = -1,
            regular = 1,
            directory,
            symlink,
            block,
            character,
            fifo,
            socket,
            unknown
        };

        enum class copy_options : int {
            none = 0,
            skip_existing = 0x1,
            overwrite_existing = 0x2,
            update_existing = 0x4,
            recursive = 0x8,
            copy_symlinks = 0x10,
            skip_symlinks = 0x20,
            directories_only = 0x40,
            create_symlinks = 0x80,
            create_hardlinks = 0x100
        };

        enum class perms : int {
            none = 0,
            owner_read = 256,
            owner_write = 128,
            owner_exec = 64,
            owner_all = owner_read | owner_write | owner_exec,
            group_read = 32,
            group_write = 16,
            group_exec = 8,
            group_all = group_read | group_write | group_exec,
            others_read = 4,
            others_write = 2,
            others_exec = 1,
            others_all = others_read | others_write | others_exec,
            all = 511,
            set_uid = 2048,
            set_gid = 1024,
            mask = 512,
            unknown = 0xFFFF,
            symlink_perms = 0x4000
        };
        //supposed to be in <ntifs.h> but weirdly this header isn't available to use but MSDN shows what it looks like
        struct REPARSE_DATA_BUFFER
        {
            ULONG  ReparseTag;
            USHORT  ReparseDataLength;
            USHORT  Reserved;
            union {
                struct {
                    USHORT  SubstituteNameOffset;
                    USHORT  SubstituteNameLength;
                    USHORT  PrintNameOffset;
                    USHORT  PrintNameLength;
                    ULONG  Flags;
                    WCHAR  PathBuffer[ 1 ];
                } SymbolicLinkReparseBuffer;
                struct {
                    USHORT  SubstituteNameOffset;
                    USHORT  SubstituteNameLength;
                    USHORT  PrintNameOffset;
                    USHORT  PrintNameLength;
                    WCHAR  PathBuffer[ 1 ];
                } MountPointReparseBuffer;
                struct {
                    UCHAR  DataBuffer[ 1 ];
                } GenericReparseBuffer;
            };
        };
        struct filesystem_time {
            unsigned short year;
            unsigned short month;
            unsigned short day_of_week;
            unsigned short day;
            unsigned short hour;
            unsigned short minute;
            unsigned short second;
            unsigned short milliseconds;
        };

        file_time_type fstime_to_stdtime( filesystem_time const & );
        filesystem_time stdtime_to_fstime( file_time_type const & );

        enum class permissions_status : int {
            replace_bits = 0,
            add_bits = 1,
            remove_bits = 2,
            follow_symlinks = 4
        };
    }
}

namespace std
{
    template<>
    struct is_error_code_enum<tinydircpp::fs::filesystem_error_codes> : public true_type
    {
    };
}


text:
NetBox requires a PostgreSQL database to store data. (Please note that MySQL is not supported, as NetBox leverages PostgreSQL's built-in [network address types](https://www.postgresql.org/docs/9.1/static/datatype-net-types.html).)

!!! note
    The installation instructions provided here have been tested to work on Ubuntu 16.04 and CentOS 6.9. The particular commands needed to install dependencies on other distributions may vary significantly. Unfortunately, this is outside the control of the NetBox maintainers. Please consult your distribution's documentation for assistance with any errors.

# Installation

**Ubuntu**

```no-highlight
# apt-get update
# apt-get install -y postgresql libpq-dev
```

**CentOS**

```no-highlight
# yum install -y postgresql postgresql-server postgresql-devel
# postgresql-setup initdb
```

CentOS users should modify the PostgreSQL configuration to accept password-based authentication by replacing `ident` with `md5` for all host entries within `/var/lib/pgsql/data/pg_hba.conf`. For example:

```no-highlight
host    all             all             127.0.0.1/32            md5
host    all             all             ::1/128                 md5
```

Then, start the service:

```no-highlight
# systemctl start postgresql
```

# Database Creation

At a minimum, we need to create a database for NetBox and assign it a username and password for authentication. This is done with the following commands.

!!! danger
    DO NOT USE THE PASSWORD FROM THE EXAMPLE.

```no-highlight
# sudo -u postgres psql
psql (9.3.13)
Type "help" for help.

postgres=# CREATE DATABASE netbox;
CREATE DATABASE
postgres=# CREATE USER netbox WITH PASSWORD 'J5brHrAXFLQSif0K';
CREATE ROLE
postgres=# GRANT ALL PRIVILEGES ON DATABASE netbox TO netbox;
GRANT
postgres=# \q
```

You can verify that authentication works issuing the following command and providing the configured password:

```no-highlight
# psql -U netbox -h localhost -W
```

If successful, you will enter a `postgres` prompt. Type `\q` to exit.


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.dataprotection.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;

/** AzureBackupParams Azure backup parameters. */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "objectType")
@JsonTypeName("AzureBackupParams")
@Fluent
public final class AzureBackupParams extends BackupParameters {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(AzureBackupParams.class);

    /*
     * BackupType ; Full/Incremental etc
     */
    @JsonProperty(value = "backupType", required = true)
    private String backupType;

    /**
     * Get the backupType property: BackupType ; Full/Incremental etc.
     *
     * @return the backupType value.
     */
    public String backupType() {
        return this.backupType;
    }

    /**
     * Set the backupType property: BackupType ; Full/Incremental etc.
     *
     * @param backupType the backupType value to set.
     * @return the AzureBackupParams object itself.
     */
    public AzureBackupParams withBackupType(String backupType) {
        this.backupType = backupType;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    @Override
    public void validate() {
        super.validate();
        if (backupType() == null) {
            throw logger
                .logExceptionAsError(
                    new IllegalArgumentException("Missing required property backupType in model AzureBackupParams"));
        }
    }
}


text:
Please see the ChangeLog for a list of the improvements and fixes present in each version of Espruino.

NOTE: This will only update devices that contain the Espruino USB Bootloader
 (like the Original Espruino Board, Espruino Pico or WiFi).
  To update other devices please see this page.

Normal Firmware Update

Just click the button below and follow the on-screen instructions.

<button class="flash_start">Flash Firmware</button>

Advanced Firmware Update

If you know the exact URL of the binary you wish to update (for instance from "Find a binary" on the Download page), please enter it below and click 'Flash from URL':

  <input type="text" class="flash_url" size="70" placeholder="https://....." value=""/><button class="flash_start_url">Flash from URL</button>

If you have the file on your computer, click <button class="flash_start_file">Flash from File</button> and you'll be able to choose the file to upload.

NOTE: STM32-based boards need to be flashed with .bin files, and nRF52 boards need .zip files (not .hex)

ESP8266 WiFi Firmware

If you're using an Espruino board with ESP8266 attached (eg. Espruino WiFi)
   then you can use the buttons below to update the WiFi module's firmware to the AT command firmware 1.1.0.0 / 1.5.4.

   Please select the type of device:

 <input type="radio" name="esp8266_type" value="espruinowifi" checked>Espruino WiFi (Serial2,rx:A3,tx:A2,pd:A13,boot:A14)

 <input type="radio" name="esp8266_type" value="espruinopicoshim">Espruino Pico WiFi shim (Serial2,rx:A3,tx:A2,pd:B9,boot:A1)

 <input type="radio" name="esp8266_type" value="pixljs"> Pixl.js with ESP8266 Shield (Serial1,rx:D0,tx:D1)

 <input type="radio" name="esp8266_type" value="pixljsmulti"> Pixl.js Multicolour (Serial1,rx:D0,tx:D1,pd:D9)

<button class="esp8266_fw_check">Check firmware version</button><button class="esp8266_fw_start">Update WiFi module Firmware (Beta)</button>


text:
import meleeAttack from '@/actions/meleeAttack';
import move from '@/actions/move';
import { Location } from '@/actions/Location';
import Entity from '@/Entity';
import Dungeon from '@/Dungeon';
import { ActionOutcome } from './ActionOutcome';

const canMoveTo = (subject: Entity, location: Location, dungeon: Dungeon): boolean => {
  const tile = dungeon.currentLevel.tileAt(location.x, location.y);
  return tile ? subject.walkableTerrains.indexOf(tile.terrain) > -1 : false;
};

const enterPosition = (
  subject: Entity,
  location: Location,
  dungeon: Dungeon,
  creatures: Entity[],
): ActionOutcome => {
  const creature = creatures.find(
    c => c.x === location.x && c.y === location.y && c.status !== 'DEAD',
  );

  if (creature) {
    return meleeAttack(subject, creature);
  }

  if (canMoveTo(subject, location, dungeon)) {
    return move(subject, location);
  }

  const outcome: ActionOutcome = { type: 'BUMP', outcome: { subject, target: location } };

  return outcome;
};

export default enterPosition;


text:
import turbogears as tg
from turbogears import controllers, expose, flash
from turbogears import identity, redirect
from cherrypy import request, response
from ecrm import model
import logging
from ecrm.util.common import *
from subcontrollers.Account import *
from subcontrollers.KohlsPO import *
from subcontrollers.BossiniPO import *
from subcontrollers.Polartec import *
from subcontrollers.Vendor import *
from subcontrollers.Region import *
#add by cz@2010-10-22
from subcontrollers.Disney import *

# from ecrm import json
log = logging.getLogger("ecrm.controllers")

class Root(controllers.RootController):
    #-------------- CLASS ATTRIBUTE-------------------
   # plsr = PLSRegionController()
    account = AccountController()
    kohlspo = KohlsPOController()
#    bossinipo = BossiniPOController()
    polartec = PolartecController()
    vendor = VendorController()
    region = RegionController()
    #add by cz@2010-10-22
    disney = DisneyController()
    #-------------  CLASS FUNCTION ------------------

    @expose(template = "ecrm.templates.page_main")
    @identity.require(identity.not_anonymous())
    @tabFocus(tab_type = "main")
    def index(self, **kw):
        return {}

    @expose(template = "ecrm.templates.page_master")
    @identity.require(identity.not_anonymous())
    @tabFocus(tab_type = "master")
    def master(self):
        return {}

    @expose(template = "ecrm.templates.page_report")
    @identity.require(identity.not_anonymous())
    #@identity.require(identity.in_any_group("Admin","KOHLS_TEAM"))
    @tabFocus(tab_type = "report")
    def report(self):
        return {}

    @expose(template = "ecrm.templates.page_access")
    @identity.require(identity.not_anonymous())
    @tabFocus(tab_type = "access")
    def access(self):
        return {}

    @expose(template = "ecrm.templates.login")
    def login(self, forward_url = None, previous_url = None, *args, **kw):

        if not identity.current.anonymous and identity.was_login_attempted() \
                and not identity.get_identity_errors():
            redirect(tg.url(forward_url or previous_url or '/', kw))

#        forward_url = None
#        previous_url = '/'

        if identity.was_login_attempted():
            msg = _("The credentials you supplied were not correct or "
                   "did not grant access to this resource.")
        elif identity.get_identity_errors():
            msg = _("You must provide your credentials before accessing "
                   "this resource.")
        else:
            msg = _("Please log in.")
            forward_url = request.headers.get("Referer", "/")

        response.status = 403
        return dict(message = msg, previous_url = previous_url, logging_in = True,
            original_parameters = request.params, forward_url = forward_url)

    @expose()
    def logout(self):
        identity.current.logout()
        redirect("/")


text:
.class public Lo/qV;
.super Ljava/io/IOException;

# direct methods
.method public constructor <init>(Ljava/lang/String;)V
    .locals 0

    invoke-direct {p0, p1}, Ljava/io/IOException;-><init>(Ljava/lang/String;)V

    return-void
.end method

.method static ʻ()Lo/qV;
    .locals 2

    new-instance v0, Lo/qV;

    const-string v1, "Protocol message tag had invalid wire type."

    invoke-direct {v0, v1}, Lo/qV;-><init>(Ljava/lang/String;)V

    return-object v0
.end method

.method static '()Lo/qV;
    .locals 2

    new-instance v0, Lo/qV;

    const-string v1, "Protocol message had too many levels of nesting.  May be malicious.  Use CodedInputStream.setRecursionLimit() to increase the depth limit."

    invoke-direct {v0, v1}, Lo/qV;-><init>(Ljava/lang/String;)V

    return-object v0
.end method

.method static ˊ()Lo/qV;
    .locals 2

    new-instance v0, Lo/qV;

    const-string v1, "While parsing a protocol message, the input ended unexpectedly in the middle of a field.  This could mean either than the input has been truncated or that an embedded message misreported its own length."

    invoke-direct {v0, v1}, Lo/qV;-><init>(Ljava/lang/String;)V

    return-object v0
.end method

.method static ˋ()Lo/qV;
    .locals 2

    new-instance v0, Lo/qV;

    const-string v1, "CodedInputStream encountered an embedded string or message which claimed to have negative size."

    invoke-direct {v0, v1}, Lo/qV;-><init>(Ljava/lang/String;)V

    return-object v0
.end method

.method static ˎ()Lo/qV;
    .locals 2

    new-instance v0, Lo/qV;

    const-string v1, "CodedInputStream encountered a malformed varint."

    invoke-direct {v0, v1}, Lo/qV;-><init>(Ljava/lang/String;)V

    return-object v0
.end method

.method static ˏ()Lo/qV;
    .locals 2

    new-instance v0, Lo/qV;

    const-string v1, "Protocol message contained an invalid tag (zero)."

    invoke-direct {v0, v1}, Lo/qV;-><init>(Ljava/lang/String;)V

    return-object v0
.end method

.method static ᐝ()Lo/qV;
    .locals 2

    new-instance v0, Lo/qV;

    const-string v1, "Protocol message end-group tag did not match expected tag."

    invoke-direct {v0, v1}, Lo/qV;-><init>(Ljava/lang/String;)V

    return-object v0
.end method


text:
<?php
namespace Elce\JWTAuthenticator\Bundle\Security;

use JWT;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;

/**
 * Class JWTUserProvider
 * @package Elce\JWTAuthenticator\Bundle\Security
 */
class JWTUserProvider implements UserProviderInterface
{
    /**
     * @param string   $jwt   The JWT token
     * @return mixed
     */
    public function decodeJWT($jwt)
    {
        return JWT::decode($jwt, '123456');
    }

    /**
     * {@inheritDoc}
     */
    public function loadUserByUsername($data)
    {
        return new User(
            $data->user_id,
            null,
            array('ROLE_USER')
        );
    }

    /**
     * {@inheritDoc}
     */
    public function refreshUser(UserInterface $user)
    {
        throw new UnsupportedUserException();
    }

    /**
     * {@inheritDoc}
     */
    public function supportsClass($class)
    {
        return 'Symfony\Component\Security\Core\User\User' === $class;
    }
}


text:
<root>
	<styles>
		<include src="s2r://panorama/styles/dotastyles.vcss_c" />
		<include src="file://{resources}/styles/libraries/containers/container.css" />
		<include src="file://{resources}/styles/libraries/containers/container_skins.css" />
	</styles>
	<scripts>
		<include src="file://{resources}/scripts/arena_util.js" />
		<include src="file://{resources}/scripts/libraries/containers/dota_inventory_item.js" />
	</scripts>
	<Panel class="ItemPanel" draggable="true">
		<Button id="ItemButton"
				onmouseover="ItemShowTooltip()"
				onmouseout="ItemHideTooltip()"
				onactivate="ActivateItem()"
				ondblclick="DoubleClickItem()"
				oncontextmenu="RightClickItem()"
				>
			<DOTAItemImage hittest="false" id="ItemImage" />
			<Panel hittest="false" id="Cooldown">
				<Panel hittest="false" id="CooldownOverlay" />
				<Label hittest="false" id="CooldownTimer" />
			</Panel>
			<Label hittest="false" class="" id="Stock"/>
			<Label hittest="false" class="Charges" id="ChargeCount" />
			<Label hittest="false" class="Charges" id="AltChargeCount" />
			<Label hittest="false" class="" id="ManaCost"/>
			<Label hittest="false" class="" id="Price"/>
			<Panel hittest="false" id="DropTargetHighlight" />
		</Button>
		<Panel hittest="false" id="Hotkey">
			<Panel hittest="false" id="HotkeyBlock" />
			<Label hittest="false" id="HotkeyText" />
		</Panel>
	</Panel>
</root>