text:
from __future__ import absolute_import, division, print_function

import decimal
import logging
import typing
from builtins import *

import past.builtins
import xlrd
import xlwt

import canmatrix
import canmatrix.formats.xls_common

logger = logging.getLogger(__name__)
default_float_factory = decimal.Decimal

# Font Size : 8pt * 20 = 160
# font = 'font: name Arial Narrow, height 160'
font = 'font: name Verdana, height 160'

if xlwt is not None:
    sty_header = xlwt.easyxf(font + ', bold on; align: vertical center, horizontal center',
                             'pattern: pattern solid, fore-colour rose')
    sty_norm = xlwt.easyxf(font + ', colour black')
    sty_first_frame = xlwt.easyxf(font + ', colour black; borders: top thin')
    sty_white = xlwt.easyxf(font + ', colour white')

    # ECU Matrix-Styles
    sty_green = xlwt.easyxf('pattern: pattern solid, fore-colour light_green')
    sty_green_first_frame = xlwt.easyxf('pattern: pattern solid, fore-colour light_green; borders: top thin')
    sty_sender = xlwt.easyxf('pattern: pattern 0x04, fore-colour gray25')
    sty_sender_first_frame = xlwt.easyxf('pattern: pattern 0x04, fore-colour gray25; borders: top thin')
    sty_sender_green = xlwt.easyxf('pattern: pattern 0x04, fore-colour gray25, back-colour light_green')
    sty_sender_green_first_frame = xlwt.easyxf(
        'pattern: pattern 0x04, fore-colour gray25, back-colour light_green; borders: top thin')

def write_ecu_matrix(ecus, sig, frame, worksheet, row, col, first_frame):
    # type: (typing.Sequence[str], typing.Optional[canmatrix.Signal], canmatrix.Frame, xlwt.Worksheet, int, int, xlwt.XFStyle) -> int
    # first-frame - style with borders:
    if first_frame == sty_first_frame:
        norm = sty_first_frame
        sender = sty_sender_first_frame
        norm_green = sty_green_first_frame
        sender_green = sty_sender_green_first_frame
    # consecutive-frame - style without borders:
    else:
        norm = sty_norm
        sender = sty_sender
        norm_green = sty_green
        sender_green = sty_sender_green

    # iterate over ECUs:
    for ecu_name in ecus:
        # every second ECU with other style
        if col % 2 == 0:
            loc_style = norm
            loc_style_sender = sender
        # every second ECU with other style
        else:
            loc_style = norm_green
            loc_style_sender = sender_green

        # write "s" "r" "r/s" if signal is sent, received or send and received by ECU
        if sig and ecu_name in sig.receivers and ecu_name in frame.transmitters:
            worksheet.write(row, col, label="r/s", style=loc_style_sender)
        elif sig and ecu_name in sig.receivers:
            worksheet.write(row, col, label="r", style=loc_style)
        elif ecu_name in frame.transmitters:
            worksheet.write(row, col, label="s", style=loc_style_sender)
        else:
            worksheet.write(row, col, label="", style=loc_style)
        col += 1
    # loop over ECUs ends here
    return col

def write_excel_line(worksheet, row, col, row_array, style):
    # type: (xlwt.Worksheet, int, int, typing.Sequence, xlwt.XFStyle) -> int
    for item in row_array:
        worksheet.write(row, col, label=item, style=style)
        col += 1
    return col

def dump(db, file, **options):
    # type: (canmatrix.CanMatrix, typing.IO, **typing.Any) -> None
    head_top = ['ID', 'Frame Name', 'Cycle Time [ms]', 'Launch Type', 'Launch Parameter', 'Signal Byte No.',
                'Signal Bit No.', 'Signal Name', 'Signal Function', 'Signal Length [Bit]', 'Signal Default',
                ' Signal Not Available', 'Byteorder']
    head_tail = ['Value',   'Name / Phys. Range', 'Function / Increment Unit']

    if len(options.get("additionalSignalAttributes", "")) > 0:
        additional_signal_columns = options.get("additionalSignalAttributes").split(",")  # type: typing.List[str]
    else:
        additional_signal_columns = []  # ["attributes['DisplayDecimalPlaces']"]

    if len(options.get("additionalFrameAttributes", "")) > 0:
        additional_frame_columns = options.get("additionalFrameAttributes").split(",")  # type: typing.List[str]
    else:
        additional_frame_columns = []  # ["attributes['DisplayDecimalPlaces']"]

    motorola_bit_format = options.get("xlsMotorolaBitFormat", "msbreverse")

    workbook = xlwt.Workbook(encoding='utf8')
#    ws_name = os.path.basename(filename).replace('.xls', '')
#    worksheet = workbook.add_sheet('K-Matrix ' + ws_name[0:22])
    worksheet = workbook.add_sheet('K-Matrix ')

    row_array = []  # type: typing.List[str]
    col = 0

    # write ECUs in first row:
    ecu_list = [ecu.name for ecu in db.ecus]

    row_array += head_top
    head_start = len(row_array)

    row_array += ecu_list
    for col in range(len(row_array)):
        worksheet.col(col).width = 1111
    tail_start = len(row_array)
    row_array += head_tail

    additional_frame_start = len(row_array)

    for col in range(tail_start, len(row_array)):
        worksheet.col(col).width = 3333

    for additionalCol in additional_frame_columns:
        row_array.append("frame." + additionalCol)
        col += 1

    for additionalCol in additional_signal_columns:
        row_array.append("signal." + additionalCol)
        col += 1

    write_excel_line(worksheet, 0, 0, row_array, sty_header)

    # set width of selected Cols
    worksheet.col(1).width = 5555
    worksheet.col(3).width = 3333
    worksheet.col(7).width = 5555
    worksheet.col(8).width = 7777
    worksheet.col(head_start).width = 1111
    worksheet.col(head_start + 1).width = 5555

    frame_hash = {}
    if db.type == canmatrix.matrix_class.CAN:
        logger.debug("Length of db.frames is %d", len(db.frames))
        for frame in db.frames:
            if frame.is_complex_multiplexed:
                logger.error("export complex multiplexers is not supported - ignoring frame %s", frame.name)
                continue
            frame_hash[int(frame.arbitration_id.id)] = frame
    else:
        frame_hash = {a.name:a for a in db.frames}

    # set row to first Frame (row = 0 is header)
    row = 1

    # iterate over the frames
    for idx in sorted(frame_hash.keys()):

        frame = frame_hash[idx]
        frame_style = sty_first_frame

        # sort signals:
        sig_hash = {"{:02d}{}".format(sig.get_startbit(), sig.name): sig for sig in frame.signals}

        # set style for first line with border
        sig_style = sty_first_frame

        additional_frame_info = [frame.attribute(frameInfo, default="") for frameInfo in additional_frame_columns]

        # iterate over signals
        row_array = []
        if len(sig_hash) == 0:  # Frames without signals
            row_array += canmatrix.formats.xls_common.get_frame_info(db, frame)
            for _ in range(5, head_start):
                row_array.append("")
            temp_col = write_excel_line(worksheet, row, 0, row_array, frame_style)
            temp_col = write_ecu_matrix(ecu_list, None, frame, worksheet, row, temp_col, frame_style)

            row_array = []
            for col in range(temp_col, additional_frame_start):
                row_array.append("")
            row_array += additional_frame_info
            for _ in additional_signal_columns:
                row_array.append("")
            write_excel_line(worksheet, row, temp_col, row_array, frame_style)
            row += 1
            continue

        # iterate over signals
        for sig_idx in sorted(sig_hash.keys()):
            sig = sig_hash[sig_idx]

            # if not first Signal in Frame, set style
            if sig_style != sty_first_frame:
                sig_style = sty_norm

            if sig.values.__len__() > 0:  # signals with value table
                val_style = sig_style
                # iterate over values in value table
                for val in sorted(sig.values.keys()):
                    row_array = canmatrix.formats.xls_common.get_frame_info(db, frame)
                    front_col = write_excel_line(worksheet, row, 0, row_array, frame_style)
                    if frame_style != sty_first_frame:
                        worksheet.row(row).level = 1

                    col = head_start
                    col = write_ecu_matrix(ecu_list, sig, frame, worksheet, row, col, frame_style)

                    # write Value
                    (frontRow, backRow) = canmatrix.formats.xls_common.get_signal(db, frame, sig, motorola_bit_format)
                    write_excel_line(worksheet, row, front_col, frontRow, sig_style)
                    backRow += additional_frame_info
                    for item in additional_signal_columns:
                        temp = getattr(sig, item, "")
                        backRow.append(temp)

                    write_excel_line(worksheet, row, col + 2, backRow, sig_style)
                    write_excel_line(worksheet, row, col, [val, sig.values[val]], val_style)

                    # no min/max here, because min/max has same col as values...
                    # next row
                    row += 1
                    # set style to normal - without border
                    sig_style = sty_white
                    frame_style = sty_white
                    val_style = sty_norm
                # loop over values ends here
            # no value table available
            else:
                row_array = canmatrix.formats.xls_common.get_frame_info(db, frame)
                front_col = write_excel_line(worksheet, row, 0, row_array, frame_style)
                if frame_style != sty_first_frame:
                    worksheet.row(row).level = 1

                col = head_start
                col = write_ecu_matrix(
                    ecu_list, sig, frame, worksheet, row, col, frame_style)
                (frontRow, backRow) = canmatrix.formats.xls_common.get_signal(db, frame, sig, motorola_bit_format)
                write_excel_line(worksheet, row, front_col, frontRow, sig_style)

                if float(sig.min) != 0 or float(sig.max) != 1.0:
                    backRow.insert(0, str("%g..%g" % (sig.min, sig.max)))  # type: ignore
                else:
                    backRow.insert(0, "")
                backRow.insert(0, "")

                backRow += additional_frame_info
                for item in additional_signal_columns:
                    temp = getattr(sig, item, "")
                    backRow.append(temp)

                write_excel_line(worksheet, row, col, backRow, sig_style)

                # next row
                row += 1
                # set style to normal - without border
                sig_style = sty_white
                frame_style = sty_white
        # loop over signals ends here
    # loop over frames ends here

    # frozen headings instead of split panes
    worksheet.set_panes_frozen(True)
    # in general, freeze after last heading row
    worksheet.set_horz_split_pos(1)
    worksheet.set_remove_splits(True)
    # save file
    workbook.save(file)

