from logging import DEBUG as _DEBUG
from logging import getLogger

from gi.repository import Gdk, GLib, Gtk
from gi.repository.GObject import TYPE_PYOBJECT
from logitech_receiver import hidpp10 as _hidpp10
from logitech_receiver.common import NamedInt as _NamedInt
from logitech_receiver.common import NamedInts as _NamedInts
from logitech_receiver.status import KEYS as _K
from solaar import NAME
from solaar.i18n import _, ngettext
# from solaar import __version__ as VERSION
from solaar.ui import ui_async as _ui_async

from . import action as _action
from . import config_panel as _config_panel
from . import icons as _icons
from .about import show_window as _show_about_window
from .diversion_rules import show_window as _show_diversion_window

_log = getLogger(__name__)
del getLogger

#
# constants
#

_SMALL_BUTTON_ICON_SIZE = Gtk.IconSize.MENU
_NORMAL_BUTTON_ICON_SIZE = Gtk.IconSize.BUTTON
_TREE_ICON_SIZE = Gtk.IconSize.BUTTON
_INFO_ICON_SIZE = Gtk.IconSize.LARGE_TOOLBAR
_DEVICE_ICON_SIZE = Gtk.IconSize.DND
try:
    import gi
    gi.check_version('3.7.4')
    _CAN_SET_ROW_NONE = None
except (ValueError, AttributeError):
    _CAN_SET_ROW_NONE = ''

# tree model columns
_COLUMN = _NamedInts(PATH=0, NUMBER=1, ACTIVE=2, NAME=3, ICON=4, STATUS_TEXT=5, STATUS_ICON=6, DEVICE=7)
_COLUMN_TYPES = (str, int, bool, str, str, str, str, TYPE_PYOBJECT)
_TREE_SEPATATOR = (None, 0, False, None, None, None, None, None)
assert len(_TREE_SEPATATOR) == len(_COLUMN_TYPES)
assert len(_COLUMN_TYPES) == len(_COLUMN)

#
# create UI layout
#

def _new_button(label, icon_name=None, icon_size=_NORMAL_BUTTON_ICON_SIZE, tooltip=None, toggle=False, clicked=None):
    b = Gtk.ToggleButton() if toggle else Gtk.Button()
    c = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 5)
    if icon_name:
        c.pack_start(Gtk.Image.new_from_icon_name(icon_name, icon_size), True, True, 0)
    if label:
        c.pack_start(Gtk.Label(label), True, True, 0)
    b.add(c)
    if clicked is not None:
        b.connect('clicked', clicked)
    if tooltip:
        b.set_tooltip_text(tooltip)
    if not label and icon_size < _NORMAL_BUTTON_ICON_SIZE:
        b.set_relief(Gtk.ReliefStyle.NONE)
        b.set_focus_on_click(False)
    return b

def _create_receiver_panel():
    p = Gtk.Box.new(Gtk.Orientation.VERTICAL, 4)

    p._count = Gtk.Label()
    p._count.set_padding(24, 0)
    p._count.set_alignment(0, 0.5)
    p.pack_start(p._count, True, True, 0)

    p._scanning = Gtk.Label(_('Scanning') + '...')
    p._spinner = Gtk.Spinner()

    bp = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 8)
    bp.pack_start(Gtk.Label(' '), True, True, 0)
    bp.pack_start(p._scanning, False, False, 0)
    bp.pack_end(p._spinner, False, False, 0)
    p.pack_end(bp, False, False, 0)

    return p

def _create_device_panel():
    p = Gtk.Box.new(Gtk.Orientation.VERTICAL, 4)

    def _status_line(label_text):
        b = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 8)
        b.set_size_request(10, 28)

        b._label = Gtk.Label(label_text)
        b._label.set_alignment(0, 0.5)
        b._label.set_size_request(170, 10)
        b.pack_start(b._label, False, False, 0)

        b._icon = Gtk.Image()
        b.pack_start(b._icon, False, False, 0)

        b._text = Gtk.Label()
        b._text.set_alignment(0, 0.5)
        b.pack_start(b._text, True, True, 0)

        return b

    p._battery = _status_line(_('Battery'))
    p.pack_start(p._battery, False, False, 0)

    p._secure = _status_line(_('Wireless Link'))
    p._secure._icon.set_from_icon_name('dialog-warning', _INFO_ICON_SIZE)
    p.pack_start(p._secure, False, False, 0)

    p._lux = _status_line(_('Lighting'))
    p.pack_start(p._lux, False, False, 0)

    #    p.pack_start(Gtk.Separator.new(Gtk.Orientation.HORIZONTAL), False, False, 0)  # spacer

    p._config = _config_panel.create()
    p.pack_end(p._config, True, True, 4)

    return p

def _create_details_panel():
    p = Gtk.Frame()
    p.set_shadow_type(Gtk.ShadowType.NONE)
    p.set_size_request(240, 0)
    p.set_state_flags(Gtk.StateFlags.ACTIVE, True)

    p._text = Gtk.Label()
    p._text.set_padding(6, 4)
    p._text.set_alignment(0, 0)
    p._text.set_selectable(True)
    p.add(p._text)

    return p

def _create_buttons_box():
    bb = Gtk.ButtonBox(Gtk.Orientation.HORIZONTAL)
    bb.set_layout(Gtk.ButtonBoxStyle.END)

    bb._details = _new_button(
        None,
        'dialog-information',
        _SMALL_BUTTON_ICON_SIZE,
        tooltip=_('Show Technical Details'),
        toggle=True,
        clicked=_update_details
    )
    bb.add(bb._details)
    bb.set_child_secondary(bb._details, True)
    bb.set_child_non_homogeneous(bb._details, True)

    def _pair_new_device(trigger):
        assert _find_selected_device_id() is not None
        receiver = _find_selected_device()
        assert receiver is not None
        assert bool(receiver)
        assert receiver.kind is None
        _action.pair(_window, receiver)

    bb._pair = _new_button(_('Pair new device'), 'list-add', clicked=_pair_new_device)
    bb.add(bb._pair)

    def _unpair_current_device(trigger):
        assert _find_selected_device_id() is not None
        device = _find_selected_device()
        assert device is not None
        assert bool(device)
        assert device.kind is not None
        _action.unpair(_window, device)

    bb._unpair = _new_button(_('Unpair'), 'edit-delete', clicked=_unpair_current_device)
    bb.add(bb._unpair)

    return bb

def _create_empty_panel():
    p = Gtk.Label()
    p.set_markup('' + _('Select a device') + '')
    p.set_sensitive(False)

    return p

def _create_info_panel():
    p = Gtk.Box.new(Gtk.Orientation.VERTICAL, 4)

    p._title = Gtk.Label(' ')
    p._title.set_alignment(0, 0.5)
    p._icon = Gtk.Image()

    b1 = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 4)
    b1.pack_start(p._title, True, True, 0)
    b1.pack_start(p._icon, False, False, 0)
    p.pack_start(b1, False, False, 0)

    p.pack_start(Gtk.Separator.new(Gtk.Orientation.HORIZONTAL), False, False, 0)  # spacer

    p._receiver = _create_receiver_panel()
    p.pack_start(p._receiver, True, True, 0)

    p._device = _create_device_panel()
    p.pack_start(p._device, True, True, 0)

    p.pack_start(Gtk.Separator.new(Gtk.Orientation.HORIZONTAL), False, False, 0)  # spacer

    p._buttons = _create_buttons_box()
    p.pack_end(p._buttons, False, False, 0)

    return p

def _create_tree(model):
    tree = Gtk.TreeView()
    tree.set_size_request(330, 0)  # enough width for simple setups
    tree.set_headers_visible(False)
    tree.set_show_expanders(False)
    tree.set_level_indentation(20)
    # tree.set_fixed_height_mode(True)
    tree.set_enable_tree_lines(True)
    tree.set_reorderable(False)
    tree.set_enable_search(False)
    tree.set_model(model)

    def _is_separator(model, item, _ignore=None):
        return model.get_value(item, _COLUMN.PATH) is None

    tree.set_row_separator_func(_is_separator, None)

    icon_cell_renderer = Gtk.CellRendererPixbuf()
    icon_cell_renderer.set_property('stock-size', _TREE_ICON_SIZE)
    icon_column = Gtk.TreeViewColumn('Icon', icon_cell_renderer)
    icon_column.add_attribute(icon_cell_renderer, 'sensitive', _COLUMN.ACTIVE)
    icon_column.add_attribute(icon_cell_renderer, 'icon-name', _COLUMN.ICON)
    tree.append_column(icon_column)

    name_cell_renderer = Gtk.CellRendererText()
    name_column = Gtk.TreeViewColumn('device name', name_cell_renderer)
    name_column.add_attribute(name_cell_renderer, 'sensitive', _COLUMN.ACTIVE)
    name_column.add_attribute(name_cell_renderer, 'text', _COLUMN.NAME)
    name_column.set_expand(True)
    tree.append_column(name_column)
    tree.set_expander_column(name_column)

    status_cell_renderer = Gtk.CellRendererText()
    status_cell_renderer.set_property('scale', 0.85)
    status_cell_renderer.set_property('xalign', 1)
    status_column = Gtk.TreeViewColumn('status text', status_cell_renderer)
    status_column.add_attribute(status_cell_renderer, 'sensitive', _COLUMN.ACTIVE)
    status_column.add_attribute(status_cell_renderer, 'text', _COLUMN.STATUS_TEXT)
    status_column.set_expand(True)
    tree.append_column(status_column)

    battery_cell_renderer = Gtk.CellRendererPixbuf()
    battery_cell_renderer.set_property('stock-size', _TREE_ICON_SIZE)
    battery_column = Gtk.TreeViewColumn('status icon', battery_cell_renderer)
    battery_column.add_attribute(battery_cell_renderer, 'sensitive', _COLUMN.ACTIVE)
    battery_column.add_attribute(battery_cell_renderer, 'icon-name', _COLUMN.STATUS_ICON)
    tree.append_column(battery_column)

    return tree

def _create_window_layout():
    assert _tree is not None
    assert _details is not None
    assert _info is not None
    assert _empty is not None

    assert _tree.get_selection().get_mode() == Gtk.SelectionMode.SINGLE
    _tree.get_selection().connect('changed', _device_selected)

    tree_scroll = Gtk.ScrolledWindow()
    tree_scroll.add(_tree)
    tree_scroll.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
    tree_scroll.set_shadow_type(Gtk.ShadowType.IN)

    tree_panel = Gtk.Box.new(Gtk.Orientation.VERTICAL, 0)
    tree_panel.set_homogeneous(False)
    tree_panel.pack_start(tree_scroll, True, True, 0)
    tree_panel.pack_start(_details, False, False, 0)

    panel = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 16)
    panel.pack_start(tree_panel, False, False, 0)
    panel.pack_start(_info, True, True, 0)
    panel.pack_start(_empty, True, True, 0)

    bottom_buttons_box = Gtk.ButtonBox(Gtk.Orientation.HORIZONTAL)
    bottom_buttons_box.set_layout(Gtk.ButtonBoxStyle.START)
    bottom_buttons_box.set_spacing(20)
    quit_button = _new_button(_('Quit %s') % NAME, 'application-exit', _SMALL_BUTTON_ICON_SIZE, clicked=destroy)
    bottom_buttons_box.add(quit_button)
    about_button = _new_button(_('About %s') % NAME, 'help-about', _SMALL_BUTTON_ICON_SIZE, clicked=_show_about_window)
    bottom_buttons_box.add(about_button)
    diversion_button = _new_button(
        _('Rule Editor'), '', _SMALL_BUTTON_ICON_SIZE, clicked=lambda *_trigger: _show_diversion_window(_model)
    )
    bottom_buttons_box.add(diversion_button)
    bottom_buttons_box.set_child_secondary(diversion_button, True)

    # solaar_version = Gtk.Label()
    # solaar_version.set_markup('' + NAME + ' v' + VERSION + '')
    # bottom_buttons_box.add(solaar_version)
    # bottom_buttons_box.set_child_secondary(solaar_version, True)

    vbox = Gtk.Box.new(Gtk.Orientation.VERTICAL, 8)
    vbox.set_border_width(8)
    vbox.pack_start(panel, True, True, 0)
    vbox.pack_end(bottom_buttons_box, False, False, 0)
    vbox.show_all()

    _details.set_visible(False)
    _info.set_visible(False)
    return vbox

