text:
<?php

namespace App\Pages\Doc;

use Zippy\Html\DataList\DataView;
use Zippy\Html\Form\AutocompleteTextInput;
use Zippy\Html\Form\Button;
use Zippy\Html\Form\CheckBox;
use Zippy\Html\Form\Date;
use Zippy\Html\Form\Form;
use Zippy\Html\Form\DropDownChoice;
use Zippy\Html\Form\SubmitButton;
use Zippy\Html\Form\TextInput;
use Zippy\Html\Label;
use Zippy\Html\Link\ClickLink;
use Zippy\Html\Link\SubmitLink;
use App\Entity\Customer;
use App\Entity\Doc\Document;
use App\Entity\Service;
use App\Entity\Store;
use App\Entity\Stock;
use App\Entity\Prodarea;
use App\Entity\Item;
use App\Entity\Employee;
use App\Entity\CAsset;
use App\Application as App;
use App\Helper as H;

/**
 * Страница  ввода  наряда  на  работу
 */
class Task extends \App\Pages\Base
{

    public $_servicelist = array();
    public $_itemlist = array();
    public $_itemlist5 = array();
    public $_emplist = array();
    public $_eqlist = array();
    private $_doc;
    private $_discount;

    public function __construct($docid = 0) {
        parent::__construct();

        $this->add(new Form('docform'));
        $this->docform->add(new TextInput('document_number'));
        $this->docform->add(new \ZCL\BT\DateTimePicker('start_date'))->setDate(time());
        $this->docform->add(new \ZCL\BT\DateTimePicker('document_date'))->setDate(time());
        $this->docform->add(new AutocompleteTextInput('customer'))->onText($this, 'OnAutoCustomer');
        $this->docform->customer->onChange($this, 'OnChangeCustomer', false);

        $this->docform->add(new TextInput('notes'));
        $this->docform->add(new TextInput('hours', "0"));

        $this->docform->add(new Label('discount'))->setVisible(false);
        $this->docform->add(new DropDownChoice('store', Store::getList(), \App\Helper::getDefStore()));
        $this->docform->add(new DropDownChoice('parea', Prodarea::findArray("pa_name", ""), 0));
        $this->docform->add(new DropDownChoice('pricetype', Item::getPriceTypeList()));
        $this->docform->add(new CheckBox('cash', true));

        $this->docform->add(new SubmitLink('addservice'))->onClick($this, 'addserviceOnClick');
        $this->docform->add(new SubmitLink('additem'))->onClick($this, 'additemOnClick');
        $this->docform->add(new SubmitLink('additem5'))->onClick($this, 'additemOnClick5');
        $this->docform->add(new SubmitLink('addcust'))->onClick($this, 'addcustOnClick');
        $this->docform->add(new SubmitLink('addeq'))->onClick($this, 'addeqOnClick');
        $this->docform->add(new SubmitLink('addemp'))->onClick($this, 'addempOnClick');
        $this->docform->add(new Button('backtolist'))->onClick($this, 'backtolistOnClick');
        $this->docform->add(new SubmitButton('savedoc'))->onClick($this, 'savedocOnClick');
        $this->docform->add(new SubmitButton('execdoc'))->onClick($this, 'savedocOnClick');

        $this->docform->add(new Label('total'));
        $this->docform->add(new Label('totalnds'));

        //service
        $this->add(new Form('editdetail'))->setVisible(false);
        $this->editdetail->add(new AutocompleteTextInput('editservice'))->onText($this, 'OnAutoServive');
        $this->editdetail->editservice->onChange($this, 'OnChangeServive', true);
        $this->editdetail->add(new TextInput('editquantity'))->setText("1");
        $this->editdetail->add(new TextInput('editprice'));
        $this->editdetail->add(new TextInput('editpricends'));
        $this->editdetail->add(new Button('cancelrow'))->onClick($this, 'cancelrowOnClick');
        $this->editdetail->add(new SubmitButton('saverow'))->onClick($this, 'saverowOnClick');

        //комплектующие
        $this->add(new Form('editdetail2'))->setVisible(false);
        $this->editdetail2->add(new AutocompleteTextInput('edititem'))->onText($this, 'OnAutoItem');
        $this->editdetail2->edititem->onChange($this, 'OnChangeItem', true);
        $this->editdetail2->add(new TextInput('editquantity2'))->setText("1");
        $this->editdetail2->add(new TextInput('editprice2'));
        $this->editdetail2->add(new TextInput('editpricends2'));
        $this->editdetail2->add(new Label('qty'));

        $this->editdetail2->add(new Button('cancelrow2'))->onClick($this, 'cancelrowOnClick');
        $this->editdetail2->add(new SubmitButton('saverow2'))->onClick($this, 'saverow2OnClick');

        //Материалы
        $this->add(new Form('editdetail5'))->setVisible(false);
        $this->editdetail5->add(new AutocompleteTextInput('edititem5'))->onText($this, 'OnAutoItem5');
        $this->editdetail5->edititem5->onChange($this, 'OnChangeItem5', true);
        $this->editdetail5->add(new TextInput('editquantity5'))->setText("1");
        $this->editdetail5->add(new TextInput('editprice5'));
        $this->editdetail5->add(new Label('qty5'));

        $this->editdetail5->add(new Button('cancelrow5'))->onClick($this, 'cancelrowOnClick');
        $this->editdetail5->add(new SubmitButton('saverow5'))->onClick($this, 'saverow5OnClick');

        //employer
        $this->add(new Form('editdetail3'))->setVisible(false);
        $this->editdetail3->add(new DropDownChoice('editemp', Employee::findArray('emp_name', "detail like '%<fired>0</fired>%'  ", 'emp_name')));
        $this->editdetail3->add(new Button('cancelrow3'))->onClick($this, 'cancelrowOnClick');
        $this->editdetail3->add(new SubmitButton('saverow3'))->onClick($this, 'saverow3OnClick');

        //equipment
        $this->add(new Form('editdetail4'))->setVisible(false);
        $this->editdetail4->add(new DropDownChoice('editeq', CAsset::findArray("ca_name", "acc_code='106' or acc_code='104'", "ca_name")));
        $this->editdetail4->add(new Button('cancelrow4'))->onClick($this, 'cancelrowOnClick');
        $this->editdetail4->add(new SubmitButton('saverow4'))->onClick($this, 'saverow4OnClick');

        //добавление нового контрагента
        $this->add(new Form('editcust'))->setVisible(false);
        $this->editcust->add(new TextInput('editcustname'));
        $this->editcust->add(new TextInput('editphone'));
        $this->editcust->add(new Button('cancelcust'))->onClick($this, 'cancelcustOnClick');
        $this->editcust->add(new SubmitButton('savecust'))->onClick($this, 'savecustOnClick');

        if ($docid > 0) {    //загружаем   содержимок  документа настраницу
            $this->_doc = Document::load($docid);
            $this->docform->document_number->setText($this->_doc->document_number);
            $this->docform->notes->setText($this->_doc->notes);
            $this->docform->hours->setText($this->_doc->headerdata['hours']);
            $this->docform->cash->setChecked($this->_doc->headerdata['cash']);

            $this->docform->start_date->setDate($this->_doc->headerdata['start_date']);
            $this->docform->pricetype->setValue($this->_doc->headerdata['pricetype']);
            $this->docform->store->setValue($this->_doc->headerdata['store']);

            $this->docform->document_date->setDate($this->_doc->headerdata['end_date']);
            $this->docform->parea->setValue($this->_doc->headerdata['parea']);
            $this->docform->customer->setKey($this->_doc->customer_id);
            $this->docform->customer->setText($this->_doc->customer_name);
            $this->OnChangeCustomer($this->docform->customer);

            foreach ($this->_doc->detaildata as $item) {
                if ($item["service_id"] > 0) {
                    $service = new Service($item);
                    $this->_servicelist[$service->service_id] = $service;
                }
                if ($item["item_id"] > 0 && strlen($item["item5_id"]) == 0) {
                    $stock = new Stock($item);
                    $this->_itemlist[$stock->stock_id] = $stock;
                }
                if ($item["item5_id"] > 0) {
                    $stock = new Stock($item);
                    $this->_itemlist5[$stock->stock_id] = $stock;
                }
                if ($item["employee_id"] > 0) {
                    $emp = new Employee($item);
                    $this->_emplist[$emp->employee_id] = $emp;
                }
                if ($item["ca_id"] > 0) {
                    $eq = new CAsset($item);
                    $this->_eqlist[$eq->ca_id] = $eq;
                }
            }
        } else {
            $this->_doc = Document::create('Task');
            $this->_doc->document_number = $this->_doc->nextNumber();
            $this->docform->document_number->setText($this->_doc->document_number);
            ;
        }

        $this->docform->add(new DataView('detail', new \Zippy\Html\DataList\ArrayDataSource(new \Zippy\Binding\PropertyBinding($this, '_servicelist')), $this, 'detailOnRow'))->Reload();
        $this->docform->add(new DataView('detail2', new \Zippy\Html\DataList\ArrayDataSource(new \Zippy\Binding\PropertyBinding($this, '_itemlist')), $this, 'detail2OnRow'))->Reload();
        $this->docform->add(new DataView('detail3', new \Zippy\Html\DataList\ArrayDataSource(new \Zippy\Binding\PropertyBinding($this, '_emplist')), $this, 'detail3OnRow'))->Reload();
        $this->docform->add(new DataView('detail4', new \Zippy\Html\DataList\ArrayDataSource(new \Zippy\Binding\PropertyBinding($this, '_eqlist')), $this, 'detail4OnRow'))->Reload();
        $this->docform->add(new DataView('detail5', new \Zippy\Html\DataList\ArrayDataSource(new \Zippy\Binding\PropertyBinding($this, '_itemlist5')), $this, 'detail5OnRow'))->Reload();
        $this->calcTotal();

        if (false == \App\ACL::checkShowDoc($this->_doc))
            return;
    }