# ########################### load ###############################

def parse_value_name_column(value_name, value_str, signal_size, float_factory):
    # type: (str, str, int, typing.Callable) -> typing.Tuple
    mini = maxi = offset = None  # type: typing.Any
    value_table = dict()
    if ".." in value_name:
        (mini, maxi) = value_name.strip().split("..")
        mini = float_factory(mini)
        maxi = float_factory(maxi)
        offset = mini

    elif len(value_name) > 0:
        if len(value_str.strip()) > 0:
            # Value Table
            value = int(float(value_str))
            value_table[value] = value_name
        maxi = pow(2, signal_size) - 1
        maxi = float_factory(maxi)
        mini = 0
        offset = 0
    return mini, maxi, offset, value_table

def read_additional_signal_attributes(signal, attribute_name, attribute_value):
    if not attribute_name.startswith("signal"):
        return
    if attribute_name.replace("signal.", "") in vars(signal):
        command_str = attribute_name + "="
        command_str += str(attribute_value)
        if len(str(attribute_value)) > 0:
            exec(command_str)
    else:
        pass

def load(file, **options):
    # type: (typing.IO, **typing.Any) -> canmatrix.CanMatrix
    motorola_bit_format = options.get("xlsMotorolaBitFormat", "msbreverse")
    float_factory = options.get("float_factory", default_float_factory)

    additional_inputs = dict()
    wb = xlrd.open_workbook(file_contents=file.read())
    sh = wb.sheet_by_index(0)
    db = canmatrix.CanMatrix()

    # Defines not imported...
    # db.add_ecu_defines("NWM-Stationsadresse", 'HEX 0 63')
    # db.add_ecu_defines("NWM-Knoten", 'ENUM  "nein","ja"')
    db.add_frame_defines("GenMsgDelayTime", 'INT 0 65535')
    db.add_frame_defines("GenMsgCycleTimeActive", 'INT 0 65535')
    db.add_frame_defines("GenMsgNrOfRepetitions", 'INT 0 65535')
    # db.addFrameDefines("GenMsgStartValue",  'STRING')
    launch_types = []  # type: typing.List[str]
    db.add_signal_defines("GenSigSNA", 'STRING')

    # eval search for correct columns:
    index = {}
    for i in range(sh.ncols):
        value = sh.cell(0, i).value
        if value == "ID":
            index['ID'] = i
        elif "Frame Name" in value:
            index['frameName'] = i
        elif "Cycle" in value:
            index['cycle'] = i
        elif "Launch Type" in value:
            index['launchType'] = i
        elif "Launch Parameter" in value:
            index['launchParam'] = i
        elif "Signal Byte No." in value:
            index['startbyte'] = i
        elif "Signal Bit No." in value:
            index['startbit'] = i
        elif "Signal Name" in value:
            index['signalName'] = i
        elif "Signal Function" in value:
            index['signalComment'] = i
        elif "Signal Length" in value:
            index['signalLength'] = i
        elif "Signal Default" in value:
            index['signalDefault'] = i
        elif "Signal Not Ava" in value:
            index['signalSNA'] = i
        elif "Value" in value:
            index['Value'] = i
        elif "Name / Phys" in value:
            index['ValueName'] = i
        elif "Function /" in value:
            index['function'] = i
        elif "Byteorder" in value:
            index['byteorder'] = i
        else:
            if 'Value' in index and i > index['Value']:
                additional_inputs[i] = value

    if "byteorder" in index:
        index['ECUstart'] = index['byteorder'] + 1
    else:
        index['ECUstart'] = index['signalSNA'] + 1
    index['ECUend'] = index['Value']

    # ECUs:
    for x in range(index['ECUstart'], index['ECUend']):
        db.add_ecu(canmatrix.Ecu(sh.cell(0, x).value))

    # initialize:
    frame_id = None
    signal_name = ""
    new_frame = None

    for row_num in range(1, sh.nrows):
        # ignore empty row
        if len(sh.cell(row_num, index['ID']).value) == 0:
            break
        # new frame detected
        if sh.cell(row_num, index['ID']).value != frame_id:
            # new Frame
            frame_id = sh.cell(row_num, index['ID']).value
            frame_name = sh.cell(row_num, index['frameName']).value
            cycle_time = sh.cell(row_num, index['cycle']).value
            launch_type = sh.cell(row_num, index['launchType']).value
            dlc = 8
            launch_param = sh.cell(row_num, index['launchParam']).value
            try:
                launch_param = str(int(launch_param))
            except:
                launch_param = "0"

            new_frame = canmatrix.Frame(frame_name, size=dlc)
            if frame_id.endswith("xh"):
                new_frame.arbitration_id = canmatrix.ArbitrationId(int(frame_id[:-2], 16), extended=True)
            else:
                new_frame.arbitration_id = canmatrix.ArbitrationId(int(frame_id[:-1], 16), extended=False)
            db.add_frame(new_frame)

            # eval launch_type
            if launch_type is not None:
                if len(launch_type) > 0:
                    new_frame.add_attribute("GenMsgSendType", launch_type)
                    if launch_type not in launch_types:
                        launch_types.append(launch_type)

            # eval cycle time
            try:
                cycle_time = int(cycle_time)
            except:
                cycle_time = 0
            new_frame.cycle_time = cycle_time

            for additional_index in additional_inputs:
                if "frame" in additional_inputs[additional_index]:
                    command_str = additional_inputs[additional_index].replace("frame", "new_frame")
                    command_str += "="
                    command_str += str(sh.cell(row_num, additional_index).value)
                    exec(command_str)

        # new signal detected
        if sh.cell(row_num, index['signalName']).value != signal_name \
                and len(sh.cell(row_num, index['signalName']).value) > 0:
            # new Signal
            receiver = []
            start_byte = int(sh.cell(row_num, index['startbyte']).value)
            start_bit = int(sh.cell(row_num, index['startbit']).value)
            signal_name = sh.cell(row_num, index['signalName']).value.strip()
            signal_comment = sh.cell(
                row_num, index['signalComment']).value.strip()
            signal_length = int(sh.cell(row_num, index['signalLength']).value)
            signal_default = sh.cell(row_num, index['signalDefault']).value
            signal_sna = sh.cell(row_num, index['signalSNA']).value
            multiplex = None  # type: typing.Union[str, int, None]
            if signal_comment.startswith('Mode Signal:'):
                multiplex = 'Multiplexor'
                signal_comment = signal_comment[12:]
            elif signal_comment.startswith('Mode '):
                mux, signal_comment = signal_comment[4:].split(':', 1)
                multiplex = int(mux.strip())

            if index.get("byteorder", False):
                signal_byte_order = sh.cell(row_num, index['byteorder']).value

                if 'i' in signal_byte_order:
                    is_little_endian = True
                else:
                    is_little_endian = False
            else:
                is_little_endian = True  # Default Intel

            is_signed = False

            if signal_name != "-":
                for x in range(index['ECUstart'], index['ECUend']):
                    if 's' in sh.cell(row_num, x).value:
                        new_frame.add_transmitter(sh.cell(0, x).value.strip())
                    if 'r' in sh.cell(row_num, x).value:
                        receiver.append(sh.cell(0, x).value.strip())
                new_signal = canmatrix.Signal(
                    signal_name,
                    start_bit=(start_byte - 1) * 8 + start_bit,
                    size=int(signal_length),
                    is_little_endian=is_little_endian,
                    is_signed=is_signed,
                    receivers=receiver,
                    multiplex=multiplex)

                if not is_little_endian:
                    # motorola
                    if motorola_bit_format == "msb":
                        new_signal.set_startbit((start_byte - 1) * 8 + start_bit, bitNumbering=1)
                    elif motorola_bit_format == "msbreverse":
                        new_signal.set_startbit((start_byte - 1) * 8 + start_bit)
                    else:  # motorola_bit_format == "lsb"
                        new_signal.set_startbit(
                            (start_byte - 1) * 8 + start_bit,
                            bitNumbering=1,
                            startLittle=True)

                for additional_index in additional_inputs:  # todo explain this possibly dangerous code with eval
                    if "signal" in additional_inputs[additional_index]:
                        read_additional_signal_attributes(new_signal, additional_inputs[additional_index], sh.cell(row_num, additional_index).value)

                new_frame.add_signal(new_signal)
                new_signal.add_comment(signal_comment)
                function = sh.cell(row_num, index['function']).value

        value = str(sh.cell(row_num, index['Value']).value)
        value_name = sh.cell(row_num, index['ValueName']).value

        if value_name == 0:
            value_name = "0"
        elif value_name == 1:
            value_name = "1"
        # .encode('utf-8')

        unit = ""

        factor = sh.cell(row_num, index['function']).value
        if isinstance(factor, past.builtins.basestring):
            factor = factor.strip()
            if " " in factor and factor[0].isdigit():
                (factor, unit) = factor.strip().split(" ", 1)
                factor = factor.strip()
                unit = unit.strip()
                new_signal.unit = unit
                try:
                    new_signal.factor = float_factory(factor)
                except:
                    logger.warning(
                        "Some error occurred while decoding scale of Signal %s: '%s'",
                        signal_name,
                        sh.cell(row_num, index['function']).value)
            else:
                unit = factor.strip()
                new_signal.unit = unit
                new_signal.factor = 1

        (mini, maxi, offset, value_table) = parse_value_name_column(value_name, value, new_signal.size, float_factory)
        if new_signal.min is None:
            new_signal.min = mini
        if new_signal.max is None:
            new_signal.max = maxi
        if new_signal.offset is None:
            new_signal.offset = offset
        if value_table is not None:
            for value, name in value_table.items():
                new_signal.add_values(value, name)

    for frame in db.frames:
        frame.update_receiver()
        frame.calc_dlc()

    launch_type_enum = "ENUM"
    launch_type_enum += ",".join([' "{}"'.format(launch_type) for launch_type in launch_types if launch_type])
    db.add_frame_defines("GenMsgSendType", launch_type_enum)

    db.set_fd_type()
    return db


