import os
import logging
import stringcase
from cgl.ui.widgets.base import LJDialog
from cgl.core.utils.general import cgl_copy
from cgl.core.utils.read_write import load_text_file, save_text_lines
from cgl.plugins.Qt import QtCore, QtGui, QtWidgets
from cgl.ui.widgets.dialog import InputDialog
from cgl.core.path import start
from cgl.ui.widgets.text import Highlighter
from cgl.ui.widgets.widgets import AdvComboBox

GUI_DICT = {'shelves.yaml': ['button name', 'command', 'icon', 'order', 'annotation', 'label'],
            'pre_publish.yaml': ['order', 'module', 'name', 'required'],
            'menus.yaml': ['order', 'name']}

class CGLTabBar(QtWidgets.QTabBar):

    def tabSizeHint(self, index):
        s = QtWidgets.QTabBar.tabSizeHint(self, index)
        s.transpose()
        return s

    # noinspection PyUnusedLocal
    def paintEvent(self, event):
        painter = QtWidgets.QStylePainter(self)
        opt = QtWidgets.QStyleOptionTab()

        for i in range(self.count()):
            self.initStyleOption(opt, i)
            painter.drawControl(QtWidgets.QStyle.CE_TabBarTabShape, opt)
            painter.save()

            s = opt.rect.size()
            s.transpose()
            r = QtCore.QRect(QtCore.QPoint(), s)
            r.moveCenter(opt.rect.center())
            opt.rect = r

            c = self.tabRect(i).center()
            painter.translate(c)
            painter.rotate(90)
            painter.translate(-c)
            painter.drawControl(QtWidgets.QStyle.CE_TabBarTabLabel, opt)
            painter.restore()

class LJTabWidget(QtWidgets.QTabWidget):
    def __init__(self, *args, **kwargs):
        QtWidgets.QTabWidget.__init__(self, *args, **kwargs)
        self.setTabBar(CGLTabBar(self))
        self.setTabPosition(QtWidgets.QTabWidget.West)

class CGLMenuButton(QtWidgets.QWidget):
    """
    Represents the "Button" within the parent "Menu".
    """
    menu_button_save_clicked = QtCore.Signal()

    def __init__(self, parent=None, preflight_name='', preflight_step_name='', attrs=None, preflight_path='',
                 menu_type='pre_publish', menu=None, reference_path=None, cfg=None):
        # TODO - we need to choose better variable names, this is obviously "preflight" specific.
        QtWidgets.QWidget.__init__(self, parent)
        try:
            dialog = self.parent().parent().parent()
            self.software = dialog.software_combo.currentText()
        except AttributeError:
            # TODO - look into this a bit deeper, this is a fairly generic catch right now.
            dialog = self.parent().parent().parent().parent().parent()
            self.software = dialog.software_combo.currentText()
        self.cfg = cfg
        self.menu_type = menu_type
        self.attrs = attrs
        self.name = attrs['name']
        self.preflight_name = preflight_name
        self.preflight_path = preflight_path
        # self.menu_name = os.path.split(preflight_path.split(menu_type)[1])[0]
        self.dirty = False
        self.menu = menu
        self.reference_path = reference_path
        # Create the Layouts
        layout = QtWidgets.QVBoxLayout(self)
        grid_layout = QtWidgets.QGridLayout()
        tool_row = QtWidgets.QHBoxLayout()

        # labels
        module_label = QtWidgets.QLabel('module')
        required_label = QtWidgets.QLabel('required')
        label_label = QtWidgets.QLabel('label')
        icon_button = QtWidgets.QToolButton()
        icon_button.setIcon(QtGui.QIcon(self.cfg.icon_path('folder24px.png')))
        self.icon_label = QtWidgets.QLabel('icon')
        name_label = QtWidgets.QLabel('name')

        # line edits
        self.command_line_edit = QtWidgets.QLineEdit()
        self.command_line_edit.setEnabled(False)
        self.required_line_edit = QtWidgets.QLineEdit()
        self.required_line_edit.setText('True')
        self.icon_path_line_edit = QtWidgets.QLineEdit()
        # self.required_line_edit.setEnabled(False)
        self.label_line_edit = QtWidgets.QLineEdit()
        self.name_line_edit = QtWidgets.QLineEdit()
        self.attrs_dict = {'module': self.command_line_edit,
                           'required': self.required_line_edit,
                           'label': self.label_line_edit,
                           'name': self.name_line_edit,
                           'icon': self.icon_path_line_edit}

        # tool buttons
        delete_button = QtWidgets.QPushButton('Delete')
        delete_button.setProperty('class', 'basic')
        open_button = QtWidgets.QPushButton('Edit')
        open_button.setProperty('class', 'basic')
        copy_button = QtWidgets.QPushButton('Copy Test Code'.format(self.software))
        copy_button.setProperty('class', 'basic')
        self.save_button = QtWidgets.QPushButton('Save')
        self.save_button.setProperty('class', 'basic')

        # Text Edit
        self.code_text_edit = QtWidgets.QPlainTextEdit()
        if reference_path:
            self.code_text_edit.setEnabled(False)
        metrics = QtGui.QFontMetrics(self.code_text_edit.font())
        self.code_text_edit.setTabStopWidth(4 * metrics.width(' '))
        Highlighter(self.code_text_edit.document())
        # Layout the Grid

        grid_layout.addWidget(label_label, 0, 0)
        grid_layout.addWidget(self.label_line_edit, 0, 1)
        grid_layout.addWidget(module_label, 1, 0)
        grid_layout.addWidget(self.command_line_edit, 1, 1)
        grid_layout.addWidget(required_label, 2, 0)
        grid_layout.addWidget(self.required_line_edit, 2, 1)
        grid_layout.addWidget(self.icon_label, 3, 0)
        grid_layout.addWidget(self.icon_path_line_edit, 3, 1)
        grid_layout.addWidget(icon_button, 3, 2)
        grid_layout.addWidget(name_label, 4, 0)
        grid_layout.addWidget(self.name_line_edit, 4, 1)

        name_label.hide()
        self.name_line_edit.hide()

        if self.menu_type != 'shelves':
            self.icon_label.hide()
            self.icon_path_line_edit.hide()
            icon_button.hide()
        else:
            self.required_line_edit.hide()
            required_label.hide()

        # Layout the tool row
        tool_row.addStretch(1)
        tool_row.addWidget(copy_button)
        tool_row.addWidget(open_button)
        tool_row.addWidget(delete_button)
        tool_row.addWidget(self.save_button)

        # layout the widget
        layout.addLayout(grid_layout)
        layout.addWidget(self.code_text_edit)
        layout.addLayout(tool_row)

        # Signals and Slots
        self.code_text_edit.textChanged.connect(self.on_code_changed)
        icon_button.clicked.connect(self.on_icon_button_clicked)
        delete_button.clicked.connect(self.on_delete_clicked)
        open_button.clicked.connect(self.on_open_clicked)
        copy_button.clicked.connect(self.on_copy_button_clicked)
        self.save_button.clicked.connect(self.on_menu_button_save_clicked)
        self.load_attrs()
        self.label_line_edit.textChanged.connect(self.on_code_changed)
        self.dirty = False
        self.save_button.hide()

    def on_copy_button_clicked(self):
        import pyperclip

        name = self.name
        text = 'import cookbook.{}.pre_publish.{}.{} as {}\nreload({})\n\n{}.{}().run()'.format(self.software,
                                                                                self.preflight_name,
                                                                                name,
                                                                                name,
                                                                                name,
                                                                                name,
                                                                                name)
        pyperclip.copy(text)

    def on_icon_button_clicked(self):
        default_folder = os.path.join(self.cfg.cookbook_folder, self.software, self.menu_type, self.preflight_name)
        file_paths = QtWidgets.QFileDialog.getOpenFileName(self, 'Choose a File to Attach', default_folder, "*")
        from_path = file_paths[0].replace('\\', '/')
        _, file_ = os.path.split(from_path)
        to_path = os.path.join(default_folder, file_).replace('\\', '/')
        if from_path != to_path:
            dirname = os.path.dirname(to_path)
            if not os.path.exists(dirname):
                os.makedirs(dirname)
            cgl_copy(from_path, to_path)
        self.icon_path_line_edit.setText(to_path)
        icon = QtGui.QIcon(to_path)
        tab_ = self.parent().parent()
        index_ = tab_.currentIndex()
        tab_.setTabIcon(index_, icon)
        # # display the icon?
        self.on_menu_button_save_clicked()

    def on_menu_button_save_clicked(self):
        if self.reference_path:
            return
        else:
            button_name = self.name
            print(self.menu)
            menu_name = self.menu.menu_name
            menu_type = self.menu.menu_type
            button_file = get_button_path(software=self.software, menu_name=menu_name, button_name=button_name,
                                          menu_type=menu_type, cfg=self.cfg)

            dir_ = os.path.dirname(button_file)
            if not os.path.exists(dir_):
                os.makedirs(dir_)
            make_init_for_folders_in_path(dir_, self.cfg)

            if self.dirty:
                print('Saving {}: {}'.format(button_name, button_file))
                code = self.code_text_edit.document().toPlainText()
                if self.software.lower() == 'unreal':
                    if os.path.exists(button_file):
                        self.dirty = False
                        return
                with open(button_file, 'w+') as x:
                    x.write(code)
                self.dirty = False
            else:
                print('No Changes to Save')

    def on_open_clicked(self):
        code_path = os.path.join(os.path.dirname(self.preflight_path), self.menu_type, self.preflight_name,
                                 '%s.py' % self.name)
        start(code_path)

    def on_code_changed(self):
        self.save_button.show()
        self.dirty = True

    def load_attrs(self):
        """
        Loads the attrs for each "button" in the "Menu".
        :return:
        """
        for attr in self.attrs:
            if attr in self.attrs_dict:
                attr_value = str(self.attrs[attr])
                if attr == 'name':
                    if not str(self.attrs[attr]):
                        split = self.attrs['module'].split()
                        attr_value = split[-1].split('.run()')[0]
                self.attrs_dict[attr].setText(attr_value)
        # load the python file into the text edit
        code_text = self.load_code_text()
        if code_text:
            self.code_text_edit.setPlainText(code_text)
        else:
            self.create_default_button()

    def load_code_text(self):
        if self.software.lower() != 'unreal':
            if not self.reference_path:
                code_path = get_button_path(self.software, self.preflight_name, self.name, menu_type=self.menu_type,
                                            cfg=self.cfg)
            else:
                code_path = self.reference_path
                print('loading code from reference {}'.format(self.reference_path))
            if os.path.exists(code_path):
                try:
                    return open(code_path).read()
                except IOError:
                    with open(code_path, 'w+') as y:
                        y.write("")
                return None
            else:
                print('%s does not exist' % code_path)
        else:
            self.code_text_edit.setPlainText("Text Edit Disabled for Unreal Engine" )
            self.code_text_edit.setEnabled(False)
            print('Not loading for Unreal Buttons')

    def create_default_button(self):
        create_button_file(software=self.software, menu_name=self.preflight_name, button_name=self.name,
                           menu_type=self.menu_type, cfg=self.cfg)
        code_text = self.load_code_text()
        if code_text:
            self.code_text_edit.setPlainText(code_text)

    def on_delete_clicked(self):
        menu_widget = self.parent().parent()
        # delete the file
        filepath = menu_widget.currentWidget().command_line_edit.text().replace('.', '\\')
        if 'import ' in filepath:
            filepath = filepath.replace('import ', '')
            filepath = filepath.split(' as ')[0]
            filepath = '{}.py'.format(filepath)
        else:
            print('not sure what to do with non-python filepath {}'.format(filepath))
        filepath = os.path.join(os.path.dirname(self.cfg.cookbook_folder), filepath)
        if os.path.exists(filepath):
            print('Deleting the file: {}'.format(filepath))
            # os.remove(filepath)
        else:
            print('File Does Not Exist: {}'.format(filepath))
        self.parent().parent().removeTab(self.parent().parent().currentIndex())