    public function cancelrowOnClick($sender) {
        $this->editdetail->setVisible(false);
        $this->editdetail2->setVisible(false);
        $this->editdetail3->setVisible(false);
        $this->editdetail4->setVisible(false);
        $this->editdetail5->setVisible(false);
        $this->docform->setVisible(true);
    }

    public function detailOnRow($row) {
        $service = $row->getDataItem();

        $row->add(new Label('service', $service->service_name));

        $row->add(new Label('quantity', $service->quantity));
        $row->add(new Label('price', H::famt($service->price)));
        $row->add(new Label('pricends', H::famt($service->pricends)));

        $row->add(new Label('amount', H::famt($service->amount)));
        $row->add(new ClickLink('edit'))->onClick($this, 'editOnClick');
        $row->add(new ClickLink('delete'))->onClick($this, 'deleteOnClick');
    }

    public function addserviceOnClick($sender) {
        $this->editdetail->setVisible(true);
        $this->docform->setVisible(false);

        $this->editdetail->editservice->setText('');
        $this->editdetail->editservice->setKey(0);
        $this->editdetail->editquantity->setText(1);
        $this->editdetail->editprice->setText('');
        $this->editdetail->editpricends->setText('');
    }

    public function editOnClick($sender) {
        $service = $sender->getOwner()->getDataItem();
        $this->editdetail->setVisible(true);
        $this->docform->setVisible(false);

        $this->editdetail->editquantity->setText(($service->quantity));
        $this->editdetail->editprice->setText($service->price);
        $this->editdetail->editpricends->setText($service->pricends);

        $this->editdetail->editservice->setKey($service->service_id);
        $this->editdetail->editservice->setText($service->service_name);
    }

    public function deleteOnClick($sender) {
        if (false == \App\ACL::checkEditDoc($this->_doc))
            return;
        $service = $sender->owner->getDataItem();

        $this->_servicelist = array_diff_key($this->_servicelist, array($service->service_id => $this->_servicelist[$service->service_id]));
        $this->docform->detail->Reload();
        $this->calcTotal();
    }

    public function saverowOnClick($sender) {
        $id = $this->editdetail->editservice->getKey();
        if ($id == 0) {
            $this->setError("Не выбрана  услуга");
            return;
        }
        $service = Service::load($id);
        $service->quantity = $this->editdetail->editquantity->getText();
        $service->price = $this->editdetail->editprice->getText();
        $service->pricends = $this->editdetail->editpricends->getText();

        $this->_servicelist[$service->service_id] = $service;
        $this->editdetail->setVisible(false);
        $this->docform->setVisible(true);
        $this->calcTotal();
        $this->docform->detail->Reload();

        //очищаем  форму
        $this->editdetail->editservice->setKey(0);
        $this->editdetail->editservice->setText('');
        $this->editdetail->editquantity->setText("1");

        $this->editdetail->editprice->setText("0");
    }

    public function detail2OnRow($row) {
        $item = $row->getDataItem();

        $row->add(new Label('item_code', $item->item_code));
        $row->add(new Label('item', $item->itemname));
        $row->add(new Label('msr', $item->msr));

        $row->add(new Label('quantity2', H::fqty($item->quantity)));
        $row->add(new Label('price2', H::famt($item->price)));
        $row->add(new Label('pricends2', H::famt($item->pricends)));

        $row->add(new Label('amount2', H::famt($item->amount)));
        $row->add(new ClickLink('edit2'))->onClick($this, 'edit2OnClick');
        $row->add(new ClickLink('delete2'))->onClick($this, 'delete2OnClick');
    }

    public function additemOnClick($sender) {
        $this->editdetail2->setVisible(true);
        $this->docform->setVisible(false);
        $this->editdetail2->edititem->setText('');
        $this->editdetail2->edititem->setKey(0);
        $this->editdetail2->editquantity2->setText(1);
        $this->editdetail2->editprice2->setText(0);
        $this->editdetail2->editpricends2->setText(0);
    }

    public function edit2OnClick($sender) {
        $item = $sender->getOwner()->getDataItem();
        $this->editdetail2->setVisible(true);
        $this->docform->setVisible(false);

        $this->editdetail2->editquantity2->setText(($item->quantity));
        $this->editdetail2->editprice2->setText($item->price);
        $this->editdetail2->editpricends2->setText($item->pricends);

        $this->editdetail2->edititem->setKey($item->stock_id);
        $this->editdetail2->edititem->setText($item->itemname);
    }

    public function saverow2OnClick($sender) {
        $id = $this->editdetail2->edititem->getKey();
        if ($id == 0) {
            $this->setError("Не выбран товар");
            return;
        }
        $stock = Stock::load($id);
        $stock->quantity = $this->editdetail2->editquantity2->getText();
        $stock->price = $this->editdetail2->editprice2->getText();
        $stock->pricends = $this->editdetail2->editpricends2->getText();

        $this->_itemlist[$stock->stock_id] = $stock;
        $this->editdetail2->setVisible(false);
        $this->docform->setVisible(true);
        $this->calcTotal();
        $this->docform->detail2->Reload();

        //очищаем  форму
        $this->editdetail2->edititem->setKey(0);
        $this->editdetail2->edititem->setText('');
        $this->editdetail2->qty->setText('');
        $this->editdetail2->editquantity2->setText("1");

        $this->editdetail2->editprice2->setText("0");
    }

    public function delete2OnClick($sender) {
        $item = $sender->owner->getDataItem();
        $this->_itemlist = array_diff_key($this->_itemlist, array($item->stock_id => $this->_itemlist[$item->stock_id]));
        $this->docform->detail2->Reload();
        $this->calcTotal();
    }

    public function detail5OnRow($row) {
        $item = $row->getDataItem();

        $row->add(new Label('item_code5', $item->item_code));
        $row->add(new Label('item5', $item->itemname));
        $row->add(new Label('msr5', $item->msr));

        $row->add(new Label('quantity5', H::fqty($item->quantity)));
        $row->add(new Label('price5', $item->price));

        $row->add(new Label('amount5', round($item->amount)));
        $row->add(new ClickLink('edit5'))->onClick($this, 'editOnClick5');
        $row->add(new ClickLink('delete5'))->onClick($this, 'deleteOnClick5');
    }

    public function additemOnClick5($sender) {
        $this->editdetail5->setVisible(true);
        $this->docform->setVisible(false);
        $this->editdetail5->edititem5->setText('');
        $this->editdetail5->edititem5->setKey(0);
        $this->editdetail5->editquantity5->setText(1);
        $this->editdetail5->editprice5->setText(0);
    }

    public function editOnClick5($sender) {
        $item = $sender->getOwner()->getDataItem();
        $this->editdetail5->setVisible(true);
        $this->docform->setVisible(false);

        $this->editdetail5->editquantity5->setText(($item->quantity));
        $this->editdetail5->editprice5->setText($item->price);

        $this->editdetail5->edititem5->setKey($item->stock_id);
        $this->editdetail5->edititem5->setText($item->itemname);
    }

    public function saverow5OnClick($sender) {
        $id = $this->editdetail5->edititem5->getKey();
        if ($id == 0) {
            $this->setError("Не выбран материал");
            return;
        }
        $stock = Stock::load($id);
        $stock->quantity = $this->editdetail5->editquantity5->getText();
        $stock->price = $this->editdetail5->editprice5->getText();
        $stock->amount = $stock->quantity * $stock->price;

        $stock->item5_id = $stock->item_id;
        $this->_itemlist5[$stock->stock_id] = $stock;
        $this->editdetail5->setVisible(false);
        $this->docform->setVisible(true);
        $this->docform->detail5->Reload();

        //очищаем  форму
        $this->editdetail5->edititem5->setKey(0);
        $this->editdetail5->edititem5->setText('');
        $this->editdetail5->editquantity5->setText("1");

        $this->editdetail5->editprice5->setText("0");
    }

    public function deleteOnClick5($sender) {
        $item = $sender->owner->getDataItem();
        $this->_itemlist5 = array_diff_key($this->_itemlist5, array($item->stock_id => $this->_itemlist5[$item->stock_id]));
        $this->docform->detail5->Reload();
    }

    //employee
    public function addempOnClick($sender) {
        $this->editdetail3->setVisible(true);
        $this->docform->setVisible(false);

        $this->editdetail3->editemp->setValue(0);
    }

    public function saverow3OnClick($sender) {
        $id = $this->editdetail3->editemp->getValue();
        if ($id == 0) {
            $this->setError("Не выбран исполнитель");
            return;
        }
        $emp = Employee::load($id);

        $this->_emplist[$emp->employee_id] = $emp;
        $this->editdetail3->setVisible(false);
        $this->docform->setVisible(true);
        $this->docform->detail3->Reload();
    }

    public function detail3OnRow($row) {
        $emp = $row->getDataItem();

        $row->add(new Label('empname', $emp->emp_name));
        $row->add(new ClickLink('delete3'))->onClick($this, 'delete3OnClick');
    }

    public function delete3OnClick($sender) {
        $emp = $sender->owner->getDataItem();
        $this->_emplist = array_diff_key($this->_emplist, array($emp->employee_id => $this->_emplist[$emp->employee_id]));
        $this->docform->detail3->Reload();
    }

    //equipment
    public function addeqOnClick($sender) {
        $this->editdetail4->setVisible(true);
        $this->docform->setVisible(false);

        $this->editdetail4->editeq->setValue(0);
    }