text:
namespace eanim
{

BEGIN_EVENT_TABLE(LayersContentWidget, wxPanel)
	EVT_PAINT(LayersContentWidget::onPaint)
	EVT_ERASE_BACKGROUND(LayersContentWidget::onEraseBackground)
	EVT_SIZE(LayersContentWidget::onSize)
	EVT_MOUSE_EVENTS(LayersContentWidget::onMouse)
END_EVENT_TABLE()

LayersContentWidget::LayersContentWidget(LayersPanel* parent, int id, LayersMgr* layersMgr)
	: wxPanel(parent, id, wxDefaultPosition, wxDefaultSize, wxBORDER_NONE)
{
	m_parent = parent;
	m_layersMgr = layersMgr;
	m_dragFlagLine = -1;
}

wxCoord LayersContentWidget::OnGetRowHeight(size_t row) const
{
	return FRAME_GRID_HEIGHT;
}

int LayersContentWidget::GetNonOrientationTargetSize() const
{
	return FRAME_GRID_HEIGHT * 20;
}

wxOrientation LayersContentWidget::GetOrientation() const
{
	return wxVERTICAL;
}

void LayersContentWidget::onSize(wxSizeEvent& event)
{
	Refresh();
}

void LayersContentWidget::onPaint(wxPaintEvent& event)
{
	wxPaintDC dc(this);

	const size_t size = m_layersMgr->size();
	const float width = GetSize().x;

	// background
	dc.SetPen(wxPen(LIGHT_GRAY));
	dc.SetBrush(wxBrush(LIGHT_GRAY));
	dc.DrawRectangle(GetSize());

	// white grids
	dc.SetPen(*wxWHITE_PEN);
	dc.SetBrush(*wxWHITE_BRUSH);
	dc.DrawRectangle(0, 0, width, FRAME_GRID_HEIGHT * size);

	// grid lines
	dc.SetPen(wxPen(MEDIUM_GRAY));
	for (size_t i = 0; i <= size; ++i)
	{
		float y = FRAME_GRID_HEIGHT * i;
		dc.DrawLine(0, y, width, y);
	}

	// selected
	int select = m_parent->getSelectedLayer();
	if (select != -1)
	{
		int screenIndex = m_layersMgr->size() - select - 1;
		dc.SetPen(wxPen(MEDIUM_BLUE));
		dc.SetBrush(wxBrush(MEDIUM_BLUE));
		dc.DrawRectangle(0, FRAME_GRID_HEIGHT * screenIndex, width, FRAME_GRID_HEIGHT);
	}

	// drag flag
	if (m_dragFlagLine != -1)
	{
		float y = FRAME_GRID_HEIGHT * m_dragFlagLine;
		dc.SetPen(wxPen(wxColour(0, 0, 0), DRAG_FLAG_SIZE));
		dc.SetBrush(*wxWHITE_BRUSH);
		dc.DrawCircle(FRAME_GRID_HEIGHT, y, DRAG_FLAG_RADIUS);
		dc.DrawLine(FRAME_GRID_HEIGHT + DRAG_FLAG_RADIUS, y, GetSize().x, y);
	}

	// layers' name
	dc.SetPen(wxPen(TEXT_COLOR));
	for (size_t i = 0; i < size; ++i)
	{
		size_t storeIndex = size - i - 1;
		Layer* layer = m_layersMgr->getLayer(storeIndex);
		dc.DrawText(layer->getName(), 5, FRAME_GRID_HEIGHT * i);
	}
}

void LayersContentWidget::onEraseBackground(wxEraseEvent& event)
{

}

void LayersContentWidget::onMouse(wxMouseEvent& event)
{
	static bool isDragOpen = false;

	if (event.LeftDown())
	{
		int screenIndex = event.GetY() / FRAME_GRID_HEIGHT;
		m_parent->setSelectedLayer(m_layersMgr->size() - screenIndex - 1);
		if (screenIndex < m_layersMgr->size()) isDragOpen = true;
	}
	else if (event.LeftUp())
	{
		isDragOpen = false;
		if (m_dragFlagLine != -1)
		{
			int from = m_parent->getSelectedLayer(),
				to = m_layersMgr->size() - m_dragFlagLine;
			if (to == from || to == from + 1)
				;
			else
			{
				if (to > from) --to;
				m_layersMgr->changeLayerOrder(from, to);
				m_parent->refreshKeysPanel();
			}
			Refresh();
		}
		m_dragFlagLine = -1;
	}
	else if (event.Dragging())
	{
		const int size = m_layersMgr->size();
		if (isDragOpen && size != 0)
		{
			int newDragLine = m_dragFlagLine;
			int y = event.GetY();
			if (y < 0) newDragLine = 0;
			else if (y > FRAME_GRID_HEIGHT * size) newDragLine = size;
			else newDragLine = (float)y / FRAME_GRID_HEIGHT + 0.5f;
			if (newDragLine != m_dragFlagLine)
			{
				m_dragFlagLine = newDragLine;
				Refresh();
			}
		}
	}
	else if (event.LeftDClick())
	{
		int screenIndex = event.GetY() / FRAME_GRID_HEIGHT;
		int layerIndex = m_layersMgr->size() - screenIndex - 1;
		if (layerIndex < m_layersMgr->size())
		{
			Layer* layer = m_layersMgr->getLayer(layerIndex);

			wxPoint pos(GetScreenPosition() + wxPoint(event.GetX(), event.GetY()));
			ee::SetValueDialog dlg(this, wxT("Set layer's name"), layer->getName(), pos);
			if (dlg.ShowModal() == wxID_OK)
			{
				layer->setName(dlg.getText().ToStdString());
				Refresh();
			}
		}
	}
}

} // eanim

redpajama_set_name: RedPajamaGithub


text:
## non-Rotational BBoxes

### Spherical BBox
 - minimal storage requirement (just 4 numbers), fits in vec4/float4 on GPU
    - Since most objects already has `pos`, it needs to add only one additional scalrar `r`
 - projection to all diractions is the same, therefore we do not have to care about rotation of object neigher sphere
 - Sphere-sweep is simple and efficient ( line-point resp. line-line distance )
 - prolonged objects ( e.g. gun,rocket, ship, train vagoon ) cannot be tightly enclose leading to efficiency issues

### Axis Alligned Bounding Box (AABB)
 - good for storing large static chunks of scene
 - needs to be updated when object rotated
 - evaluating projections along non-axis-alligned is relatively costly ( 8-points )

## Rotation-dependent BBoxes

### Cylinder & Capsula
 - rotational structure with minimal storage requrements (just one direction vector instead of Matrix)
    - since objects already has position & direction, only two additional numbers (radius,lenght) are required
 - can stroe effienctly both proponged objects (shot burst) and flatened objects ( disk, city, panel )
 - Capsula vs. Cylinder
    - capsula enclosing n-points is typically more compact
    - capsula-sphere overlap is eariser to calculate as line-point distance
    - capsula is more difficult to construct than cylinder ( needs sqrt per each point     `tc = sqrt(Rc^2-ri^2) - ti`      )

### Rotated BBox
 - Often most thightly-fitting shape from all easy-to-calculate shapes
 - Can rotate easily with objects
 - evaluating overlap of two differently rotated shapes may be rather complicated and costly

### Elipsoiede
 - it is just sphere in distorted space
 - however interaction of two differently rotated elipsoides can be difficult - it can be transformed to sphere-elipsoide intersection


text:
package org.xbmc.kore.testutils;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;

import org.xbmc.kore.host.HostInfo;
import org.xbmc.kore.host.HostManager;
import org.xbmc.kore.jsonrpc.ApiException;
import org.xbmc.kore.jsonrpc.ApiList;
import org.xbmc.kore.host.HostConnection;
import org.xbmc.kore.jsonrpc.method.AudioLibrary;
import org.xbmc.kore.jsonrpc.method.VideoLibrary;
import org.xbmc.kore.jsonrpc.type.AudioType;
import org.xbmc.kore.jsonrpc.type.LibraryType;
import org.xbmc.kore.jsonrpc.type.VideoType;
import org.xbmc.kore.provider.MediaContract;
import org.xbmc.kore.service.library.SyncMusic;
import org.xbmc.kore.service.library.SyncMusicVideos;
import org.xbmc.kore.service.library.SyncTVShows;
import org.xbmc.kore.service.library.SyncUtils;
import org.xbmc.kore.utils.LogUtils;