def _create(delete_action):
    window = Gtk.Window()
    window.set_title(NAME)
    window.set_role('status-window')

    # window.set_type_hint(Gdk.WindowTypeHint.UTILITY)
    # window.set_skip_taskbar_hint(True)
    # window.set_skip_pager_hint(True)
    window.connect('delete-event', delete_action)

    vbox = _create_window_layout()
    window.add(vbox)

    geometry = Gdk.Geometry()
    geometry.min_width = 600
    geometry.min_height = 320
    window.set_geometry_hints(vbox, geometry, Gdk.WindowHints.MIN_SIZE)
    window.set_position(Gtk.WindowPosition.CENTER)

    style = window.get_style_context()
    style.add_class('solaar')

    return window

#
# window updates
#

def _find_selected_device():
    selection = _tree.get_selection()
    model, item = selection.get_selected()
    return model.get_value(item, _COLUMN.DEVICE) if item else None

def _find_selected_device_id():
    selection = _tree.get_selection()
    model, item = selection.get_selected()
    if item:
        return _model.get_value(item, _COLUMN.PATH), _model.get_value(item, _COLUMN.NUMBER)

# triggered by changing selection in the tree
def _device_selected(selection):
    model, item = selection.get_selected()
    device = model.get_value(item, _COLUMN.DEVICE) if item else None
    # if _log.isEnabledFor(_DEBUG):
    #     _log.debug("window tree selected device %s", device)
    if device:
        _update_info_panel(device, full=True)
    else:
        # When removing a receiver, one of its children may get automatically selected
        # before the tree had time to remove them as well.
        # Rather than chase around for another device to select, just clear the selection.
        _tree.get_selection().unselect_all()
        _update_info_panel(None, full=True)

def _receiver_row(receiver_path, receiver=None):
    assert receiver_path
    r = _model.get_iter_first()
    while r:
        r = _model.iter_next(r)

    item = _model.get_iter_first()
    while item:
        # first row matching the path must be the receiver one
        if _model.get_value(item, _COLUMN.PATH) == receiver_path:
            return item
        item = _model.iter_next(item)

    if not item and receiver:
        icon_name = _icons.device_icon_name(receiver.name)
        status_text = None
        status_icon = None
        row_data = (receiver_path, 0, True, receiver.name, icon_name, status_text, status_icon, receiver)
        assert len(row_data) == len(_TREE_SEPATATOR)
        if _log.isEnabledFor(_DEBUG):
            _log.debug('new receiver row %s', row_data)
        item = _model.append(None, row_data)
        if _TREE_SEPATATOR:
            _model.append(None, _TREE_SEPATATOR)

    return item or None

def _device_row(receiver_path, device_number, device=None):
    assert receiver_path
    assert device_number is not None

    receiver_row = _receiver_row(receiver_path, None if device is None else device.receiver)

    if device_number == 0xFF or device_number == 0x0:  # direct-connected device, receiver row is device row
        if receiver_row:
            return receiver_row
        item = None
        new_child_index = 0
    else:
        item = _model.iter_children(receiver_row)
        new_child_index = 0
        while item:
            if _model.get_value(item, _COLUMN.PATH) != receiver_path:
                _log.warn(
                    'path for device row %s different from path for receiver %s', _model.get_value(item, _COLUMN.PATH),
                    receiver_path
                )
            item_number = _model.get_value(item, _COLUMN.NUMBER)
            if item_number == device_number:
                return item
            if item_number > device_number:
                item = None
                break
            new_child_index += 1
            item = _model.iter_next(item)

    if not item and device:
        icon_name = _icons.device_icon_name(device.name, device.kind)
        status_text = None
        status_icon = None
        row_data = (
            receiver_path, device_number, bool(device.online), device.codename, icon_name, status_text, status_icon, device
        )
        assert len(row_data) == len(_TREE_SEPATATOR)
        if _log.isEnabledFor(_DEBUG):
            _log.debug('new device row %s at index %d', row_data, new_child_index)
        item = _model.insert(receiver_row, new_child_index, row_data)

    return item or None

#
#
#

def select(receiver_path, device_number=None):
    assert _window
    assert receiver_path is not None
    if device_number is None:
        item = _receiver_row(receiver_path)
    else:
        item = _device_row(receiver_path, device_number)
    if item:
        selection = _tree.get_selection()
        selection.select_iter(item)
    else:
        _log.warn('select(%s, %s) failed to find an item', receiver_path, device_number)

def _hide(w, _ignore=None):
    assert w == _window
    # some window managers move the window to 0,0 after hide()
    # so try to remember the last position
    position = _window.get_position()
    _window.hide()
    _window.move(*position)
    return True

def popup(trigger=None, receiver_path=None, device_id=None):
    if receiver_path:
        select(receiver_path, device_id)
    _window.present()
    return True

def toggle(trigger=None):
    if _window.get_visible():
        _hide(_window)
    else:
        _window.present()

#
#
#

def _update_details(button):
    assert button
    visible = button.get_active()

    if visible:
        # _details._text.set_markup('reading...')

        def _details_items(device, read_all=False):
            # If read_all is False, only return stuff that is ~100% already
            # cached, and involves no HID++ calls.

            yield (_('Path'), device.path)
            if device.kind is None:
                # 046d is the Logitech vendor id
                yield (_('USB ID'), '046d:' + device.product_id)

                if read_all:
                    yield (_('Serial'), device.serial)
                else:
                    yield (_('Serial'), '...')

            else:
                # yield ('Codename', device.codename)
                yield (_('Index'), device.number)
                if device.wpid:
                    yield (_('Wireless PID'), device.wpid)
                if device.product_id:
                    yield (_('Product ID'), '046d:' + device.product_id)
                hid_version = device.protocol
                yield (_('Protocol'), 'HID++ %1.1f' % hid_version if hid_version else _('Unknown'))
                if read_all and device.polling_rate:
                    yield (
                        _('Polling rate'), _('%(rate)d ms (%(rate_hz)dHz)') % {
                            'rate': device.polling_rate,
                            'rate_hz': 1000 // device.polling_rate
                        }
                    )

                if read_all or not device.online:
                    yield (_('Serial'), device.serial)
                else:
                    yield (_('Serial'), '...')
                if read_all and device.unitId and device.unitId != device.serial:
                    yield (_('Unit ID'), device.unitId)

            if read_all:
                if device.firmware:
                    for fw in list(device.firmware):
                        yield ('  ' + _(str(fw.kind)), (fw.name + ' ' + fw.version).strip())
            elif device.kind is None or device.online:
                yield ('  %s' % _('Firmware'), '...')

            flag_bits = device.status.get(_K.NOTIFICATION_FLAGS)
            if flag_bits is not None:
                flag_names = ('(%s)' % _('none'), ) if flag_bits == 0 else _hidpp10.NOTIFICATION_FLAG.flag_names(flag_bits)
                yield (_('Notifications'), ('\n%15s' % ' ').join(flag_names))

        def _set_details(text):
            _details._text.set_markup(text)

        def _make_text(items):
            text = '\n'.join('%-13s: %s' % (name, value) for name, value in items)
            return '<tt>' + text + '</tt>'

        def _displayable_items(items):
            for name, value in items:
                value = GLib.markup_escape_text(str(value).replace('\x00', '')).strip()
                if value:
                    yield name, value

        def _read_slow(device):
            items = _details_items(selected_device, True)
            items = _displayable_items(items)
            text = _make_text(items)
            if device == _details._current_device:
                GLib.idle_add(_set_details, text)

        selected_device = _find_selected_device()
        assert selected_device
        _details._current_device = selected_device

        read_all = not (selected_device.kind is None or selected_device.online)
        items = _details_items(selected_device, read_all)
        _set_details(_make_text(items))

        if read_all:
            _details._current_device = None
        else:
            _ui_async(_read_slow, selected_device)

    _details.set_visible(visible)

def _update_receiver_panel(receiver, panel, buttons, full=False):
    assert receiver

    devices_count = len(receiver)

    paired_text = _(
        _('No device paired.')
    ) if devices_count == 0 else ngettext('%(count)s paired device.', '%(count)s paired devices.', devices_count) % {
        'count': devices_count
    }

    if (receiver.max_devices > 0):
        paired_text += '\n\n%s' % ngettext(
            'Up to %(max_count)s device can be paired to this receiver.',
            'Up to %(max_count)s devices can be paired to this receiver.', receiver.max_devices
        ) % {
            'max_count': receiver.max_devices
        }
    elif devices_count > 0:
        paired_text += '\n\n%s' % _('Only one device can be paired to this receiver.')
    pairings = receiver.remaining_pairings()
    if (pairings is not None and pairings >= 0):
        paired_text += '\n%s' % (
            ngettext('This receiver has %d pairing remaining.', 'This receiver has %d pairings remaining.', pairings) %
            pairings
        )

    panel._count.set_markup(paired_text)

    is_pairing = receiver.status.lock_open
    if is_pairing:
        panel._scanning.set_visible(True)
        if not panel._spinner.get_visible():
            panel._spinner.start()
        panel._spinner.set_visible(True)
    else:
        panel._scanning.set_visible(False)
        if panel._spinner.get_visible():
            panel._spinner.stop()
        panel._spinner.set_visible(False)

    panel.set_visible(True)

    # b._insecure.set_visible(False)
    buttons._unpair.set_visible(False)

    if not is_pairing and (receiver.remaining_pairings() is None or receiver.remaining_pairings() != 0) and \
       (receiver.re_pairs or devices_count < receiver.max_devices):
        buttons._pair.set_sensitive(True)
    else:
        buttons._pair.set_sensitive(False)

    buttons._pair.set_visible(True)