    public function saverow4OnClick($sender) {
        $id = $this->editdetail4->editeq->getValue();
        if ($id == 0) {
            $this->setError("Не выбрано оборудование ");
            return;
        }
        $eq = CAsset::load($id);

        $this->_eqlist[$eq->ca_id] = $eq;
        $this->editdetail4->setVisible(false);
        $this->docform->setVisible(true);
        $this->docform->detail4->Reload();
    }

    public function detail4OnRow($row) {
        $eq = $row->getDataItem();

        $row->add(new Label('eq_name', $eq->ca_name));
        $row->add(new ClickLink('delete4'))->onClick($this, 'delete4OnClick');
    }

    public function delete4OnClick($sender) {
        $eq = $sender->owner->getDataItem();
        $this->_emplist = array_diff_key($this->_eqlist, array($eq->ca_id => $this->_eqlist[$eq->ca_id]));
        $this->docform->detail4->Reload();
    }

    public function savedocOnClick($sender) {
        if (false == \App\ACL::checkEditDoc($this->_doc))
            return;
        $this->_doc->document_number = $this->docform->document_number->getText();
        $this->_doc->document_date = strtotime($this->docform->document_date->getText());
        $this->_doc->notes = $this->docform->notes->getText();
        $this->_doc->customer_id = $this->docform->customer->getKey();

        if ($this->checkForm() == false) {
            return;
        }

        $this->calcTotal();

        $old = $this->_doc->cast();

        $this->_doc->headerdata = array(
            'parea' => $this->docform->parea->getValue(),
            'pricetype' => $this->docform->pricetype->getValue(),
            'pricetypename' => $this->docform->pricetype->getValueName(),
            'store' => $this->docform->store->getValue(),
            'cash' => $this->docform->cash->isChecked(),
            'hours' => $this->docform->hours->getText(),
            'start_date' => $this->docform->start_date->getDate(),
            'end_date' => $this->docform->document_date->getDate(),
            'totalnds' => $this->docform->totalnds->getText(),
            'total' => $this->docform->total->getText()
        );
        $this->_doc->detaildata = array();
        foreach ($this->_servicelist as $item) {
            $this->_doc->detaildata[] = $item->getData();
        }
        foreach ($this->_itemlist as $item) {
            $this->_doc->detaildata[] = $item->getData();
        }
        foreach ($this->_itemlist5 as $item) {
            $this->_doc->detaildata[] = $item->getData();
        }
        foreach ($this->_eqlist as $item) {
            $this->_doc->detaildata[] = $item->getData();
        }

        $total = $this->docform->total->getText();
        $cnt = count($this->_emplist);

        foreach ($this->_emplist as $item) {
            $item->pay = round($total / $cnt); //сумма поровну
            $this->_doc->detaildata[] = $item->getData();
        }

        $isEdited = $this->_doc->document_id > 0;
        $this->_doc->amount = $this->docform->total->getText();

        $conn = \ZDB\DB::getConnect();
        $conn->BeginTrans();
        try {

            $this->_doc->save();

            if ($sender->id == 'execdoc') {
                if (!$isEdited) {
                    $this->_doc->updateStatus(Document::STATE_NEW);
                }

                //  $this->_doc->updateStatus(Document::STATE_EXECUTED);
                $this->_doc->updateStatus(Document::STATE_INPROCESS);

                $this->_doc->save();
            } else {
                $this->_doc->updateStatus($isEdited ? Document::STATE_EDITED : Document::STATE_NEW);
            }

            $conn->CommitTrans();
            if ($isEdited)
                App::RedirectBack();
            else
                App::Redirect("\\App\\Pages\\Register\\TaskList");
        } catch (\Exception $ee) {
            global $logger;
            $conn->RollbackTrans();
            $this->setError($ee->getMessage());

            $logger->error($ee->getMessage() . " Документ " . $this->_doc->meta_desc);
            return;
        }
    }

    /**
     * Расчет  итого
     *
     */
    private function calcTotal() {

        $total = 0;
        $totalnds = 0;

        foreach ($this->_servicelist as $item) {
            $item->amount = $item->price * $item->quantity;

            if (H::usends()) {
                $item->amount = $item->pricends * $item->quantity;
            }
            $totalnds = $totalnds + ($item->pricends - $item->price) * $item->quantity;
            $total = $total + $item->amount;
        }

        foreach ($this->_itemlist as $item) {

            $item->amount = $item->price * $item->quantity;
            if (H::usends()) {
                $item->amount = $item->pricends * $item->quantity;
            }
            $totalnds = $totalnds + ($item->pricends - $item->price) * $item->quantity;
            $total = $total + $item->amount;
        }

        $this->docform->total->setText(H::famt($total));
        $this->docform->totalnds->setText(H::famt($totalnds));
    }

    /**
     * Валидация   формы
     *
     */
    private function checkForm() {
        if (strlen($this->_doc->document_number) == 0) {
            $this->setError('Введите номер документа');
        }
        if (strlen($this->_doc->document_date) == 0) {
            $this->setError('Введите дату документа');
        }
        if (count($this->_servicelist) == 0) {
            $this->setError("Не введена  ни одна работа");
        }

        return !$this->isError();

        $this->docform->detail->Reload();
    }

    public function backtolistOnClick($sender) {
        App::RedirectBack();
    }

    public function OnAutoCustomer($sender) {
        $text = Customer::qstr('%' . $sender->getText() . '%');
        return Customer::findArray("customer_name", "customer_name like " . $text);
    }

    public function OnChangeCustomer($sender) {
        $this->_discount = 0;
        $customer_id = $this->docform->customer->getKey();
        if ($customer_id > 0) {
            $customer = Customer::load($customer_id);
            $this->_discount = $customer->discount;
        }
        $this->calcTotal();
        if ($this->_discount > 0) {
            $this->docform->discount->setVisible(true);
            $this->docform->discount->setText('Скидка ' . $this->_discount . '%');
        } else {
            $this->docform->discount->setVisible(false);
        }
    }

    public function OnAutoServive($sender) {

        $text = Service::qstr('%' . $sender->getText() . '%');
        return Service::findArray("service_name", "    service_name like {$text}");
    }

    public function OnChangeServive($sender) {
        $id = $sender->getKey();

        $item = Service::load($id);
        $price = $item->price;

        $price = $price - $price / 100 * $this->_discount;
        $this->editdetail->editprice->setText(H::famt($price));

        if (H::usends()) {
            $this->editdetail->editpricends->setText(H::famt($price));
            $this->editdetail->editprice->setText(H::famt($price - $price * H::nds(true)));
        }

        $this->updateAjax(array('editprice', 'editpricends'));
    }

    public function OnAutoItem($sender) {
        $store_id = $this->docform->store->getValue();
        $text = Item::qstr('%' . $this->editdetail2->edititem->getText() . '%');
        return Stock::findArrayEx("store_id={$store_id} and acc_code='281'  and (itemname like {$text} or item_code like {$text}) ");
    }

    public function OnAutoItem5($sender) {
        $store_id = $this->docform->store->getValue();
        $text = Item::qstr('%' . $this->editdetail5->edititem5->getText() . '%');
        return Stock::findArrayEx("store_id={$store_id} and acc_code in('201','204') and (itemname like {$text} or item_code like {$text}) ");
    }

    public function OnChangeItem($sender) {
        $id = $sender->getKey();
        $stock = Stock::load($id);
        $this->editdetail2->qty->setText(H::fqty($stock->qty));

        $item = Item::load($stock->item_id);
        $price = $item->getPrice($this->docform->pricetype->getValue(), $stock->partion > 0 ? $stock->partion : 0);
        $price = $price - $price / 100 * $this->_discount;
        $this->editdetail2->editprice2->setText($price);

        if (H::usends()) {
            $this->editdetail2->editpricends2->setText(H::famt($price));
            $this->editdetail2->editprice2->setText(H::famt($price - $price * H::nds(true)));
        }

        $this->updateAjax(array('qty', 'editprice2', 'editpricends2'));
    }

    public function OnChangeItem5($sender) {
        $id = $sender->getKey();
        $stock = Stock::load($id);
        $this->editdetail5->qty5->setText(Stock::getQuantity($id));

        $item = Item::load($stock->item_id);
        $price = $item->getPrice($this->docform->pricetype->getValue(), $stock->partion > 0 ? $stock->partion : 0);
        //$price = $price - $price / 100 * $this->_discount;

        $this->editdetail5->editprice5->setText($price);

        $this->updateAjax(array('qty5', 'editprice5'));
    }

    //добавление нового контрагента
    public function addcustOnClick($sender) {
        $this->editcust->setVisible(true);
        $this->docform->setVisible(false);

        $this->editcust->editcustname->setText('');
        $this->editcust->editphone->setText('');
    }

    public function savecustOnClick($sender) {
        $custname = trim($this->editcust->editcustname->getText());
        if (strlen($custname) == 0) {
            $this->setError("Не введено имя");
            return;
        }
        $cust = new Customer();
        $cust->customer_name = $custname;
        $cust->phone = $this->editcust->editcustname->getText();
        $cust->save();
        $this->docform->customer->setText($cust->customer_name);
        $this->docform->customer->setKey($cust->customer_id);

        $this->editcust->setVisible(false);
        $this->docform->setVisible(true);
    }

    public function cancelcustOnClick($sender) {
        $this->editcust->setVisible(false);
        $this->docform->setVisible(true);
    }

}


text:
window.config = {
  nSamples: 1024, // number of colors in each map
}

async function init(){
  // console.clear()

  window.params = initParams()
  window.exportCode = initExport()
  window.image = await initImage()
  window.custom = initCustom()
  window.transform = initTransform()
  window.brush = initBrush()
  window.scales = initScales()
  window.gamma = initGamma()

  window.scales.update()
}

init()

redpajama_set_name: RedPajamaGithub