import java.io.IOException;
import java.util.ArrayList;

public class Database {
    public static final String TAG = LogUtils.makeLogTag(Database.class);

    public static HostInfo fill(HostInfo hostInfo, Context context, ContentResolver contentResolver) throws ApiException, IOException {
        SyncMusic syncMusic = new SyncMusic(null);
        insertMovies(context, contentResolver, hostInfo.getId());
        insertArtists(context, contentResolver, syncMusic, hostInfo.getId());
        insertGenres(context, contentResolver, syncMusic, hostInfo.getId());
        insertAlbums(context, contentResolver, syncMusic, hostInfo.getId());
        insertSongs(context, contentResolver, syncMusic, hostInfo.getId());

        SyncTVShows syncTVShows = new SyncTVShows(hostInfo.getId(), null);
        insertTVShows(context, contentResolver, syncTVShows);

        SyncMusicVideos syncMusicVideos = new SyncMusicVideos(hostInfo.getId(), null);
        insertMusicVideos(context, contentResolver, syncMusicVideos);

        return hostInfo;
    }

    public static void flush(ContentResolver contentResolver) {
        contentResolver.delete(MediaContract.Hosts.CONTENT_URI, null, null);
    }

    public static HostInfo addHost(Context context) {
        return addHost(context, "127.0.0.1", HostConnection.PROTOCOL_TCP,
                       HostInfo.DEFAULT_HTTP_PORT, HostInfo.DEFAULT_TCP_PORT, false,
                       HostInfo.DEFAULT_KODI_VERSION_MAJOR);

    }

    public static HostInfo addHost(Context context, String hostname, int protocol, int httpPort,
                                   int tcpPort, boolean useEventServer, int kodiMajorVersion) {
        return HostManager.getInstance(context).addHost("TestHost", hostname, protocol, httpPort,
                                                        tcpPort, null, null, "52:54:00:12:35:02", 9, true,
                                                        useEventServer, HostInfo.DEFAULT_EVENT_SERVER_PORT,
                                                        kodiMajorVersion,
                                                        HostInfo.DEFAULT_KODI_VERSION_MINOR,
                                                        HostInfo.DEFAULT_KODI_VERSION_REVISION,
                                                        HostInfo.DEFAULT_KODI_VERSION_TAG,
                                                        false);
    }

    private static void insertMovies(Context context, ContentResolver contentResolver, int hostId)
            throws ApiException, IOException {
        VideoLibrary.GetMovies getMovies = new VideoLibrary.GetMovies();
        String result = FileUtils.readFile(context, "Video.Details.Movie.json");
        ApiList<VideoType.DetailsMovie> movieList = getMovies.resultFromJson(result);

        ContentValues[] movieValuesBatch = new ContentValues[movieList.items.size()];
        int castCount = 0;

        // Iterate on each movie
        for (int i = 0; i < movieList.items.size(); i++) {
            VideoType.DetailsMovie movie = movieList.items.get(i);
            movieValuesBatch[i] = SyncUtils.contentValuesFromMovie(hostId, movie);
            castCount += movie.cast.size();
        }

        contentResolver.bulkInsert(MediaContract.Movies.CONTENT_URI, movieValuesBatch);

        ContentValues[] movieCastValuesBatch = new ContentValues[castCount];
        int count = 0;
        // Iterate on each movie/cast
        for (VideoType.DetailsMovie movie : movieList.items) {
            for (VideoType.Cast cast : movie.cast) {
                movieCastValuesBatch[count] = SyncUtils.contentValuesFromCast(hostId, cast);
                movieCastValuesBatch[count].put(MediaContract.MovieCastColumns.MOVIEID, movie.movieid);
                count++;
            }
        }

        contentResolver.bulkInsert(MediaContract.MovieCast.CONTENT_URI, movieCastValuesBatch);
    }

    private static void insertArtists(Context context, ContentResolver contentResolver, SyncMusic syncMusic, int hostId) throws ApiException, IOException {
        AudioLibrary.GetArtists getArtists = new AudioLibrary.GetArtists(false);
        String result = FileUtils.readFile(context, "AudioLibrary.GetArtists.json");
        ArrayList<AudioType.DetailsArtist> artistList = (ArrayList<AudioType.DetailsArtist>) getArtists.resultFromJson(result).items;

        syncMusic.insertArtists(hostId, artistList, contentResolver);
    }

    private static void insertGenres(Context context, ContentResolver contentResolver, SyncMusic syncMusic, int hostId) throws ApiException, IOException {
        AudioLibrary.GetGenres getGenres = new AudioLibrary.GetGenres();
        ArrayList<LibraryType.DetailsGenre> genreList =
                (ArrayList<LibraryType.DetailsGenre>) getGenres.resultFromJson(FileUtils.readFile(context,
                                                                        "AudioLibrary.GetGenres.json"));

        syncMusic.insertGenresItems(hostId, genreList, contentResolver);
    }

    private static void insertAlbums(Context context, ContentResolver contentResolver, SyncMusic syncMusic, int hostId) throws ApiException, IOException {
        AudioLibrary.GetAlbums getAlbums = new AudioLibrary.GetAlbums();
        String result = FileUtils.readFile(context, "AudioLibrary.GetAlbums.json");
        ArrayList<AudioType.DetailsAlbum> albumList = (ArrayList<AudioType.DetailsAlbum>) getAlbums.resultFromJson(result).items;

        syncMusic.insertAlbumsItems(hostId, albumList, contentResolver);
    }

    private static void insertSongs(Context context, ContentResolver contentResolver, SyncMusic syncMusic, int hostId) throws ApiException, IOException {
        AudioLibrary.GetSongs getSongs = new AudioLibrary.GetSongs();
        ArrayList<AudioType.DetailsSong> songList =
                (ArrayList<AudioType.DetailsSong>) getSongs.resultFromJson(FileUtils.readFile(context, "AudioLibrary.GetSongs.json")).items;

        syncMusic.insertSongsItems(hostId, songList, contentResolver);
    }

    private static void insertTVShows(Context context, ContentResolver contentResolver, SyncTVShows syncTVShows)
            throws ApiException, IOException {
        VideoLibrary.GetTVShows getTVShows = new VideoLibrary.GetTVShows();
        String result = FileUtils.readFile(context, "VideoLibrary.GetTVShows.json");
        ArrayList<VideoType.DetailsTVShow> tvShowList = (ArrayList<VideoType.DetailsTVShow>) getTVShows.resultFromJson(result).items;

        syncTVShows.insertTVShows(tvShowList, contentResolver);

        for ( VideoType.DetailsTVShow tvShow : tvShowList ) {
            VideoLibrary.GetSeasons getSeasons = new VideoLibrary.GetSeasons(tvShow.tvshowid);
            result = FileUtils.readFile(context, "VideoLibrary.GetSeasons.json");
            ArrayList<VideoType.DetailsSeason> detailsSeasons = (ArrayList<VideoType.DetailsSeason>) getSeasons.resultFromJson(result);
            syncTVShows.insertSeason(tvShow.tvshowid, detailsSeasons, contentResolver);
        }

        VideoLibrary.GetEpisodes getEpisodes = new VideoLibrary.GetEpisodes(0);
        result = FileUtils.readFile(context, "VideoLibrary.GetEpisodes.json");
        ArrayList<VideoType.DetailsEpisode> detailsEpisodes = (ArrayList<VideoType.DetailsEpisode>) getEpisodes.resultFromJson(result);
        syncTVShows.insertEpisodes(detailsEpisodes, contentResolver);
    }

    private static void insertMusicVideos(Context context, ContentResolver contentResolver, SyncMusicVideos syncMusicVideos)
        throws ApiException, IOException {
        VideoLibrary.GetMusicVideos getMusicVideos = new VideoLibrary.GetMusicVideos();
        String result = FileUtils.readFile(context, "VideoLibrary.GetMusicVideos.json");
        ArrayList<VideoType.DetailsMusicVideo> musicVideoList = (ArrayList<VideoType.DetailsMusicVideo>) getMusicVideos.resultFromJson(result);

        syncMusicVideos.insertMusicVideos(musicVideoList, contentResolver);
    }
}


text:
package applicationendpoint

import (
	"fmt"

	"strings"
)

// An exposed service endpoint
type ApplicationEndpoint struct {
	ServiceID      string
	InstanceID     int
	Application    string
	Purpose        string
	HostID         string
	HostIP         string // Host where the endpoint is running. Used to determine if it's running locally or if we need to mux it
	HostPort       uint16
	ContainerID    string
	ContainerIP    string // The container IP that we're routing to (usually a container except for the cc api endpoint)
	ContainerPort  uint16 // The container port that we're routing to
	Protocol       string
	VirtualAddress string
	ProxyPort      uint16 // The port in the container we're listening on
}

type EndpointReport struct {
	Endpoint ApplicationEndpoint

	// FIXME: Refactor into some kind of array of typed messages (e.g. info, warn and error)
	Messages []string
}

// BuildEndpointReports converts an array of ApplicationEndpoints to an array of EndpointReports
func BuildEndpointReports(appEndpoints []ApplicationEndpoint) []EndpointReport {
	endpoints := make([]EndpointReport, 0)
	for _, appEndpoint := range appEndpoints {
		endpoints = append(endpoints, EndpointReport{Endpoint: appEndpoint, Messages: []string{}})
	}
	return endpoints
}

// Returns a string which uniquely identifies an endpoint instance
func (endpoint *ApplicationEndpoint) GetID() string {
	return strings.ToLower(fmt.Sprintf("%s/%d %s %s", endpoint.ServiceID, endpoint.InstanceID, endpoint.Purpose, endpoint.Application))
}