class CGLMenu(QtWidgets.QWidget):
    """
    This creates the top level "Menu" Tab with the "buttons" within it.  Menu is a catch all for "Menus", "Shelves",
    "pre_publish", "Context-menus" and anything else in the future that fits the structure we've got here.

    """
    menu_button_save_clicked = QtCore.Signal(object)

    def __init__(self, parent=None, software=None, menu_type='menus', menu_name='', menu=None, menu_path='', cfg=None):
        QtWidgets.QWidget.__init__(self, parent)
        # initialize variables
        self.menu_type = menu_type
        if self.menu_type == 'shelves':
            self.singular = 'shelf'
        elif self.menu_type == 'menus':
            self.singular = 'menu'
        elif self.menu_type == 'pre_publish':
            self.singular = 'preflight'
        elif self.menu_type == 'context-menus':
            self.singular = 'context-menu'
        else:
            self.singluar = 'not defined'
        self.software = software
        self.cfg = cfg
        self.menu = menu
        self.menu_name = menu_name
        self.menu_path = menu_path
        self.new_button_widget = None

        # create layouts
        layout = QtWidgets.QVBoxLayout(self)
        title_layout = QtWidgets.QHBoxLayout()
        if menu_type != 'shelves':
            self.buttons_tab_widget = LJTabWidget()
            self.buttons_tab_widget.setProperty('class', 'vertical')
            self.buttons_tab_widget.tabBar().setProperty('class', 'vertical')
        else:
            self.buttons_tab_widget = QtWidgets.QTabWidget()

        self.title = ''
        if self.menu_type == 'menus':
            self.title = QtWidgets.QLabel('%s %s Buttons: (Drag to Reorder)' % (self.menu_name, self.menu_type.title()))
        elif self.menu_type == 'pre_publish':
            self.title = QtWidgets.QLabel('%s %s Steps: (Drag to Reorder)' % (self.menu_name, self.menu_type.title()))
        elif self.menu_type == 'pre_render':
            self.title = QtWidgets.QLabel('%s %s Steps: (Drag to Reorder)' % (self.menu_name, self.menu_type.title()))
        elif self.menu_type == 'tasks':
            self.title = QtWidgets.QLabel('')
        elif self.menu_type == 'shelves':
            self.title = QtWidgets.QLabel('%s Shelf Buttons: (Drag to Reorder)' % self.menu_name)
        elif self.menu_type == 'context-menus':
            self.title = QtWidgets.QLabel('Context Menu Buttons: (Drag to Reorder)')
        self.title.setProperty('class', 'title')
        if self.menu_type == 'shelves':
            self.add_button = QtWidgets.QPushButton('add shelf button')
            self.import_menu_button = QtWidgets.QPushButton('import shelf button')
        elif self.menu_type == 'pre_publish':
            self.add_button = QtWidgets.QPushButton('add step')
            self.import_menu_button = QtWidgets.QPushButton('import pre_publish step')
        elif self.menu_type == 'pre_render':
            self.add_button = QtWidgets.QPushButton('add step')
            self.import_menu_button = QtWidgets.QPushButton('import pre_render step')
        elif self.menu_type == 'tasks':
            self.add_button = QtWidgets.QPushButton('add task')
            self.import_menu_button = QtWidgets.QPushButton('import task')
        else:
            self.add_button = QtWidgets.QPushButton('add %s button' % self.singular)
            self.import_menu_button = QtWidgets.QPushButton('import %s button' % self.singular)
        self.add_submenu_button = QtWidgets.QPushButton('add submenu')
        self.add_submenu_button.hide()
        self.import_menu_button.hide()
        self.add_button.setProperty('class', 'add_button')
        self.add_submenu_button.setProperty('class', 'add_button')
        self.import_menu_button.setProperty('class', 'add_button')

        # set parameters
        self.buttons_tab_widget.setMovable(True)

        # layout the widget
        title_layout.addWidget(self.title)
        title_layout.addWidget(self.add_submenu_button)
        title_layout.addWidget(self.import_menu_button)
        title_layout.addWidget(self.add_button)
        title_layout.addStretch(1)
        layout.addLayout(title_layout)
        layout.addWidget(self.buttons_tab_widget)

        # connect SIGNALS and SLOTS
        self.add_button.clicked.connect(self.on_add_menu_button)
        self.add_submenu_button.clicked.connect(self.on_submenu_button_clicked)
        self.import_menu_button.clicked.connect(self.on_import_menu_button_clicked)
        self.load_buttons()

    @staticmethod
    def on_import_menu_button_clicked():
        dialog = InputDialog(title="Feature In Progress",
                             message="This button will allow you to import buttons/pre_publish from other menus")
        dialog.exec_()
        if dialog.button == 'Ok' or dialog.button == 'Cancel':
            dialog.accept()

    @staticmethod
    def on_submenu_button_clicked():
        dialog = InputDialog(title="Feature In Progress",
                             message="This button will allow you to create a submenu!")
        dialog.exec_()
        if dialog.button == 'Ok' or dialog.button == 'Cancel':
            dialog.accept()

    def on_add_menu_button(self):
        if self.menu_type == 'tasks':
            self.schema = get_schema(self.cfg)
            singular = 'Task'
            dialog = InputDialog(title='Add %s' % singular,
                                 message='Choose Task to Create a %s Recipe For\n '
                                         'Or Type to Create Your Own' % singular,
                                 line_edit=False, combo_box_items=task_list(), regex='[a-zA-Z]',
                                 name_example='Only letters & Numbers Allowed in %s Names' % singular)
            dialog.exec_()
            if dialog.button == 'Ok':
                long_name = dialog.combo_box.currentText()
                task_name = ''
                if long_name in self.schema['long_to_short']['assets']:
                    task_name = self.schema['long_to_short']['assets'][long_name]
                elif long_name in self.schema['long_to_short']['shots']:
                    task_name = self.schema['long_to_short']['shots'][long_name]
                else:
                    task_name = long_name
                if task_name:
                    self.do_add_task(task_name)
            return
        elif self.menu_type == 'pre_publish':
            title_ = 'Add Preflight Step'
            message = 'Enter a Name for your Preflight Step'
        elif self.menu_type == 'menus':
            title_ = 'Add Menu'
            message = 'Enter a Name for your Menu Button'
        elif self.menu_type == 'shelves':
            title_ = 'Add Shelf'
            message = 'Enter a Name for your Shelf button'
        elif self.menu_type == 'context-menus':
            title_ = 'Add Context Menu Item'
            message = 'Enter a name for your Context Menu Item'

        dialog = NewButtonDialog(software=self.software, menu_type=self.menu_type, menu_name=self.menu_name,
                                 cfg=self.cfg)
        dialog.exec_()
        if dialog.button == 'Ok':
            text_ = stringcase.snakecase(dialog.button_name_line_edit.text().lower())
            button_name = stringcase.pascalcase(text_)
            label = stringcase.titlecase(text_)
            if dialog.cgl_button_type == 'New':
                command = self.get_command_text(button_name=button_name, menu_type=self.menu_type)
                module = self.default_preflight_text(button_name)
                module_path = None
            elif dialog.cgl_button_type == 'Referenced':
                command = dialog.command
                module = dialog.module
                module_path = dialog.button_path

            if self.menu_type == 'pre_publish' or self.menu_type == 'pre_render':
                attrs = {'label': label,
                         'name': button_name,
                         'required': 'True',
                         'module': module,
                         'reference_path': module_path}
            elif self.menu_type == 'menus' or self.menu_type == 'context-menus':
                attrs = {'label': label,
                         'name': button_name,
                         'module': command,
                         'reference_path': module_path}
            elif self.menu_type == 'shelves':
                attrs = {'label': label,
                         'name': button_name,
                         'module': command,
                         'icon': '',
                         'reference_path': module_path}

            self.new_button_widget = CGLMenuButton(parent=self.buttons_tab_widget, preflight_name=self.menu_name,
                                                   preflight_step_name=button_name, menu=self,
                                                   attrs=attrs, preflight_path=self.menu_path, menu_type=self.menu_type,
                                                   reference_path=module_path, cfg=self.cfg)
            if 'icon' in attrs.keys():
                icon = QtGui.QIcon(attrs['icon'])
                index = self.buttons_tab_widget.addTab(self.new_button_widget, icon, button_name)
            else:
                index = self.buttons_tab_widget.addTab(self.new_button_widget, button_name)
            self.buttons_tab_widget.setCurrentIndex(index)

    def do_add_task(self, task_name):
        print('Adding Task {}'.format(task_name))
        module = 'cookbook.%s.tasks.tasks.%s' % (self.software, task_name)
        attrs = {'label': task_name,
                 'name': task_name,
                 'module': module
                 }
        self.new_button_widget = CGLMenuButton(parent=self.buttons_tab_widget, preflight_name='tasks',
                                               preflight_step_name=task_name, menu=self,
                                               attrs=attrs, preflight_path=self.menu_path, menu_type=self.menu_type,
                                               cfg=self.cfg)
        # TODO - make sure that a smart_task.py file exists in the folder.
        smart_task_path = self.menu_path.replace('.cgl', '\\tasks\\smart_task.py')
        if not os.path.exists(smart_task_path):
            template_path = (os.path.join(self.cfg.get_cgl_resources_path(), 'alchemists_cookbook', 'default', 'smart_task.py'))
            template_lines = load_text_file(template_path)
            changed_lines = []
            for l in template_lines:
                if 'SOFTWARE' in l:
                    new_l = l.replace('SOFTWARE', self.software)
                    changed_lines.append(new_l)
                else:
                    changed_lines.append(l)
            save_text_lines(changed_lines, smart_task_path)
            # TODO - replace 'SOFTWARE' with self.software in the smart_task.py file.
        index = self.buttons_tab_widget.addTab(self.new_button_widget, task_name)
        self.buttons_tab_widget.setCurrentIndex(index)

    def get_command_text(self, button_name, menu_type, branch='master'):
        menu_directory = os.path.join(self.cfg.cookbook_folder, self.software, self.menu_type)
        rel_dir = menu_directory.split(r'\config')[-1]
        cookbook_dir = menu_directory.split('r\cookbook')[-1]
        if self.software.lower() == 'unreal':
            # TODO - disable the text edit
            return "/config{}/{}/{}.uasset".format(rel_dir, self.menu_name, button_name).replace('\\', '/')
        else:
            rel_dir = rel_dir.replace('\\', '.')
            cookbook_dir = cookbook_dir.replace('\\', '.')
            print(rel_dir)
            print(cookbook_dir)
            print('---------------')
            #TODO - this seems sus - fix this later

            return 'import cookbook%s.%s.%s as %s; %s.run()' % (cookbook_dir, self.menu_name, button_name,
                                                               button_name, button_name)

    def default_preflight_text(self, preflight_name):
        return 'cookbook.%s.%s.%s.%s' % (self.software, self.menu_type, self.menu_name, preflight_name)

    def load_buttons(self):
        if self.menu:
            if 'buttons' in self.menu.keys():
                for button in self.menu['buttons']:
                    try:
                        ref_path = button['reference_path']
                    except KeyError:
                        ref_path = None
                    button_widget = CGLMenuButton(parent=self.buttons_tab_widget, preflight_name=self.menu_name,
                                                  preflight_step_name=button['label'],
                                                  attrs=button, preflight_path=self.menu_path,
                                                  menu_type=self.menu_type, menu=self, reference_path=ref_path,
                                                  cfg=self.cfg)
                    if 'icon' in button.keys():
                        if button['icon']:
                            icon = QtGui.QIcon(button['icon'])
                            self.buttons_tab_widget.addTab(button_widget, icon, button['name'])
                        else:
                            self.buttons_tab_widget.addTab(button_widget, button['name'])
                    else:
                        self.buttons_tab_widget.addTab(button_widget, button['name'])
            else:
                for i in range(len(self.menu)):
                    for button in self.menu:
                        if button != 'order':
                            if i == self.menu[button]['order']:
                                button_widget = CGLMenuButton(parent=self.buttons_tab_widget, preflight_name=self.menu_name,
                                                              preflight_step_name=button,
                                                              attrs=self.menu[button], preflight_path=self.menu_path,
                                                              menu_type=self.menu_type, menu=self, cfg=self.cfg)
                                if 'icon' in self.menu[button].keys():
                                    if self.menu[button]['icon']:
                                        icon = QtGui.QIcon(self.menu[button]['icon'])
                                        self.buttons_tab_widget.addTab(button_widget, icon, self.menu[button]['name'])
                                    else:
                                        self.buttons_tab_widget.addTab(button_widget, button)
                                else:
                                    self.buttons_tab_widget.addTab(button_widget, button)