text:
package org.apache.hadoop.yarn.server.resourcemanager.recovery;

import io.hops.util.DBUtility;
import io.hops.util.RMStorageFactory;
import io.hops.util.YarnAPIStorageFactory;
import java.io.IOException;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.server.records.Version;
import org.apache.hadoop.yarn.server.records.impl.pb.VersionPBImpl;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp;
import org.junit.Before;
import org.junit.Test;

public class TestDBRMStateStore extends RMStateStoreTestBase {

  private DBRMStateStore stateStore = null;
  private YarnConfiguration conf;

  @Before
  public void setup() throws IOException {
    conf = new YarnConfiguration();
    YarnAPIStorageFactory.setConfiguration(conf);
    RMStorageFactory.setConfiguration(conf);
    DBUtility.InitializeDB();
  }

  @Test(timeout = 60000)
  public void testApps() throws Exception {
    dbStateStoreTester tester = new dbStateStoreTester();
    testRMAppStateStore(tester);
  }

  @Test(timeout = 60000)
  public void testClientTokens() throws Exception {
    dbStateStoreTester tester = new dbStateStoreTester();
    testRMDTSecretManagerStateStore(tester);
  }

  @Test(timeout = 60000)
  public void testVersion() throws Exception {
    dbStateStoreTester tester = new dbStateStoreTester();
    testCheckVersion(tester);
  }

  @Test(timeout = 60000)
  public void testEpoch() throws Exception {
    dbStateStoreTester tester = new dbStateStoreTester();
    testEpoch(tester);
  }

  @Test(timeout = 60000)
  public void testAppDeletion() throws Exception {
    dbStateStoreTester tester = new dbStateStoreTester();
    testAppDeletion(tester);
  }

  @Test(timeout = 60000)
  public void testDeleteStore() throws Exception {
    dbStateStoreTester tester = new dbStateStoreTester();
    testDeleteStore(tester);
  }

  @Test(timeout = 60000)
  public void testAMTokens() throws Exception {
    dbStateStoreTester tester = new dbStateStoreTester();
    testAMRMTokenSecretManagerStateStore(tester);
  }

  class dbStateStoreTester implements RMStateStoreHelper {

    @Override
    public RMStateStore getRMStateStore() throws Exception {
      if (stateStore != null) {
        stateStore.close();
      }
      stateStore = new DBRMStateStore();
      stateStore.init(conf);
      stateStore.start();
      return stateStore;
    }

    @Override
    public boolean isFinalStateValid() throws Exception {
      // There should be 5 total entries:
      //   2 entries for app 0010 with one attempt
      //   3 entries for app 0001 with two attempts
      return stateStore.getNumEntriesInDatabase() == 5;
    }

    @Override
    public void writeVersion(Version version) throws Exception {
      byte[] versionDb = ((VersionPBImpl) version).getProto().toByteArray();
      stateStore.storeVersiondb(versionDb);
    }

    @Override
    public Version getCurrentVersion() throws Exception {
      return stateStore.getCurrentVersion();
    }

    @Override
    public boolean appExists(RMApp app) throws Exception {
      return stateStore.loadRMAppState(app.getApplicationId()) != null;
    }
  }

}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Brachystele hatschbachii Pabst

### Remarks
null


text:
class BodyTable;
class VariablesTable;
class FuncsTable;
class TypesTable;
class InheritanceTable;
class NamespaceTable;
class TemplateParTypesRelation;

class AccessTable : public Table {

public:

    AccessTable(char *name, BodyTable *bodies, VariablesTable *var, FuncsTable *funcs, TypesTable *types,
		InheritanceTable *inh, NamespaceTable *namespaces, TemplateParTypesRelation *tp2t);

	~AccessTable();

    virtual void extract(ATCollection &trees);

	virtual void init();

private:

	BodyTable *bodies;
	FuncsTable *funcs;
	VariablesTable *vars;
	TypesTable *types;
	InheritanceTable *inh;
	NamespaceTable *namespaces;
	TemplateParTypesRelation *tp2t;

};
#endif //ACCESSTABLE_H


text:
class LUtils{
public:
	//Get the current version of the Lumina desktop
	static QString LuminaDesktopVersion();

	//Run an external command and return the exit code
	static int runCmd(QString cmd, QStringList args = QStringList());
	//Run an external command and return any text output (one line per entry)
	static QStringList getCmdOutput(QString cmd, QStringList args = QStringList());

	//Read a text file
	static QStringList readFile(QString filepath);
	//Write a text file
	static bool writeFile(QString filepath, QStringList contents, bool overwrite=false);

	//Check whether a file/path is a valid binary
	static bool isValidBinary(QString& bin); //full path or name only
	static bool isValidBinary(const char *bin){
	  QString bins(bin);
	  return isValidBinary(bins); //overload for a "junk" binary variable input
	}

	//List all the sub-directories of a parent dir (recursive)
	static QStringList listSubDirectories(QString dir, bool recursive = true);

	//Get the list of all file extensions which Qt can read (lowercase)
	static QStringList imageExtensions();

	//Load a translation file for a Lumina Project
	static QTranslator* LoadTranslation(QApplication *app, QString appname, QString locale = "", QTranslator *cTrans = 0);
	//Other localization shortcuts
	static QStringList knownLocales(); //Note: This only lists locales known to Lumina (so the i18n files need to be installed)
	static void setLocaleEnv(QString lang, QString msg="", QString time="", QString num="" ,QString money="",QString collate="", QString ctype="");

	//Number format conversions
	static double DisplaySizeToBytes(QString num); //Turn a display size (like 50M or 50KB) into a double for calculations (bytes)
	static QString BytesToDisplaySize(qint64 bytes); //convert into a readable size (like 50M or 50KB)

	//Various function for finding valid QtQuick plugins on the system
	static bool validQuickPlugin(QString ID);
	static QString findQuickPluginFile(QString ID);
	static QStringList listQuickPlugins(); //List of valid ID's
	static QStringList infoQuickPlugin(QString ID); //Returns: [Name, Description, Icon]

	//Various functions for the favorites sub-system
	// Formatting Note: "<name>::::[dir/app/<mimetype>]::::<path>"
	//   the <name> field might not be used for "app" flagged entries
	static QStringList listFavorites();
	static bool saveFavorites(QStringList);
	static bool isFavorite(QString path);
	static bool addFavorite(QString path, QString name = "");
	static void removeFavorite(QString path);
	static void upgradeFavorites(int fromoldversionnumber);

	//Load the default setup for the system
	static void LoadSystemDefaults(bool skipOS = false);

};

#endif


text:
package tdl.record.sourcecode.snapshot.file;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.*;
import java.util.function.Consumer;
import tdl.record.sourcecode.snapshot.KeySnapshot;
import tdl.record.sourcecode.snapshot.SnapshotType;
import tdl.record.sourcecode.snapshot.helpers.ByteHelper;

public class Reader implements Iterator<Integer>, AutoCloseable {

    private final File file;

    private final RandomAccessFile randomAccessFile;

    private Header fileHeader;

    public Reader(File file) throws IOException {
        this.file = file;
        this.randomAccessFile = new RandomAccessFile(file, "r");
        reset();
    }

    private byte[] readBytesFromOffset(int offset, int length) throws IOException {
        byte[] bytes = new byte[length];
        long lastPosition = randomAccessFile.getFilePointer();
        randomAccessFile.seek(offset);
        randomAccessFile.read(bytes, 0, length);
        randomAccessFile.seek(lastPosition);
        return bytes;
    }

    private long readLong(int offset) throws IOException {
        return ByteHelper.byteArrayToLittleEndianLong(readBytesFromOffset(offset, 8));
    }

    private byte[] readBytes(int length) throws IOException {
        byte[] bytes = new byte[length];
        randomAccessFile.read(bytes, 0, length);
        return bytes;
    }

    @Override
    public boolean hasNext() {
        try {
            return randomAccessFile.getFilePointer() < randomAccessFile.length() - 1;
        } catch (IOException ex) {
            return false;
        }
    }

    @Override
    public Integer next() {
        try {
            long address = randomAccessFile.getFilePointer();
            long size = readSegmentSizeFromAddress((int) address);
            int skip = Segment.HEADER_SIZE + (int) size;
            randomAccessFile.skipBytes(skip);
            return (int) address;
        } catch (IOException ex) {
            //TODO raise as a proper exception
            return null;
        }
    }

    public Segment nextSegment() throws IOException {
        int address = next();
        return readSegmentByAddress(address);
    }

    private Header readFileHeader() throws IOException {
        Header header = new Header();
        header.setMagicBytes(readBytesFromOffset(0, Header.MAGIC_BYTES.length));
        header.setTimestamp(readLong(6));
        if (!header.isValid()) {
            throw new IOException("Cannot parse header");
        }
        randomAccessFile.seek(Header.SIZE);
        return header;
    }

    private long readSegmentSizeFromAddress(int address) throws IOException {
        return readLong(address + Segment.SIZE_ADDRESS);
    }

    @Override
    public void remove() {
        Iterator.super.remove();
    }

    @Override
    public void forEachRemaining(Consumer<? super Integer> action) {
        Iterator.super.forEachRemaining(action); //To change body of generated methods, choose Tools | Templates.
    }

    public final void reset() throws IOException {
        randomAccessFile.seek(0);
        fileHeader = readFileHeader();
    }