def _update_device_panel(device, panel, buttons, full=False):
    assert device
    is_online = bool(device.online)
    panel.set_sensitive(is_online)

    if device.status.get(_K.BATTERY_LEVEL) is None:
        device.status.read_battery(device)

    battery_level = device.status.get(_K.BATTERY_LEVEL)
    battery_voltage = device.status.get(_K.BATTERY_VOLTAGE)
    if battery_level is None and battery_voltage is None:
        panel._battery.set_visible(False)
    else:
        panel._battery.set_visible(True)
        battery_next_level = device.status.get(_K.BATTERY_NEXT_LEVEL)
        charging = device.status.get(_K.BATTERY_CHARGING)
        icon_name = _icons.battery(battery_level, charging)
        panel._battery._icon.set_from_icon_name(icon_name, _INFO_ICON_SIZE)
        panel._battery._icon.set_sensitive(True)
        panel._battery._text.set_sensitive(is_online)

        if battery_voltage is not None:
            panel._battery._label.set_text(_('Battery Voltage'))
            text = '%dmV' % battery_voltage
            tooltip_text = _('Voltage reported by battery')
        else:
            panel._battery._label.set_text(_('Battery Level'))
            text = ''
            tooltip_text = _('Approximate level reported by battery')
        if battery_voltage is not None and battery_level is not None:
            text += ', '
        if battery_level is not None:
            text += _(str(battery_level)) if isinstance(battery_level, _NamedInt) else '%d%%' % battery_level
        if battery_next_level is not None and not charging:
            if isinstance(battery_next_level, _NamedInt):
                text += ' (' + _('next reported ') + _(str(battery_next_level)) + ')'
            else:
                text += ' (' + _('next reported ') + ('%d%%' % battery_next_level) + ')'
            tooltip_text = tooltip_text + _(' and next level to be reported.')
        if is_online:
            if charging:
                text += ' (%s)' % _('charging')
        else:
            text += ' (%s)' % _('last known')

        panel._battery._text.set_markup(text)
        panel._battery.set_tooltip_text(tooltip_text)

    if device.status.get(_K.LINK_ENCRYPTED) is None:
        panel._secure.set_visible(False)
    elif is_online:
        panel._secure.set_visible(True)
        panel._secure._icon.set_visible(True)
        if device.status.get(_K.LINK_ENCRYPTED) is True:
            panel._secure._text.set_text(_('encrypted'))
            panel._secure._icon.set_from_icon_name('security-high', _INFO_ICON_SIZE)
            panel._secure.set_tooltip_text(_('The wireless link between this device and its receiver is encrypted.'))
        else:
            panel._secure._text.set_text(_('not encrypted'))
            panel._secure._icon.set_from_icon_name('security-low', _INFO_ICON_SIZE)
            panel._secure.set_tooltip_text(
                _(
                    'The wireless link between this device and its receiver is not encrypted.\n'
                    'This is a security issue for pointing devices, and a major security issue for text-input devices.'
                )
            )
    else:
        panel._secure.set_visible(True)
        panel._secure._icon.set_visible(False)
        panel._secure._text.set_markup('%s' % _('offline'))
        panel._secure.set_tooltip_text('')

    if is_online:
        light_level = device.status.get(_K.LIGHT_LEVEL)
        if light_level is None:
            panel._lux.set_visible(False)
        else:
            panel._lux._icon.set_from_icon_name(_icons.lux(light_level), _INFO_ICON_SIZE)
            panel._lux._text.set_text(_('%(light_level)d lux') % {'light_level': light_level})
            panel._lux.set_visible(True)
    else:
        panel._lux.set_visible(False)

    buttons._pair.set_visible(False)
    buttons._unpair.set_sensitive(device.receiver.may_unpair if device.receiver else False)
    buttons._unpair.set_visible(True)

    panel.set_visible(True)

    if full:
        _config_panel.update(device, is_online)

def _update_info_panel(device, full=False):
    if device is None:
        # no selected device, show the 'empty' panel
        _details.set_visible(False)
        _info.set_visible(False)
        _empty.set_visible(True)
        return

    # a receiver must be valid
    # a device must be paired
    assert device

    _info._title.set_markup('%s' % device.name)
    icon_name = _icons.device_icon_name(device.name, device.kind)
    _info._icon.set_from_icon_name(icon_name, _DEVICE_ICON_SIZE)

    if device.kind is None:
        _info._device.set_visible(False)
        _info._icon.set_sensitive(True)
        _info._title.set_sensitive(True)
        _update_receiver_panel(device, _info._receiver, _info._buttons, full)
    else:
        _info._receiver.set_visible(False)
        is_online = bool(device.online)
        _info._icon.set_sensitive(is_online)
        _info._title.set_sensitive(is_online)
        _update_device_panel(device, _info._device, _info._buttons, full)

    _empty.set_visible(False)
    _info.set_visible(True)

    if full:
        _update_details(_info._buttons._details)

#
# window layout:
#  +--------------------------------+
#  |  tree      | receiver  | empty |
#  |            | or device |       |
#  |------------| status    |       |
#  | details    |           |       |
#  |--------------------------------|
#  | (about)                        |
#  +--------------------------------|
# either the status or empty panel is visible at any point
# the details panel can be toggle on/off

_model = None
_tree = None
_details = None
_info = None
_empty = None
_window = None

def init(show_window, hide_on_close):
    Gtk.Window.set_default_icon_name(NAME.lower())
    Gtk.Window.set_default_icon_from_file(_icons.icon_file(NAME.lower()))

    global _model, _tree, _details, _info, _empty, _window
    _model = Gtk.TreeStore(*_COLUMN_TYPES)
    _tree = _create_tree(_model)
    _details = _create_details_panel()
    _info = _create_info_panel()
    _empty = _create_empty_panel()
    _window = _create(_hide if hide_on_close else destroy)
    if show_window:
        _window.present()

def destroy(_ignore1=None, _ignore2=None):
    global _model, _tree, _details, _info, _empty, _window
    w, _window = _window, None
    w.destroy()
    w = None
    _config_panel.destroy()

    _empty = None
    _info = None
    _details = None
    _tree = None
    _model = None

def update(device, need_popup=False, refresh=False):
    if _window is None:
        return

    assert device is not None

    if need_popup:
        popup()

    selected_device_id = _find_selected_device_id()

    if device.kind is None:  # receiver
        # receiver
        is_alive = bool(device)
        item = _receiver_row(device.path, device if is_alive else None)

        if is_alive and item:
            was_pairing = bool(_model.get_value(item, _COLUMN.STATUS_ICON))
            is_pairing = (not device.isDevice) and bool(device.status.lock_open)
            _model.set_value(item, _COLUMN.STATUS_ICON, 'network-wireless' if is_pairing else _CAN_SET_ROW_NONE)

            if selected_device_id == (device.path, 0):
                full_update = need_popup or was_pairing != is_pairing
                _update_info_panel(device, full=full_update)

        elif item:
            if _TREE_SEPATATOR:
                separator = _model.iter_next(item)
                if separator:
                    _model.remove(separator)
            _model.remove(item)

    else:
        path = device.receiver.path if device.receiver is not None else device.path
        assert device.number is not None and device.number >= 0, 'invalid device number' + str(device.number)
        item = _device_row(path, device.number, device if bool(device) else None)

        if bool(device) and item:
            update_device(device, item, selected_device_id, need_popup, full=refresh)
        elif item:
            _model.remove(item)
            _config_panel.clean(device)

    # make sure all rows are visible
    _tree.expand_all()

def update_device(device, item, selected_device_id, need_popup, full=False):
    was_online = _model.get_value(item, _COLUMN.ACTIVE)
    is_online = bool(device.online)
    _model.set_value(item, _COLUMN.ACTIVE, is_online)

    battery_level = device.status.get(_K.BATTERY_LEVEL)
    battery_voltage = device.status.get(_K.BATTERY_VOLTAGE)
    if battery_level is None:
        _model.set_value(item, _COLUMN.STATUS_TEXT, _CAN_SET_ROW_NONE)
        _model.set_value(item, _COLUMN.STATUS_ICON, _CAN_SET_ROW_NONE)
    else:
        if battery_voltage is not None and False:  # Use levels instead of voltage here
            status_text = '%(battery_voltage)dmV' % {'battery_voltage': battery_voltage}
        elif isinstance(battery_level, _NamedInt):
            status_text = _(str(battery_level))
        else:
            status_text = '%(battery_percent)d%%' % {'battery_percent': battery_level}
        _model.set_value(item, _COLUMN.STATUS_TEXT, status_text)

        charging = device.status.get(_K.BATTERY_CHARGING)
        icon_name = _icons.battery(battery_level, charging)
        _model.set_value(item, _COLUMN.STATUS_ICON, icon_name)

    _model.set_value(item, _COLUMN.NAME, device.codename)

    if selected_device_id is None or need_popup:
        select(device.receiver.path if device.receiver else device.path, device.number)
    elif selected_device_id == (device.receiver.path if device.receiver else device.path, device.number):
        full_update = full or was_online != is_online
        _update_info_panel(device, full=full_update)

def find_device(serial):
    assert serial, 'need serial number or unit ID to find a device'
    result = None

    def check(_store, _treepath, row):
        nonlocal result
        device = _model.get_value(row, _COLUMN.DEVICE)
        if device and device.kind and (device.unitId == serial or device.serial == serial):
            result = device
            return True

    _model.foreach(check)
    return result


import sys
from json import load as load_json

with open("data.json", "rt") as data:
    data = load_json(data)

data.sort(key=lambda mls: mls["code"])

tbody = ""
for mls in data:
    code, en, ru, es = mls["code"], mls["en"], mls.get("ru", None), mls.get("es", None)

    tbody += "
"
    tbody += "" + code + "	"
    tbody += ""
    tbody += "" + en["name"] + ""
    if ru is not None:
        tbody += "" + ru["name"] + ""
    else:
        tbody += ""
    if es is not None:
        tbody += "" + es["name"] + ""
    else:
        tbody += ""
    tbody += "en	"
    if ru is not None:
        tbody += "ru	"
    else:
        tbody += "ru	"
    if es is not None:
        tbody += "es	"
    else:
        tbody += "es	"
    tbody += "
"
    tbody += "
"
    tbody += ""
    tbody += "

" + en["description"] + "

" + en["explanation"] + "

"
    if ru is not None:
        tbody += "

" + ru["description"] + "

" + ru["explanation"] + "

"
    else:
        tbody += "

"
    if es is not None:
        tbody += "

" + es["description"] + "

" + es["explanation"] + "

"
    else:
        tbody += "

"
    tbody += "	"
    tbody += "
"

with open(sys.argv[1], "wt") as out:
    out.write("""<!DOCTYPE html><meta charset="UTF-8"><title>Переводы умений в Войнах Чатов</title><link rel='stylesheet' href='./table.css'>""")
    out.write("""

""" + tbody + """

""")


import numpy as np

class Scoords:
    @staticmethod
    def st_text_menu(st):
        st.header('Построение изображений 2D-кривых')

        st.subheader('Задание:')
        st.write('Написать и отладить программу, строящую изображение заданной замечательной кривой.')
        st.latex(r"ρ = {a\overϕ}, \qquad 0 < A \leq ϕ \leq B")
        st.markdown(r'''
            * $ρ,ϕ$- полярные координаты
            * $x,y$ – декартовы координаты t – независимый параметр.
            * $a,b, k,A,B$ - константы, значения которых выбираются пользователем.
        ''')
        b_default = float("{0:.1f}".format(2*np.pi))
        a_varible = st.slider('Выберите A', 0.01, b_default-0.04, step=0.01, value=3.13)
        b_varible = st.slider('Выберите B', a_varible, b_default, step=0.01, value=b_default)
        a_lower_case_varible = st.slider('Выберите a', -1, 1, step=2, value=1)
        st.latex(f'0 < {a_varible} \leq ϕ \leq {b_varible}')
        return a_varible, b_varible, a_lower_case_varible

    @staticmethod
    def logistic_func(a, p):
        return a/p


import heapq

class LLNode:
  def __init__(self, value):
    self.value = value
    self.next = None

  def __str__(self):
    return str(self.value) + "->" + str(self.next)

# Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

def mergeKSortedLinkedList(lists):
  heap = []
  current = head = LLNode(None)

  for node in lists:
    heapq.heappush(heap, (node.value, node))

  while heap:
    minNode = heapq.heappop(heap)[1]
    current.next = minNode
    current = current.next

    if minNode.next:
      heapq.heappush(heap, (minNode.next.value, minNode.next))

  return head.next