def create_button_file(software, menu_name, button_name, menu_type, cfg):
    button_path = get_button_path(software, menu_name, button_name, menu_type=menu_type, cfg=cfg)
    if software == 'magic_browser':
        template_software = 'magic_browser'
    elif software == 'blender':
        template_software = 'blender'
    elif software.lower() == 'unreal':
        template_software = 'unreal'
    else:
        template_software = 'default'
    if software.lower() == 'unreal':
        button_template = os.path.join(cfg.get_cgl_resources_path(), 'alchemists_cookbook', template_software, 'buttons',
                                       'for_%s.uasset' % menu_type)
        dirname = os.path.dirname(button_path)
        if not os.path.exists(dirname):
            os.makedirs(dirname)
        # copy button_template to button_path
        print('Copying {} to {}'.format(button_template, button_path))
        cgl_copy(button_template, button_path)
        return
    else:
        button_template = os.path.join(cfg.get_cgl_resources_path(), 'alchemists_cookbook',
                                       template_software, 'buttons',
                                       'for_%s.py' % menu_type)
    button_lines = load_text_file(button_template)
    changed_lines = []
    for l in button_lines:
        if software == 'blender':
            if l.startswith('class ButtonTemplate'):
                new_l = l.replace('ButtonTemplate', button_name)
                changed_lines.append(new_l)
            elif 'object.button_template' in l:
                new_l = l.replace('button_template', stringcase.snakecase(button_name))
                changed_lines.append(new_l)
            elif 'bl_label' in l:
                new_l = l.replace('button_template', stringcase.titlecase(button_name))
                changed_lines.append(new_l)
            elif 'print' in l:
                new_l = l.replace('button_template', stringcase.titlecase(button_name))
                new_l = l.replace('PreflightTemplate', stringcase.titlecase(button_name))
                changed_lines.append(new_l)
            elif 'PreflightTemplate' in l:
                new_l = l.replace('PreflightTemplate', stringcase.titlecase(button_name))
                changed_lines.append(new_l)
            else:
                changed_lines.append(l)
        else:
            if 'print' in l:
                new_l = l.replace('button_template', stringcase.titlecase(button_name))
                changed_lines.append(new_l)
            elif 'PreflightTemplate' in l:
                new_l = l.replace('PreflightTemplate', button_name)
                changed_lines.append(new_l)
            elif 'SOFTWARE' in l:
                new_l = l.replace('SOFTWARE', software)
                changed_lines.append(new_l)
            else:
                changed_lines.append(l)
    dirname = os.path.dirname(button_path)
    if not os.path.exists(dirname):
        os.makedirs(dirname)
    save_text_lines(changed_lines, button_path)
    return button_path

def get_menu_path(software, menu_name, menu_file=False, menu_type='menus', cfg=None):
    """
    returns the menu path for a menu with the given name
    :param software: software package to get the menu path for.
    :param menu_name: CamelCase string - all menus created with cookbook designer are CamelCase
    :param menu_file: if True returns a menu path with a menu_name.py file.
    :param menu_type: menus, pre_publish, shelves, context-menus
    :return:
    """
    cfg = cfg
    if menu_file:
        menu_folder = os.path.join(cfg.cookbook_folder, software, menu_type, menu_name, '%s.py' % menu_name)
    else:
        logging.debug("software: {}".format(software),
                      "menu type: {}".format(menu_type),
                      "menu_name: {}".format(menu_name))
        menu_folder = os.path.join(cfg.cookbook_folder, software, menu_type, menu_name)
        print(menu_folder)
    return menu_folder

def get_button_path(software, menu_name, button_name, menu_type='menus', cfg=None):
    """

    :param software: software as it appears in cookbook designer.
    :param menu_name: CamelCase menu name
    :param button_name: CamelCase button name
    :param menu_type: menus, pre_publish, shelves, context-menus
    :return:
    """
    if isinstance(menu_name, dict):
        menu_name = menu_name['name']
    menu_folder = get_menu_path(software, menu_name, menu_type=menu_type, cfg=cfg)
    if software.lower() == 'unreal':
        button_path = os.path.join(menu_folder, '%s.uasset' % button_name)
    else:
        button_path = os.path.join(menu_folder, '%s.py' % button_name)
    return button_path

def make_init_for_folders_in_path(folder, cfg):
    config = cfg.cookbook_folder.replace('\\', '/')
    if folder:
        folder = folder.replace('\\', '/')
        folder = folder.replace(config, '')
        parts = folder.split('/')
        if '' in parts:
            parts.remove('')
        string = config
        for p in parts:
            if ':' not in p:
                if '.' not in p:
                    string = '%s/%s' % (string, p)
                    init = '%s/__init__.py' % string
                    if not os.path.exists(init):
                        make_init(os.path.dirname(init))

def make_init(folder):
    if '*' not in folder:
        with open(os.path.join(folder, '__init__.py'), 'w+') as i:
            i.write("")

class NewButtonDialog(LJDialog):
    def __init__(self, parent=None, software=None, menu_type=None, menu_name=None, cfg=None):
        LJDialog.__init__(self, parent)
        self.cfg = cfg
        self.software = software
        self.cgl_button_type = 'New Button'
        self.menu_type = menu_type
        self.module = None
        self.command = None
        self.button_path = None
        layout = QtWidgets.QVBoxLayout(self)
        self.setWindowTitle('New Pipeline Button')
        self.reference_button_label = QtWidgets.QLabel()
        self.reference_button_label.setProperty('class', 'title')
        self.reference_button_label.hide()
        combo_label = QtWidgets.QLabel("Button Type: ")
        self.reference_combo_label = QtWidgets.QLabel('Reference :')
        self.button_type = QtWidgets.QComboBox()
        self.reference_buttons = AdvComboBox()
        self.menu_name = menu_name
        self.menu_types = ['menus', 'context-menus', 'shelves', 'pre_publish']
        self.menu_directory = os.path.join(self.cfg.cookbook_folder, self.software, self.menu_type)
        self.button_type.addItems(['New', 'Referenced'])
        self.new_button_label = QtWidgets.QLabel()
        self.button_name_line_edit = QtWidgets.QLineEdit()
        self.ok_button = QtWidgets.QPushButton('Ok')
        self.cancel_button = QtWidgets.QPushButton('Cancel')
        self.button = 'Cancel'

        grid = QtWidgets.QGridLayout()

        #grid.addWidget(combo_label, 0, 0)
        #grid.addWidget(self.button_type, 0, 1)
        #grid.addWidget(self.reference_combo_label, 1, 0)
        #grid.addWidget(self.reference_buttons, 1, 1)
        grid.addWidget(self.new_button_label, 2, 0)
        grid.addWidget(self.button_name_line_edit, 2, 1)

        button_row = QtWidgets.QHBoxLayout()
        button_row.addStretch(1)
        button_row.addWidget(self.cancel_button)
        button_row.addWidget(self.ok_button)

        layout.addLayout(grid)
        layout.addLayout(button_row)

        self.reference_buttons.hide()
        self.reference_combo_label.hide()

        self.ok_button.clicked.connect(self.on_ok_clicked)
        self.cancel_button.clicked.connect(self.on_cancel_clicked)
        self.button_type.currentIndexChanged.connect(self.on_type_changed)
        self.reference_buttons.currentTextChanged.connect(self.on_reference_button_selected)
        self.on_type_changed()
        self.load_buttons_for_reference()

    def load_buttons_for_reference(self):
        """
        loads all available buttons into the adv combo box.
        :return:
        """
        self.reference_buttons.clear()
        self.reference_buttons.addItem('')
        print('loading buttons from {}'.format(self.menu_directory))
        for root, dirs, files in os.walk(self.menu_directory):
            for name in files:
                if self.menu_name not in root:
                    if name.endswith('.py'):
                        if '__init__' not in name:
                            button_name = '{}/{}'.format(os.path.basename(root), name)
                            self.reference_buttons.addItem(button_name)

    def on_reference_button_selected(self):
        """

        :return:
        """
        button_text = self.reference_buttons.currentText()
        if '.py' in button_text:
            menu, button = os.path.split(button_text)
            button_name = button.replace('.py', '')
            full_button_path = os.path.join(self.menu_directory, menu, button)
            splitted = full_button_path.split('_config')[-1].split('\\')
            if splitted[0] == '':
                splitted.pop(0)
            module = '.'.join(splitted).replace('.py', '')
            command = 'import {} as {}; {}.run()'.format(module, button_name, button_name)
            self.button_path = full_button_path
            self.module = module
            self.command = command
            self.button_name_line_edit.setText(button_name)
            print(self.button_path)
            print(self.module)
            print(self.command)

    def on_type_changed(self):
        """
        when the type changes, change the text
        :return:
        """
        self.new_button_label.setText('Button Name'.format(self.button_type.currentText()))
        self.cgl_button_type = self.button_type.currentText()
        if self.cgl_button_type == 'Referenced':
            self.reference_buttons.show()
            self.reference_combo_label.show()
            # dialog = QtWidgets.QFileDialog()
            # dialog.title = 'Choose a Button To Reference'
            # dialog.setDirectory(os.path.join(get_cgl_tools(), self.software, self.menu_type))
            # if dialog.exec_():
            #     file_names = dialog.selectedFiles()
            #     if file_names:
            #         button_path = file_names[0]
            #         splitted = button_path.split('_config')[-1].split('/')
            #         if splitted[0] == '':
            #             splitted.pop(0)
            #         filename = splitted[-1].replace('.py', '')
            #         module = '.'.join(splitted).replace('.py', '')
            #         from_label = "Referencing: {}".format(module)
            #         command = 'import {} as {}; {}.run()'.format(module, filename, filename)
            #         self.reference_button_label.setText(from_label)
            #         self.reference_button_label.show()
            #         self.button_path = button_path
            #         self.module = module
            #         self.command = command
        else:
            self.reference_buttons.hide()
            self.reference_combo_label.hide()

    def on_ok_clicked(self):
        self.button = 'Ok'
        self.accept()

    def on_cancel_clicked(self):
        self.accept()

    def load_buttons(self):
        print(self.menu_types_combo.currentText())