    public long getFilePointer() {
        try {
            return randomAccessFile.getFilePointer();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    public Header getFileHeader() {
        return fileHeader;
    }

    public void skip() {
        next();
    }

    public List<Integer> getSegmentAddresses() throws IOException {
        reset();
        List<Integer> list = new ArrayList<>();
        forEachRemaining(list::add);
        return list;
    }

    /**
     * @param index Inclusive.
     */
    public List<Segment> getReplayableSnapshotSegmentsUntil(int index) throws Exception {
        Segment snapshot = getSnapshotAt(index);
        if (snapshot.getSnapshot() instanceof KeySnapshot) {
            return Collections.singletonList(snapshot);
        }
        int first = getFirstKeySnapshotBefore(index);
        return getSnapshotSegmentsByRange(first, index + 1);
    }

    /**
     * @param start inclusive.
     * @param end exclusive.
     */
    public List<Segment> getSnapshotSegmentsByRange(int start, int end) throws IOException {
        List<Segment> list = new ArrayList<>();
        reset();
        int index = 0;
        while (index < end) {
            if (index >= start) {
                Segment snapshot = nextSegment();
                list.add(snapshot);
            } else {
                skip();
            }
            index++;
        }
        reset();
        return list;
    }

    public int getFirstKeySnapshotBefore(int index) throws IOException {
        int keyIndex = 0;
        int start = 0;
        reset();
        while (start < index) {
            Segment snapshot = nextSegment();
            if (snapshot.getSnapshot() instanceof KeySnapshot) {
                keyIndex = start;
            }
            start++;
        }
        reset();
        return keyIndex;
    }

    public Segment readSegmentByAddress(int address) throws IOException {
        long lastPosition = randomAccessFile.getFilePointer();
        randomAccessFile.seek(address);
        Segment segment = new Segment();
        segment.setAddress(address);
        segment.setType(SnapshotType.fromMagicBytes(readBytes(SnapshotType.MAGIC_BYTES_LENGTH)));
        segment.setTimestampSec(ByteHelper.byteArrayToLittleEndianInt(readBytes(Segment.LONG_SIZE)));
        segment.setSize(ByteHelper.byteArrayToLittleEndianInt(readBytes(Segment.LONG_SIZE)));
        segment.setTag(asString(readBytes(Segment.TAG_SIZE)));
        segment.setChecksum(readBytes(Segment.CHECKSUM_SIZE));
        segment.setData(readBytes((int) segment.getSize()));
        if (segment.isChecksumMismatch()) {
            throw new IOException("Checksum mismatch");
        }
        randomAccessFile.seek(lastPosition);
        return segment;
    }

    private String asString(byte[] bytes) {
        int indexOfZero = Arrays.binarySearch(bytes, (byte) 0);

        int newLength = bytes.length;
        if (indexOfZero >= 0) {
            newLength = indexOfZero;
        }

        return new String(bytes, 0, newLength).trim();
    }

    private Segment generateEmptySegment() {
        Segment segment = new Segment();
        segment.setType(SnapshotType.EMPTY);
        byte[] bytes = new byte[0];
        segment.setData(bytes);
        segment.setTimestampSec(0);
        segment.generateFromData();
        return segment;
    }

    public Segment getSnapshotAt(int index) throws IOException {
        int start = 0;
        reset();
        while (start < index) {
            skip();
            start++;
        }
        int address = next();
        Segment snapshot = readSegmentByAddress(address);
        reset();
        return snapshot;
    }

    public List<Segment> getSegments() throws IOException {
        List<Segment> list = new ArrayList<>();
        reset();
        forEachRemaining((address) -> {
            Segment segment;
            try {
                segment = readSegmentByAddress(address);
            } catch (IOException ex) {
                //Do nothing
                segment = generateEmptySegment();
            }
            list.add(segment);
        });
        return list;
    }

    public int getIndexBeforeForTag(String tag) throws IOException {
        int index = 0;
        reset();
        do {
            Segment segment = nextSegment();
            if (Objects.equals(segment.getTag(), tag)) {
                break;
            }
            index++;
        } while (hasNext());
        reset();
        return index;
    }

    public int getIndexBeforeOrEqualsTimestamp(long timestamp) throws IOException {
        int index = 0;
        reset();
        do {
            Segment segment = nextSegment();
            if (segment.getTimestampSec() > timestamp) {
                index--;
                break;
            }
            index++;
        } while (hasNext());
        reset();
        return index;
    }

    @Override
    public void close() {
        try {
            randomAccessFile.close();
        } catch (IOException ex) {
            //
        }
    }

    public File getFile() {
        return file;
    }
}


text:
var test = require("test");
run("loader-test.js");
(function() {
    test.run();
}).start().join();


text:
/**
 * @class Container
 */
class Container {
    /**
     * @constructor
     */
    constructor() {
        /*
         * Dependencies
         */
        this._shared = new Map()
    }

    /**
     * register - register dependency
     *
     * @param  {string} name
     * @param  {any} dependency
     * @returns {Cotnainer}
     */
    register( name, dependency ) {
        this.shared.set( name, dependency )

        return this
    }

    /**
     * get - gets dependency by name
     *
     * @param  {string} name
     * @returns {Service|Component|undefined}
     */
    get( name ) {
        return this.shared.get( name )
    }

    /**
     * get - services loaded
     *
     * @returns {Map}
     */
    get shared() {
        return this._shared
    }
}

module.exports = Container


text:
Rails.application.routes.draw do

  mount ActiveadminBeautifier::Engine => "/activeadmin_beautifier"
end


text:
var slideshow = (function () {
  "use strict";

  // slideshow elements
  var $actvSlide = $('#actv-slide');
  var $controls = $('#controls a');
  var $nextSlide = $('#next-slide');
  var $nextBtn = $('#next-btn');
  var $prevSlide = $('#prev-slide');
  var $prevBtn = $('#prev-btn');

  // disables navigation
  var disableNav = function() {
    $controls.on('click', nothing);
    $controls.off('click', navigate);
    $(window).off('popstate', updateState);
  };

  // enables navigation
  var enableNav = function() {
    $controls.off('click', nothing);
    $controls.on('click', navigate);
    $(window).on('popstate', updateState);
  };

  // preloads previous / next slides (determined by next/previous buttons)
  var loadPreviousNext = function() {
    // load previous slide
    $prevSlide.load($('.link-meta .prev', $actvSlide).attr('href') + ' #actv-slide >');
    // load next slide & enabled navigation
    $nextSlide.load($('.link-meta .next', $actvSlide).attr('href') + ' #actv-slide >', enableNav);
  };

  // detects which button has been clicked
  var navigate = function(e) {
    e.preventDefault();
    disableNav();
    var state = {};

    if (this == $prevBtn[0]) {
      previous();
      state = {
        direction: 'prev',
        url: $prevBtn.attr('href')
      };
    } else if (this == $nextBtn[0]) {
      next();
      state = {
        direction: 'next',
        url: $nextBtn.attr('href')
      };
    }

    if (typeof state.url != 'undefined') {
      window.history.pushState({ $actvSlide: state.url }, document.title, state.url);
    }
  };

  // moves to the next slide
  var next = function() {
    $actvSlide.animate({
      left: '-20%'
    }, 500, 'swing', function() {
      $nextSlide.animate({
        left: '0%'
      }, 500, 'swing', updateSlide);
    });
  };

  // moves to the previous slide
  var previous = function() {
    $actvSlide.animate({
      left: '60%'
    }, 500, 'swing', function() {
      $prevSlide.animate({
        left: '40%'
      }, 500, 'swing', updateSlide);
    });
  };

  // updates links for next / prev buttons
  var updateLinks = function() {
    var prevLink = $('.link-meta .prev', $actvSlide),
    nextLink = $('.link-meta .next', $actvSlide);

    if (prevLink[0]) {
      $prevBtn.attr('href', prevLink.attr('href'));
    }

    if (nextLink[0]) {
      $nextBtn.attr('href', nextLink.attr('href'));
    }
  };

  // updates active slide
  var updateSlide = function() {
    if (this == $nextSlide[0]) {
      activateNext();
    } else {
      activatePrev();
    }

    // reset the css
    $([$prevSlide, $actvSlide, $nextSlide]).each(function(i, e) {
      this.css('left', '');
    });
  };

  // bring the next slide into view
  var activateNext = function() {
    $prevSlide.remove();
    $prevSlide = $actvSlide;
    $prevSlide.attr('id', 'prev-slide');
    $actvSlide = $nextSlide;
    $actvSlide.attr('id', 'actv-slide');
    updateLinks();
    $nextSlide = $('

').appendTo('#slides-wrapper');
    $nextSlide.load($('.link-meta .next', $actvSlide).attr('href') + ' #actv-slide >', postLoad);
  };

  // bring the previous slide into view
  var activatePrev = function() {
    $nextSlide.remove();
    $nextSlide = $actvSlide;
    $nextSlide.attr('id', 'next-slide');
    $actvSlide = $prevSlide;
    $actvSlide.attr('id', 'actv-slide');
    updateLinks();
    $prevSlide = $('

').prependTo('#slides-wrapper');
    $prevSlide.load($('.link-meta .prev', $actvSlide).attr('href') + ' #actv-slide >', postLoad);
  };

  // update the current state of the slideshow
  var updateState = function(e) {
    console.log(e.originalEvent.state);
  };

  // performs any tasks after the next / previous slides have been loaded
  var postLoad = function() {
    // the buttons work again
    enableNav();
  };

  // do nothing
  var nothing = function() {
    return false;
  };

  return {
    initialise: function(options) {
      loadPreviousNext();
    }
  };

})();


text:
package com.example.actionbarviewpager;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends FragmentActivity implements TabListener {
    private ActionBar actionBar;
    private ViewPager viewPager;

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

        viewPager = (ViewPager)findViewById(R.id.pager);

        FragmentPagerAdapter pagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {

            @Override
            public int getCount() {
                return 3;
            }

            @Override
            public Fragment getItem(int arg0) {
                Fragment fragment = new DummyFragment();
                Bundle args = new Bundle();
                args.putInt(DummyFragment.ARG_SECTION_NUMBER, arg0 + 1);
                fragment.setArguments(args);
                return fragment;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                switch (position) {
                case 0:
                    return "Page 1";
                case 1:
                    return "Page 2";
                case 2:
                    return "Page 3";

                default:
                    break;
                }
                return null;
            }
        };

        actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        for (int i = 0; i < pagerAdapter.getCount(); i++) {
            actionBar.addTab(actionBar.newTab().setText(pagerAdapter.getPageTitle(i)).setTabListener(this));
        }
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                actionBar.setSelectedNavigationItem(arg0);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub

    }

}


text:
import AnalyticsPage from '../index';

import expect from 'expect';
import { shallow } from 'enzyme';
import React from 'react';

describe('<AnalyticsPage />', () => {

});


text:
import sys
import os
from PyQt4 import QtGui, QtCore
from lib.configobj import ConfigObj
import glob
import serial
import socket
from interface import editorView

print 'Run'
#sock = socket.socket()
#sock.connect(('192.168.0.13', 6647)) #6526
#sock.connect(('127.0.0.1', 6576)) #6526

#sock2 = socket.socket()
#sock2.connect(('192.168.42.1', 6003)) #6526

sock = ''
sock2 = ''

from module.servo import ServoWiget
print 'Run servo'
from module.mjpgsteamview import CamWidget
print 'Run mjpgsteamview'
from module.move import MoveWidget
print 'Run move'
from module.moveSimple import MoveSimpleWidget
print 'Run moveSimple'
from module.soundPlay import PlaySoundWidget
print 'Run soundPlay'
from module.tts import TTSWidget
print 'Run tts'
from module.battery import BattaryWidget

print 'Run'
version = "0.0.11"

class USBcommunication():
    def __init__(self):
        self.baudrate = 115200
        self.port = ''
        self.portConnect = ''

    def setPort(self, port):
        self.port = port

    def getPortList(self):
        if sys.platform.startswith('win'):
            ports = ['COM%s' % (i + 1) for i in range(256)]
        elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
            ports = glob.glob('/dev/tty[A-Za-z]*')
        elif sys.platform.startswith('darwin'):
            ports = glob.glob('/dev/tty.*')
        else:
            raise EnvironmentError('Unsupported platform')

        result = []
        for port in ports:
            try:
                s = serial.Serial(port)
                s.close()
                result.append(port)
            except (OSError, serial.SerialException):
                pass
        return result

    def setBaudrate(self, baudrate):
        self.baudrate = baudrate

    def sendData(self, data):
        if self.portConnect:
            self.portConnect.write(data + "\n")

    def connect(self):
        if self.port:
            self.portConnect = serial.Serial(self.port, baudrate=self.baudrate, dsrdtr = 1,  timeout=1)

class ChoicePort(QtGui.QDialog):
    def __init__(self, parent=None):
        super(ChoicePort, self).__init__(parent)
        #self.usbCom = USBcommunication()
        #self.devices = self.usbCom.getPortList()

    def setMainWindow(self, window):
        self.mainWindow = window
        self.setWindowTitle('Serial Port')

        self.buttonBox = QtGui.QDialogButtonBox(self)
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)

        self.devicesList = QtGui.QListWidget(self)
        self.speed = QtGui.QComboBox()
        speedList = ['300', '1200', '2400', '4800', '9600', '14400', '19200', '28800', '38400', '57600', '115200']

        '''
        for i in speedList:
            self.speed.addItem(i)

        for i in self.devices:
            self.devicesList.addItem(i)
        '''

        self.verticalLayout = QtGui.QVBoxLayout(self)
        self.update = QtGui.QPushButton('update')
        self.verticalLayout.addWidget(self.update)
        self.update.clicked.connect(self.updatePorts)
        self.verticalLayout.addWidget(self.devicesList)
        self.verticalLayout.addWidget(self.speed)
        self.verticalLayout.addWidget(self.buttonBox)

        self.buttonBox.button(QtGui.QDialogButtonBox.Ok).clicked.connect(self.returnPort)
        self.buttonBox.button(QtGui.QDialogButtonBox.Cancel).clicked.connect(lambda : super(ChoicePort, self).accept())

    def returnPort(self):
        portItem = self.devicesList.currentItem()

        if portItem:
            portName = portItem.text()
            getSpeed = str(self.speed.currentText())
            self.mainWindow.choiceUsbPort(str(portName), str(getSpeed))
            super(ChoicePort, self).accept()

    def updatePorts(self):
        self.devicesList.clear()
        self.devices = self.usbCom.getPortList()
        for i in self.devices:
            self.devicesList.addItem(i)

class SubWindow(QtGui.QMdiSubWindow):

    def __init__(self, parent=None):
        self.parent = parent
        QtGui.QMdiSubWindow.__init__(self)
        #super(SubWindow, self).__init__(parent)

    def closeEvent(self, QCloseEvent):
        print '+++++++++++++++++++++++++++++++++++++++++++++++'
        self.parent.updateData()

    def focusOutEvent(self, event):

        print event

        self.parent.updateData()
        print self.widget()

class MainWindow(QtGui.QMainWindow):

    def __init__(self, portWindow):
        print 'Loading GUI'
        QtGui.QMainWindow.__init__(self)
        self.sock = sock
        self.setGeometry(100, 100, 900, 650)

        #self.usbCom = USBcommunication()
        self.port = ''
        self.statusBar()

        self.labelPort  = QtGui.QLabel(self.port)
        self.statusBar().addWidget( self.labelPort,2)

        self.mdi = QtGui.QMdiArea()
        self.mdi.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
        self.mdi.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
        self.mdi.setBackground(QtGui.QBrush(QtGui.QColor(240, 240, 240)))
        self.mdi.setBackground(QtGui.QBrush(QtGui.QPixmap('icons/logo.png')))
        #self.mdi.mousePressEvent(self, self.test2)
        self.setCentralWidget(self.mdi)

        self.docList = QtGui.QDockWidget('Objects')
        self.docList_Contents = QtGui.QWidget()
        self.docList.setWidget(self.docList_Contents)

        self.docList_Layout = QtGui.QGridLayout()
        self.listElements = QtGui.QListWidget()
        self.docList_Layout.addWidget(self.listElements)
        self.docList_Contents.setLayout(self.docList_Layout)

        self.docListServo2 = QtGui.QDockWidget('Properties editor')
        self.docListServo_Contents2 = QtGui.QWidget()
        self.docListServo2.setWidget(self.docListServo_Contents2)
        self.docListServo_Layout2 = QtGui.QGridLayout()
        self.tableProperties = QtGui.QTableWidget()
        self.docListServo_Layout2.addWidget(self.tableProperties)
        self.docListServo_Contents2.setLayout(self.docListServo_Layout2)
        self.tableProperties.verticalHeader().hide()
        self.tableProperties.horizontalHeader().hide()
        self.tableProperties.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)