// Find the entry in endpoints which matches the specified endpoint
func (endpoint *ApplicationEndpoint) Find(endpoints []ApplicationEndpoint) *ApplicationEndpoint {
	// Yes, this is brute-force linear search, but in practice the lists should be small, few 10s at most
	endpointID := endpoint.GetID()
	for _, entry := range endpoints {
		if entry.GetID() == endpointID {
			return &entry
		}
	}
	return nil
}

// Equals verifies whether two endpoint objects are equal
func (a *ApplicationEndpoint) Equals(b *ApplicationEndpoint) bool {
	if a.ServiceID != b.ServiceID {
		return false
	}
	if a.InstanceID != b.InstanceID {
		return false
	}
	if a.Application != b.Application {
		return false
	}
	if a.Purpose != b.Purpose {
		return false
	}
	if a.HostID != b.HostID {
		return false
	}
	if a.HostIP != b.HostIP {
		return false
	}
	if a.HostPort != b.HostPort {
		return false
	}
	if a.ContainerID != b.ContainerID {
		return false
	}
	if a.ContainerIP != b.ContainerIP {
		return false
	}
	if a.ContainerPort != b.ContainerPort {
		return false
	}
	if a.Protocol != b.Protocol {
		return false
	}
	if a.VirtualAddress != b.VirtualAddress {
		return false
	}
	return true
}

// ApplicationEndpointSlice is an ApplicationEndpoint array sortable by ServiceID, InstanceID, and Application
type ApplicationEndpointSlice []ApplicationEndpoint

func (s ApplicationEndpointSlice) Len() int {
	return len(s)
}

func (s ApplicationEndpointSlice) Less(i, j int) bool {
	return s[i].GetID() < s[j].GetID()
}

func (s ApplicationEndpointSlice) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}


text:
#pragma once
#include <aws/iotevents/IoTEvents_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/iotevents/model/Payload.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace IoTEvents
{
namespace Model
{

  /**
   *
Sends an AWS IoT Events input, passing in information about the detector
   * model instance and the event that triggered the action.

See Also:

   * AWS
   * API Reference

   */
  class AWS_IOTEVENTS_API IotEventsAction
  {
  public:
    IotEventsAction();
    IotEventsAction(Aws::Utils::Json::JsonView jsonValue);
    IotEventsAction& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The name of the AWS IoT Events input where the data is sent.

     */
    inline const Aws::String& GetInputName() const{ return m_inputName; }

    /**
     *
The name of the AWS IoT Events input where the data is sent.

     */
    inline bool InputNameHasBeenSet() const { return m_inputNameHasBeenSet; }

    /**
     *
The name of the AWS IoT Events input where the data is sent.

     */
    inline void SetInputName(const Aws::String& value) { m_inputNameHasBeenSet = true; m_inputName = value; }

    /**
     *
The name of the AWS IoT Events input where the data is sent.

     */
    inline void SetInputName(Aws::String&& value) { m_inputNameHasBeenSet = true; m_inputName = std::move(value); }

    /**
     *
The name of the AWS IoT Events input where the data is sent.

     */
    inline void SetInputName(const char* value) { m_inputNameHasBeenSet = true; m_inputName.assign(value); }

    /**
     *
The name of the AWS IoT Events input where the data is sent.

     */
    inline IotEventsAction& WithInputName(const Aws::String& value) { SetInputName(value); return *this;}

    /**
     *
The name of the AWS IoT Events input where the data is sent.

     */
    inline IotEventsAction& WithInputName(Aws::String&& value) { SetInputName(std::move(value)); return *this;}

    /**
     *
The name of the AWS IoT Events input where the data is sent.

     */
    inline IotEventsAction& WithInputName(const char* value) { SetInputName(value); return *this;}

    /**
     *
You can configure the action payload when you send a message to an AWS IoT
     * Events input.

     */
    inline const Payload& GetPayload() const{ return m_payload; }

    /**
     *
You can configure the action payload when you send a message to an AWS IoT
     * Events input.

     */
    inline bool PayloadHasBeenSet() const { return m_payloadHasBeenSet; }

    /**
     *
You can configure the action payload when you send a message to an AWS IoT
     * Events input.

     */
    inline void SetPayload(const Payload& value) { m_payloadHasBeenSet = true; m_payload = value; }

    /**
     *
You can configure the action payload when you send a message to an AWS IoT
     * Events input.

     */
    inline void SetPayload(Payload&& value) { m_payloadHasBeenSet = true; m_payload = std::move(value); }

    /**
     *
You can configure the action payload when you send a message to an AWS IoT
     * Events input.

     */
    inline IotEventsAction& WithPayload(const Payload& value) { SetPayload(value); return *this;}

    /**
     *
You can configure the action payload when you send a message to an AWS IoT
     * Events input.

     */
    inline IotEventsAction& WithPayload(Payload&& value) { SetPayload(std::move(value)); return *this;}

  private:

    Aws::String m_inputName;
    bool m_inputNameHasBeenSet;

    Payload m_payload;
    bool m_payloadHasBeenSet;
  };

} // namespace Model
} // namespace IoTEvents
} // namespace Aws


text:
import asyncio
import re

from asyncio import ensure_future
from ftplib import FTP
from io import BytesIO

from concurrent.futures import ThreadPoolExecutor

from pypeman import channels, nodes, message

# Can be redefined
default_thread_pool = ThreadPoolExecutor(max_workers=3)

class FTPConnection():
    """
    FTP connection manager.
    """
    def __init__(self, host, port, credentials):
        """
        :param host: FTP host.
        :param port: FTP port
        :param credentials: A tuple with (login, password,)
        :return:
        """
        self.host = host
        self.port = port
        self.credentials = credentials

    def __enter__(self):
        self.ftp = FTP(self.host)
        self.ftp.login(*self.credentials)
        return self.ftp

    def __exit__(self, type, value, tb):
        try:
            self.ftp.quit()
        except Exception:
            self.ftp.close()

class FTPHelper():
    """
    FTP helper to abstract ftp access.
    """
    # TODO reuse ftp connection if possible

    def __init__(self, host, port, credentials):
        self.host = host
        self.port = port
        self.credentials = credentials

    def list_dir(self, path):
        with FTPConnection(self.host, self.port, self.credentials) as ftp_conn:
            ftp_conn.cwd(path)
            return set(ftp_conn.nlst())

    def download_file(self, filepath):
        """
        Download a file from ftp asynchronously.
        :param filepath: file path to download.
        :return: content of the file.
        """
        output = BytesIO()

        # Get file from ftp
        with FTPConnection(self.host, self.port, self.credentials) as ftp_conn:
            ftp_conn.retrbinary("RETR %s" % filepath, output.write)

        content = output.getvalue()
        output.close()

        return content

    def upload_file(self, filepath, content):
        """
        Upload an file to ftp.
        :param filepath: Path of file to create.
        :param content: Content to upload.
        """
        input = BytesIO(content)

        # Get file from ftp
        with FTPConnection(self.host, self.port, self.credentials) as ftp_conn:
            ftp_conn.storbinary('STOR %s' % filepath, input)

        input.close()

        return content

    def rename(self, fromfilepath, tofilepath):
        """
        Rename a file from path to another path in ftp.
        :param fromfilepath: original file to rename.
        :param tofilepath: destination file.
        """
        with FTPConnection(self.host, self.port, self.credentials) as ftp_conn:
            ftp_conn.rename(fromfilepath, tofilepath)

    def delete(self, filepath):
        """
        Delete an FTP file.
        :param filepath: File to delete.
        """
        with FTPConnection(self.host, self.port, self.credentials) as ftp_conn:
            ftp_conn.delete(filepath)

class FTPWatcherChannel(channels.BaseChannel):
    """
    Channel that watch ftp for file creation.
    """
    def __init__(self, *args, host="", port=21, credentials="", basedir="", regex='.*',
                 interval=60, delete_after=False, encoding="utf-8",
                 thread_pool=None, sort_function=sorted, **kwargs):
        super().__init__(*args, **kwargs)

        self.basedir = basedir
        self.interval = interval
        self.delete_after = delete_after
        self.re = re.compile(regex)
        self.encoding = encoding
        self.sort_function = sort_function
        self.ls_prev = set()

        # pool used to make ftp connection out of thread
        self.executor = thread_pool or default_thread_pool

        self.ftphelper = FTPHelper(host, port, credentials)

    async def start(self):
        await super().start()
        ensure_future(self.watch_for_file(), loop=self.loop)

    def download_file(self, filename):
        """
        Download a file from ftp asynchronously.

        :param filepath: file path to download.

        :return: Content of the downloaded file.
        """
        if not self.is_stopped():
            return self.ftphelper.download_file(self.basedir + '/' + filename)

    async def get_file_and_process(self, filename):
        """
        Download a file from ftp and launch channel processing on msg with result as payload.
        Also add a `filepath` header with ftp relative path of downloaded file.

        :param filename: file to download relative to `basedir`.

        :return: processed result
        """

        payload = await self.loop.run_in_executor(self.executor, self.download_file, filename)

        msg = message.Message()
        msg.payload = payload
        msg.meta['filepath'] = self.basedir + '/' + filename

        if not self.is_stopped():
            result = await super().handle(msg)

            if self.delete_after:
                await self.loop.run_in_executor(
                                self.executor,
                                self.ftphelper.delete,
                                self.basedir + '/' + filename)

            return result

    async def tick(self):
        """
        One iteration of watching.
        """

        ls = await self.loop.run_in_executor(self.executor, self.ftphelper.list_dir, self.basedir)

        # Make diff from previous one.
        added = self.sort_function(ls-self.ls_prev)
        self.ls_prev = ls

        for filename in added:
            if self.re.match(filename) and not self.is_stopped():
                ensure_future(self.get_file_and_process(filename), loop=self.loop)

    async def watch_for_file(self):
        """
        Watch recursively for ftp new files.
        If file match regex, it is downloaded then processed in a message.
        """
        await asyncio.sleep(self.interval, loop=self.loop)
        try:
            await self.tick()
        finally:
            if not self.is_stopped():
                ensure_future(self.watch_for_file(), loop=self.loop)