def get_schema(cfg):
    config = cfg.project_config
    proj_man = config['account_info']['project_management']
    def_schema = config['project_management'][proj_man]['api']['default_schema']
    schema = config['project_management'][proj_man]['tasks'][def_schema]
    return schema

def task_list(cfg):
    schema = get_schema(cfg)
    task_list = []
    try:
        for each in schema['long_to_short']['assets']:
            if each not in task_list:
                task_list.append(each)
        for each in schema['long_to_short']['shots']:
            if each not in task_list:
                task_list.append(each)
    except TypeError:
        print('Problems found in your globals "schema"')
        return
    task_list.sort()
    task_list.insert(0, '')
    return task_list


"""Support for tracking a Volvo."""
from homeassistant.components.device_tracker import SOURCE_TYPE_GPS
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.util import slugify

from . import DATA_KEY, SIGNAL_STATE_UPDATED

async def async_setup_scanner(hass, config, async_see, discovery_info=None):
    """Set up the Volvo tracker."""
    if discovery_info is None:
        return

    vin, component, attr = discovery_info
    data = hass.data[DATA_KEY]
    instrument = data.instrument(vin, component, attr)

    async def see_vehicle():
        """Handle the reporting of the vehicle position."""
        host_name = instrument.vehicle_name
        dev_id = f"volvo_{slugify(host_name)}"
        await async_see(
            dev_id=dev_id,
            host_name=host_name,
            source_type=SOURCE_TYPE_GPS,
            gps=instrument.state,
            icon="mdi:car",
        )

    async_dispatcher_connect(hass, SIGNAL_STATE_UPDATED, see_vehicle)

    return True


import pandas as pd
import base64
from Crypto.Cipher import AES

class EncryptData(object):
    def __init__(self, key):
        self.key = key.encode("utf8")  # 初始化密钥
        self.length = AES.block_size  # 初始化数据块大小
        self.aes = AES.new(self.key, AES.MODE_ECB)  # 初始化AES,ECB模式的实例
        # 截断函数，去除填充的字符
        self.unpad = lambda date: date[0:-ord(date[-1])]

    def pad(self, text):
        '''
        #填充函数，使被加密数据的字节码长度是block_size的整数倍
        '''
        count = len(text.encode('utf-8'))
        add = self.length - (count % self.length)
        entext = text + (chr(add) * add)
        return entext

    def encrypt(self, encrData):  # 加密函数
        res = self.aes.encrypt(self.pad(encrData).encode("utf8"))
        msg = str(base64.b64encode(res), encoding="utf8")
        return msg

    def decrypt(self, decrData): # 解密函数
            decrData=str(decrData)

            res = base64.decodebytes(decrData.encode("utf8"))
            msg = self.aes.decrypt(res).decode("utf8")
            return self.unpad(msg)

def handwritingClassTest(path):

    eg = EncryptData("!@#qwedsazxc@!@#")
    if path.endswith("xlsx"):

       df = pd.read_excel(path)
    else:
       df=pd.read_csv(path)
    cols=df.columns
    for col in list(cols):
        df[col] = df[col].map(lambda s: eg.encrypt(str(s)))
    return df

if __name__ == '__main__':
    import os
    path=os.getcwd()
    for root, dirs, files in os.walk(path):
        for i in files:
            if i.endswith("xlsx"):
                input_file=os.path.join(root, i)
                data = handwritingClassTest(input_file)
                output_file = input_file.replace(".xlsx", "-encrypt.xlsx")
                data.to_excel(output_file, index=False)
            if i.endswith("csv"):
                input_file = os.path.join(root, i)
                data = handwritingClassTest(input_file)
                output_file = input_file.replace(".csv", "-encrypt.csv")
                data.to_excel(output_file, index=False)


"""
 There should be a insightful documentation here
"""

import yaml
from messageApp.intervals import Interval

class Messages():
	def __init__(self, messagesFile):
		self.load(messagesFile)

	def load(self, messagesFile):
		self.messagesFile = messagesFile
		self._populateObject(self.messagesFile)

	# initialise from a file and create messages dict from it
	def reload(self):
		self.load(self.messagesFile)

	def getMessage(self, time):
		for interval in self.intervals:
			message = interval.getMessage(time)
			if message:
				return (self.title, message)

		if self.defaultMessage:
			return (self.title, self.defaultMessage)

		return None

	# load conf file and instanciate title and Intervals
	def _populateObject(self, messagesFile):
		f = open(messagesFile, 'r')
		variables = yaml.load(f)
		self.title = variables['title']
		self.defaultMessage = variables['default'] if 'default' in variables else ''
		self.intervals = []
		for messages in variables['messages']:
			relative = messages['relative'] if 'relative' in messages else False
			interval = messages['interval'] if 'interval' in messages else '* * * * * *'
			intervals = Interval(interval, messages['messages'].items(), relative)
			self.intervals.append(intervals)

	def __str__(self):
		txt =  "Title   : " + self.title + "\n"
		txt += "Default : " + self.defaultMessage + "\n"
		txt += "Messages:\n"
		for i in self.intervals:
			txt += str(i) + "\n"
		return txt


# -*- coding: utf-8 -*-
import datetime
from odoo import models, fields, api
"""
@miguel.cabrera

"""
class CoreGeneradorFolios(models.Model):
    _name = 'core_generador_folio';
    nombre_folio = fields.Char(string='Nombre del folio', required=True)
    prefijo = fields.Char(string='Prefijo', required=True,
                          help='Se se usará como parte fundamental en el folio generado')
    contador = fields.Integer(default=0)
    incrementar = fields.Integer(default=lambda self: 1)
    numero_zeros = fields.Integer(string='Número de ceros a la izquierda', default=0)
    formato_fecha = fields.Char(string='Ingrese el formato de la fecha si lo requiere',
                                help='Por ejemplo: %Y-%m-%d o %Y%m%d%H%%i%s')

    tipo_folio_id = fields.Many2one(
        'core_formato_folio',
        string='Formato del folio',
        inverse_name='formato',
        ondelete='set null'
    )

    # agregar el constrain de prefijo unico

    @api.multi
    def getFolio(self, par_prefijo_folio):
        coreFolio = self.env['core_generador_folio'].search([('prefijo','=', par_prefijo_folio)])
        folio = ""
        if coreFolio:
            contador_actual = coreFolio.contador + coreFolio.incrementar
            folio = self.crearFolioByFormato(coreFolio.tipo_folio_id.formato, coreFolio, contador_actual)
            coreFolio.write({'contador': contador_actual})
        return folio

    def crearFolioByFormato(self, par_formato, par_campos, contador_actual):
        folio_final = str(par_formato)
        fields_search = [
            'prefijo',
            'numero_zeros',
            'contador',
            'formato_fecha'
        ]
        for val in fields_search:
            if val in par_campos:
                key = par_campos[val]
                if val == 'contador':
                    key = str(contador_actual).zfill(par_campos.numero_zeros)
                elif val == 'formato_fecha' and key:
                    key = str(datetime.datetime.now().strftime(key))
                key = str(key)
                folio_final = folio_final.replace('{' + val + '}', key)
        return folio_final;

    def createGenericFolio(self, data):
        self.create(data)
        # print (data)
        return self.getFolio(data['prefijo'])


import numpy as np
import math

import matplotlib.pyplot as plt

def get_mn_log_likelihood(obs,probs):
    """ Return the (log)likelihood of obs, given the probs"""
    multinomial_coeff_denom= 0
    prod_probs = 0
    for x in range(0,len(obs)): # loop through state counts in each observation
        multinomial_coeff_denom = multinomial_coeff_denom + math.log(math.factorial(obs[x]))
        prod_probs = prod_probs + obs[x]*math.log(probs[x])

    multinomial_coeff = math.log(math.factorial(sum(obs))) -  multinomial_coeff_denom
    likelihood = multinomial_coeff + prod_probs
    return likelihood

# 1st:  Coin B, {HTTTHHTHTH}, 5H,5T
# 2nd:  Coin A, {HHHHTHHHHH}, 9H,1T
# 3rd:  Coin A, {HTHHHHHTHH}, 8H,2T
# 4th:  Coin B, {HTHTTTHHTT}, 4H,6T
# 5th:  Coin A, {THHHTHHHTH}, 7H,3T
# so, from MLE: pA(heads) = 0.80 and pB(heads)=0.45

head_counts = np.array([5,9,8,4,7])
tail_counts = 10-head_counts
experiments = zip(head_counts,tail_counts)

pA_heads = np.zeros(100); pA_heads[0] = 0.60
pB_heads = np.zeros(100); pB_heads[0] = 0.50

# E-M begins!
delta = 0.001
j = 0 # iteration counter
improvement = float('inf')
while (improvement>delta):
    expectation_A = np.zeros((5,2), dtype=float)
    expectation_B = np.zeros((5,2), dtype=float)
    for i in range(0,len(head_counts)):
        e = [head_counts[i],tail_counts[i]] # i'th experiment
        ll_A = get_mn_log_likelihood(e,np.array([pA_heads[j],1-pA_heads[j]])) # loglikelihood of e given coin A
        ll_B = get_mn_log_likelihood(e,np.array([pB_heads[j],1-pB_heads[j]])) # loglikelihood of e given coin B

        weightA = math.exp(ll_A) / ( math.exp(ll_A) + math.exp(ll_B) ) # corresponding weight of A proportional to likelihood of A
        weightB = math.exp(ll_B) / ( math.exp(ll_A) + math.exp(ll_B) ) # corresponding weight of B proportional to likelihood of B

        expectation_A[i] = np.dot(weightA, e)
        expectation_B[i] = np.dot(weightB, e)

    pA_heads[j+1] = sum(expectation_A)[0] / sum(sum(expectation_A));
    pB_heads[j+1] = sum(expectation_B)[0] / sum(sum(expectation_B));
    print(pA_heads[j+1], pB_heads[j+1])
    improvement = max( abs(np.array([pA_heads[j+1],pB_heads[j+1]]) - np.array([pA_heads[j],pB_heads[j]]) ))
    j = j+1
print(j)

deltas = np.array([0.00001, 0.0001, 0.001, 0.01, 0.1])
iterations = np.array([13, 11, 8, 5, 2])

#figsize(7, 5)
plt.plot([0.00001, 0.0001, 0.001, 0.01, 0.1], [13, 11, 8, 5, 2], 'ro')
plt.axis([-0.001, 0.11, 0, 14])
plt.xlabel('Tolerance level')
plt.ylabel('Iterations')
plt.title('Relationship between tolerance level and number of iterations')
plt.savefig('coin_toss.pdf')


#!/usr/bin/env python

import os
import fnmatch
import re

from yaml import dump as yaml_dump
try:
	from yaml import CDumper as Dumper
except ImportError:
	from yaml import Dumper

try:
	from colorama import init as colorama_init
	from colorama import Fore, Style
except ImportError:
	class EmptyString(object):
		def __getattr__(self, name):
			return ''

	def colorama_init(autoreset=False):
		pass

	Fore = EmptyString()
	Style = EmptyString()
	Back = EmptyString()

verbose = True