        '''
         self.docTerminal = QtGui.QDockWidget('Terminal')
        self.docTerminal_Contents = QtGui.QWidget()
        self.docTerminal.setWidget(self.docTerminal_Contents)
        #self.docTerminal.setAllowedAreas(QtCore.Qt.BottomDockWidgetArea)

        self.docTerminal_Layout = QtGui.QGridLayout()
        self.terminal = QtGui.QTextEdit()
        self.docTerminal_Layout.addWidget(self.terminal)
        #self.docTerminal_Layout.setVerticalSpacing(1)
        #self.docTerminal.setTitleBarWidget(QtGui.QWidget(self.docTerminal))
        self.docTerminal_Contents.setLayout(self.docTerminal_Layout)
        '''
        self.view = editorView.editorViewClass(self)
        self.timeLine = self.view.s.startTimeLine
        self.view2 = editorView.editorViewClass(self)
        self.docTerminal = QtGui.QDockWidget('Terminal')
        self.docTerminal_Contents = QtGui.QWidget()
        self.docTerminal.setWidget(self.docTerminal_Contents)
        #self.docTerminal.setAllowedAreas(QtCore.Qt.BottomDockWidgetArea)

        self.docTerminal_Layout = QtGui.QGridLayout()
        self.terminal = QtGui.QTextEdit()
        self.layato = QtGui.QGridLayout()
        scene1 = QtGui.QLineEdit("Nao 1")
        scene1.setMaximumHeight(100)
        scene1.setMaximumWidth(100)
        self.start1 = QtGui.QPushButton("Start >")
        self.start1.clicked.connect(self.timeLine)

        self.start1.setMaximumHeight(200)
        self.start1.setMaximumWidth(200)
        close1 = QtGui.QPushButton("X")
        close1.setMaximumHeight(100)
        close1.setMaximumWidth(40)
        log1 = QtGui.QPushButton("Log")
        log1.setMaximumHeight(100)
        log1.setMaximumWidth(40)

        self.layato.addWidget(scene1, 0, 0)
        self.layato.addWidget(close1, 0, 1)
        self.layato.addWidget(self.start1, 1, 0)
        self.layato.addWidget(log1, 1, 1)
        self.wiglayayot = QtGui.QWidget()
        self.wiglayayot.setLayout(self.layato)

        startAll1 = QtGui.QPushButton("Start/Pause")
        startAll1.setMaximumHeight(100)
        startAll1.setMaximumWidth(100)
        stopAll1 = QtGui.QPushButton("Stop")
        stopAll1.setMaximumHeight(100)
        stopAll1.setMaximumWidth(60)
        battarryWd10 = BattaryWidget()
        battarryWd1 = battarryWd10.getWidget()
        self.docTerminal_Layout.addWidget(startAll1, 0, 0)
        self.docTerminal_Layout.addWidget(stopAll1, 0, 1)
        #self.docTerminal_Layout.addWidget(stopAll1, 0, 2)
        self.docTerminal_Layout.addWidget(self.wiglayayot, 1, 0, )
        self.docTerminal_Layout.addWidget(self.view, 1, 1)
        self.docTerminal_Layout.addWidget(battarryWd1, 1, 2)