l1 = LLNode(1)
l1.next = LLNode(21)
l2 = LLNode(24)
l2.next = LLNode(83)

print (mergeKSortedLinkedList([l1, l2]))


import cv2
import numpy as numpy
import os

print(cv2.__version__)

def gotClicked(e,x,y,flags,params):
    if e==cv2.EVENT_LBUTTONDOWN:
        print('Coords: ', x, y)

imgOriginal = cv2.imread("./images/bales/bales.jpg")               # open image

cv2.namedWindow('frame')
cv2.setMouseCallback('frame', gotClicked)

if imgOriginal is None:                            # if image was not read successfully
    print("\nerror: image not read from file \n\n")  # print error message to std out
    os.system("pause")                                  # pause so user can see error message
    # end if

cv2.imshow('frame', imgOriginal)
cv2.waitKey(0)
cv2.destroyAllWindows()


from pflacco.pflacco import create_initial_sample, create_feature_object, calculate_feature_set, calculate_features
import numpy as np

# Load samples into x (list of genomes/observations) and y (list of fitnesses/objective values)
data_file = "all_genomes_rwg_homogeneous_team_nn_1_2_3_1_4_8_4_1_3_7_1_3.0_0.2_2_1000_500_5_0_linear_100000_normal_0_1_.csv"
f = open(data_file, "r")
lines = f.read().strip().split("\n")
x = np.array([np.array([float(element) for element in row.split(",")[0:-1]]) for row in lines])
y = np.array([float(row.split(",")[-1]) for row in lines])
x_mini = x[0:10001, :]
y_mini = y[0:10001]

# Create feature object. minimize=False because the objective is to maximise. Lower and upper are arbitrarily chosen to
# be outside the range of the sampled genomes
feat_object = create_feature_object(x=x_mini, y=y_mini, minimize=False, lower=-10, upper=10)
y_dist_features = calculate_feature_set(feat_object, 'ela_distr')
print(y_dist_features)


#给你一个字符串 croakOfFrogs，它表示不同青蛙发出的蛙鸣声（字符串 "croak" ）的组合。由于同一时间可以有多只青蛙呱呱作响，所以 croakOfFrogs 中会混合多个 “croak” 。请你返回模拟字符串中所有蛙鸣所需不同青蛙的最少数目。

#注意：要想发出蛙鸣 "croak"，青蛙必须 依序 输出 ‘c’, ’r’, ’o’, ’a’, ’k’ 这 5 个字母。如果没有输出全部五个字母，那么它就不会发出声音。

#如果字符串 croakOfFrogs 不是由若干有效的 "croak" 字符混合而成，请返回 -1 。

#来源：力扣（LeetCode）
#链接：https://leetcode-cn.com/problems/minimum-number-of-frogs-croaking
#著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
class Solution:
    def minNumberOfFrogs(self, croakOfFrogs: str) -> int:
        #c一定在最前--k一定在最后
        c,r,o,a,k=0,0,0,0,0
        ans=0
        for i in range(len(croakOfFrogs)):
            if croakOfFrogs[i]=="c":
                c+=1
            if croakOfFrogs[i]=="r":
                r+=1
            if croakOfFrogs[i]=="o":
                o+=1
            if croakOfFrogs[i]=="a":
                a+=1
            if croakOfFrogs[i]=="k":
                k+=1
            ans=max(c-k,ans)
            if(c>=r and r>=o and o>=a and a>=k):
                continue
            else:
                break
        if (c==r and r==o and o==a and a==k):
            return ans
        else:
            return -1


from typing import Optional

import tensorflow as tf
from tensorflow.python.ops import embedding_ops

from merlin.models.tf.blocks.sampling.base import EmbeddingWithMetadata, ItemSampler
from merlin.models.tf.typing import TabularData

@tf.keras.utils.register_keras_serializable(package="merlin.models")
class PopularityBasedSampler(ItemSampler):
    """
    Provides a popularity-based negative sampling for the softmax layer
    to ensure training efficiency when the catalog of items is very large.
    The capacity of the queue is fixed and is equal to the catalog size.
    For each batch, we sample `max_num_samples` unique negatives.

    This implementation does not require the actual item frequencies/probabilities
    distribution, but instead tries to approximate the item
    probabilities using the log_uniform (zipfian) distribution.
    The only requirement is that the item ids are decreasingly sorted by their count frequency.
    We use the default log-uniform (zipfian) sampler given by Tensorflow:
        [log_uniform_candidate_sampler](https://www.tensorflow.org/api_docs/python/tf/random/log_uniform_candidate_sampler)
    The `Categorify` op provided by nvtabular supports the frequency-based encoding as default.

    P.s. Ignoring the false negatives (negative items equal to the positive ones) is
    managed by `ItemRetrievalScorer(..., sampling_downscore_false_negatives=True)`

    Parameters
    ----------
    max_num_samples: int
        The number of unique negatives to sample at each batch.
    max_id: int
        The maximum id value to be sampled. It should be equal to the
        categorical feature cardinality
    min_id: int
        The minimum id value to be sampled. Useful to ignore the first categorical
        encoded ids, which are usually reserved for <nulls>, out-of-vocabulary or padding.
        Defaults to 0.
    seed: int
        Fix the random values returned by the sampler to ensure reproducibility
        Defaults to None
    item_id_feature_name: str
        Name of the column containing the item ids
        Defaults to `item_id`
    """

    def __init__(
        self,
        max_id: int,
        min_id: int = 0,
        max_num_samples: int = 100,
        seed: Optional[int] = None,
        item_id_feature_name: str = "item_id",
        **kwargs,
    ):
        super().__init__(max_num_samples=max_num_samples, **kwargs)
        self.max_id = max_id
        self.min_id = min_id
        self.seed = seed
        self.item_id_feature_name = item_id_feature_name

        assert (
            self.max_num_samples <= self.max_id
        ), f"Number of items to sample `{self.max_num_samples}`"
        f" should be less than total number of ids `{self.max_id}`"

    def _check_inputs(self, inputs):
        assert (
            self.item_id_feature_name in inputs["metadata"]
        ), "The 'item_id' metadata feature is required by PopularityBasedSampler."

    def add(self, embeddings: tf.Tensor, items_metadata: TabularData, training=True):
        pass

    def call(
        self, inputs: TabularData, item_weights: tf.Tensor, training=True
    ) -> EmbeddingWithMetadata:
        if training:
            self._check_inputs(inputs)

        tf.assert_equal(
            int(tf.shape(item_weights)[0]),
            self.max_id + 1,
            "The first dimension of the items embeddings "
            f"({int(tf.shape(item_weights)[0])}) and "
            f"the the number of possible classes ({self.max_id+1}) should match.",
        )

        items_embeddings = self.sample(item_weights)
        return items_embeddings

    def _required_features(self):
        return [self.item_id_feature_name]

    def sample(self, item_weights) -> EmbeddingWithMetadata:  # type: ignore
        sampled_ids, _, _ = tf.random.log_uniform_candidate_sampler(
            true_classes=tf.ones((1, 1), dtype=tf.int64),
            num_true=1,
            num_sampled=self.max_num_samples,
            unique=True,
            range_max=self.max_id - self.min_id,
            seed=self.seed,
        )

        # Shifting the sampled ids to ignore the first ids (usually reserved for nulls, OOV)
        sampled_ids += self.min_id

        items_embeddings = embedding_ops.embedding_lookup(item_weights, sampled_ids)

        return EmbeddingWithMetadata(
            items_embeddings,
            metadata={self.item_id_feature_name: tf.cast(sampled_ids, tf.int32)},
        )

    def get_distribution_probs(self):
        """Tries to approximate the log uniform (zipfian) distribution
        used by tf.random.log_uniform_candidate_sampler
        (https://www.tensorflow.org/api_docs/python/tf/random/log_uniform_candidate_sampler)

        Returns
        -------
        tf.Tensor
            A tensor with the expected probability distribution of item ids
            assuming log-uniform (zipfian) distribution
        """
        range_max = self.max_id - self.min_id
        ids = tf.range(0, range_max, dtype=tf.float32)
        estimated_probs = (tf.math.log(ids + 2.0) - tf.math.log(ids + 1.0)) / tf.math.log(
            range_max + 1.0
        )
        # Appending zero(s) in the beginning as padding items should never be samples
        # (thus prob must be zero)
        estimated_probs = tf.concat(
            [tf.zeros(self.min_id + 1, dtype=tf.float32), estimated_probs], axis=0
        )
        return estimated_probs

    def get_config(self):
        config = super().get_config()
        config["max_id"] = self.max_id
        config["min_id"] = self.min_id
        config["max_num_samples"] = self.max_num_samples
        config["seed"] = self.seed
        config["item_id_feature_name"] = self.item_id_feature_name

        return config


import os
import platform

from argparse import (
    ArgumentParser,
    _SubParsersAction,
)

from async_service import background_asyncio_service
from eth_utils import ValidationError

from lahja.base import EndpointAPI

from trinity.boot_info import BootInfo
from trinity.constants import (
    MAINNET_NETWORK_ID,
    ROPSTEN_NETWORK_ID,
)
from trinity.extensibility import (
    AsyncioIsolatedComponent,
)

from trinity.components.builtin.ethstats.ethstats_service import (
    EthstatsService,
)

DEFAULT_SERVERS_URLS = {
    MAINNET_NETWORK_ID: 'wss://ethstats.net/api',
    ROPSTEN_NETWORK_ID: 'wss://ropsten-stats.parity.io/api',
}

def get_default_server_url(network_id: int) -> str:
    return DEFAULT_SERVERS_URLS.get(network_id, '')

class EthstatsComponent(AsyncioIsolatedComponent):
    name = 'ethstats'

    server_url: str
    server_secret: str
    stats_interval: int
    node_id: str
    node_contact: str

    @classmethod
    def configure_parser(cls, arg_parser: ArgumentParser, subparser: _SubParsersAction) -> None:
        ethstats_parser = arg_parser.add_argument_group('ethstats (experimental)')

        ethstats_parser.add_argument(
            '--enable-ethstats',
            action='store_true',
            help='Enable node stats reporting service',
        )

        ethstats_parser.add_argument(
            '--ethstats-server-url',
            help='Node stats server URL (e. g. wss://example.com/api)',
            default=os.environ.get('ETHSTATS_SERVER_URL'),
        )
        ethstats_parser.add_argument(
            '--ethstats-server-secret',
            help='Node stats server secret',
            default=os.environ.get('ETHSTATS_SERVER_SECRET'),
        )
        ethstats_parser.add_argument(
            '--ethstats-node-id',
            help='Node ID for stats server',
            default=os.environ.get('ETHSTATS_NODE_ID', platform.node()),
        )
        ethstats_parser.add_argument(
            '--ethstats-node-contact',
            help='Node contact information for stats server',
            default=os.environ.get('ETHSTATS_NODE_CONTACT', ''),
        )
        ethstats_parser.add_argument(
            '--ethstats-interval',
            help='The interval at which data is reported back',
            default=10,
        )

    @classmethod
    def validate_cli(cls, boot_info: BootInfo) -> None:
        args = boot_info.args

        if not args.enable_ethstats:
            return

        network_id = boot_info.trinity_config.network_id

        if not (args.ethstats_server_url or get_default_server_url(network_id)):
            raise ValidationError(
                'You must provide ethstats server url using the `--ethstats-server-url`'
            )

        if not args.ethstats_server_secret:
            raise ValidationError(
                'You must provide ethstats server secret using `--ethstats-server-secret`'
            )

    @property
    def is_enabled(self) -> bool:
        return bool(self._boot_info.args.enable_ethstats)

    async def do_run(self, event_bus: EndpointAPI) -> None:
        boot_info = self._boot_info
        args = boot_info.args

        if args.ethstats_server_url:
            server_url = args.ethstats_server_url
        else:
            server_url = get_default_server_url(boot_info.trinity_config.network_id)

        service = EthstatsService(
            boot_info,
            event_bus,
            server_url,
            args.ethstats_server_secret,
            args.ethstats_node_id,
            args.ethstats_node_contact,
            args.ethstats_interval,
        )

        async with background_asyncio_service(service) as manager:
            await manager.wait_finished()