class FTPFileReader(nodes.ThreadNode):
    """
    Node to read a file from FTP.
    """
    def __init__(self, host="", port=21, credentials=None, filepath=None, **kwargs):

        super().__init__(**kwargs)

        self.filepath = filepath

        self.ftphelper = FTPHelper(host, port, credentials)

    def process(self, msg):

        filepath = nodes.choose_first_not_none(
            nodes.callable_or_value(self.filepath, msg),
            msg.meta.get('filepath'))

        content = self.ftphelper.download_file(filepath)

        msg.payload = content
        msg.meta['filepath'] = filepath

        return msg

class FTPFileDeleter(nodes.ThreadNode):
    """
    Node to delete a file from FTP.
    """
    def __init__(self, host="", port=21, credentials=None, filepath=None, **kwargs):

        super().__init__(**kwargs)

        self.filepath = filepath

        self.ftphelper = FTPHelper(host, port, credentials)

    def process(self, msg):

        filepath = nodes.choose_first_not_none(
            nodes.callable_or_value(self.filepath, msg),
            msg.meta.get('filepath'))

        self.ftphelper.delete(filepath)

        return msg

class FTPFileWriter(nodes.ThreadNode):
    """
    Node to write content to FTP. File is first written with `.part` concatenated
    to its name then renamed to avoid partial upload.
    """
    def __init__(self, host="", port=21, credentials=None, filepath=None, **kwargs):

        super().__init__(**kwargs)

        self.filepath = filepath

        self.ftphelper = FTPHelper(host, port, credentials)

    def process(self, msg):

        filepath = nodes.choose_first_not_none(
            nodes.callable_or_value(self.filepath, msg),
            msg.meta.get('filepath'))

        self.ftphelper.upload_file(filepath + '.part', msg.payload)
        self.ftphelper.rename(filepath + '.part', filepath)

        return msg


text:
<?php declare(strict_types=1);
/**
 * Represents a base Object.
 */

namespace OsuApi\Objects;

abstract class Object {
	public function __toString() : string {
		return print_r($this, true);
	}
}


text:
package nonimmutables;

import java.util.Collections;
import java.util.Iterator;

// Dummy custom collection, mostly for compilation testing
public final class CustColl<E> implements Iterable<E> {

  @Override
  public Iterator<E> iterator() {
    return Collections.emptyIterator();
  }

  public static <E> CustColl<E> from(Iterable<? extends E> elements) {
    elements.toString();
    return new CustColl<>();
  }

  public static <E> CustColl<E> of() {
    return new CustColl<>();
  }

  public static <E> Builder<E> builder() {
    return new Builder<>();
  }

  public static class Builder<E> {
    public Builder<E> addAll(Iterable<? extends E> elements) {
      elements.toString();
      return this;
    }

    public Builder<E> add(E element) {
      element.toString();
      return this;
    }

    public CustColl<E> build() {
      return new CustColl<>();
    }
  }
}


text:
class CreatePtickets < ActiveRecord::Migration
  def change
    create_table :ptickets do |t|
    	t.string :eventName
    	t.integer :quantity

      t.timestamps
    end
  end
end