# Lists of the file extensions to check for rospy or roscpp nodes.
python_ext = ['py']
cpp_ext = ['c', 'cpp', 'cc', 'cxx']

#def write_yaml
def write_yaml(pynodes, cppnodes):
	output = {'nodes': \
				[{'name': n['name'], 'exec':os.path.basename(n['path'])} for n in pynodes + cppnodes]
			 }

	return yaml_dump(output, default_flow_style = False)

#def check_for_errors
def check_for_errors(pynodes, cppnodes):
	nodes = pynodes + cppnodes

	### Check for multiple nodes with the same name.
	duplicates = {}
	for node in nodes:
		if node['name'] in duplicates:
			duplicates[node['name']] += 1
		else:
			duplicates[node['name']] = 1

	for node, dups in duplicates.items():
		if dups > 1:
			print(Fore.YELLOW + "Warning: " + str(dups) + " nodes found with name '" + node + "'!")

	### Check for multiple nodes defined in the same file.
	duplicates = {}
	for node in nodes:
		if node['path'] in duplicates:
			duplicates[node['path']] += 1
		else:
			duplicates[node['path']] = 1

	for node, dups in duplicates.items():
		if dups > 1:
			print(Fore.YELLOW + "Warning: " + str(dups) + " nodes initialized in source file '" + node + "'!")

	return False

#def parse_cpp
def parse_cpp(files):
	cpp_rosincludes = []
	cpp_nodes = []

	# Loop through the input files.
	for f in files:
		included = False

		# Open the file for reading.
		fread = open(f, 'r')
		if fread != None:
			# If there are no errors, loop through the lines in the file.
			for line in fread:
				match = False
				if included:
					# If we find a ros::init call, mark down that there's a node in this
					# file.  Keep searching, because it's possible that multiple nodes are
					# defined in a single file.
					match = re.search('ros::init\(.+?, ?.+?, ?"(.+?)"\)', line)
					if match:
						cpp_nodes.append({'path':f, 'name':match.group(1)})
						continue
				# If we haven't included ros.h, look for the include call.
				else:
					match = re.search('#include ((<)?(")?)ros/ros.h(?(2)>)(?(3)")', line)
					if match:
						included = True
		# If included, add to cpp_rosincludes
		if included:
			cpp_rosincludes.append(f)

	if verbose:
		if len(cpp_rosincludes) > 0:
			print(Fore.BLUE + 'Found ' + str(len(cpp_rosincludes)) + ' c++ files that include ros.h:')
			print(Fore.BLUE + '    ' + ', '.join(cpp_rosincludes))
		else:
			print(Fore.BLUE + 'Found 0 c++ files that include ros.h.')

	# We've searched all files, so let's return our results.
	return cpp_nodes

### This function parses the python files to find rospy imports
### and calls to rospy.init_node.
def parse_py(files):
	py_rosimports = []
	py_nodes = []

	# Loop through the input files.
	for f in files:
		imported = False
		modname = 'rospy'

		# Open the file for reading.
		fread = open(f, 'r')
		if fread != None:
			# If there are no errors, loop through the lines in the file.
			for line in fread:
				match = False
				# If we've imported rospy, try to find an init_node call.
				match = re.search(modname + '.init_node\(\'(.+?)\'', line)
				if imported:
					# If we find a init_node call, mark down that there's a node in this
					# file.  Keep searching, because it's possible that multiple nodes are
					# defined in a single file.
					if match:
						py_nodes.append({'path':f, 'name':match.group(1)})
						continue
				# If we haven't imported rospy, look for the import.
				else:
					# Try first to match the import ... as ... statement.
					match = re.search('import rospy as (.+)', line)
					# If successful, save the name rospy was imported as.
					if match:
						imported = True
						modname = match.group(1)
					# If not, try to match 'import rospy'.
					else:
						match = re.search('import rospy', line)
						if match:
							imported = True

			# We've reached EOF.  Keep track of nodes that have been imported.
			if imported:
				py_rosimports.append(f)

	if verbose:
		if len(py_rosimports) > 0:
			print(Fore.BLUE + 'Found ' + str(len(py_rosimports)) + ' python files with rospy imports:')
			print(Fore.BLUE + '    ' + ', '.join(py_rosimports))
		else:
			print(Fore.BLUE + 'Found 0 python files with rospy imports.')

	# We've searched all files, so let's return our results.
	return py_nodes

### This function generates two lists, one of c++ source files
### recursively below this directory, and the second of python
### source files.  This is a "dumb" function - it only filters
### using file extensions, it doesn't infer type from content.
def gen_file_lists():
	file_lists = ([], [])
	for root, dirs, files in os.walk('.'):
		for pext in python_ext:
			for f in fnmatch.filter(files, '*.' + pext):
				file_lists[0].append(os.path.join(root, f))
		for cext in cpp_ext:
			for f in fnmatch.filter(files, '*.' + cext):
				file_lists[1].append(os.path.join(root, f))

	return file_lists

def main():
	# Initialize colorama for colored output.
	colorama_init(autoreset=True)

	# Get the list of files for consideration.
	py_files, cpp_files = gen_file_lists()

	# Filter the python files to the ones that call rospy.init_node().
	py_nodes = parse_py(py_files)
	# Filter the c++ files to the ones that call ros::init().
	cpp_nodes = parse_cpp(cpp_files)

	# If there are no errors, convert the node lists to YAML and write them to project.yaml.
	if not check_for_errors(py_nodes, cpp_nodes):
		projfile = open('project.yaml', 'w')
		projfile.write(write_yaml(py_nodes, cpp_nodes))

		print(Fore.GREEN + "RIDE node file generated without errors!")
		print(Style.BRIGHT + "Make sure to look at the generated file, as it is likely incorrect/incomplete.")

if __name__ == '__main__':
	main()


import json
import os
import time
import uuid

from datetime import datetime

from google.appengine.api import urlfetch
from google.appengine.ext import ndb

from models import Profile

def getUserId(user, id_type="email"):
    if id_type == "email":
        return user.email()

    if id_type == "oauth":
        """A workaround implementation for getting userid."""
        auth = os.getenv('HTTP_AUTHORIZATION')
        bearer, token = auth.split()
        token_type = 'id_token'
        if 'OAUTH_USER_ID' in os.environ:
            token_type = 'access_token'
        url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?%s=%s'
               % (token_type, token))
        user = {}
        wait = 1
        for i in range(3):
            resp = urlfetch.fetch(url)
            if resp.status_code == 200:
                user = json.loads(resp.content)
                break
            elif resp.status_code == 400 and 'invalid_token' in resp.content:
                url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?%s=%s'
                       % ('access_token', token))
            else:
                time.sleep(wait)
                wait = wait + i
        return user.get('user_id', '')

    if id_type == "custom":
        # implement your own user_id creation and getting algorythm
        # this is just a sample that queries datastore for an existing profile
        # and generates an id if profile does not exist for an email
        profile = Conference.query(Conference.mainEmail == user.email())
        if profile:
            return profile.id()
        else:
            return str(uuid.uuid1().get_hex())

class MultiPropInequality(object):
    """Wrapper class that handles inequalities operating on multiple properties.

    NOTE: GQL is not supported.

    The original result set returned by the underlying query will be filtered
    using post filters. Only those results that satisfy all of the post filters
    will be handed back.

    For better effeciency, set the first inequality filter that is most likely
    to return the least number of data.

    To use:

        query = MultiPropInequality(Model)

    or with search by ancestor:

        query = MultiPropInequality(Model.query(ancestor=key))

    or with pre-built query:

        query = Model.query().filter(Model.prop='value')
        query = MultiPropInequality(query)

    filter() method returns self, so chaining is posible:

        query = MultiPropInequality(Model) \
                    .filter(Model.prop1<='value2') \
                    .filter(Model.prop2!='value2')

    filter() method updates itself (instead of creating a new query), so there
    is no need to reassign the variable:

        query = query.filter(Model.prop1!=0)    # Not necessary

        query.filter(Model.prop1!=0)            # (better) query is updated

    To access the result set, iterate through:

        for result in query:
            # do something with result
    """

    def __init__(self, model_or_query):
        """Creates new instance of this class.

        Parameters:
            model_or_query - Required. An instance of a Model or a pre-built
                             Query object with at most 1 property that is being
                             evaluated for inequalities.
        """
        if isinstance(model_or_query, ndb.model.MetaModel):
            self.query = model_or_query.query()
        elif isinstance(model_or_query, ndb.query.Query):
            self.query = model_or_query
        else:
            raise TypeError(
                'Must be a subclass of Model or an instance of Query.'
            )

        self.first_inequality = self._get_first_inequality(self.query.filters)
        self.post_inq_filters = []

    def filter(self, *args):
        """Checks if each arg is an inequality filter and appends it to the list
        inequality post filters.

        If arg is an inquality filter (or at least one of its subnodes is an
        inequality filter), and operates on a property that is different from
        the first inequality, then it will be added to the list of post
        inequality filters. Otherwise, it will be passed on to the underlying
        query.

        Parameters:
            args - Optional. Node. Can be instances of any of the subclasess of
                   Node (e.g. FilterNode, ConjunctionNode, DisjunctionNode).

        Returns the instance of this class.
        """
        if not args:
            return self

        for arg in args:
            if not isinstance(arg, ndb.query.Node):
                raise TypeError('Filter should be instance of Node.')
            if not self._push_filter(arg):
                self.query = self.query.filter(arg)

        return self

    def _get_first_inequality(self, f_node):
        """Returns the first inquality of a given node. Returns None if no
        inequality can be found.
        """
        inequalities = self._get_inequalities(f_node)
        return None if len(inequalities) == 0 else inequalities[0]

    def _get_inequalities(self, f_node):
        """Returns a list of inequalities in a given node and all of it's
        subnodes
        """
        inequalities = []
        if isinstance(f_node,
                (ndb.query.DisjunctionNode, ndb.query.ConjunctionNode)):
            for f_n in f_node:
               inequalities.extend(self._get_inequalities(f_n))
        elif isinstance(f_node, ndb.query.FilterNode):
            filter_dict = self._node_to_dict(f_node)
            if filter_dict['symbol'] != '=':
                inequalities.append(filter_dict)
        return inequalities

    def _push_filter(self, filter_node):
        """Adds filter_node to the list post inquality filters if filter_node
        has at least 1 inquality that operates on a property that is different
        from the first inequality.

        Returns True if filter_node is added to the list of post inquality
        filters. If filter_node is the first inequality, returns False.
        """
        inequalities = self._get_inequalities(filter_node)
        push_to_post = False

        for inq in inequalities:
            if not self.first_inequality:
                self.first_inequality = inq
            elif self.first_inequality['name'] != inq['name']:
                push_to_post = True
                break

        if push_to_post:
            self.post_inq_filters.append(filter_node)

        return push_to_post

    def _node_to_dict(self, f_node):
        """Converts a Filter to a dictionary"""
        filter_dict = {}
        node_dict = getattr(f_node, '__dict__')
        for key, value in node_dict.items():
            if key.endswith('name'):
                filter_dict['name'] = value
            elif key.endswith('symbol'):
                filter_dict['symbol'] = value
            elif key.endswith('value'):
                filter_dict['value'] = value
        return filter_dict

    def _make_evaluator(self, filter_node):
        """Returns an evaluator for a given FilterNode"""
        def make_closure(f_d):
            if (f_d['symbol'] == '>'):
                return lambda x: getattr(x, f_d['name']) > f_d['value']
            elif (f_d['symbol'] == '<'):
                return lambda x: getattr(x, f_d['name']) < f_d['value']
            elif (f_d['symbol'] == '>='):
                return lambda x: getattr(x, f_d['name']) >= f_d['value']
            elif (f_d['symbol'] == '<='):
                return lambda x: getattr(x, f_d['name']) <= f_d['value']
            elif (f_d['symbol'] == '!='):
                return lambda x: getattr(x, f_d['name']) != f_d['value']
            elif (f_d['symbol'] == '='):
                return lambda x: getattr(x, f_d['name']) == f_d['value']
            else:
                raise NotImplementedError(
                    'Unsuported operator: {}'.format(f_d['symbol'])
                )

        f_dict = self._node_to_dict(filter_node)

        # FilterNode coverts TimeProperty and DateProperty to datetime.
        # Convert back to time or date
        prop_type = ndb.Model._kind_map[self.query.kind] \
                        ._properties[f_dict['name']].__class__.__name__
        if prop_type == 'TimeProperty' \
                and isinstance(f_dict['value'], datetime):
            f_dict['value'] = f_dict['value'].time()
        elif prop_type == 'DateProperty' \
                and isinstance(f_dict['value'], datetime):
            f_dict['value'] = f_dict['value'].date()

        return make_closure(f_dict)

    def _make_and_evaluator(self, con_node):
        """Returns an evaluator that performs AND operation on subnodes of a
        given ConjunctionNode
        """
        post_evals = self._check_node(con_node)
        def and_evaluators(x):
            for p_eval in post_evals:
                if not p_eval(x):
                    return False
            return True

        return and_evaluators

    def _make_or_evaluator(self, dis_node):
        """Returns an evaluator that performs OR operation on subnodes of a
        given DisjunctionNode
        """
        post_evals = self._check_node(dis_node)
        def or_evaluators(x):
            for p_eval in post_evals:
                if p_eval(x):
                    return True
            return False

        return or_evaluators

    def _check_node(self, a_node):
        """Returns a list of evaluator functions from a given Node"""
        output = []
        for f_n in a_node:
            if isinstance(f_n, ndb.query.ConjunctionNode):
                output.append(self._make_and_evaluator(f_n))
            elif isinstance(f_n, ndb.query.DisjunctionNode):
                output.append(self._make_or_evaluator(f_n))
            elif isinstance(f_n, ndb.query.FilterNode):
                output.append(self._make_evaluator(f_n))
            # FalseNode is ignored
            # ParameterNode is not yet supported
        return output

    def __iter__(self):
        """Iterates through the result set of the underlying query, and hands
        back only those that satify all of the post inequality filters.
        """
        post_evaluator = self._make_and_evaluator(self.post_inq_filters)
        for result in self.query:
            try:
                if post_evaluator(result):
                    yield result
            except TypeError:
                pass            # Value of a property from datastore is None