from .AccidentData import AccidentData

class FullAccidentData(AccidentData):
    """Clase que describe los datos entregados por el cliente sobre accidentes viales"""
    def __init__(self, information):
        super().__init__()

        self.client = information.client
        self.client_name = information.client_name
        self.client_contact = information.client_contact
        self.client_phone = information.client_phone
        self.data_origin = information.data_origin

        self.id_accident = 0
        self.date = None
        self.day_week = ""
        self.month = ""
        self.year = ""
        self.location = ""
        self.abs_design = 0
        self.n_incident = 0
        self.vehicles_involved = ""
        self.total_injured = 0
        self.total_death = 0
        self.total_minor_injured = 0
        self.total_serious_injured = 0
        self.accident_class = ""
        self.infrastructure_affected = ""
        self.accident_type = ""
        self.accident_cause = ""
        self.conditions = ""
        self.description = ""
        self.post_accident_actions = None

    def set_id_accident(self, x):
        if x is "":
            self.id_accident = float('nan')
        else:
            self.id_accident = int(x)

    def set_date(self, x):
        if x is "":
            self.date = float('nan')
        else:
            self.date = x

    def set_day_week(self, x):
        if x is "":
            self.day_week = float('nan')
        else:
            self.day_week = x

    def set_month(self, x):
        if x is "":
            self.month = float('nan')
        else:
            self.month = x

    def set_year(self, x):
        if x is "":
            self.year = float('nan')
        else:
            self.year = int(x)

    def set_location(self, x):
        if x is "":
            self.location = float('nan')
        else:
            self.location = x

    def set_abs_design(self, x):
        if x is "":
            self.abs_design = float('nan')
        else:
            self.abs_design = x

    def set_n_incident(self, x):
        if x is "":
            self.n_incident = float('nan')
        else:
            self.n_incident = int(x)

    def set_vehicles_involved(self, x):
        if x is "":
            self.vehicles_involved = float('nan')
        else:
            self.vehicles_involved = x

    def set_total_injured(self, x):
        if x is "":
            self.total_injured = float('nan')
        else:
            self.total_injured = int(x)

    def set_total_death(self, x):
        if x is "":
            self.total_death = float('nan')
        else:
            self.total_death = int(x)

    def set_total_minor_injured(self, x):
        if x is "":
            self.total_minor_injured = float('nan')
        else:
            self.total_minor_injured = int(x)

    def set_total_serious_injured(self, x):
        if x is "":
            self.total_serious_injured = float('nan')
        else:
            self.total_serious_injured = int(x)

    def set_accident_class(self, x):
        if x is "":
            self.accident_class = float('nan')
        else:
            self.accident_class = x

    def set_infrastructure_affected(self, x):
        if x is "":
            self.infrastructure_affected = float('nan')
        else:
            self.infrastructure_affected = x

    def set_accident_type(self, x):
        if x is "":
            self.accident_type = float('nan')
        else:
            self.accident_type = x

    def set_accident_cause(self, x):
        if x is "":
            self.accident_cause = float('nan')
        else:
            self.accident_cause = x

    def set_conditions(self, x):
        if x is "":
            self.conditions = float('nan')
        else:
            self.conditions = x

    def set_description(self, x):
        if x is "":
            self.description = float('nan')
        else:
            self.description = x


from DirectoryTreeNode import DirectoryTreeNode

class DaySeven:

    def __init__(self, input_path):
        self.input_path = input_path

    def get_small_dir_sum(self, root, max_threshold):

        # check if root is a file with size > 0
        if 0 < root.size:
            return 0, root.size

        small_dir_sum = 0
        total_size = 0

        for child in root.children:
            find_small_directories_result = self.get_small_dir_sum(child, max_threshold)
            small_dir_sum += find_small_directories_result[0]
            total_size += find_small_directories_result[1]

        # check if root is a directory with total size <= threshold
        if root.size == 0 and total_size <= max_threshold:
            small_dir_sum += total_size

        if root.parent == None:
            return small_dir_sum
        else:
            return small_dir_sum, total_size

    def get_smallest_dir_size(self, root, min_threshold=0):

        # check if root is a file with size > 0
        if 0 < root.size:
            return root.size

        total_size = 0
        smallest_child_dir_sizes = []

        for child in root.children:
            if 0 < child.size:
                total_size += child.size
            else:
                smallest_child_dir_sizes.append(self.get_smallest_dir_size(child, min_threshold))

        smallest_child_dir_sizes.sort()

        # if exists, return the smallest dir size <= min_threshold
        for smallest_child_dir_size in smallest_child_dir_sizes:
            if min_threshold <= smallest_child_dir_size:
                return smallest_child_dir_size

            total_size += smallest_child_dir_size

        return total_size

    def main(self, part):

        f = open(self.input_path, "r")

        root_node = None
        current_node = None
        total_size = 0

        # build the directory tree
        for line in f:
            line_split = line.split()

            # create and traverse directories
            if line_split[0] == "$" and line_split[1] == "cd":
                dir_name = line_split[2]

                if current_node == None:
                    root_node = DirectoryTreeNode(dir_name)
                    current_node = root_node
                elif dir_name == "..":
                    current_node = current_node.parent
                else:
                    new_child_node = DirectoryTreeNode(dir_name)
                    current_node.add_child(new_child_node)
                    current_node = new_child_node

            # create files in current directory node
            elif line_split[0] != "$" and line_split[0] != "dir":
                file_size = int(line_split[0])
                total_size += file_size
                current_node.add_child(DirectoryTreeNode(line_split[1], file_size))

        if part == 1:
            return self.get_small_dir_sum(root_node, 100000)

        else:
            used_disk_space = root_node.get_total_size()
            free_disk_space = 70000000 - used_disk_space
            smallest_dir_size_min_threshold = 30000000 - free_disk_space
            return self.get_smallest_dir_size(root_node, smallest_dir_size_min_threshold)

day_seven = DaySeven("Input/DaySevenInput.txt")

print("Part One: " + str(day_seven.main(1)))

print("Part Two: " + str(day_seven.main(2)))


import math
import torch
import torch.nn as nn

class LSTM(nn.Module):
    """
    Own implementation of LSTM cell.
    """

    def __init__(self, lstm_hidden_dim, embedding_size):
        """
        Initialize all parameters of the LSTM class.

        Parameters
        ----------
        lstm_hidden_dim : int
            hidden state dimension.
        embedding_size : int
            size of embedding (and hence input sequence).
        """
        super(LSTM, self).__init__()
        self.hidden_dim = lstm_hidden_dim
        self.embed_dim = embedding_size
        #######################
        # PUT YOUR CODE HERE  #
        #######################
        # embedding weights
        self.w_x = nn.Parameter(
            torch.zeros(4 * self.hidden_dim, self.embed_dim), requires_grad=True
        )
        self.w_h = nn.Parameter(
            torch.zeros(4 * self.hidden_dim, self.hidden_dim), requires_grad=True
        )
        # bias
        self.b_g = nn.Parameter(torch.zeros(self.hidden_dim), requires_grad=True)
        self.b_i = nn.Parameter(torch.zeros(self.hidden_dim), requires_grad=True)
        self.b_f = nn.Parameter(torch.zeros(self.hidden_dim), requires_grad=True)
        self.b_o = nn.Parameter(torch.zeros(self.hidden_dim), requires_grad=True)
        # cell and hidden state
        self.h = None
        self.c = None
        #######################
        # END OF YOUR CODE    #
        #######################
        self.init_parameters()

    def init_parameters(self):
        """
        Parameters initialization.

        Parameters
        ----------
        self.parameters: list of all parameters.
        self.hidden_dim: hidden state dimension.
        """
        #######################
        # PUT YOUR CODE HERE  #
        #######################
        for param in self.parameters():
            # initialize weights as specified by inst
            nn.init.uniform_(
                param, -1 / math.sqrt(self.hidden_dim), 1 / math.sqrt(self.hidden_dim)
            )
        # add one to forget gate bias
        with torch.no_grad():
            self.b_f += 1
        #######################
        # END OF YOUR CODE    #
        #######################

    def forward(self, embeds):
        """
        Forward pass of LSTM.

        Parameters
        ----------
        embeds : array-like
            embedded input sequence with shape
            (input length, batch size, embedding_size)

        Returns
        -------
        output : array-like
            output of LSTM with shape
            (input length, batch size, hidden_size)
        """
        #
        #######################
        # PUT YOUR CODE HERE  #
        #######################

        # initialize output, ensuring its on the same device as embeds
        output = torch.zeros(
            (embeds.shape[0], embeds.shape[1], self.hidden_dim), device=self.w_x.device
        )
        # initialize hidden and cell states if necessary
        if self.h is None:
            self.h = torch.zeros(
                embeds.shape[1], self.hidden_dim, device=self.w_x.device
            )
        if self.c is None:
            self.c = torch.zeros(
                embeds.shape[1], self.hidden_dim, device=self.w_h.device
            )
        # LSTM computation
        for j, seq_el in enumerate(embeds):
            biases = torch.hstack((self.b_i, self.b_f, self.b_o, self.b_g))
            opt_mult = seq_el @ self.w_x.T + self.h @ self.w_h.T + biases
            i, f, o, g = torch.chunk(opt_mult, 4, dim=1)
            g = torch.tanh(g)
            i = torch.sigmoid(i)
            f = torch.sigmoid(f)
            o = torch.sigmoid(o)
            self.c = g * i + self.c * f
            self.h = torch.tanh(self.c) * o
            output[j] = self.h
        return output
        #######################
        # END OF YOUR CODE    #
        #######################