        self.layato2 = QtGui.QGridLayout()
        scene2 = QtGui.QLineEdit("Nao 2")
        scene2.setMaximumHeight(100)
        scene2.setMaximumWidth(100)
        start2 = QtGui.QPushButton("Start >")
        start2.setMaximumHeight(100)
        start2.setMaximumWidth(100)
        close2 = QtGui.QPushButton("X")
        close2.setMaximumHeight(100)
        close2.setMaximumWidth(40)
        log2 = QtGui.QPushButton("Log")
        log2.setMaximumHeight(100)
        log2.setMaximumWidth(40)

        self.layato2.addWidget(scene2, 0, 0)
        self.layato2.addWidget(close2, 0, 1)
        self.layato2.addWidget(start2, 1, 0)
        self.layato2.addWidget(log2, 1, 1)
        self.wiglayayot2 = QtGui.QWidget()
        self.wiglayayot2.setLayout(self.layato2)
        battarryWd20 = BattaryWidget()
        battarryWd2 = battarryWd20.getWidget()
        self.docTerminal_Layout.addWidget(self.wiglayayot2, 2, 0)
        self.docTerminal_Layout.addWidget(self.view2, 2, 1)
        self.docTerminal_Layout.addWidget(battarryWd2, 2, 2)
        #self.docTerminal_Layout.setVerticalSpacing(1)
        #self.docTerminal.setTitleBarWidget(QtGui.QWidget(self.docTerminal))
        self.docTerminal_Contents.setLayout(self.docTerminal_Layout)

        self.docWidgets = QtGui.QDockWidget('Robots')
        self.docWidgets_Contents = QtGui.QWidget()
        self.docWidgets.setWidget(self.docWidgets_Contents)

        self.docWidgets_Layout = QtGui.QGridLayout()
        self.docWidgets_Layout.setSpacing(0)
        self.listWidgetsDoc = QtGui.QListWidget()
        self.docWidgets_Layout.addWidget(self.listWidgetsDoc)
        self.docWidgets_Contents.setLayout(self.docWidgets_Layout)
        #self.updateWitdgetList()
        self.listWidgetsDoc.addItem("Nao")
        self.listWidgetsDoc.itemDoubleClicked.connect(self.tx)

        self.addDockWidget(QtCore.Qt.DockWidgetArea(1), self.docWidgets)
        self.addDockWidget(QtCore.Qt.DockWidgetArea(2), self.docList)
        self.addDockWidget(QtCore.Qt.DockWidgetArea(2), self.docListServo2)
        self.addDockWidget(QtCore.Qt.DockWidgetArea(2), self.docTerminal)

        self.fileName = ''
        self.programIsSave = 0

        self.lastServoNamber = 0    #Последняя подключенная
        self.columnServo = 0
        self.rowServo = 0
        self.servoInColumn = 6
        self.servoInWindow = 0

        self.setWindowTitle('Robot Control ' + str(version))

        self.massServoGrid = QtGui.QGridLayout() #Хранилище блоков управления сервами
        self.massServoGrid.setSpacing(10)

        exit = QtGui.QAction(QtGui.QIcon('icons/exit.png'), 'Exit', self)
        exit.setShortcut('Ctrl+Q')
        exit.setStatusTip('Exit application')
        self.connect(exit, QtCore.SIGNAL('triggered()'), QtCore.SLOT('close()'))

        open = QtGui.QAction(QtGui.QIcon('icons/open.png'), 'Open project ...', self)
        open.setShortcut('Ctrl+O')
        open.setStatusTip('Open project file')
        self.connect(open, QtCore.SIGNAL('triggered()'), self.openProject)

        save = QtGui.QAction(QtGui.QIcon('icons/save.png'), 'Save', self)
        save.setShortcut('Ctrl+S')
        save.setStatusTip('Save project')
        self.connect(save, QtCore.SIGNAL('triggered()'), self.saveThisFile)

        saveAs = QtGui.QAction('Save project As ...', self)
        saveAs.setStatusTip('Save project file')
        self.connect(saveAs, QtCore.SIGNAL('triggered()'), self.saveProject)

        newProject = QtGui.QAction(QtGui.QIcon('icons/new.png'), 'New Project...', self)
        newProject.setShortcut('Ctrl+N')
        newProject.setStatusTip('New Project')
        self.connect(newProject, QtCore.SIGNAL('triggered()'), self.newProject)

        add = QtGui.QAction(QtGui.QIcon('icons/add.png'), 'Servo', self)
        add.setShortcut('Ctrl+N')
        add.setStatusTip('Add servo')
        self.connect(add, QtCore.SIGNAL('triggered()'), self.addServo)

        addImg = QtGui.QAction(QtGui.QIcon('icons/add.png'), 'WebCam', self)
        addImg.setShortcut('Ctrl+N')
        addImg.setStatusTip('Add image')
        self.connect(addImg, QtCore.SIGNAL('triggered()'), self.addImage)

        addMove = QtGui.QAction(QtGui.QIcon('icons/add.png'), 'Move', self)
        addMove.setShortcut('Ctrl+N')
        addMove.setStatusTip('Add move')
        self.connect(addMove, QtCore.SIGNAL('triggered()'), self.addMove)

        addMoveSimple = QtGui.QAction(QtGui.QIcon('icons/add.png'), 'Move simple', self)
        addMoveSimple.setShortcut('Ctrl+N')
        addMoveSimple.setStatusTip('Add move simple')
        self.connect(addMoveSimple, QtCore.SIGNAL('triggered()'), self.addMoveSimple)

        addSoundPlay = QtGui.QAction(QtGui.QIcon('icons/add.png'), 'Sound Play', self)
        addSoundPlay.setShortcut('Ctrl+N')
        addSoundPlay.setStatusTip('Add sound Play')
        self.connect(addSoundPlay, QtCore.SIGNAL('triggered()'), self.addSoundPlay)

        addTTS = QtGui.QAction(QtGui.QIcon('icons/add.png'), 'TTS', self)
        addTTS.setShortcut('Ctrl+N')
        addTTS.setStatusTip('Add sound Play')
        self.connect(addTTS, QtCore.SIGNAL('triggered()'), self.addTTS)

        addBattery = QtGui.QAction(QtGui.QIcon('icons/add.png'), 'Battery', self)
        addBattery.setShortcut('Ctrl+N')
        addBattery.setStatusTip('Battery')
        self.connect(addBattery, QtCore.SIGNAL('triggered()'), self.addBattary)

        #portLabel = QtGui.QLabel('Port: ')
        port = QtGui.QAction(QtGui.QIcon('icons/usb.png'), 'Connetcion...', self)
        port.setShortcut('Ctrl+C')
        port.setStatusTip('Connection to Arduino')
        self.connect(port, QtCore.SIGNAL('triggered()'), portWindow.show)

        hint =QtGui.QAction(QtGui.QIcon('icons/usb.png'), 'Hint', self)
        self.connect(hint, QtCore.SIGNAL('triggered()'), self.hintEvent)
        self.isHintSubWindows = False

        doc =QtGui.QAction(QtGui.QIcon('icons/usb.png'), 'Doc', self)
        self.connect(doc, QtCore.SIGNAL('triggered()'), self.docVisible)
        self.isHintDocWindows = False

        test = QtGui.QAction(QtGui.QIcon('icons/usb.png'), 'test...', self)
        test.setShortcut('Ctrl+C')
        test.setStatusTip('test to test')

        menubar = self.menuBar()
        #menubar.connect(serialPort, QtCore.SIGNAL('hovered()'), self.choiceUsbPort)

        file = menubar.addMenu('&File')
        file.addAction(newProject)
        file.addAction(open)
        file.addAction(save)
        file.addAction(saveAs)
        file.addAction(exit)

        #service = menubar.addMenu('&Service')
        #serialPort = service.addMenu('&Serial Port')
        #self.connect(serialPort, QtCore.SIGNAL('actionTriggered(int)'), self.choiceUsbPort)
        #serialPort.addAction(test)
        #serialPort.actionEvent(self.choiceUsbPort)
        #service.addAction(sp, self.choiceUsbPort)

        toolbar = self.addToolBar('Add')
        toolbar.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
        toolbar.addAction(add)
        toolbar.addAction(addImg)
        toolbar.addAction(addMove)
        toolbar.addAction(addMoveSimple)
        toolbar.addAction(addSoundPlay)
        toolbar.addAction(addTTS)
        toolbar.addAction(addBattery)
        toolbar.addAction(port)
        toolbar.addAction(hint)
        toolbar.addAction(doc)

        self.servoW=[]
        self.webCam=[]
        self.move = []
        self.moveSimple = []
        self.soundPlay = []
        self.tts = []
        self.battary = []

        self.servoSub = []
        self.servoData =[]
        #self.connect(QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_W), self), QtCore.SIGNAL('activated()'), self.tx)

        print 'GUI >> OK'

    def startTime1(self):
        self.view.s.startTime()
    def tx(self, item):
        print 'asd' + str(item.text())
    def keyPressEvent(self, event):
        print str(event.key()), 'dfsfsdf'
        #if (event.key() == QtCore.Qt.Key_W): #and  (event.modifiers() == QtCore.Qt.ControlModifier):
        if event.nativeScanCode() == 83:
            print 'KKKKKKKKKKKK'

    def docVisible(self):
        if not self.isHintDocWindows:
            self.docWidgets.close()
            self.docList.close()
            self.docListServo2.close()
            self.docTerminal.close()
            self.isHintDocWindows = True
        else:
            self.docWidgets.show()
            self.docList.show()
            self.docListServo2.show()
            self.docTerminal.show()
            self.isHintDocWindows = False