import random
import sys
import math
import time
import copy
from mpi4py import MPI
import numpy
import itertools
from matplotlib import pyplot as plt

comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()
stat = MPI.Status()

# Initialize Grid and Generation
prob = 0.7
COLS = 400
ROWS_TOTAL = 198
generations = 20
ROWS = ROWS_TOTAL//size+2

#==== init first array
N=numpy.random.binomial(1,prob,size=(ROWS+2)*COLS)
M=numpy.reshape(N,(ROWS+2,COLS))

M[0,:] = 0
M[ROWS+1,:] = 0
M[:,0] = 0
M[:,COLS-1] = 0

initM = numpy.copy(M)
print(initM)
print("First Generation")

#plt.imshow(initM, interpolation='nearest')
#plt.show()

#==== init first array

if size > ROWS:
    print("Not enough ROWS")
    exit()

# MPI core functions
def msgUp(subGrid):
	# Sends and Recvs rows with (Rank+1)%size for cylindricaly
    comm.send(subGrid[ROWS-2],dest=(rank+1)%size)
    subGrid[ROWS-1]=comm.recv(source=(rank+1)%size)
    return 0

def msgDn(subGrid):
	# Sends and Recvs rows with (Rank-1)%size for cylindrical
    comm.send(subGrid[1],dest=(rank-1)%size)
    subGrid[0] = comm.recv(source=(rank-1)%size)
    return 0

def computeGridPoints(M):
    intermediateM = numpy.copy(M)
    for ROWelem in range(1,ROWS+1):
        for COLelem in range(1,COLS-1):
            sum = ( M[ROWelem-1,COLelem-1]+M[ROWelem-1,COLelem]+M[ROWelem-1,COLelem+1]
                    +M[ROWelem,COLelem-1]+M[ROWelem,COLelem+1]
                    +M[ROWelem+1,COLelem-1]+M[ROWelem+1,COLelem]+M[ROWelem+1,COLelem+1] )
#               print(ROWelem," ",COLelem," ",sum)
            if M[ROWelem,COLelem] == 1:
                if sum < 2:
                        intermediateM[ROWelem,COLelem] = 0
                elif sum > 3:
                        intermediateM[ROWelem,COLelem] = 0
                else:
                        intermediateM[ROWelem,COLelem] = 1
                if M[ROWelem,COLelem] == 0:
                        if sum == 3:
                                intermediateM[ROWelem,COLelem] = 1
                        else:
                                intermediateM[ROWelem,COLelem] = 0
    M = numpy.copy(intermediateM)
    return M

def printf(format, *args):
    sys.stdout.write(format % args)

def showgraph(nx,ny,arr):
    for i in range(len(arr)):
        for j in range(nx-1):
            if arr[i][j] == 1:
                printf('\033[45m'"%d "'\033[0m',arr[i][j])
            else:
                printf('\033[43m'"%d "'\033[0m',arr[i][j])
        printf("\n")
    printf('\x1b[2J\x1b[H')
    time.sleep(1)

for step in range(generations):
    # Game of Life Role
    computeGridPoints(M)
    # cylindrical boundaries : no need (rank==0) and (rank==n-1)	conditions
    msgUp(M)
    msgDn(M)
    tempGrid=comm.gather(M[1:ROWS-1],root=0)

    if rank == 0:
        newGrid=list(itertools.chain.from_iterable(tempGrid))
        if step%5 ==0:
            print("-----------Generation:", step, "---------------")
            showgraph(COLS, ROWS, newGrid)


import requests
import logging
from io import StringIO
from datetime import datetime, timezone, timedelta

logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())

def handle_response(response):
    if response.status_code == 200:
        logger.debug('response status: {}, length: {}, elapsed: {}, url: {}'.format(
            response.status_code,
            len(response.content),
            response.elapsed,
            response.url
        ))
    else:
        logger.critical(
            'request failed with {}, content = "{}", headers = "{}", cookies = "{}"'.format(
                response.status_code,
                response.content,
                response.headers,
                response.cookies)
        )
        response.raise_for_status()

def handle_request(url):
    with requests.get(url) as response:
        handle_response(response)
        content = response.content.decode('utf-8-sig')
        return StringIO(content)

def to_datetime(timestamp):
    if isinstance(timestamp, datetime):
        return timestamp
    try:
        return datetime.fromtimestamp(timestamp, timezone(timedelta(hours=2)))
    except TypeError:
        return to_datetime(int(timestamp))


import pymysql
import time
import random

from selenium import webdriver
class main():
    def s(self,a,b):
        ti=random.randint(a,b)
        time.sleep(ti)

    def init(self,url):
        #selenium登录
        browser = "Chrome"
        if browser == "Chrome":
            option = webdriver.ChromeOptions()
            # option.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记
            #option.add_argument(                '--user-data-dir=C:\\Users\\coco.chen\\AppData\\Local\\Google\\Chrome\\User Data')  # 设置成用户自己的数据目录
            driver = webdriver.Chrome(chrome_options=option)
        else:
            if browser == "Firefox":
                driver = webdriver.Firefox()
            else:
                driver = webdriver.PhantomJS()

        driver.get(url)

        #等待用户自己登陆

        #判断是否登陆成功
        name = input("Go?")
        print(name)

        driver.get('https://vcp.jd.com/sub_item/item/initItemListPage')
        self.s(3, 4)

        prt_data=self.get_sku_id()
        for i in range (len(prt_data)):
            sku_id=prt_data[i][0]
            new_sku_name=prt_data[i][1]
            print(sku_id,new_sku_name)

            driver.find_element_by_id('wareId').clear()
            driver.find_element_by_id('wareId').send_keys(sku_id)

            self.s(1,2)
            driver.find_element_by_css_selector('.btn.btn-primary').click()
            self.s(2,3)

            nowhandle = driver.current_window_handle  # 在这里得到当前窗口句柄
            btn_down_path = "//table[@class='grid']/tbody/tr[1]/td[@id='td_wareId']/div/button[@class='btn btn-default dropdown-toggle']"
            driver.find_element_by_xpath(btn_down_path).click()
            self.s(1,1)
            driver.find_elements_by_xpath("//ul[@class='dropdown-menu']/li/a")[0].click()
            self.s(5, 6)
            # 需要获取新弹开的窗口
            allhandles = driver.window_handles  # 获取所有窗口句柄
            for handle in allhandles:  # 在所有窗口中查找弹出窗口
                if handle != nowhandle:
                    driver.close()
                    driver.switch_to.window(handle)
            current_url = driver.current_url
            print(current_url)
            if "https://vcp.jd.com/sub_item/item/initItemListPage" in current_url:
                self.update_caigou_price(sku_id,'reviewing')
            else:
                driver.get(current_url)
                content = driver.page_source
                # print(content)
                self.s(3, 4)
                driver.find_element_by_id('cid3Submit').click()
                self.s(2, 4)

                driver.find_element_by_id('auditedSubmit').click()
                self.s(2, 4)

                yanse = "黑色"
                driver.find_elements_by_class_name("combo-arrow")[1].click()
                if yanse == "红色":
                    yanse_xpath = "//div[@value='703187' ]"
                    driver.find_element_by_xpath(yanse_xpath).click()
                elif yanse == "黄色":
                    yanse_xpath = "//div[@value='703188' ]"
                    driver.find_element_by_xpath(yanse_xpath).click()
                elif yanse == "蓝色":
                    yanse_xpath = "//div[@value='703189' ]"
                    driver.find_element_by_xpath(yanse_xpath).click()
                elif yanse == "绿色":
                    yanse_xpath = "//div[@value='703190' ]"
                    driver.find_element_by_xpath(yanse_xpath).click()
                elif yanse == "双色":
                    yanse_xpath = "//div[@value='703193' ]"
                    driver.find_element_by_xpath(yanse_xpath).click()
                elif yanse == "黑色":
                    yanse_xpath = "//div[@value='703192' ]"
                    driver.find_element_by_xpath(yanse_xpath).click()
                elif yanse == "白色":
                    yanse_xpath = "//div[@value='703191' ]"
                    driver.find_element_by_xpath(yanse_xpath).click()

                driver.find_element_by_id('createApply').click()
                self.s(1, 2)

            driver.get('https://vcp.jd.com/sub_item/item/initItemListPage')
            self.s(3, 4)

    def get_sku_id(self):
        db = pymysql.connect("10.168.2.147", "root", "123456", "jd_vcp")
        cursor = db.cursor()
        db.set_charset("utf8")
        cursor.execute("SET NAMES utf8;")
        cursor.execute("SET CHARACTER SET utf8;")
        cursor.execute("SET character_set_connection=utf8;")
        sql = "select sku_id,new_sku_name from sku_name_change where status is null "
        try:
            cursor.execute(sql)
            data = cursor.fetchall()
            return data
        except Exception as err:
            db.rollback()
            print('---------------Error------Message--------:' + str(err))
        cursor.close()
        db.close()

    def update_caigou_price(self,sku_id,state):
        db = pymysql.connect("10.168.2.147", "root", "123456", "jd_vcp")
        cursor = db.cursor()
        db.set_charset("utf8")
        cursor.execute("SET NAMES utf8;")
        cursor.execute("SET CHARACTER SET utf8;")
        cursor.execute("SET character_set_connection=utf8;")
        sql = "update sku_name_change set  status='%s' where sku_id ='%s'" %(state,sku_id)
        try:
            cursor.execute(sql)
            db.commit()
        except Exception as err:
            db.rollback()
            print('---------------Error------Message--------:' + str(err))
        cursor.close()
        db.close()