class TextGenerationModel(nn.Module):
    """
    This module uses your implemented LSTM cell for text modelling.
    It should take care of the character embedding,
    and linearly maps the output of the LSTM to your vocabulary.
    """

    def __init__(self, args):
        """
        Initializing the components of the TextGenerationModel.

        Parameters
        ----------
        args.vocabulary_size: int
            The size of the vocabulary.
        args.embedding_size: int
            The size of the embedding.
        args.lstm_hidden_dim: int
            The dimension of the hidden state in the LSTM cell.
        """
        super(TextGenerationModel, self).__init__()
        #######################
        # PUT YOUR CODE HERE  #
        #######################
        self.embedding = nn.Embedding(args.vocabulary_size, args.embedding_size)
        self.lstm = LSTM(args.lstm_hidden_dim, args.embedding_size)
        self.linear = nn.Linear(args.lstm_hidden_dim, args.vocabulary_size)
        self.vocabulary_size = args.vocabulary_size
        #######################
        # END OF YOUR CODE    #
        #######################

    def forward(self, x):
        """
        Forward pass.

        Parameters
        ----------
        x : array-like
            input sequence with shape (seq_len, batch_size)
        """
        #######################
        # PUT YOUR CODE HERE  #
        #######################
        # embedding gives (seq_len, batch_size, embedding_size)
        x = self.embedding(x)
        # lstm forward gives (seq_len, batch_size, hidden_size)
        x = self.lstm(x)
        # linear forward gives (seq_len, batch_size, vocabulary_size)
        out = self.linear(x)
        return out
        #######################
        # END OF YOUR CODE    #
        #######################

    def sample(self, batch_size=4, sample_length=30, temperature=0.0):
        """
        Sampling from the text generation model.

        Parameters
        ----------
        batch_size : int
            Number of samples to return
        sample_length : int
            length of desired sample.
        temperature: float
            temperature of the sampling process (see exercise sheet for definition).

        Returns
        -------
        samples : array-like
            samples with shape (sample_length, batch_size)
        """
        #######################
        # PUT YOUR CODE HERE  #
        #######################
        # initialize characters randomly
        chars = torch.randint(self.vocabulary_size, (sample_length, batch_size))

        # overwrite all chars except first with sampled characters
        for step in range(1, sample_length):
            # use previous step, hidden/cell state are stored and kept track of BTS
            pred = self.forward(chars[step - 1].view(1, -1))[-1]
            # pred is of shape (1, batch_size, vocabulary_size)
            if temperature == 0:
                # argmax gives (1, batch_size)
                new_char = pred.argmax(dim=-1)
            else:
                # randomly sample using temperature-scaled softmax weights
                new_char = torch.multinomial(
                    torch.softmax(pred / temperature, dim=-1), 1
                ).squeeze()
            # save new char to the current step
            chars[step] = new_char

        return chars
        #######################
        # END OF YOUR CODE    #
        #######################

if __name__ == "__main__":
    hidden_dim = 5
    embed_size = 10
    batch_n = 3

    lstm = LSTM(hidden_dim, embed_size)
    out = lstm.forward(torch.randn(2, batch_n, embed_size))
    print(out.shape)


"""Apache Beam Pipeline to get estimated capacity using solar_data_tools
"""
import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions
import logging
from typing import Any, Dict, List
from pvinsight_apache_beam.transformers.solar_data_tools_ptransforms \
    import CreateDataHandler, SummarizePowerTimeSeries, GetEstimatedCapacity
import argparse

def run(input_query: str, output_file: str, beam_args: List[str] = None) -> None:
    """Build and run the pipeline."""
    options = PipelineOptions(beam_args)

    with beam.Pipeline(options=options) as pipeline:
        capacity_estimates = (
                pipeline
                | "Read from BigQuery" >> beam.io.Read(beam.io.BigQuerySource(query=input_query))
                # rows returned as dictionary with keys matching BQ columns
                | "Group by system id" >> beam.WithKeys(lambda row: row['site_id'])
                | "Create data handler" >> beam.ParDo(CreateDataHandler())
                | "Run pipeline" >> beam.ParDo(SummarizePowerTimeSeries())
                | "Get capacity estimate" >> beam.ParDo(GetEstimatedCapacity())
        )

        # Output the results into BigQuery table.
        _ = capacity_estimates | "Write to text file" >> beam.io.WriteToText(
            output_file
        )

if __name__ == "__main__":
    logging.getLogger().setLevel(logging.INFO)

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--output_file",
        help="Output file path"
    )
    parser.add_argument(
        "--input_query",
        help="SQL query to pull power data"
    )
    args, beam_args = parser.parse_known_args()

    run(
        input_query=args.input_query,
        output_file=args.output_file,
        beam_args=beam_args,
    )


classes = {}

def add_class(lst: list):
    if len(lst) == 1:
        classes[lst[0]] = []
    else:
        classes[lst[0]] = lst[lst.index(':') + 1:]

def is_parent(parent: str, children: list):
    # классы вообще есть,
    if (parent not in classes.keys()) or (children[0] not in classes.keys()):
        return "No"

    # один и тот же класс
    if parent in children:
        return "Yes"

    # прямой предок
    union_parents = []
    for child in children:
        union_parents.extend(classes[child])
    union_parents = list(set(union_parents))
    if parent in union_parents:
        return "Yes"

    # уходим вглубь
    if len(union_parents) == 0:
        return "No"
    return is_parent(parent, union_parents)

n = int(input())
for i in range(n):
    add_class(input().split())

q = int(input())
for i in range(q):
    p, c = input().split()
    print(is_parent(p, [c]))

# test data
'''classes = dict(G=['F'], A=[], B=['A'], C=['A'], D=['B', 'C'], E=['D'], F=['D'], X=[], Y=['X', 'A'], Z=['X'],
               V=['Z', 'Y'], W=['V'])
lst = [
    'A G',  # Yes   # A предок G через B/C, D, F
    'A Z',      # No    # Y потомок A, но не Y
    'A W',      # Yes   # A предок W через Y, V
    'X W',      # Yes   # X предок W через Y, V
    'A X',      # No    # классы есть, но они нет родства :)
    'X X',      # Yes   # родитель он же потомок
    '1 1',      # No    # несуществующий класс
    'X QWE'    # No    # нет такого класса QWE
]

for e in lst:
    p, c = e.split()
    print(p, c, end= ' ')
    print(is_parent(p, [c]))

'''


real = ['Robert', 'William', 'James', 'John', 'Margaret',
        'Edward', 'Sarah', 'Andrew', 'Anthony', 'Deborah']
nick = ['Dick', 'Bill', 'Jim', 'Jack', 'Peggy',
        'Ed', 'Sally', 'Andy', 'Tony', 'Debbie']
n = int(input())
for i in range(n):
    s = input()
    found = False
    for j in range(10):
        if s == real[j]:
            print(nick[j])
            found = True
            break
        elif s == nick[j]:
            print(real[j])
            found = True
            break
    if(not found):
        print('Not found')


import pytest

from conftest import (
    load_ansible_vars,
    get_pg_type,
    get_barmanserver,
    get_pg_version,
    get_primary,
    get_pg_unix_socket_dir
)

def test_setup_barmanserver_packages():
    host = get_barmanserver()
    packages = [
        'barman',
        'barman-cli'
    ]

    for package in packages:
        assert host.package(package).is_installed, \
            "Package %s not installed" % packages

def test_setup_barmanserver_config_file():
    host = get_barmanserver()
    ansible_vars = load_ansible_vars()
    config_file = ansible_vars['barman_configuration_file']

    assert host.file(config_file).exists, \
        "%s does not exist" % config_file

def test_setup_barmanserver_sudo():
    host = get_barmanserver()
    ansible_vars = load_ansible_vars()
    barman_user = ansible_vars['barman_user']

    with host.sudo(barman_user):
        cmd = host.run('barman -h')
        result = cmd.stdout.strip()

    assert len(result) > 0, \
        "%s could not be used as a sudo user" % barman_user


import re
import sys
from collections import namedtuple
from copy import deepcopy

pattern = re.compile(r"(-?\d+)")

Pos = namedtuple("Pos", "x, y")
Vel = namedtuple("Vel", "x, y")

def parse():
    pos = []
    vel = []
    with open(r".././data/day_10.txt") as f:
        for line in f:
            p1, p2, v1, v2 = re.findall(pattern, line)
            p = Pos(int(p1), int(p2))
            v = Vel(int(v1), int(v2))
            pos.append(p)
            vel.append(v)
    return pos, vel

def grid(rows, cols):
    return [["."] * rows for _ in range(cols)]

def part01(grid, new, offset):
    for n in new:
        grid[n.y - offset][n.x - offset] = "#"
    for g in grid:
        print(" ".join(g))

def get_row_col_and_offsets(pos):

    cols = [p.x for p in pos]
    rows = [p.y for p in pos]
    cmin, col = min(cols), max(cols)
    rmin, row = min(rows), max(rows)
    cols_offset = abs(cmin)
    rows_offset = abs(rmin)

    return col, row, cols_offset, rows_offset

if __name__ == "__main__":
    pos, vel = parse()
    col, row, cols_offset, rows_offset = get_row_col_and_offsets(pos)
    start = [Pos(p.x + cols_offset, p.y + rows_offset) for p in pos]
    size = [col + cols_offset, row + rows_offset]

    for count in range(1, sys.maxsize):
        new = []
        for i in range(len(start)):
            new.append(Pos(start[i].x + vel[i].x, start[i].y + vel[i].y))
        col, row, cols_offset, rows_offset = get_row_col_and_offsets(new)

        new_size = [col + cols_offset, row + rows_offset]

        if size[0] < new_size[0] or size[1] < new_size[1]:
            print(f"A winner in `{count}` seconds")
            # Part 2 answer
            assert count == 10081

            grid = grid(col - cols_offset + 1, row - rows_offset + 1)
            part01(grid, new, cols_offset)

            break

        size = new_size
        start = new


##Binary search algorithm
#Binary search alog is used to search an element inside and sorted array
#This code only works for list[int,float]
def sear(ar,n):
    pos=-1      #base case(element not found)
    l=0
    r=len(ar)-1
    mid=(r-l)//2
    while l<=r:
        mid=(r+l)//2
        if ar[mid]==n:
            return mid
            break
        else:
            if ar[mid]>n:
                r=mid-1
            elif ar[mid]<n:
                l=mid+1
    return pos

#Driving code
ar=[2,3,7,67]
n=3
print(sear(ar,n))


import optparse

from ch02.scanner import port_scan

if __name__ == '__main__':
    parser = optparse.OptionParser('usage %prog -H <target host> -p <target port>')
    parser.add_option('-H', dest='tgtHost', type='string', help='specify target host')
    parser.add_option('-p', dest='tgtPort', type='string', help='specify target port')
    (options, args) = parser.parse_args()
    tgt_host = options.tgtHost
    tgt_port = options.tgtPort
    tgt_ports = str(tgt_port).split(',')
    if (tgt_host is None) | (tgt_port is None):
        print(parser.usage)
        exit(0)
    port_scan(tgt_host, tgt_ports)


'''
Created on Mar 25, 2013

@author: manju
'''
import math

from misc.printer import Printer

class InstanceWeighter(object):
    '''
        weight instances to improve learned models
    '''

    def __init__(self):
        '''
        Constructor
        '''

    def weight_instances(self, instance_dic, metainfo):
        '''
            weight instances by the root mean squared distance to the minimal runtime
            Args:
                metainfo: trainer.trainer_parser.coseal_reader.Metainfo()
                instance_dic: instance name -> Instance()
            Modifies: weights of all Instances() in <instance_dic>
        '''

        args_ = metainfo.options

        Printer.print_verbose("\n Instance Weighting")

        if args_.approx_weights == "max":
            for inst_ in instance_dic.values():
                runtimes = inst_._transformed_cost_vec
                weight = max(runtimes) - min(runtimes)
                inst_._weight = max(weight, 0.0001)# weight has to be large 0

        if args_.approx_weights == "rmsd":
            for inst_ in instance_dic.values():
                inst_._weight = max(self.__root_msd(inst_), 0.0001) # weight has to be large 0

        if args_.approx_weights == "nrmsd":
            weights = []
            inst_list = instance_dic.values()
            for inst_ in inst_list:
                weights.append(self.__root_msd(inst_))

            mean_weights, variance_weights = self.__mean_variance(weights)

            for inst_,weight in zip(inst_list,weights):
                normed_weight = ((weight - mean_weights) / math.sqrt(variance_weights)) + 10
                inst_._weight = max(normed_weight, 0.0001)

    def __root_msd(self, inst_):
        '''
            root mean squared distance
        '''
        runtimes = inst_._transformed_cost_vec
        min_time = min(runtimes)
        mean_squared_dist = sum(list(math.pow(min_time - x,2) for x in runtimes)) / len(runtimes)
        root_msd = math.sqrt(mean_squared_dist)
        return root_msd

    def __mean_variance(self, list_):
        s2 = 0
        s = 0
        n = len(list_)
        for e in list_:
            s += e
            s2 += e * e
        mean = s / n
        variance = (s2 - (s*s) / n) / n
        return mean, variance