    def hintEvent(self):
        print 1
        if not self.isHintSubWindows:
            for i in self.mdi.subWindowList():
                #i.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred).setHeightForWidth(True))
                i.setWindowFlags(QtCore.Qt.FramelessWindowHint)
                #i.setOption(QtGui.QMdiSubWindow.RubberBandMove, on=False)
                i.update()
            self.isHintSubWindows = True
        else:
            for i in self.mdi.subWindowList():
                #i.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred).setHeightForWidth(True))
                i.normalGeometry()
                #i.setWindowFlags(QtCore.Qt.CustomizeWindowHint)
                #i.setWindowFlags(QtCore.Qt.Frame)
                #i.setOption(QtGui.QMdiSubWindow.RubberBandMove, on=False)
                i.update()
            self.isHintSubWindows = False

    def choiceUsbPort(self, port, br):
        if port:
            self.port = port
            self.usbCom.setPort(self.port)
            self.usbCom.setBaudrate(br)
            self.labelPort.setText('Arduino on '+self.port)
            self.usbCom.connect()

    def updateWitdgetList(self):
        allFiles = os.listdir('module')
        modules = filter(lambda x: x.endswith('.py'), allFiles)
        print modules
        #self.ui.tableScripts.setColumnCount(2)
        #self.ui.tableScripts.setRowCount(len(files))
        for widget in modules:
            if '__init__' not in widget:
                print widget
                foo = imp.load_source(widget, 'module/'+widget)
                name = foo.Widget()

                self.listWidgetsDoc.addItem(name.getName())
        print dict

    def addBattary(self):
        self.battary.append(BattaryWidget())

        self.lastServoNamber +=1

        sub = QtGui.QMdiSubWindow()
        #sub.normalGeometry()
        sub.setWidget(self.battary[-1].getWidget())

        sub.setWindowTitle("battary "+str(self.lastServoNamber))

        self.mdi.addSubWindow(sub)

        sub.show()
        #self.listElements.clear()
        self.listElements.addItem(str(self.mdi.subWindowList()[-1].windowTitle()))

    def addTTS(self):
        self.tts.append(TTSWidget(sock))

        self.lastServoNamber +=1

        sub = QtGui.QMdiSubWindow()

        sub.setWidget(self.tts[-1].getWidget())

        sub.setWindowTitle("Say "+str(self.lastServoNamber))
        self.mdi.addSubWindow(sub)

        sub.show()
        #self.listElements.clear()
        self.listElements.addItem(str(self.mdi.subWindowList()[-1].windowTitle()))

    def addSoundPlay(self):
        self.soundPlay.append(PlaySoundWidget(sock))

        self.lastServoNamber +=1

        sub = QtGui.QMdiSubWindow()

        sub.setWidget(self.soundPlay[-1].getWidget())

        sub.setWindowTitle("move "+str(self.lastServoNamber))
        self.mdi.addSubWindow(sub)

        sub.show()
        #self.listElements.clear()
        self.listElements.addItem(str(self.mdi.subWindowList()[-1].windowTitle()))

    def addMoveSimple(self):
        self.moveSimple.append(MoveSimpleWidget(sock))

        self.lastServoNamber +=1

        sub = QtGui.QMdiSubWindow()

        sub.setWidget(self.moveSimple[-1].getWidget())

        sub.setWindowTitle("move "+str(self.lastServoNamber))
        self.mdi.addSubWindow(sub)

        sub.show()
        #self.listElements.clear()
        self.listElements.addItem(str(self.mdi.subWindowList()[-1].windowTitle()))

    def addMove(self):
        self.move.append(MoveWidget(sock))

        self.lastServoNamber +=1

        sub = QtGui.QMdiSubWindow()

        sub.setWidget(self.move[-1].getWidget())

        sub.setWindowTitle("move "+str(self.lastServoNamber))
        self.mdi.addSubWindow(sub)

        sub.show()
        #self.listElements.clear()
        self.listElements.addItem(str(self.mdi.subWindowList()[-1].windowTitle()))

    def addImage(self):
        cam = CamWidget(self)
        self.webCam.append(cam)

        self.lastServoNamber +=1

        sub = SubWindow(cam)

        sub.setWidget(self.webCam[-1].getWidget())

        sub.setWindowTitle("ipCam "+str(self.lastServoNamber))
        self.mdi.addSubWindow(sub)
        #self.test(cam)

        sub.show()

        self.listElements.addItem(str(self.mdi.subWindowList()[-1].windowTitle()))

    def test2(self):
        print self.sender()

    def test(self, cam):
        self.tableProperties.setColumnCount(2)
        data = cam.getData()
        self.tableProperties.setRowCount(len(data))

        for i, name in enumerate(data.keys()):
            inf = data[name]
            item = QtGui.QTableWidgetItem()
            item.setText(name)
            self.tableProperties.setItem(i, 0, item)

            item = QtGui.QTableWidgetItem()
            item.setText(str(inf))
            self.tableProperties.setItem(i, 1, item)
        #self.listElements.clear()
        self.listElements.addItem(str(self.mdi.subWindowList()[-1].windowTitle()))

    def addServo(self):
        servo = ServoWiget(self)
        self.servoW.append(servo)
        self.lastServoNamber +=1

        sub = SubWindow(self.servoW[-1])
        self.servoSub.append(sub)

        self.servoSub[-1].setWidget(self.servoW[-1].getWidget())

        self.servoSub[-1].setWindowTitle("servo "+str(self.lastServoNamber))

        self.mdi.addSubWindow(self.servoSub[-1])

        #self.tableProperties.itemChanged.connect(self.servoW[-1].test)

        sub.show()
        #self.listElements.clear()
        self.listElements.addItem(str(self.mdi.subWindowList()[-1].windowTitle()))

    def servoEvent(self, pos):
        id = self.slider.index(self.sender())
        pin = self.pin[id].value()
        data = 'S|D'+str(pin) +'>'+str(pos)
        #print data
        self.terminal.append('SEND: ' + data)
        if self.port:
            self.usbCom.sendData(data)

    def delServo(self):
        id = self.delButton.index(self.sender())
        servoName = str(self.servoName[id].text())
        quit_msg = "Are you sure want to delete <" + servoName  + "> ?"
        dialog = QtGui.QMessageBox.question(self, 'Delete servo.',
                     quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)

        if dialog == QtGui.QMessageBox.Yes:
            self.massServoGrid.removeItem(self.servoGrid[id])
            self.servoGrid[id] = 0
            #self.centralWidget = QtGui.QWidget()
            #self.setCentralWidget(self.centralWidget)
            #self.centralWidget.setLayout(self.massServoGrid)
            self.servoInWindow -=1
            self.statusBar().showMessage('Servo ' + servoName + ' delete!')

    def setMinForSlider(self, arg):
        id = self.minValue.index(self.sender())
        self.slider[id].setMinimum(arg)

    def setMaxForSlider(self, arg):
        id = self.maxValue.index(self.sender())
        self.slider[id].setMaximum(arg)

    def openProject(self):
        dialog = 0
        print self.servoInWindow
        if self.servoInWindow > 0:
            quit_msg = "Open saved projects? All changes in the current project will be lost!"
            dialog = QtGui.QMessageBox.question(self, 'Open saved projects.',
                         quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)

        if dialog == QtGui.QMessageBox.Yes or self.servoInWindow == 0:
            self.columnServo = 0
            self.rowServo = 0
            self.servoInWindow = 0
            self.lastServoNamber = 0
            filename = QtGui.QFileDialog.getOpenFileName(self, 'Open file', 'servoControl')
            if filename:
                self.fileName = filename
                settings = ConfigObj(str(filename))
                servoQuantity = int(settings['Servo'])
                self.addSerovoWidget(quantity = servoQuantity, load = 1, file = settings)

    def saveThisFile(self):
        if self.fileName:
            self.saveProject(wasSave=0)
            self.statusBar().showMessage('Saving is done!')
        else:
            self.saveProject()

    def newProject(self):
        portWindow = ChoicePort()
        MainWindow(portWindow)

        main = MainWindow(portWindow)
        portWindow.setMainWindow(main)
        main.show()

    def saveProject(self, wasSave=1):
        if wasSave:
            self.fileName = QtGui.QFileDialog.getSaveFileName(self, 'Save Project', 'servoControl', filter='*.servo', selectedFilter='*.servo')
        if self.fileName and self.lastServoNamber>0:
            if sys.platform.startswith('linux'):
                projectName = str(self.fileName).split('/')[-1]
            else:
                projectName = str(self.fileName).split('\\')[-1]

            self.setWindowTitle('ServoConrol. Project: ' + projectName)

            config = ConfigObj()
            config['ProjectName'] = projectName
            config['Servo'] = self.servoInWindow

            id = 1
            for i in range(1, self.lastServoNamber+1):
                if self.servoGrid[i] != 0:
                    servoName = str(self.servoName[i].text())
                    minPos =self.minValue[i].value()
                    maxPos =self.maxValue[i].value()
                    pin = self.pin[i].value()
                    sliderPos = self.slider[i].value()
                    config[str(id)] = {'servoName'+str(id): servoName, 'minPos'+str(id): minPos,
                                'maxPos'+str(id): maxPos, 'pin'+str(id): pin, 'sliderPos'+str(id): sliderPos}
                    id +=1

            self.fileName = self.fileName if '.servo' in self.fileName else self.fileName+'.servo'
            config.filename = self.fileName
            config.write()

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    portWindow = ChoicePort()
    main = MainWindow(portWindow)
    portWindow.setMainWindow(main)
    main.show()
    sys.exit(app.exec_())