if __name__=="__main__":
    main=main()
    #url="http://www.baidu.com"
    url="https://passport.jd.com/new/login.aspx?rs=vc&ReturnUrl=//vcp.jd.com"
    main.init(url)

JD后台/VC后台/正阳门-商品重新提交.py

正阳门-商品重新提交.py


import numpy as np
import matplotlib.pyplot as plt

def sigmoid(soma):
    return 1 / (1 + np.exp(-soma))

def sigmoidDerivada(sig):
    return sig * (1 - sig)

x = np.array([[0,0],[0,1],[1,0],[1,1]])

t = np.array([[0], [1], [1], [0]])

v = 2*np.random.random((2,3)) - 1
w = 2*np.random.random((3,1)) - 1

ciclosMax = 15000
a = 0.1
ciclo = 1

for j in range(ciclosMax):
    somaSinapse0 = np.dot(x, v)
    camadaOculta = sigmoid(somaSinapse0)

    somaSinapse1 = np.dot(camadaOculta, w)
    camadaSaida = sigmoid(somaSinapse1)

    erroCamadaSaida = t - camadaSaida
    erroQuadratico = 0.5 * (erroCamadaSaida**2)
    mediaAbsoluta = np.mean(np.abs(erroQuadratico))
    print("Erro: " + str(mediaAbsoluta))
    plt.scatter(j,mediaAbsoluta, color='orange', marker='.')

    derivadaSaida = sigmoidDerivada(camadaSaida)
    deltaSaida = erroCamadaSaida * derivadaSaida

    wTransposta = w.T
    deltaSaidaxPeso = deltaSaida.dot(wTransposta)
    deltaBv = deltaSaidaxPeso * sigmoidDerivada(camadaOculta)

    camadaOcultaTrasposta = camadaOculta.T
    deltinhaW = camadaOcultaTrasposta.dot(deltaSaida)
    w = (w * ciclo) + (deltinhaW * a)

    xTransposta = x.T
    deltinhaV = xTransposta.dot(deltaBv)
    v = (v * ciclo) + (deltinhaV * a)

plt.show()
for i in range(0, 4):
    print(str(camadaSaida[i]))


import socket
import threading
import sys
from tkinter import *
import json

username = ''
ip = ''
client = None

with open('./Client/latest.json') as json_file:
	latest = json.load(json_file)

def addd(new_data):
	global latest
	if new_data in latest:
		pass
	else:
		if len(latest) == 10:
			latest.remove(latest[-1])
		latest = [new_data] + latest
		with open('./Client/latest.json', 'w') as outfile:
			json.dump(latest, outfile)

class con:

	def __init__(self):
		self.root = Toplevel(window)
		self.root.geometry('250x250')
		self.root.title('Connection')
		Label(self.root, text='Username', bg='#F0F8FF', font=('arial', 12, 'normal')).place(x=40, y=30)
		n = StringVar()
		self.Name=Entry(self.root, text=n)
		self.Name.place(x=40, y=60)
		Label(self.root, text='Server IP', bg='#F0F8FF', font=('arial', 12, 'normal')).place(x=40, y=90)
		i = StringVar()
		self.IP=Entry(self.root, text=i)
		self.IP.place(x=40, y=120)
		Button(self.root, text='Confirm', bg='#F0F8FF', font=('arial', 12, 'normal'), command=self.send).place(x=70, y=150)
		self.root.mainloop()

	def send(self):
		global username
		global ip
		global client
		username = self.Name.get()
		ip = self.IP.get()
		username = username.strip()
		ip = ip.strip()
		if ((len(username) > 0) and (len(ip) > 0)):
			client = Client(ip, username)
			print('Connected to {} as {}.'.format(ip, username))
			messages.insert(INSERT, 'Connected to {} as {}.\n\n'.format(ip, username))
			messages.see(END)
			client.sendMsg('joined the chat.')
			addd((ip, username))
			self.root.destroy()
			#threading.Thread(target=client.work)

def recon(conn):
	global client
	client = Client(conn[0], conn[1])
	print('Connected to {} as {}.'.format(conn[0], conn[1]))
	messages.insert(INSERT, 'Connected to {} as {}.\n\n'.format(conn[0], conn[1]))
	client.sendMsg('joined server')
	messages.see(END)

window = Tk()
input_user = StringVar()
input_field = Entry(window, text=input_user)
input_field.pack(side=BOTTOM, fill=X)
sb = Scrollbar(window)
messages = Text(window)
sb.pack(side = RIGHT, fill = Y)
messages.pack()

sb.config( command = messages.yview )

menubar = Menu(window)

menubar.add_command(label="Connect", command=con)
if len(latest) > 0:
	reco = Menu(menubar, tearoff=0)
	for item in latest:
		reco.add_command(label='As {} to {}'.format(item[1], item[0]), command=lambda: recon(item))
	menubar.add_cascade(label="Reconnect", menu=reco)
menubar.add_command(label="Exit", command=window.quit)
window.config(menu=menubar)

#input_user = StringVar()
#input_field = Entry(window, text=input_user)
#input_field.pack(side=BOTTOM, fill=X)

def Enter_pressed(event):
	input_get = input_field.get()
	input_user.set('')
	input_get = input_get.strip()
	if len(input_get) > 0:
		client.sendMsg(input_get)
		#messages.insert(INSERT, '%s\n' % input_get)
		messages.see(END)
		return "break"

frame = Frame(window)
input_field.bind("<Return>", Enter_pressed)
frame.pack()

class Client:

	def sendMsg(self, mes):
		self.sock.send(bytes(str([self.name, mes]), 'utf-8'))

	def __init__(self, address, username):
		self.name = username
		self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		address, port = address.split(':')
		self.sock.connect((address, int(port)))

		iThread = threading.Thread(target=self.work)
		iThread.daemon = True
		iThread.start()

	def work(self):
		while True:

			data = self.sock.recv(1024)
			if not data:
				break
			data = str(data, 'utf-8')
			data = eval(data)
			user, data = data[0], data[1]
			if len(user)>7:
				user += '\t'
			else:
				user += '\t\t'
			messages.insert(INSERT, user + str(data) + '\n\n')
			messages.see(END)
			#return user + str(data)

#client = Client(address, username)
window.mainloop()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import django.contrib.auth.models