import argparse
import torch
import torch.optim as  optim
from torchvision.utils import save_image
from utils import prepare_MNIST
import torch.nn.functional as F
import os
import time
import math
import random
import pickle
from encoder import *
import shutil
from torch.utils.data import DataLoader
import numpy as np
import matplotlib.pyplot as plt
from torch.distributions.kl import kl_divergence
from torch.distributions.normal import Normal
import time
from dataset import Dataset
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

cuda = torch.cuda.is_available()
device = torch.device("cpu")

parser = argparse.ArgumentParser(description='Convolutional VAE MNIST Example')
parser.add_argument('--result_dir', type=str, default='./result', metavar='DIR',
					help='output directory')
parser.add_argument('--save_dir', type=str, default='./mydata', metavar='DIR',
					help='model saving directory')
parser.add_argument('--batch_size', type=int, default=128, metavar='N',
					help='input batch size for training (default: 128)')
parser.add_argument('--epochs', type=int, default=20, metavar='N',
					help='number of epochs to train (default: 10)')
parser.add_argument('--seed', type=int, default=1, metavar='S',
					help='random seed (default: 1)')
parser.add_argument('--model', default='./model/ooo/epoch_19.pt', type=str, metavar='PATH',
					help='path to latest checkpoint (default: None')
parser.add_argument('--test_every', default=5, type=int, metavar='N',
					help='test after every epochs')
parser.add_argument('--num_worker', type=int, default=2, metavar='N',
					help='num_worker')
parser.add_argument('--data_dir', type=str, default='./mydata/', metavar='DIR',
					help='data directory')

# model options
parser.add_argument('--lr', type=float, default=1e-4,
					help='learning rate')
parser.add_argument('--line_dim', type=int, default=25, metavar='N',
					help='attribute vector size of encoder')
parser.add_argument('--input_dim', type=int, default=28 * 28, metavar='N',
					help='input dimension (28*28 for MNIST)')
parser.add_argument('--input_channel', type=int, default=1, metavar='N',
					help='input channel (1 for MNIST)')

args = parser.parse_args()
kwargs = {'num_workers': 2, 'pin_memory': True} if cuda else {}
def load_data(image_data,start_data,number_data,lebal_data,thick_data,segment_data, batch_size):
    data_loader = None
    if number_data != '':
        image = pickle.load(open(image_data,'rb'))
        number = pickle.load(open(number_data, 'rb'))
        lebal = pickle.load(open(lebal_data, 'rb'))
        data = Dataset(image ,number,lebal)
        data_loader = DataLoader(data, batch_size=batch_size, shuffle = False)
    return data_loader

def filter(images,positions,sums):
    rate = 0.0
    lists = [0,0,0,0,0,0,0,0,0,0]
    sources, lines = [], []
    for i in range(len(images)):
        threshold = 2
        position = np.round( positions[i] ).astype(int)
        pos = (position[0],position[1])
        image = images[i][0].cpu().numpy()
        value = image[pos]
        valid = ( value < 0.25) * 1
        invalid = np.sum(valid)
        index = sums[i].int()
        if index == 8 or index == 9 : threshold = 3
        if index == 1 : threshold = 1
        if invalid >= threshold:
            rate += 1
            lists[index] += 1
            continue
        sources.append(image)
        lines.append(positions[i])

    rate = rate / len(images)
    print("rate is :",rate)

    print("got filter :",len(sources))

    return sources, lines

def get_more_sample(sources,lines):
    lens = len(sources)
    images = []
    new_lines = []
    test = [0,0,0,0]
    for i in range(lens):
        image = sources[i]

        pos  = np.nonzero(image)
        pos = list(pos)

        images.append(sources[i])
        new_lines.append(lines[i])

        right_up , right_down , left_up , left_down = 0,0,0,0

        x_min = np.min(pos[1])
        x_max = 27 - np.max(pos[1])
        y_min = np.min(pos[0])
        y_max = 27 - np.max(pos[0])

        right_up = min( y_min, x_max )
        right_down = min( x_max , y_max )
        left_down = min ( x_min , y_max )
        left_up =  min ( x_min , y_min )

        ll = random.sample(range(0,4),2)
        for index in ll:
            if index == 0 and right_up >=2 :
                test[0]+=1
                add_new = image[ 2: , :26 ]
                add_new = np.pad(add_new,((0,2),(2,0)),'constant', constant_values=(0,0))
                line = lines[i].copy()
                line[1]+=2
                line[0]-=2

                images.append( add_new )
                new_lines.append( line )
                continue

            if index == 1 and right_down >=2:
                test[1]+=1
                add_new = image[ :26 , :26 ]
                add_new = np.pad(add_new,((2,0),(2,0)),'constant', constant_values=(0,0))
                line = lines[i].copy()
                line[1]+=2
                line[0]+=2

                images.append( add_new )
                new_lines.append( line )
                continue

            if index == 2 and left_down >=2:
                test[2]+=1
                add_new = image[ :26 , 2: ]
                add_new = np.pad(add_new,((2,0),(0,2)),'constant', constant_values=(0,0))
                line = lines[i].copy()
                line[1]-=2
                line[0]+=2

                images.append( add_new )
                new_lines.append( line )
                continue

            if index == 3 and left_up >=2:
                test[3]+=1
                add_new = image[ 2: , 2: ]
                add_new = np.pad(add_new,((0,2),(0,2)),'constant', constant_values=(0,0))
                line = lines[i].copy()
                line[1]-=2
                line[0]-=2

                images.append( add_new )
                new_lines.append( line )

    print(test)
    return images, new_lines

def get_thickness( images , positions):
    lists = []
    for j in range(len(images)):
        position = np.round( positions[j] ).astype(int)
        image = images[j]
        thicks= np.array([])

        for i in range(len(position[0])) :
            y = position[0,i]
            x = position[1,i]
            slash_pos =min([x,y])
            slash_pos2 =min ([27-x,y])
            left, right,up,down,upleft,downleft,upright,downright = 0,0,0,0,0,0,0,0

            right = image[y , x:].argmin(axis = 0)
            left = image[y , x::-1].argmin(axis = 0)
            horizontal = right + left -1

            up = image  [y::-1 , x].argmin(axis = 0)
            down = image[y:, x].argmin(axis = 0)
            vertical = up + down -1

            upleft = image.diagonal(x-y)[slash_pos::-1].argmin(axis = 0)
            downright = image.diagonal(x-y)[slash_pos:].argmin(axis = 0)
            diagonal = upleft + downright

            upright = np.fliplr(image).diagonal(27-x-y)[slash_pos2::-1].argmin(axis = 0)
            downleft = np.fliplr(image).diagonal(27-x-y)[slash_pos2:].argmin(axis = 0)
            back_diagonal = upright + downleft
            data =np.array([horizontal,vertical,diagonal,back_diagonal])
            thick = np.min(data)
            thicks = np.append(thicks,thick)
        pos_thick = np.vstack((positions[j],thicks))
        lists.append(pos_thick)

    return lists

def train():
    model = ConvEncoder(input_channels=args.input_channel, x_dim= line_dim , y_dim = line_dim ).cuda()
    model.load_state_dict(torch.load(args.model))
    model.cuda()
    optimizer = optim.Adam(model.parameters(), lr=args.lr)
    start_epoch = 0
    if not os.path.exists(args.result_dir):
        os.makedirs(args.result_dir)

    data_loader = load_data( args.data_dir + 'all_image.pickle',
                             args.data_dir + 'all_start.pickle',
                             args.data_dir + 'all_data.pickle',
                             args.data_dir +'all_sum.pickle',
                             args.data_dir +'all_thick.pickle',
                             args.data_dir +'all_segment.pickle',
                             args.batch_size )

    positions, sources  ,digit= [],[],[]
    with torch.no_grad():
        for i, data in enumerate(data_loader):
            inputs = data[0]
            inputer = inputs.clone()
            inputer[:,0:2,0:2] =0 ; inputer[:,0:2,26:] = 0 ; inputer[:,26:,0:2] = 0 ; inputer[:,26:,26:] = 0

            images = data[1]
            sums = data[2]
            inputs = inputs.unsqueeze(1)

            model.cuda()
            x_line,y_line = model(inputs)
            x_line = x_line.cpu().detach().numpy()
            y_line = y_line.cpu().detach().numpy()

            for j in range(len(images)):
                x = x_line[j]
                y = y_line[j]
                pos = np.stack((y, x))
                positions.append(pos)
                sources.append(images[j])
                digit.append(sums[j])

        print('len of positions is :',len(positions))
        print('len of images is :',len(sources))

        sources, lines = filter(sources,positions,digit)
        pos_thick = get_thickness( sources , lines)
        print('got thickness')
        new_images , new_lines =  get_more_sample(sources,pos_thick)
        print('added sample:',len(new_images))

        if not os.path.exists(args.save_dir):
            os.makedirs(args.save_dir)
        pickle.dump(new_images,open(args.save_dir+'/processed_sources.pickle', 'wb'))
        pickle.dump(new_lines,open(args.save_dir+'/processed_inputs.pickle', 'wb'))
        print("data saved")

if __name__ == '__main__':
    sample_num = 20
    resolution = 1.5
    test_num = 15

    dis_para = 10
    std_para = 100
    line_dim = args.line_dim
    if torch.cuda.is_available():
        print('Using: ', torch.cuda.get_device_name(torch.cuda.current_device()))
    else:
        print('CPU mode')
    train()


import tensorflow as tf
from tspmdp.modules.graph_encoder import CustomizableEncoder, GraphEncoder, WouterEncoder
import pytest
import shutil

def test_graph_encoder():
    B, N, F = 512, 14, 2
    n_heads = 8
    d_key = 64
    d_hidden = 256
    depth = 6
    d_model = 128
    model = GraphEncoder(d_model, depth, n_heads, d_key, d_hidden)
    inputs = tf.ones((B, N, F))
    assert model(inputs).shape == (B, N, d_model)

def test_woter_graph_encoder():
    B, N, F = 512, 14, 2
    n_heads = 8
    d_key = 64
    d_hidden = 256
    depth = 6
    d_model = 128
    model = WouterEncoder(d_model, depth, n_heads, d_key, d_hidden)
    inputs = tf.ones((B, N, F))
    assert model(inputs).shape == (B, N, d_model)

@pytest.mark.parametrize("final_ln", [True, False])
@pytest.mark.parametrize("transformer", ["preln", "gate", "linear", "postbn"])
def test_customizable_encoder(transformer, final_ln):
    B, N, F = 512, 14, 2
    n_heads = 8
    d_key = 64
    d_hidden = 256
    depth = 6
    d_model = 128
    model = CustomizableEncoder(d_model, depth, n_heads, d_key, d_hidden)
    inputs = tf.ones((B, N, F))
    assert model(inputs).shape == (B, N, d_model)


from django.conf.urls import patterns, include, url
from django.contrib import admin
#from django.conf import settings

# Uncomment the next two lines to enable the admin:
admin.autodiscover()