text:
;(function(window, Reveal, hljs) {
  if (typeof window.RevealCodeFocus == 'function') {
    return;
  }

  var currentSlide, currentFragments, scrollToFocused, prevSlideData = null;

  function forEach(array, callback) {
    var i = -1, length = array ? array.length : 0;
    while (++i < length) {
      callback(array[i]);
    }
  }

  function indexOf(array, elem) {
    var i = -1, length = array ? array.length : 0;
    while (++i < length) {
      if (array[i] === elem) {
        return i;
      }
    }
  }

  var ran;
  function init(e) {
    // Initialize code only once.
    // TODO: figure out why `init` is being called twice.
    if (ran) {
      return;
    }
    ran = true;

    forEach(document.querySelectorAll('pre code'), function(element) {
      // Trim whitespace if the `data-trim` attribute is present.
      if (element.hasAttribute('data-trim') && typeof element.innerHTML.trim == 'function') {
        element.innerHTML = element.innerHTML.trim();
      }

      // Highlight code using highlight.js.
      hljs.highlightBlock(element);

      // Split highlighted code into lines.
      var openTags = [], reHtmlTag = /<(\/?)span(?:\s+(?:class=(['"])hljs-.*?\2)?\s*|\s*)>/g;
      element.innerHTML = element.innerHTML.replace(/(.*?)\r?\n/g, function(_, string) {
        if (!string) {
          return ' ';
        }
        var openTag, stringPrepend;
        // Re-open all tags that were previously closed.
        if (openTags.length) {
          stringPrepend = openTags.join('');
        }
        // Match all HTML `<span>` tags.
        reHtmlTag.lastIndex = 0;
        while (openTag = reHtmlTag.exec(string)) {
          // If it is a closing tag, remove the opening tag from the list.
          if (openTag[1]) {
            openTags.pop();
          }
          // Otherwise if it is an opening tag, push it to the list.
          else {
            openTags.push(openTag[0]);
          }
        }
        // Close all opened tags, so that strings can be wrapped with `span.line`.
        if (openTags.length) {
          string += Array(openTags.length + 1).join('');
        }
        if (stringPrepend) {
          string = stringPrepend + string;
        }
        return '' + string + '';
      });
    });

    Reveal.addEventListener('slidechanged', updateCurrentSlide);

    Reveal.addEventListener('fragmentshown', function(e) {
      focusFragment(e.fragment);
    });

    // When a fragment is hidden, clear the current focused fragment,
    // and focus on the previous fragment.
    Reveal.addEventListener('fragmenthidden', function(e) {
      var index = indexOf(currentFragments, e.fragment);
      focusFragment(currentFragments[index - 1]);
    });

    updateCurrentSlide(e);
  }

  function updateCurrentSlide(e) {
    currentSlide = e.currentSlide;
    currentFragments = currentSlide.getElementsByClassName('fragment');
    clearPreviousFocus();
    if (
        currentFragments.length &&
        prevSlideData &&
        (
          prevSlideData.indexh > e.indexh ||
          (prevSlideData.indexh == e.indexh && prevSlideData.indexv > e.indexv)
        )
    ) {
      while (Reveal.nextFragment()) {}
      var currentFragment = currentFragments[currentFragments.length - 1];
      currentFragment.classList.add('current-fragment');
      focusFragment(currentFragment);
    }
    // Update previous slide information.
    prevSlideData = {
      'indexh': e.indexh,
      'indexv': e.indexv
    };
  }

  // Remove
  function clearPreviousFocus() {
    forEach(currentSlide.querySelectorAll('pre code .line.focus'), function(line) {
      line.classList.remove('focus');
    });
  }

  function focusFragment(fragment) {
    clearPreviousFocus();
    if (!fragment) {
      return;
    }

    var lines = fragment.getAttribute('data-code-focus');
    if (!lines) {
      return;
    }

    var code = currentSlide.querySelectorAll('pre code .line'),
        codeParent, scrollLineTop, scrollLineBottom;

    function focusLine(lineNumber) {
      var line = code[lineNumber - 1];
      if (!line) {
        return;
      }

      line.classList.add('focus');

      if (scrollLineTop == null) {
        scrollLineTop = scrollLineBottom = lineNumber - 1;
      } else {
        scrollLineTop = Math.min(scrollLineTop, line.offsetTop);
        scrollLineBottom = Math.max(scrollLineBottom, lineNumber - 1);
      }
    }

    forEach(lines.split(','), function(line) {
      lines = line.split('-');
      if (lines.length == 1) {
        focusLine(lines[0]);
      } else {
        var i = lines[0] - 1, j = lines[1];
        while (++i <= j) {
          focusLine(i);
        }
      }
    });

    if (scrollToFocused && scrollLineTop != null) {
      codeParent = code[scrollLineTop].parentNode;
      scrollLineTop = code[scrollLineTop].offsetTop;
      scrollLineBottom = code[scrollLineBottom].offsetTop + code[scrollLineBottom].clientHeight;
      codeParent.scrollTop = scrollLineTop - (codeParent.clientHeight - (scrollLineBottom - scrollLineTop)) / 2;
    }
  }

  function RevealCodeFocus(options) {
    options || (options = {
      'scrollToFocused': true
    });

    if (options.scrollToFocused != null) {
      scrollToFocused = options.scrollToFocused;
    }

    if (Reveal.isReady()) {
      init({ currentSlide: Reveal.getCurrentSlide() });
    } else {
      Reveal.addEventListener('ready', init);
    }
  }

  window.RevealCodeFocus = RevealCodeFocus;
}(this, this.Reveal, this.hljs));


text:
#ifndef __kmnd_malloc_h
#define __kmnd_malloc_h

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

#include <unistd.h>

unsigned char kmnd_mem_valid(const void *pointer);

ssize_t kmnd_mem_usage(void);

void kmnd_mem_disable_start(void);
unsigned char kmnd_mem_disable_end(void);

#define KMND_MEM_LEAK_PRE()  const ssize_t prior = kmnd_mem_usage();
#define KMND_MEM_LEAK_POST() EXPECT_EQ(0, kmnd_mem_usage() - prior);

#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* __kmnd_malloc_h */


text:
#pragma once

#if ENABLE(CONTEXT_MENUS)

#include <wtf/Forward.h>

namespace WebCore {

    class Frame;
    class URL;

    class ContextMenuClient {
    public:
        virtual ~ContextMenuClient() = default;
        virtual void contextMenuDestroyed() = 0;

        virtual void downloadURL(const URL& url) = 0;
        virtual void searchWithGoogle(const Frame*) = 0;
        virtual void lookUpInDictionary(Frame*) = 0;
        virtual bool isSpeaking() = 0;
        virtual void speak(const String&) = 0;
        virtual void stopSpeaking() = 0;

#if PLATFORM(COCOA)
        virtual void searchWithSpotlight() = 0;
#endif

#if USE(ACCESSIBILITY_CONTEXT_MENUS)
        virtual void showContextMenu() = 0;
#endif
    };

} // namespace WebCore

#endif // ENABLE(CONTEXT_MENUS)


text:
<?php declare(strict_types=1);
namespace Phan\Language\Type;

class ObjectType extends NativeType {
    const NAME = 'object';
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="<?php echo base_url("assets/css/bootstrap.css"); ?>" />
    <link rel="stylesheet" href="<?php echo base_url("assets/css/bootstrap-switch.min.css"); ?>" />

    <title>EDS Palonegro</title>

     <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
       Toggle navigation

     </button>
     EDS Palonegro

<a href="<?php echo base_url('index.php/panel_usr'); ?>">Inicio(current)

Perfil

            Ver

            <?php
            if($this->session->has_userdata('nom_entidades'))
            {
              echo "
";
              $nom=$this->session->userdata('nom_entidades');
              $id=$this->session->userdata('id_entidades');
              for ($i=0; $i < count($id); $i++)
              {
                echo "
".$nom[$i]."
";
              }
              echo '
';
            }
            ?>

<?php echo anchor(base_url('index.php/log_usr/log_out'), 'Cerrar sesión')?>

      <?php echo "
".anchor(base_url('index.php/panel_usr'), 'INICIO',"")."
" ?>
      <?php echo "
".anchor(base_url('index.php/panel_enti/datenti/'.$this->session->userdata('act_enti')),getname_enti(),"")."
" ?>
      <?php echo "
".anchor(base_url('index.php/panel_mod/datamod/04'), 'CAJA',"")."
" ?>

PROVEEDORES

Proveedores

        Crear, editar y visualizar datos personales de proveedores.

        <button type="button" id='new_proveedor' class="btn btn-info" data-toggle="modal" data-target="#proveedor">Agregar proveedor</button>

                Nit o Identificación
                Nombre
                Dirección
                Teléfono
                E-mail
                Ciudad
                Acciones

            <button type="button" class="close" data-dismiss="modal">×</button>

Proveedores

            <form role="form" class="form_size" id="form">

                Nit o identificación
                <input type="text" class="form-control" id="nit" name="nit" placeholder="Nit o Identificación">

Número de Nit o identificación ya existe.

                Nombre proveedor
                <input type="text" class="form-control" id="nom_pro" name="nom_pro">

                Dirección proveedor
                <input type="text" class="form-control" id="dir_pro" name="dir_pro">

                Teléfono proveedor
                <input type="text" class="form-control" id="tel_pro" name="tel_pro">

                E-mail proveedor
                <input type="text" class="form-control" id="email_pro" name="email_pro">

                Ciudad proveedor
                <input type="text" class="form-control" id="ciudad" name="ciudad">

              <button type="button" id='pro_clear' class="btn btn-danger">Limpiar</button>
              <button type="button" id='pro_modify' class="btn btn-info">Modificar</button>
              <button type="button" id='pro_send' class="btn btn-success">Registrar</button>
            </form>

            <button type="button" id="modal_pro" class="btn btn-default" data-dismiss="modal">Cerrar</button>

  <link rel="stylesheet" type="text/css" href="<?php echo base_url("assets/public/css/style.css"); ?>">


text:
/**
 * Created by serhii.holdun on 10/6/15.
 */

var employeeServices = angular.module('huntCoder.employeeServices', ['elasticsearch']);

employeeServices.factory('employeesService',
    ['$q', 'esFactory', function($q, esFactory){
            var client = esFactory({
            host: 'localhost:9201'
        });

        /**
         * Given a term and an offset, load another round of 10 employees.
         *
         * Returns a promise.
         */
        var search = function(term, offset){
            var deferred = $q.defer();
            var query = {
                "match": {
                    "_all": term
                }
            };
            console.log(term);
            client.search({
                "index": 'employees',
                "type": 'employee',
                "body": {
                    "size": 10,
                    "from": (offset || 0) * 10,
                    "query": query
                }
            }).then(function(result) {
                console.log(result.hits);
                var ii = 0, hits_in, hits_out = [];
                hits_in = (result.hits || {}).hits || [];
                for(;ii < hits_in.length; ii++){
                    hits_out.push(hits_in[ii]._source);
                }
                deferred.resolve(hits_out);
            }, deferred.reject);

            return deferred.promise;
        };

        return {
            "search": search
        };
    }]
);


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by CodeZu.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

var Client = require('../../../client'), constants = Client.constants;

module.exports = Client.sub({
	getCheckoutSettings: Client.method({
		method: constants.verbs.GET,
		url: '{+tenantPod}api/commerce/settings/checkout/?responseFields={responseFields}'
	})
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
    jcr:description="Path Browser With Preview"
    jcr:primaryType="cq:Component"
    jcr:title="Path Browser With Preview"
    sling:resourceSuperType="foundation/components/parbasse"
    componentGroup="AEM Dev Components"/>


text:
package com.navercorp.nbasearc.gcp;

import java.util.concurrent.TimeUnit;

import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;

import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;

class SingleThreadEventLoop {
    private final EventLoopGroup eventLoop;
    private final HashedTimingWheel timer;

    SingleThreadEventLoop() {
        this.eventLoop = new NioEventLoopGroup(1);
        this.timer = new HashedTimingWheel(500, 256);
    }

    void init() {
        eventLoop.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    beCron();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 1, 1000, TimeUnit.MILLISECONDS);
    }

    private void beCron() {
        final long currTimestamp = System.currentTimeMillis();
        timer.processLines(currTimestamp);
    }

    ListenableFuture<?> close() {
        final SettableFuture<?> sf = SettableFuture.create();

        eventLoop.execute(new Runnable() {
            @Override
            public void run() {
                eventLoop.shutdownGracefully();
                sf.set(null);
            }
        });

        return sf;
    }

    void addTimer(TimerCallback tc) {
        timer.add(tc);
    }

    void delTimer(TimerCallback tc) {
        timer.del(tc);
    }

    EventLoopGroup getEventLoopGroup() {
        return eventLoop;
    }
}


text:
/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 3.0.7
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */
package com.ctp.field;

import com.ctp.swig.ctpJNI;

public class CThostFtdcMarketDataStaticField
{
	private transient long swigCPtr;
	protected transient boolean swigCMemOwn;

	protected CThostFtdcMarketDataStaticField(long cPtr, boolean cMemoryOwn)
	{
		swigCMemOwn = cMemoryOwn;
		swigCPtr = cPtr;
	}

	public static long getCPtr(CThostFtdcMarketDataStaticField obj)
	{
		return (obj == null) ? 0 : obj.swigCPtr;
	}

	protected void finalize()
	{
		delete();
	}

	public synchronized void delete()
	{
		if (swigCPtr != 0)
		{
			if (swigCMemOwn)
			{
				swigCMemOwn = false;
				ctpJNI.delete_CThostFtdcMarketDataStaticField(swigCPtr);
			}
			swigCPtr = 0;
		}
	}

	public void setOpenPrice(double value)
	{
		ctpJNI.CThostFtdcMarketDataStaticField_OpenPrice_set(swigCPtr, this, value);
	}

	public double getOpenPrice()
	{
		return ctpJNI.CThostFtdcMarketDataStaticField_OpenPrice_get(swigCPtr, this);
	}

	public void setHighestPrice(double value)
	{
		ctpJNI.CThostFtdcMarketDataStaticField_HighestPrice_set(swigCPtr, this, value);
	}

	public double getHighestPrice()
	{
		return ctpJNI.CThostFtdcMarketDataStaticField_HighestPrice_get(swigCPtr, this);
	}

	public void setLowestPrice(double value)
	{
		ctpJNI.CThostFtdcMarketDataStaticField_LowestPrice_set(swigCPtr, this, value);
	}

	public double getLowestPrice()
	{
		return ctpJNI.CThostFtdcMarketDataStaticField_LowestPrice_get(swigCPtr, this);
	}

	public void setClosePrice(double value)
	{
		ctpJNI.CThostFtdcMarketDataStaticField_ClosePrice_set(swigCPtr, this, value);
	}

	public double getClosePrice()
	{
		return ctpJNI.CThostFtdcMarketDataStaticField_ClosePrice_get(swigCPtr, this);
	}

	public void setUpperLimitPrice(double value)
	{
		ctpJNI.CThostFtdcMarketDataStaticField_UpperLimitPrice_set(swigCPtr, this, value);
	}

	public double getUpperLimitPrice()
	{
		return ctpJNI.CThostFtdcMarketDataStaticField_UpperLimitPrice_get(swigCPtr, this);
	}

	public void setLowerLimitPrice(double value)
	{
		ctpJNI.CThostFtdcMarketDataStaticField_LowerLimitPrice_set(swigCPtr, this, value);
	}

	public double getLowerLimitPrice()
	{
		return ctpJNI.CThostFtdcMarketDataStaticField_LowerLimitPrice_get(swigCPtr, this);
	}

	public void setSettlementPrice(double value)
	{
		ctpJNI.CThostFtdcMarketDataStaticField_SettlementPrice_set(swigCPtr, this, value);
	}

	public double getSettlementPrice()
	{
		return ctpJNI.CThostFtdcMarketDataStaticField_SettlementPrice_get(swigCPtr, this);
	}

	public void setCurrDelta(double value)
	{
		ctpJNI.CThostFtdcMarketDataStaticField_CurrDelta_set(swigCPtr, this, value);
	}

	public double getCurrDelta()
	{
		return ctpJNI.CThostFtdcMarketDataStaticField_CurrDelta_get(swigCPtr, this);
	}

	public CThostFtdcMarketDataStaticField()
	{
		this(ctpJNI.new_CThostFtdcMarketDataStaticField(), true);
	}
}


text:
package nl.vpro.poel.service;

import nl.vpro.poel.domain.Bonus;
import nl.vpro.poel.dto.BonusForm;

import java.time.Instant;
import java.util.List;
import java.util.Optional;

public interface BonusService {

    Optional<Bonus> findById(Long id);

    List<Bonus> findAll();

    List<Bonus> findAllCompleted();

    List<Bonus> findAllUnfinished(Instant instant);

    List<Bonus> findBonusesToPredict(Instant instant);

    void save(BonusForm bonusForm);
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace NekoKun.UI
{
    public class LynnNumericUpDown : NumericUpDown
    {
        internal NativeWindow native;

        public LynnNumericUpDown()
        {
            if (UIManager.Enabled)
                native = new NativeBorder(this, 0xf /* WM_PAINT */, true, false);
        }

    }
}


text:
namespace atom {

namespace {

// Async handle to execute the stored v8 callback.
uv_async_t g_callback_uv_handle;

// Stored v8 callback, to be called by the async handler.
base::Closure g_v8_callback;

// Dummy class type that used for crashing the program.
struct DummyClass { bool crash; };

// Async handler to execute the stored v8 callback.
void UvOnCallback(uv_async_t* handle) {
  g_v8_callback.Run();
}

void Crash() {
  static_cast<DummyClass*>(NULL)->crash = true;
}

// Called when there is a fatal error in V8, we just crash the process here so
// we can get the stack trace.
void FatalErrorCallback(const char* location, const char* message) {
  LOG(ERROR) << "Fatal error in V8: " << location << " " << message;
  Crash();
}

void Log(const base::string16& message) {
  logging::LogMessage("CONSOLE", 0, 0).stream() << message;
}

void ScheduleCallback(const base::Closure& callback) {
  g_v8_callback = callback;
  uv_async_send(&g_callback_uv_handle);
}

}  // namespace

AtomBindings::AtomBindings() {
  uv_async_init(uv_default_loop(), &call_next_tick_async_, OnCallNextTick);
  call_next_tick_async_.data = this;

  uv_async_init(uv_default_loop(), &g_callback_uv_handle, UvOnCallback);
}

AtomBindings::~AtomBindings() {
}

void AtomBindings::BindTo(v8::Isolate* isolate,
                          v8::Handle<v8::Object> process) {
  v8::V8::SetFatalErrorHandler(FatalErrorCallback);

  mate::Dictionary dict(isolate, process);
  dict.SetMethod("crash", &Crash);
  dict.SetMethod("log", &Log);
  dict.SetMethod("scheduleCallback", &ScheduleCallback);
  dict.SetMethod("activateUvLoop",
      base::Bind(&AtomBindings::ActivateUVLoop, base::Unretained(this)));

  v8::Handle<v8::Object> versions;
  if (dict.Get("versions", &versions)) {
    versions->Set(mate::StringToV8(isolate, "atom-shell"),
                  mate::StringToV8(isolate, ATOM_VERSION_STRING));
    versions->Set(mate::StringToV8(isolate, "chrome"),
                  mate::StringToV8(isolate, CHROME_VERSION_STRING));
  }

  v8::Handle<v8::Value> event = mate::StringToV8(isolate, "BIND_DONE");
  node::MakeCallback(isolate, process, "emit", 1, &event);
}

void AtomBindings::ActivateUVLoop(v8::Isolate* isolate) {
  node::Environment* env = node::Environment::GetCurrent(isolate);
  if (std::find(pending_next_ticks_.begin(), pending_next_ticks_.end(), env) !=
      pending_next_ticks_.end())
    return;

  pending_next_ticks_.push_back(env);
  uv_async_send(&call_next_tick_async_);
}

// static
void AtomBindings::OnCallNextTick(uv_async_t* handle) {
  AtomBindings* self = static_cast<AtomBindings*>(handle->data);
  for (std::list<node::Environment*>::const_iterator it =
           self->pending_next_ticks_.begin();
       it != self->pending_next_ticks_.end(); ++it) {
    node::Environment* env = *it;
    node::Environment::TickInfo* tick_info = env->tick_info();

    v8::Context::Scope context_scope(env->context());
    if (tick_info->in_tick())
      continue;

    if (tick_info->length() == 0) {
      tick_info->set_index(0);
      continue;
    }

    tick_info->set_in_tick(true);
    env->tick_callback_function()->Call(env->process_object(), 0, NULL);
    tick_info->set_in_tick(false);
  }

  self->pending_next_ticks_.clear();
}

}  // namespace atom


text:
package org.talkingpuffin.snippet

class LineCollector {
  var msgs = List[LineCollector.InfoLine]()
  def disp(heading: String, value: AnyRef) = msgs = LineCollector.InfoLine(heading, value) :: msgs
}

object LineCollector {
  case class InfoLine(heading: String, value: AnyRef)
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TS3ClientQueryFramework.TS3Models
{
    public class ServerGroup
    {
        public int SgId { get; set; }
        private string name = null;
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = TS3Helper.UnescapeString(value);
            }
        }
        public int Type { get; set; }
        public ulong IconId { get; set; }
        public int SaveDb { get; set; }
        public int SortId { get; set; }
        public int NameMode { get; set; }
        public int NModifyP { get; set; }
        public int NMemberAddP { get; set; }
        public int NMemberRemoveP { get; set; }

        public Result Result { get; set; }

        public override string ToString()
        {
            return Name;
        }

        public ServerGroup FillWithResult(Result result)
        {
            return FillWithResult(result, result.ResultsList.First());
        }

        public ServerGroup FillWithResult(Result result, Dictionary<string, string> list)
        {
            if (result.GetResultByList(list, ServerGroupProperties.sgid.ToString()) != null)
                this.SgId = Convert.ToInt32(result.GetResultByList(list, ServerGroupProperties.sgid.ToString()));
            if (result.GetResultByList(list, ServerGroupProperties.name.ToString()) != null)
                this.Name = result.GetResultByList(list, ServerGroupProperties.name.ToString());
            if (result.GetResultByList(list, ServerGroupProperties.type.ToString()) != null)
                this.Type = Convert.ToInt32(result.GetResultByList(list, ServerGroupProperties.type.ToString()));
            if (result.GetResultByList(list, ServerGroupProperties.iconid.ToString()) != null)
                this.IconId = Convert.ToUInt64(result.GetResultByList(list, ServerGroupProperties.iconid.ToString()));
            if (result.GetResultByList(list, ServerGroupProperties.savedb.ToString()) != null)
                this.SaveDb = Convert.ToInt32(result.GetResultByList(list, ServerGroupProperties.savedb.ToString()));
            if (result.GetResultByList(list, ServerGroupProperties.sortid.ToString()) != null)
                this.SortId = Convert.ToInt32(result.GetResultByList(list, ServerGroupProperties.sortid.ToString()));
            if (result.GetResultByList(list, ServerGroupProperties.namemode.ToString()) != null)
                this.NameMode = Convert.ToInt32(result.GetResultByList(list, ServerGroupProperties.namemode.ToString()));
            if (result.GetResultByList(list, ServerGroupProperties.n_modifyp.ToString()) != null)
                this.NModifyP = Convert.ToInt32(result.GetResultByList(list, ServerGroupProperties.n_modifyp.ToString()));
            if (result.GetResultByList(list, ServerGroupProperties.n_member_addp.ToString()) != null)
                this.NMemberAddP = Convert.ToInt32(result.GetResultByList(list, ServerGroupProperties.n_member_addp.ToString()));
            if (result.GetResultByList(list, ServerGroupProperties.n_member_removep.ToString()) != null)
                this.NMemberRemoveP = Convert.ToInt32(result.GetResultByList(list, ServerGroupProperties.n_member_removep.ToString()));
            this.Result = result;
            return this;
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Phyllosticta azevinhi Torrend

### Remarks
null


text:
import { physicalDamage, defenderDodged } from './utils/battleCalcs.js';

//this enemy attack is called before battle component renders
export function enemyAttack(hero, enemy, id) {
  let amount = physicalDamage(enemy[id], hero)
  let dodge = defenderDodged(enemy[id], hero);

  return {
    type: 'ENEMY_ATTACK',
    amount: dodge ? 0 : amount,
    message:
      dodge ?        "You dodge the attack" :
      amount === 0 ? "You blocked the attack" :
        enemy[id].name + " attacks with " + enemy[id].equipment.rightHand.name + " dealing " + amount + " damage!"
  }
}