class Migration(migrations.Migration):

    dependencies = [
        ('auth', '0006_require_contenttypes_0002'),
    ]

    operations = [
        migrations.CreateModel(
            name='User',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('password', models.CharField(max_length=128, verbose_name='password')),
                ('last_login', models.DateTimeField(null=True, verbose_name='last login', blank=True)),
                ('username', models.CharField(unique=True, max_length=50)),
                ('full_name', models.CharField(max_length=245)),
                ('email', models.EmailField(unique=True, max_length=254, verbose_name=b'email address', db_index=True)),
                ('is_active', models.BooleanField(default=True)),
                ('is_staff', models.BooleanField(default=False)),
                ('is_superuser', models.BooleanField(default=False)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='GroupProxy',
            fields=[
            ],
            options={
                'verbose_name': 'Group',
                'proxy': True,
                'verbose_name_plural': 'Groups',
            },
            bases=('auth.group',),
            managers=[
                ('objects', django.contrib.auth.models.GroupManager()),
            ],
        ),
        migrations.AddField(
            model_name='user',
            name='groups',
            field=models.ManyToManyField(related_name='users', to='auth.Group', blank=True),
        ),
    ]


import logging
import time
import urllib2

class InetController(object):

    def __init__(self):
        self._logger = logging.getLogger('root.inet_controller')

    def checkConnection(self, count=0):
        if count == 3:
            return False
        # check if the inet connection is available and discogs api is reachable
        self._logger.debug('check inet connection')

        try:
            urllib2.urlopen('http://74.125.113.99',timeout=5)
            self._logger.debug('connection available')
            return True
        except Exception as exception:
            self._logger.debug("inet connection failed [%s] try again ..." % exception)
            time.sleep(2)
            self.checkConnection(count+1)


import json
import random
import shutil
import subprocess
from subprocess import call

from pprint import pprint

with open('FFNames.json') as data_file:
	data = json.load(data_file)

firstnameCount = len(data["FirstNames"])
lastnameCount = len(data["LastNames"])
middlenameCount = len(data["MiddleNames"])

middlenameChance = .3

middleNameRandomNumber = random.random()
#pprint(middleNameRandomNumber)
#pprint(middleNameRandomNumber <= middlenameChance)

with open("FFNames.txt", "w") as f:
	f.truncate()
	for i in range(20):
		name = data["FirstNames"][random.randint(0, firstnameCount - 1)]
		if middleNameRandomNumber <= middlenameChance:
			name += ' ' + data["MiddleNames"][random.randint(0, middlenameCount - 1)]
		name += ' ' + data["LastNames"][random.randint(0, lastnameCount - 1)]
		pprint(name)
		f.write(name + '\n')

shutil.copy2("gimpBatch.scm", "c:/Users/kimme/.gimp-2.8/scripts/")
call(["c:/Program Files/GIMP 2/bin/gimp-console-2.8.exe", "-i", "-b", "(batch-ffcard-process)", "-b", "(gimp-quit 0)"])

#pprint(data)


from azure.storage.blob import BlockBlobService
import os

def get_azure_connection(account_name, account_key):
    """
    Get azure connection to handle blob files presented on container.

    :param String account_name: Azure storage account name
    :param String account_key: Azure storage account key to allows connection with azure.
    :return: Instance of Blob Service Class
    :rtype: Object
    """
    return BlockBlobService(account_name=account_name, account_key=account_key)

def download_blob_file(connection,container_name,blob_name,path_output):
    """
    Get blob file from cloud and downloads on local machine.

    :param Object connection: Azure connection instance
    :param str container_name: Azure Container name.
    :param str blob_name: Azure Blob name to download.
    :param str blob_name: Path where file will be saved.
    :return: True if download works and False if something went wrong.
    :rtype: Boolean
    """
    try:
        connection.get_blob_to_path(container_name=container_name,blob_name=blob_name, file_path=path_output)
        actual_size = os.path.getsize(path_output)
        print('File saved in {0}'.format(path_output))
        return True
    except ValueError:
        print("Something went wrong")
        return False

def upload_blob_file(connection,container_name,local_file_name, full_path):
    """
    Upload local file to cloud.

    :param Object connection: Azure connection instance
    :param str container_name: Azure Container name.
    :param str local_file_name: File name to upload.
    :param str full_path: Path file that will be uploaded.
    :return: True if upload works and False if something went wrong.
    :rtype: Boolean
    """
    try:
        connection.create_blob_from_path(container_name,local_file_name,full_path)
        print('File {0} uploaded'.format(local_file_name))
        return True
    except ValueError:
        print("Something went wrong")
        return False


"""
RFarm Model Processing Tool

__date__ = '20190902'
__version__ = '4.0.0'
__author__ = 'Fabio Delogu            (fabio.delogu@cimafoundation.org,
              Simone Gabellani        (simone.gabellani@cimafoundation.org)
              Francesco Silvestro     (francesco.silvestro@cimafoundation.org)
              Nicola Rebora           (nicola.rebora@cimafoundation.org)'
__library__ = 'hyde'

General command line:
python3 HYDE_Model_RFarm.py -settings_file configuration.json -time YYYYMMDDHHMM

Version(s):
20190902 (4.0.0) --> Porting in Hyde package and python 3.x
20171114 (3.5.1) --> Fix bugs (accumulated and istantaneous rain)
20170530 (3.5.0) --> Update version
20150924 (3.0.2) --> Final release for FP Marche project
20150823 (3.0.0) --> Final release for DRIHM project
20140408 (2.0.1) --> Final release based on Rainfarm 1.0
"""

# ----------------------------------------------------------------------------------------------------------------------
# Library
import time
import argparse

from src.common.log.lib_logging import setLoggingFile

from src.hyde.algorithm.settings.model.rfarm.lib_rfarm_args import logger_formatter, logger_handle, logger_name

from src.hyde.driver.configuration.generic.drv_configuration_algorithm import DataAlgorithm
from src.hyde.driver.configuration.model.rfarm.drv_configuration_time_rfarm import DataTime

from src.hyde.driver.model.rfarm.drv_model_rfarm_geo import DataGeo
from src.hyde.driver.model.rfarm.drv_model_rfarm_base import ModelTime, ModelRunner
# ----------------------------------------------------------------------------------------------------------------------

# ----------------------------------------------------------------------------------------------------------------------
# Method to get script argument(s)
def getArgs():
    args_parser = argparse.ArgumentParser()
    args_parser.add_argument('-settings_file', action="store", dest="settings_file")
    args_parser.add_argument('-time', action="store", dest="time_arg")
    args_values = args_parser.parse_args()

    script_name = args_parser.prog

    if 'settings_file' in args_values:
        settings_file = args_values.settings_file
    else:
        settings_file = 'configuration.json'

    if 'time_arg' in args_values:
        time_arg = args_values.time_arg
    else:
        time_arg = None

    return script_name, settings_file, time_arg
# ----------------------------------------------------------------------------------------------------------------------

# ----------------------------------------------------------------------------------------------------------------------
# Script Main
def main():

    # -------------------------------------------------------------------------------------
    # Version and algorithm information
    project_name = 'HYDE'
    alg_version = '4.0.0'
    alg_type = 'Model'
    alg_name = 'RFarm Processing Tool'
    # Time algorithm information
    alg_start_time = time.time()
    # -------------------------------------------------------------------------------------

    # -------------------------------------------------------------------------------------
    # Get script argument(s)
    [script_name, file_setting, time_arg] = getArgs()

    # Set algorithm configuration
    driver_algorithm_settings = DataAlgorithm(file_setting)
    [data_algorithm_settings, data_algorithm_path,
     data_algorithm_flags, data_algorithm_colormap] = driver_algorithm_settings.getDataSettings()

    # Set logging file
    log_stream = setLoggingFile(data_algorithm_path['log'], logger_name, logger_handle, logger_formatter)
    # -------------------------------------------------------------------------------------

    # -------------------------------------------------------------------------------------
    # Start Program
    log_stream.info('[' + project_name + ' ' + alg_type + ' - ' + alg_name + ' (Version ' + alg_version + ')]')
    log_stream.info('[' + project_name + '] Start Program ... ')
    # -------------------------------------------------------------------------------------

    # -------------------------------------------------------------------------------------
    # Get data time
    log_stream.info(' --> Set algorithm time ... ')
    driver_algorithm_time = DataTime(
        time_arg,
        time_settings=data_algorithm_settings['time']['time_now'],
        time_period_past=int(data_algorithm_settings['time']['time_period']),
        time_frequency=data_algorithm_settings['time']['time_frequency'],
        time_rounding=data_algorithm_settings['time']['time_rounding'])
    data_algorithm_time = driver_algorithm_time.getDataTime()
    log_stream.info(' --> Set algorithm time ... DONE')
    # -------------------------------------------------------------------------------------

    # -------------------------------------------------------------------------------------
    # Get data geo
    log_stream.info(' --> Set grid data ... ')
    data_algorithm_geo = DataGeo(
        data_algorithm_path['terrain_data'], data_algorithm_path['grid_data'],
        file_updating=data_algorithm_flags['cleaning_static_data'])
    data_geo = data_algorithm_geo.getDataGeo()
    log_stream.info(' --> Set grid data ... DONE')
    # -------------------------------------------------------------------------------------

    # -------------------------------------------------------------------------------------
    # Iterate over time steps
    for time_step in data_algorithm_time['time_steps']:

        # -------------------------------------------------------------------------------------
        # Compute dynamic time
        log_stream.info(' --> Compute time ... ')
        driver_dynamic_time = ModelTime(
            time_step=time_step,
            time_run=data_algorithm_time['time_run'],
            time_settings=data_algorithm_settings['data']['dynamic']['time'])
        data_dynamic_time = driver_dynamic_time.computeModelTime()
        log_stream.info(' --> Compute time ... DONE')
        # -------------------------------------------------------------------------------------

        # -------------------------------------------------------------------------------------
        # Configure and execute model
        log_stream.info(' --> Initialize model ... ')
        driver_model_runner = ModelRunner(
            time_step=data_dynamic_time.time_step,
            time_range=data_dynamic_time.time_range,
            variable_in=data_algorithm_settings['variables']['input']['rain_data'],
            variable_out=data_algorithm_settings['variables']['outcome']['rain_data'],
            data_geo=data_geo,
            template=data_algorithm_settings['data']['dynamic']['template'],
            parameters=data_algorithm_settings['algorithm']['parameters'],
            file_ancillary_in=data_algorithm_path['rain_input_ancillary'],
            file_ancillary_out=data_algorithm_path['rain_outcome_ancillary'],
            file_in=data_algorithm_path['rain_input_data'],
            file_out=data_algorithm_path['rain_outcome_data'],
            file_ancillary_in_updating=data_algorithm_flags['cleaning_dynamic_ancillary_in'],
            file_ancillary_out_updating=data_algorithm_flags['cleaning_dynamic_ancillary_out'],
            file_out_updating=data_algorithm_flags['cleaning_dynamic_out'],
            file_out_zipping=data_algorithm_flags['zipping_dynamic_out'],
            file_write_engine=data_algorithm_settings['algorithm']['ancillary']['write_engine']
        )
        log_stream.info(' --> Initialize model ... DONE')

        # Collect data
        log_stream.info(' --> Collect model data ... ')
        data_dynamic = driver_model_runner.collect(data_dynamic_time)
        log_stream.info(' --> Collect model data ... DONE!')

        # Configure model
        log_stream.info(' --> Configure model ... ')
        driver_model_runner.configure(data_dynamic)
        log_stream.info(' --> Configure model ... DONE!')

        # Execute model
        log_stream.info(' --> Execute model ... ')
        data_run = driver_model_runner.exec()
        log_stream.info(' --> Execute model ... DONE')

        # Finalize model
        log_stream.info(' --> Save model result ... ')
        driver_model_runner.save(data_run)
        log_stream.info(' --> Save model result ... DONE')

        # Clean tmp file(s)
        driver_model_runner.clean(cleaning_dynamic_tmp=data_algorithm_flags['cleaning_dynamic_tmp'])
        # -------------------------------------------------------------------------------------

    # -------------------------------------------------------------------------------------

    # ----------------------------------------------------------------------------------------------------------------------
    # Note about script parameter(s)
    log_stream.info('NOTE - Algorithm parameter(s)')
    log_stream.info('Script: ' + str(script_name))
    # ----------------------------------------------------------------------------------------------------------------------

    # ----------------------------------------------------------------------------------------------------------------------
    # End Program
    alg_time_elapsed = round(time.time() - alg_start_time, 1)

    log_stream.info('[' + project_name + ' ' + alg_type + ' - ' + alg_name + ' (Version ' + alg_version + ')]')
    log_stream.info('End Program - Time elapsed: ' + str(alg_time_elapsed) + ' seconds')
    # ----------------------------------------------------------------------------------------------------------------------

# ----------------------------------------------------------------------------------------------------------------------
# Call script from external library
if __name__ == "__main__":
    main()
# ----------------------------------------------------------------------------------------------------------------------


from accountsApp.forms import LoginForm
from datetime import datetime, timedelta
from django.utils import timezone

def say_hello(request):
	return {
		'say_hello': "Hello"
	}

def include_login_form(request):
	form = LoginForm
	return {'login_form': form}

def confirmation_countdown_message(request):

	if request.user.is_authenticated():

		if request.user.is_confirmed == False and timezone.now() - request.user.date_joined >= timedelta(days=3):

			time_remaining = 'Account Expired, confirm your email now'
			return {
				'time_remaining' : "Account expired, confirm your email now"
			}

		else:

			current_date = timezone.now()
			expired_date = request.user.date_joined + timedelta(days=3)
			difference_in_days = abs((current_date-expired_date).days)
			time_remaining = difference_in_days

			return {
				'time_remaining' : time_remaining
			}
	return {}


u"""Módulo Trabajador Form."""

from django import forms
from apps.sad.models import User
from apps.params.models import IDENTITY_TYPE_CHOICES
from django.utils.translation import ugettext_lazy as _
from crispy_forms.layout import Field, Div, Row, HTML
from crispy_forms.bootstrap import FormActions, TabHolder, Tab
from crispy_forms.helper import FormHelper, Layout
from apps.utils.forms import smtSave, btnCancel, btnReset
from django.utils.text import capfirst, get_text_list

class TrabajadorForm(forms.ModelForm):
    u"""Trabajador Form."""
    nombre = forms.CharField(max_length=100)
    apellidos = forms.CharField(max_length=100)
    numero = forms.IntegerField(required=False)
    tipo_documento = forms.ChoiceField(choices=IDENTITY_TYPE_CHOICES)
    fecha_de_nacimiento = forms.DateField(
        widget=forms.DateInput(attrs={'class': 'datepicker', }),
        required=False)

    class Meta:
        """Meta."""
        model = User
        exclude = ()
        fields = ('is_veterinario',)

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        self.object = kwargs.pop('object', None)
        super(TrabajadorForm, self).__init__(*args, **kwargs)
        self.fields['photo'] = forms.ImageField(
            label='', required=False,
            initial='persons/default.png',
            help_text=u'<small class="help-error"></small> %s' % _(
                u'JPG, GIF, o PNG.'),
        )
        self.helper = FormHelper()
        self.helper.layout = Layout(
            Row(
                Div(Div(Field('photo'), css_class='text-center'),css_class='col-md-4'),
                Div(
                    Div(Field('nombre',  placeholder='Ingrese un nombre')),
                    Div(Field('apellidos', placeholder='Ingrese sus apellidos'),),
                    Div(Field('tipo_documento',),),
                    Div(Field('numero', placeholder='Ingrese un número'),),
                    Div(Field('fecha_de_nacimiento', placeholder='YYYY-MM-DD'),),
                    Div(Field('is_veterinario', placeholder='Ingrese el nombre'),),
                    FormActions(
                        smtSave(),
                        btnCancel(),
                    ), css_class='col-md-8'),
            ),
        )