urlpatterns = patterns('',
    # Global URLs
    url(r'^$', 'py_arduino_web.dj.views.home', name='home'),
    url(r'^connect/?$', 'py_arduino_web.dj.views.connect', name='connect'),

    # URLs for methods
    url(r'^pin_mode/?$', 'py_arduino_web.dj.views.pin_mode', name='pin_mode'),
    url(r'^digital_write/?$', 'py_arduino_web.dj.views.digital_write', name='digital_write'),
    url(r'^analog_write/?$', 'py_arduino_web.dj.views.analog_write', name='analog_write'),
    url(r'^analog_read/?$', 'py_arduino_web.dj.views.analog_read', name='analog_read'),
    url(r'^digital_read/?$', 'py_arduino_web.dj.views.digital_read', name='digital_read'),
    url(r'^delay/?$', 'py_arduino_web.dj.views.delay', name='delay'),
    url(r'^get_avr_cpu_type$', 'py_arduino_web.dj.views.get_avr_cpu_type',
        name='get_avr_cpu_type'),
    url(r'^get_arduino_type_struct$', 'py_arduino_web.dj.views.get_arduino_type_struct',
        name='get_arduino_type_struct'),
    url(r'^ping$', 'py_arduino_web.dj.views.ping', name='ping'),
    url(r'^validate_connection$', 'py_arduino_web.dj.views.validate_connection',
        name='validate_connection'),
    url(r'^get_free_memory$', 'py_arduino_web.dj.views.get_free_memory',
        name='get_free_memory'),
    url(r'^close$', 'py_arduino_web.dj.views.close', name='close'),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
)

urlpatterns += patterns('django.contrib.staticfiles.views',
    url(r'^static/(?P<path>.*)$', 'serve'),
)


#!/usr/bin/env python
a = [1,2,3,4,5,6,7,8,9]

def reverse(a):
	i = 0
	while i < len(a)/2:
		tmp = a[i]
		a[i] = a[len(a)-i-1]
		a[len(a)-i-1] = tmp
		i += 1
	return a

def main():

	print(reverse(a))

if __name__ == '__main__':
	main()


# -*- coding: utf-8 -*-
import numpy as np
import scipy.integrate as sci
import scipy.optimize as opt
import time
import tarfile
import os
import csv
import argparse
from montagn import *
import gui_getoption
from sys import argv, exit

#from IPython import parallel
#import thread
from multiprocessing import Pool
#from multiprocessing import Process

def usemontagn(liste):
    #filename="test_"+str(int(n))

    #Translation of the list params
    n=liste[0]
    ask_in=liste[1]
    usemodel_in=liste[2]
    add_in=liste[3]
    usethermal_in=liste[4]
    nphot_in=liste[5]
    filename_in=liste[6]
    nscattmax_in=liste[7]
    modelmont_in=liste[8]
    display_in=liste[9]
    cluster_in=liste[10]
    thetaobs_in=liste[11]
    dthetaobs_in=liste[12]
    path_in=liste[13]
    cmap_in=liste[14]
    force_wvl_in=liste[15]
    paramfile_in=liste[16]

    #adapting the filenames for multpile runs
    if(n<10):
        number='00'+str(int(n))
    elif(n<100) :
        number='0'+str(int(n))
    else:
        number=str(int(n))
    if(filename_in is None):
        filename="test_"+number
    else:
        filename=filename_in+'_'+number

    #managing the ask, paramfile and usemodel parameters
    ask=0 #ask unavailable in parallel launch
    if(paramfile_in=='void' or paramfile_in=='None' or paramfile_in==None):
        if(usemodel_in==None):
            print('No paramfile or model specified')
            print('Using model 0')
            ask=0
            usemodel=0
        else:
            usemodel=float(usemodel_in)
            ask=0
    else:
        usemodel=None

    #Setting defaults values if none
    if(add_in==None):
        add=0
    else:
        add=int(add_in)
    if(usethermal_in==None):
        usethermal=0
    else:
        usethermal=int(usethermal_in)
    if(nphot_in==None):
        print('No photon number given')
        print('launching 100 packets')
        nphot=100
    else:
        nphot=int(nphot_in)
    if(nscattmax_in==None):
        nscattmax=50
    else:
        nscattmax=int(nscattmax_in)
    modelmont=[] #no model already computed usable
    if(display_in==None):
        display=0 #No display available
    else:
        display=int(display_in)
    if(cluster_in==None):
        cluster=0
    else:
        cluster=int(cluster_in)
    #if(thetaobs : unused keyword)
    #if(sthetaobs : unused keyword)
    if(path_in==None):
        path=''
    else:
        path=path_in
    if(display_in==1):
        if(cmap_in==None):
            cmap=[] #No cmap available because no display
    else:
        cmap=[]
    if(force_wvl_in==None or force_wvl_in=='None' or force_wvl_in=='none'):
        force_wvl=[]
    else:
        if(float(force_wvl_in)<1e-9):
            force_wvl=[]
        else:
            force_wvl=float(force_wvl_in)
    if(paramfile_in=='void' or paramfile_in==None):
        paramfile=[]
    else:
        paramfile=paramfile_in

    #Launching
    #model=montAGN(ask=int(liste[1]),usemodel=float(liste[2]),add=int(liste[3]),usethermal=int(liste[4]),nphot=int(liste[5]),filename=filename,ndiffmax=int(liste[7]),display=int(liste[9]),cluster=int(liste[10]),path=path,force_wvl=liste[15],paramfile=paramfile,nsimu=int(n))
    model=montAGN(ask=ask,usemodel=usemodel,add=add,usethermal=usethermal,nphot=nphot,filename=filename,nscattmax=nscattmax,display=display,cluster=cluster,path=path,force_wvl=force_wvl,paramfile=paramfile,nsimu=int(n))

def main():

    # initialisation
    sc = gui_getoption.getoption(opt='wes', optval='r', param=['add','display','cluster'], paramval=['usemodel','nphot','filename','nscattmax','nlaunch','thetaobs','dthetaobs','cmap','force_wvl','paramfile','ask','usethermal','path'], man='This is the manual page. Thanks you for using getoption')

    # appel de la commande
    sc(argv)

    # test option de commande
    if sc['r'] is not None: print("r option was given")

    if 'h' in sc.optkey:
        print(sc.man)
        #exit()

    #for tycho usage
    if(sc['cluster']==1):
        #n=os.getenv("i")
        if(sc['nlaunch'] is None):
            n=1
        else:
            n=int(sc['nlaunch'])
        if(n is None): n=1
        liste=[n,sc['ask'],sc['usemodel'],sc['add'],sc['usethermal'],sc['nphot'],sc['filename'],sc['nscattmax'],sc['modelmont'],sc['display'],sc['cluster'],sc['thetaobs'],sc['dthetaobs'],sc['path'],sc['cmap'],sc['force_wvl'],sc['paramfile']]
        #print liste
        usemontagn(liste)

        #for normal usage
    else:
        if(sc['nlaunch'] is None):
            n=1
        else:
            n=int(sc['nlaunch'])
        #name=np.linspace(1,n,n)
        liste=[]
        for i in range(n):
            liste.append([i+1,sc['ask'],sc['usemodel'],sc['add'],sc['usethermal'],sc['nphot'],sc['filename'],sc['nscattmax'],sc['modelmont'],sc['display'],sc['cluster'],sc['thetaobs'],sc['dthetaobs'],sc['path'],sc['cmap'],sc['force_wvl'],sc['paramfile']])

        #print liste
        #Pool(n).map(usemontagn,name)
        if(n>1):
            Pool(n).map(usemontagn,liste)
        else:
            liste=['1',sc['ask'],sc['usemodel'],sc['add'],sc['usethermal'],sc['nphot'],sc['filename'],sc['nscattmax'],sc['modelmont'],sc['display'],sc['cluster'],sc['thetaobs'],sc['dthetaobs'],sc['path'],sc['cmap'],sc['force_wvl'],sc['paramfile']]
            usemontagn(liste)
        #Pool(n).apply_async(usemontagn[,scriptcall])

if __name__ == '__main__':

    main()


from flask import Flask , render_template, url_for ,request, jsonify,redirect, flash
from event import events
from alerts import simulate_event_generation
#from alerts import *
app = Flask(__name__)
@app.route('/')
def index():
    return render_template("index.html")

@app.route("/details" , methods = ['POST'])
def details():
    vehicle_id = request.form['id']
    matching_events = [event for event in events if event['vehicle_id'] == int(vehicle_id)]
    if matching_events:
        return render_template("details.html" , value = vehicle_id)
    else:
        return "<h1> Vehicle does not exist in DB </h1>"

@app.route("/alerts/<vehicle_id>" , methods = ["GET"])
def notify():
    alert = simulate_event_generation(int(request.form["id"]),30 )
    return render_template('alertnotify.html', vehicle_id=request.form["id"], alerts=alert)

"""@app.route('/check_vehicle', methods=['POST'])
def check_vehicle():
        vehicle_id = request.form.get('id')
        matching_events = [event for event in events if event['vehicle_id'] == int(vehicle_id)]
        if matching_events:
            return jsonify({"message: vehicle exists"})
    # Check if the vehicle_id exists in events

        else:
            return jsonify({"message": "Vehicle does not exist in events data."})

"""

if __name__ == "__main__":
    app.run(debug = True)


from odoo import api, models

class StockLocation(models.Model):
    _inherit = "stock.location"

    @api.model
    def name_search(self, name, args=None, operator='ilike', limit=160):
        branch_id = self._context.get('branch_id', False)
        if branch_id:
            branch = self.env['pos.branch'].browse(branch_id)
            company_id = branch.pos_company_id.id
            warehouse_code = branch.warehouse_id.code
            recs = self.search(
                [
                    ('company_id', '=', company_id),
                    ('complete_name', 'like', warehouse_code + '/')
                ] + args
            )
            if name:
                name = name.upper()
                recs = recs.filtered(
                    lambda x: name in x.name.upper()
                )
            return recs.sudo().name_get()
        return super(StockLocation, self).name_search(name, args, operator, limit)


# importing the nltk suite
import nltk

# importing edit distance
from nltk.metrics.distance import edit_distance

# Downloading and importing package 'words'
nltk.download('words')
from nltk.corpus import words

# Assigning to variable
crt_wrds = words.words()

# loop for finding correct spellings based on edit distance and printing the correct words
def auto_crt(wrd):
	temp = [(edit_distance(wrd, w),w) for w in crt_wrds if w[0]==wrd[0]]
	return(sorted(temp, key = lambda val:val[0])[0][1])

# taking input from you
in_wrds=list(input("Enter words:").split(","))

# looping the list you have given and calling the auto corrector to print
for wrd in in_wrds:
    print(auto_crt(wrd.lower()))


import Signal_Processing
import numpy as np
import matplotlib.pyplot as plt

# Create Single class
SP1 = Signal_Processing.Sig_Proc('192.168.10.10',5005)
# Testing values
N = 1024
T = 1.0/800.0
x = np.linspace(0.0,N*T,N)
y = np.sin(50.0*2.0*np.pi*x)

# Fucntion Calls
SP1.stream_data = y #sample data
SP1.run()
print(np.angle(SP1.fft_data[0],deg=1))
print(np.angle(SP1.fft_data[1],deg=1))
print(np.angle(SP1.fft_data[2],deg=1))
print(np.angle(SP1.fft_data[3],deg=1))
print(np.angle(SP1.fft_data[4],deg=1))
print(np.angle(SP1.fft_data[5],deg=1))
# Plot results
freq = np.linspace(-0.5, 0.5, 1024)
plt.plot(freq, SP1.fft_data)
plt.axis([-0.5, 0.5, -50, 100])
plt.title("Frequency response of the Hanning window")
plt.ylabel("Normalized magnitude [dB]")
plt.xlabel("Normalized frequency [cycles per sample]")
plt.show()