import logger

def follower_analysis(username):
    logs = logger.logger_2(username)
    follow_data = logger.load_dataset(logs.follow_log_path)

    # User ids that were followed and unfollowed by bot
    terminated_followings = []
    # once logs get big, use dictionary for open_followings to speed up
    # User ids the bot has followed but not yet unfollowed
    open_followings = []
    # User ids that were unfollowed but not followed by bot
    error_unfollows = []
    # Number of times an account was followed more than once
    duplicate_follow_count = 0

    # Iterate over follow_data twice, once to add and one to remove
    for row in follow_data.itertuples():
        if row.relationship_change == "follow":
            if row.user_id in open_followings:
                duplicate_follow_count += 1
            else:
                open_followings.append(row.user_id)

    for row in follow_data.itertuples():
        if row.relationship_change == "unfollow":
            if row.user_id in open_followings:
                open_followings.remove(row.user_id)
                terminated_followings.append(row.user_id)
            else:
                error_unfollows.append(row.user_id)

    return {"terminated_followings" : terminated_followings,
            "open_followings" : open_followings,
            "error_unfollows" : error_unfollows,
            "duplicate_follow_count" : duplicate_follow_count}


from shiboken2 import wrapInstance
from PySide2 import QtCore, QtWidgets, QtGui
from maya import OpenMayaUI as OpenMayaUI
from maya import cmds
from maya.app.general.mayaMixin import MayaQWidgetDockableMixin
from maya.OpenMayaUI import MQtUtil
from rigging_utils import json_utils
from rigging_utils.controls import cv_data
import rigging_panel_tools as rpt
reload(rpt)

class RiggingPanel(MayaQWidgetDockableMixin, QtWidgets.QDialog):
    toolName = "Rigging Panel"
    toolVersion = "0.1.0"
    bcg_color = "darkCyan"
    headerColor = "{ background-color: %s; color: rgba(250, 250, 250, 250);}" %bcg_color

    def __init__(self, parent = None):
        # delete self first
        self.deleteInstances()

        super(self.__class__, self).__init__(parent = parent)
        mayaMainWindowPtr = OpenMayaUI.MQtUtil.mainWindow()
        self.mayaMainWindow = wrapInstance(long(mayaMainWindowPtr), QtWidgets.QMainWindow)
        self.setObjectName(self.__class__.toolName) # Make this unique enough if using it to clear previous instance!

        # Setup window"s properties
        self.setWindowFlags(QtCore.Qt.Window)
        self.setWindowTitle(self.toolName+" "+self.toolVersion)
        self.resize(200, 200)

        """
        # create menu bar to change ui color
        self.mainMenu = QtWidgets.QMenuBar(self)
        self.editMenu = self.mainMenu.addMenu("UI Color")
        for c in self.colors:
            item = QtWidgets.QAction(c, self)
            self.editMenu.addAction(item)
        """

        # Create tab widgets
        self.tab_bar = QtWidgets.QTabWidget(self)
        self.setup_tab = QtWidgets.QWidget()
        self.binding_tab = QtWidgets.QWidget()
        self.utils_tab = QtWidgets.QTabWidget()
        self.tab_bar.addTab(self.setup_tab, "Setup")
        self.tab_bar.addTab(self.binding_tab, "Binding")
        self.tab_bar.addTab(self.utils_tab, "Utilities")

        #######################################################################
        # Create main layout and align the tabs to the top
        #######################################################################

        self.main_layout = QtWidgets.QVBoxLayout()
        #self.main_layout.addWidget(self.mainMenu)
        self.main_layout.setAlignment(QtCore.Qt.AlignTop)
        self.main_layout.addWidget(self.tab_bar)

        #######################################################################
        # Create setup tab and widgets
        #######################################################################

        # Create joint widgets
        self.joints_label = QtWidgets.QLabel("JOINTS")
        self.joints_label.setStyleSheet("QLabel %s" %self.headerColor)
        self.joints_label.setAlignment(QtCore.Qt.AlignCenter)
        self.joint_size_label = QtWidgets.QLabel("Joint Size")
        self.joint_size_label.setAlignment(QtCore.Qt.AlignCenter)
        self.joint_size_number = QtWidgets.QDoubleSpinBox()
        self.joint_size_number.setSingleStep(0.1)
        self.joint_size_number.setRange(0.1, 10.0)
        self.joint_size_number.setButtonSymbols(QtWidgets.QAbstractSpinBox.NoButtons)
        self.joint_size_number.setValue(1)
        self.joint_size_slider = QtWidgets.QSlider(QtCore.Qt.Horizontal)
        self.joint_size_slider.setSliderPosition(10)
        self.joint_size_slider.setRange(1, 100)
        self.split_joint_number = QtWidgets.QSpinBox()
        self.split_joint_number.setRange(1, 100)
        self.split_joint_button = QtWidgets.QPushButton("Split Joint")
        self.draw_joint_button = QtWidgets.QPushButton("Draw Joint Tool")
        self.sc_ik_button = QtWidgets.QPushButton("SC IK")
        self.rp_ik_button = QtWidgets.QPushButton("RP IK")
        self.joint_to_sel_button = QtWidgets.QPushButton("Joint To Selected")

        # Slots for joint widgets
        self.joint_size_slider.valueChanged.connect(self.joint_size_slider_changed)
        self.joint_size_number.editingFinished.connect(self.joint_size_number_changed)
        self.split_joint_button.clicked.connect(lambda: rpt.split_joint(self.split_joint_number.value()))
        self.draw_joint_button.clicked.connect(rpt.draw_joint)
        self.sc_ik_button.clicked.connect(rpt.sc_ik)
        self.rp_ik_button.clicked.connect(rpt.rp_ik)
        self.joint_to_sel_button.clicked.connect(rpt.joint_to_selected)

        # Create control widgets
        self.control_label = QtWidgets.QLabel("CONTROLS")
        self.control_label.setStyleSheet("QLabel %s" %self.headerColor)
        self.control_label.setAlignment(QtCore.Qt.AlignCenter)
        self.control_shape = QtWidgets.QComboBox()
        for s in sorted(cv_data.get_control_dict()):
            self.control_shape.addItem(s)
        self.control_color = QtWidgets.QComboBox()
        for c in QtGui.QColor.colorNames():
            self.control_color.addItem(c)
        self.current_color = QtGui.QColor.getRgb(QtGui.QColor(self.control_color.currentText()))
        self.create_control_button = QtWidgets.QPushButton("Create Control")
        self.update_color_button = QtWidgets.QPushButton("Update Color")

        # Slots for control widgets
        self.control_color.currentIndexChanged["QString"].connect(self.color_change)
        self.create_control_button.clicked.connect(lambda: rpt.create_control(self.control_shape.currentText(), self.current_color))
        self.update_color_button.clicked.connect(lambda: rpt.update_color(self.current_color))

        # Create renamer widgets
        self.rename_label = QtWidgets.QLabel("RENAMER")
        self.rename_label.setStyleSheet("QLabel %s" %self.headerColor)
        self.rename_label.setAlignment(QtCore.Qt.AlignCenter)
        self.rename_number_label = QtWidgets.QLabel("Use # in place of numbers when iterating.\narm_L0_001_jnt would be arm_L0_###_jnt")
        self.rename_dag_cb = QtWidgets.QCheckBox("Dag")
        self.rename_line = QtWidgets.QLineEdit()
        self.rename_button = QtWidgets.QPushButton("Rename")
        self.replace_line = QtWidgets.QLineEdit()
        self.replace_with_line = QtWidgets.QLineEdit()
        self.replace_button = QtWidgets.QPushButton("Replace")

        # slots for renamer widgets
        self.rename_button.clicked.connect(lambda: rpt.rename_with_pound(self.rename_line.text(), self.rename_dag_cb.isChecked()))
        self.replace_button.clicked.connect(lambda: rpt.replace(self.replace_line.text(), self.replace_with_line.text(), self.rename_dag_cb.isChecked()))

        # Create attributes widgets
        self.attr_label = QtWidgets.QLabel("ATTRIBUTES")
        self.attr_label.setStyleSheet("QLabel %s" %self.headerColor)
        self.attr_label.setAlignment(QtCore.Qt.AlignCenter)
        self.attr_name_line = QtWidgets.QLineEdit()
        self.attr_trans_cb = QtWidgets.QCheckBox("Translates")
        self.attr_rots_cb = QtWidgets.QCheckBox("Rotates")
        self.attr_scales_cb = QtWidgets.QCheckBox("Scales")
        self.attr_channelbox_cb = QtWidgets.QCheckBox("Channel Box")
        self.get_default_values_button = QtWidgets.QPushButton("Get Default Values")
        self.make_keyable_button = QtWidgets.QPushButton("Keyable / Displayable")
        self.make_lock_button = QtWidgets.QPushButton("Lock / Unlock")
        self.make_hidden_button = QtWidgets.QPushButton("Hide / Unhide")
        self.unhide_all_button = QtWidgets.QPushButton("Unhide All (T/R/S)")
        self.unhide_all_custom_button = QtWidgets.QPushButton("Unhide All (Custom)")
        self.zero_out_button = QtWidgets.QPushButton("Zero Out (T/R/S)")
        self.move_up_button = QtWidgets.QPushButton("Move Selected Attr Up")
        self.move_down_button = QtWidgets.QPushButton("Move Selected Attr Down")

        # Slots for attributes widgets
        self.get_default_values_button.clicked.connect(rpt.attr_defaults)
        self.make_keyable_button.clicked.connect(lambda: rpt.attr_keyable(self.attr_trans_cb.isChecked(),
                                                                        self.attr_rots_cb.isChecked(),
                                                                        self.attr_scales_cb.isChecked(),
                                                                        self.attr_channelbox_cb.isChecked()))
        self.make_lock_button.clicked.connect(lambda: rpt.attr_lock(self.attr_trans_cb.isChecked(),
                                                                    self.attr_rots_cb.isChecked(),
                                                                    self.attr_scales_cb.isChecked(),
                                                                    self.attr_channelbox_cb.isChecked()))
        self.make_hidden_button.clicked.connect(lambda: rpt.attr_hide(self.attr_trans_cb.isChecked(),
                                                                    self.attr_rots_cb.isChecked(),
                                                                    self.attr_scales_cb.isChecked(),
                                                                    self.attr_channelbox_cb.isChecked()))
        self.unhide_all_button.clicked.connect(rpt.attr_unhide)
        self.unhide_all_custom_button.clicked.connect(rpt.attr_unhide_custom)
        self.zero_out_button.clicked.connect(rpt.zero_out)
        self.move_up_button.clicked.connect(rpt.move_attr_up)
        self.move_down_button.clicked.connect(rpt.move_attr_down)

        #######################################################################
        # Create the layout for the setup tab and align to the top
        #######################################################################

        self.setup_tab_layout = QtWidgets.QGridLayout()
        self.setup_tab_layout.setAlignment(QtCore.Qt.AlignTop)
        self.setup_tab_sub_layout = QtWidgets.QGridLayout()
        self.setup_tab_sub_layout.setAlignment(QtCore.Qt.AlignTop)
        self.setup_tab_sub_layout.setSizeConstraint(QtWidgets.QLayout.SetMinimumSize)

        self.joints_main_layout = QtWidgets.QGridLayout()
        self.joints_sub_layout = QtWidgets.QGridLayout()

        self.controls_main_layout = QtWidgets.QGridLayout()
        self.controls_sub_layout = QtWidgets.QGridLayout()

        self.renamer_main_layout = QtWidgets.QGridLayout()
        self.renamer_sub_layout = QtWidgets.QGridLayout()

        self.attributes_main_layout = QtWidgets.QGridLayout()
        self.attributes_sub_layout = QtWidgets.QGridLayout()

        # set the scroll area and the main layout
        self.setup_scroll_widget = QtWidgets.QWidget()
        self.setup_scroll_widget.setLayout(self.setup_tab_sub_layout)
        self.setup_scroll_area = QtWidgets.QScrollArea()
        self.setup_tab_layout.addWidget(self.setup_scroll_area)
        self.setup_scroll_area.setWidget(self.setup_scroll_widget)
        self.setup_scroll_area.setWidgetResizable(True)

        # spacing out the layouts
        self.setup_tab_layout.setVerticalSpacing(20)

        self.joints_main_layout.setVerticalSpacing(20)
        self.joints_sub_layout.setVerticalSpacing(3)

        self.controls_main_layout.setVerticalSpacing(20)
        self.controls_sub_layout.setVerticalSpacing(3)

        self.renamer_main_layout.setVerticalSpacing(20)
        self.renamer_sub_layout.setVerticalSpacing(5)

        self.attributes_main_layout.setVerticalSpacing(20)
        self.attributes_sub_layout.setVerticalSpacing(3)

        # adding all the main layouts to the setup tab layout
        self.setup_tab_sub_layout.addLayout(self.joints_main_layout, 0, 0, QtCore.Qt.AlignTop)
        self.setup_tab_sub_layout.addLayout(self.controls_main_layout, 1, 0, QtCore.Qt.AlignTop)
        self.setup_tab_sub_layout.addLayout(self.renamer_main_layout, 2, 0, QtCore.Qt.AlignTop)
        self.setup_tab_sub_layout.addLayout(self.attributes_main_layout, 3, 0, QtCore.Qt.AlignTop)

        # adding the sub layouts to the joints main layout
        self.joints_main_layout.addWidget(self.joints_label, 0, 0)
        self.joints_main_layout.addLayout(self.joints_sub_layout, 1, 0, QtCore.Qt.AlignTop)

        # adding sub layouts to the controls main layout
        self.controls_main_layout.addWidget(self.control_label, 0, 0)
        self.controls_main_layout.addLayout(self.controls_sub_layout, 1, 0, QtCore.Qt.AlignTop)

        # adding the sub layouts to the renamer main layout
        self.renamer_main_layout.addWidget(self.rename_label, 0, 0)
        self.renamer_main_layout.addLayout(self.renamer_sub_layout, 1, 0, QtCore.Qt.AlignTop)

        # adding the sub layouts to the attributes main layout
        self.attributes_main_layout.addWidget(self.attr_label, 0, 0)
        self.attributes_main_layout.addLayout(self.attributes_sub_layout, 1, 0, QtCore.Qt.AlignTop)

        # adding the widgets to the joints sub layout
        self.joints_sub_layout.addWidget(self.joint_size_label, 0, 0, 1, 2)
        self.joints_sub_layout.addWidget(self.joint_size_number, 1, 0)
        self.joints_sub_layout.addWidget(self.joint_size_slider, 1, 1)
        self.joints_sub_layout.addWidget(self.split_joint_number, 2, 0)
        self.joints_sub_layout.addWidget(self.split_joint_button, 2, 1)
        self.joints_sub_layout.addWidget(self.draw_joint_button, 3, 0, 1, 2)
        self.joints_sub_layout.addWidget(self.sc_ik_button, 4, 0, 1, 2)
        self.joints_sub_layout.addWidget(self.rp_ik_button, 5, 0, 1, 2)
        self.joints_sub_layout.addWidget(self.joint_to_sel_button, 6, 0, 1, 2)

        # adding the widgets to the control sub layout
        self.controls_sub_layout.addWidget(self.control_shape, 0, 0)
        self.controls_sub_layout.addWidget(self.control_color, 1, 0)
        self.controls_sub_layout.addWidget(self.create_control_button, 2, 0)
        self.controls_sub_layout.addWidget(self.update_color_button, 3, 0)

        # adding the widgets to the renamer sub layout
        self.renamer_sub_layout.addWidget(self.rename_number_label, 0, 0, 1, 2)
        self.renamer_sub_layout.addWidget(self.rename_dag_cb, 1, 0)
        self.renamer_sub_layout.addWidget(self.rename_line, 2, 0, 1, 2)
        self.renamer_sub_layout.addWidget(self.rename_button, 3, 0, 1, 2)
        self.renamer_sub_layout.addWidget(self.replace_line, 4, 0)
        self.renamer_sub_layout.addWidget(self.replace_with_line, 4, 1)
        self.renamer_sub_layout.addWidget(self.replace_button, 5, 0, 1, 2)

        # adding the widgets to the attributes sub layout
        self.attributes_sub_layout.addWidget(self.attr_trans_cb, 0, 0)
        self.attributes_sub_layout.addWidget(self.attr_rots_cb, 0, 1)
        self.attributes_sub_layout.addWidget(self.attr_scales_cb, 0, 2)
        self.attributes_sub_layout.addWidget(self.attr_channelbox_cb, 1, 0)
        #self.attributes_sub_layout.addWidget(self.attr_name_line, 1, 1, 1, 2)
        self.attributes_sub_layout.addWidget(self.get_default_values_button, 2, 0, 1, 3)
        self.attributes_sub_layout.addWidget(self.make_keyable_button, 3, 0, 1, 3)
        self.attributes_sub_layout.addWidget(self.make_lock_button, 4, 0, 1, 3)
        self.attributes_sub_layout.addWidget(self.make_hidden_button, 5, 0, 1, 3)
        self.attributes_sub_layout.addWidget(self.unhide_all_button, 6, 0, 1, 3)
        self.attributes_sub_layout.addWidget(self.unhide_all_custom_button, 7, 0, 1, 3)
        self.attributes_sub_layout.addWidget(self.zero_out_button, 8, 0, 1, 3)
        self.attributes_sub_layout.addWidget(self.move_up_button, 9, 0, 1, 3)
        self.attributes_sub_layout.addWidget(self.move_down_button, 10, 0, 1, 3)

        #######################################################################
        # Create binding tab and widgets
        #######################################################################

        # Create binding widgets
        self.binding_label = QtWidgets.QLabel("SKINNING")
        self.binding_label.setStyleSheet("QLabel %s" %self.headerColor)
        self.binding_label.setAlignment(QtCore.Qt.AlignCenter)
        self.smooth_bind_button = QtWidgets.QPushButton("Smooth Bind")
        self.detach_skin_button = QtWidgets.QPushButton("Detach Skin")
        self.copy_skin_weights_button = QtWidgets.QPushButton("Copy Skin Weights")
        self.paint_skin_weights_button = QtWidgets.QPushButton("Paint Skin Weights")
        self.smooth_skin_weights_button = QtWidgets.QPushButton("Smooth Skin Weights")
        self.mirror_weights_button = QtWidgets.QPushButton("Mirror Weights")
        self.lock_sel_weights_button = QtWidgets.QPushButton("Lock Weights On Selected")
        self.unlock_sel_weights_button = QtWidgets.QPushButton("Unlock Weights On Selected")
        self.lock_all_weights_button = QtWidgets.QPushButton("Lock All Weights")
        self.unlock_all_weights_button = QtWidgets.QPushButton("Unlock All Weights")
        self.select_influences_button = QtWidgets.QPushButton("Select Influences")
        self.select_skin_cluster_button = QtWidgets.QPushButton("Select Skin Cluster")

        # slots for binding widgets
        self.smooth_bind_button.clicked.connect(rpt.smooth_bind)
        self.detach_skin_button.clicked.connect(rpt.detach_skin)
        self.copy_skin_weights_button.clicked.connect(rpt.copy_skin)
        self.paint_skin_weights_button.clicked.connect(rpt.paint_skin)
        self.smooth_skin_weights_button.clicked.connect(rpt.smooth_skin)
        self.mirror_weights_button.clicked.connect(rpt.mirror_skin)
        self.lock_sel_weights_button.clicked.connect(rpt.lock_weights)
        self.unlock_sel_weights_button.clicked.connect(rpt.unlock_weights)
        self.lock_all_weights_button.clicked.connect(rpt.lock_all_weights)
        self.unlock_all_weights_button.clicked.connect(rpt.unlock_all_weights)
        self.select_influences_button.clicked.connect(rpt.select_influences)
        self.select_skin_cluster_button.clicked.connect(rpt.select_skin_cluster)

        # Create constraint widgets
        self.constraint_label = QtWidgets.QLabel("CONSTRAINTS")
        self.constraint_label.setStyleSheet("QLabel %s" %self.headerColor)
        self.constraint_label.setAlignment(QtCore.Qt.AlignCenter)
        self.constraint_offset_cb = QtWidgets.QCheckBox("Maintain Offset")
        self.constraint_exclude_trans_cb = QtWidgets.QCheckBox("Exclude Translates")
        self.constraint_exclude_rots_cb = QtWidgets.QCheckBox("Exclude Rotates")
        self.constraint_combo_box = QtWidgets.QComboBox()
        for con in ['Parent', 'Orient', 'Scale', 'Point', 'Aim', 'Pole Vector']:
            self.constraint_combo_box.addItem(con)
        self.create_constraint_button = QtWidgets.QPushButton("Create Constraint")

        # slots for constraint widgets
        self.create_constraint_button.clicked.connect(lambda: rpt.create_constraint(self.constraint_offset_cb.isChecked(),
                                                                                self.constraint_exclude_trans_cb.isChecked(),
                                                                                self.constraint_exclude_rots_cb.isChecked(),
                                                                                self.constraint_combo_box.currentText()))

        #######################################################################
        # Create the layout for the binding tab and align to the top
        #######################################################################
        self.binding_tab_layout = QtWidgets.QGridLayout()
        self.binding_tab_layout.setAlignment(QtCore.Qt.AlignTop)
        self.binding_tab_sub_layout = QtWidgets.QGridLayout()
        self.binding_tab_sub_layout.setAlignment(QtCore.Qt.AlignTop)
        self.binding_tab_sub_layout.setSizeConstraint(QtWidgets.QLayout.SetMinimumSize)

        self.skinning_main_layout = QtWidgets.QGridLayout()
        self.skinning_sub_layout = QtWidgets.QGridLayout()

        self.constraints_main_layout = QtWidgets.QGridLayout()
        self.constraints_sub_layout = QtWidgets.QGridLayout()

        # set the scroll area and the main layout
        self.binding_scroll_widget = QtWidgets.QWidget()
        self.binding_scroll_widget.setLayout(self.binding_tab_sub_layout)
        self.binding_scroll_area = QtWidgets.QScrollArea()
        self.binding_tab_layout.addWidget(self.binding_scroll_area)
        self.binding_scroll_area.setWidget(self.binding_scroll_widget)
        self.binding_scroll_area.setWidgetResizable(True)

        # spacing out the layouts
        self.binding_tab_layout.setVerticalSpacing(20)

        self.skinning_main_layout.setVerticalSpacing(20)
        self.skinning_sub_layout.setVerticalSpacing(3)

        self.constraints_main_layout.setVerticalSpacing(20)
        self.constraints_sub_layout.setVerticalSpacing(3)

        # adding all the main layouts to the skinning tab layout
        self.binding_tab_sub_layout.addLayout(self.skinning_main_layout, 0, 0, QtCore.Qt.AlignTop)
        self.binding_tab_sub_layout.addLayout(self.constraints_main_layout, 1, 0, QtCore.Qt.AlignTop)

        # adding sub layouts to the skinning main layout
        self.skinning_main_layout.addWidget(self.binding_label, 0, 0, QtCore.Qt.AlignTop)
        self.skinning_main_layout.addLayout(self.skinning_sub_layout, 1, 0, QtCore.Qt.AlignTop)

        # adding the sub layouts to the renamer main layout
        self.constraints_main_layout.addWidget(self.constraint_label, 0, 0)
        self.constraints_main_layout.addLayout(self.constraints_sub_layout, 1, 0, QtCore.Qt.AlignTop)

        # add the widgets to the skinning tab layout
        self.skinning_sub_layout.addWidget(self.smooth_bind_button, 0, 0)
        self.skinning_sub_layout.addWidget(self.detach_skin_button, 1, 0)
        self.skinning_sub_layout.addWidget(self.copy_skin_weights_button, 2, 0)
        self.skinning_sub_layout.addWidget(self.paint_skin_weights_button, 3, 0)
        self.skinning_sub_layout.addWidget(self.smooth_skin_weights_button, 4, 0)
        self.skinning_sub_layout.addWidget(self.mirror_weights_button, 5, 0)
        self.skinning_sub_layout.addWidget(self.lock_sel_weights_button, 6, 0)
        self.skinning_sub_layout.addWidget(self.unlock_sel_weights_button, 7, 0)
        self.skinning_sub_layout.addWidget(self.lock_all_weights_button, 8, 0)
        self.skinning_sub_layout.addWidget(self.unlock_all_weights_button, 9, 0)
        self.skinning_sub_layout.addWidget(self.select_influences_button, 10, 0)
        self.skinning_sub_layout.addWidget(self.select_skin_cluster_button, 11, 0)

        # adding the widgets to the constraints sub layout
        self.constraints_sub_layout.addWidget(self.constraint_offset_cb, 0, 0)
        self.constraints_sub_layout.addWidget(self.constraint_exclude_trans_cb, 1, 0)
        self.constraints_sub_layout.addWidget(self.constraint_exclude_rots_cb, 1, 1)
        self.constraints_sub_layout.addWidget(self.constraint_combo_box, 2, 0, 1, 2)
        self.constraints_sub_layout.addWidget(self.create_constraint_button, 3, 0, 1, 2)

        #######################################################################
        # Create utilities tab and widgets
        #######################################################################
        # Create MISC widgets
        self.misc_label = QtWidgets.QLabel("MISC")
        self.misc_label.setStyleSheet("QLabel %s" %self.headerColor)
        self.misc_label.setAlignment(QtCore.Qt.AlignCenter)
        self.freeze_transforms_button = QtWidgets.QPushButton("Freeze Transforms")
        self.delete_history_button = QtWidgets.QPushButton("Delete History")
        self.center_pivot_button = QtWidgets.QPushButton("Center Pivot")
        self.draw_curve_button = QtWidgets.QPushButton("Draw Curve")
        self.rivet_button = QtWidgets.QPushButton("Rivet")

        # Slots for misc widgets
        self.freeze_transforms_button.clicked.connect(rpt.freeze)
        self.delete_history_button.clicked.connect(rpt.delete_history)
        self.center_pivot_button.clicked.connect(rpt.center_pivot)
        self.draw_curve_button.clicked.connect(rpt.draw_curve)
        self.rivet_button.clicked.connect(rpt.create_rivet)

        # Create alembic widgets
        self.alembic_label = QtWidgets.QLabel("ALEMBIC")
        self.alembic_label.setStyleSheet("QLabel %s" %self.headerColor)
        self.alembic_label.setAlignment(QtCore.Qt.AlignCenter)
        self.export_hierarchy_button = QtWidgets.QPushButton("Export Hierarchy")
        self.export_selected_button = QtWidgets.QPushButton("Export Selected")
        self.import_alembic_button = QtWidgets.QPushButton("Import Alembic")

        # slots for alembic widgets

        #######################################################################
        # Create the layout for the utilities tab and align to the top
        #######################################################################

        self.utils_tab_layout = QtWidgets.QGridLayout()
        self.utils_tab_layout.setAlignment(QtCore.Qt.AlignTop)
        self.utils_tab_sub_layout = QtWidgets.QGridLayout()
        self.utils_tab_sub_layout.setAlignment(QtCore.Qt.AlignTop)
        self.utils_tab_sub_layout.setSizeConstraint(QtWidgets.QLayout.SetMinimumSize)

        self.misc_main_layout = QtWidgets.QGridLayout()
        self.misc_sub_layout = QtWidgets.QGridLayout()

        self.alembic_main_layout = QtWidgets.QGridLayout()
        self.alembic_sub_layout = QtWidgets.QGridLayout()

        # set the scroll area and the main layout
        self.utils_scroll_widget = QtWidgets.QWidget()
        self.utils_scroll_widget.setLayout(self.utils_tab_sub_layout)
        self.utils_scroll_area = QtWidgets.QScrollArea()
        self.utils_tab_layout.addWidget(self.utils_scroll_area)
        self.utils_scroll_area.setWidget(self.utils_scroll_widget)
        self.utils_scroll_area.setWidgetResizable(True)

        # spacing out the layouts
        self.utils_tab_layout.setVerticalSpacing(20)

        self.misc_main_layout.setVerticalSpacing(20)
        self.misc_sub_layout.setVerticalSpacing(3)

        self.alembic_main_layout.setVerticalSpacing(20)
        self.alembic_sub_layout.setVerticalSpacing(3)

        # adding all the main layouts to the utils tab layout
        self.utils_tab_sub_layout.addLayout(self.misc_main_layout, 1, 0, QtCore.Qt.AlignTop)
        self.utils_tab_sub_layout.addLayout(self.alembic_main_layout, 1, 0, QtCore.Qt.AlignTop)

        # adding sub layouts to the binding main layout
        self.misc_main_layout.addWidget(self.misc_label, 0, 0, QtCore.Qt.AlignTop)
        self.misc_main_layout.addLayout(self.misc_sub_layout, 1, 0, QtCore.Qt.AlignTop)

        # add the widgets to the misc button layout
        self.misc_sub_layout.addWidget(self.freeze_transforms_button, 0, 0)
        self.misc_sub_layout.addWidget(self.delete_history_button, 1, 0)
        self.misc_sub_layout.addWidget(self.center_pivot_button, 2, 0)
        self.misc_sub_layout.addWidget(self.draw_curve_button, 3, 0)
        self.misc_sub_layout.addWidget(self.rivet_button, 4, 0)

        #######################################################################
        # Set tab layouts and the main layout
        #######################################################################

        # Set the main layout to the window
        self.setLayout(self.main_layout)
        self.setup_tab.setLayout(self.setup_tab_layout)
        self.binding_tab.setLayout(self.binding_tab_layout)
        self.utils_tab.setLayout(self.utils_tab_layout)

    def color_change(self, text):
        self.control_color.setStyleSheet("QComboBox {background-color: %s;}" %text)
        self.current_color = QtGui.QColor.getRgb(QtGui.QColor(self.control_color.currentText()))

    def joint_size_slider_changed(self):
        value = float(self.joint_size_slider.value()) / 10.0
        self.joint_size_number.setValue(value)
        rpt.joint_size_set(value)

    def joint_size_number_changed(self):
        value = self.joint_size_number.value()
        self.joint_size_slider.setValue(int(value*10))
        rpt.joint_size_set(value)

    # Delete any instances of this class
    def deleteInstances(self):
        if cmds.workspaceControl(self.__class__.toolName+"WorkspaceControl", exists=True, q=True) == True:
            cmds.deleteUI(self.__class__.toolName+"WorkspaceControl", control=True)

    # Show window with docking ability
    def run(self):
        self.show(dockable = True)


def extractKonkoSTranslations(item):
	"""
	Parser for 'Konko's Translations'
	"""
	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol) or 'preview' in item['title'].lower():
		return None

	tagmap = [
		('I Bought a Girl',                           'I Bought a Girl',                                  'translated'),
		('Elf',                                       'Kuishinbo Elf',                                    'translated'),
		('The strongest 10 years old magician',       'Juu Sai no Saikyou Madoushi',                      'translated'),
		('Cheat na Kaineko',                          'Cheat na Kaineko no Okage de Rakuraku Level Up',   'translated'),
		('Pervert Healer',                            'I Work As A Healer In Another World\'s Labyrinth City',   'translated'),
	]

	for tagname, name, tl_type in tagmap:
		if tagname in item['tags']:
			return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)

	return False


from rest_framework import serializers
from stores.models import Store, Notice

class StoreSerializer(serializers.ModelSerializer):
    image = serializers.ImageField(use_url=True)

    class Meta:
        model = Store
        fields = [
            'pk',
            'shopkeeper',
            'name',
            'locations',
            'phone',
            'description',
            'image',
            'created_at',
            'updated_at',
        ]

        read_only_fields =['pk', 'shopkeeper']

class NoticeSerializer(serializers.ModelSerializer):
    image = serializers.ImageField(use_url=True)

    class Meta:
        model = Notice
        fields =[
            'pk',
            'store',
            'title',
            'text',
            # 'like',
            # 'hit',
            'image',
            # 'category',
        ]

        read_only_fields = ['pk', 'store']

    # def create(self, validated_data):
    #     store = Store.objects.get(pk=self.store_id)
    #     return Notice(**validated_data)

    # def get
    '''
    this functions is to get store_pk to filter notice
    which is store-related

    '''


from servidor.database.connection import transaction
from servidor.sistema.usuarios.usuario.model import Modulo
from servidor.sistema.usuarios.rol.model import Rol
from servidor.sistema.usuarios.ajuste.model import Ajuste

def insertions():
    with transaction() as session:
        user_m = session.query(Modulo).filter(Modulo.nombre == 'usuarios_mod').first()
        if user_m is None:
            user_m = Modulo(titulo='Usuarios', nombre='usuarios_mod', icono='group')

        ajustes_m = session.query(Modulo).filter(Modulo.nombre == 'ajuste').first()
        if ajustes_m is None:
            ajustes_m = Modulo(titulo='Ajuste', ruta='/ajuste', nombre='ajuste', icono='settings')

        user_m.children.append(ajustes_m)

        query_ajuste = session.query(Modulo).filter(Modulo.nombre == 'rol_query').first()
        if query_ajuste is None:
            query_ajuste = Modulo(titulo='Consultar', ruta='', nombre='ajuste_query', menu=False)
        insert_ajuste = session.query(Modulo).filter(Modulo.nombre == 'ajuste_insert').first()
        if insert_ajuste is None:
            insert_ajuste = Modulo(titulo='Adicionar', ruta='/ajuste_insert', nombre='ajuste_insert', menu=False)
        update_ajuste = session.query(Modulo).filter(Modulo.nombre == 'ajuste_update').first()
        if update_ajuste is None:
            update_ajuste = Modulo(titulo='Actualizar', ruta='/ajuste_update', nombre='ajuste_update', menu=False)
        delete_ajuste = session.query(Modulo).filter(Modulo.nombre == 'ajuste_delete').first()
        if delete_ajuste is None:
            delete_ajuste = Modulo(titulo='Dar de Baja', ruta='/ajuste_delete', nombre='ajuste_delete', menu=False)

        ajustes_m.children.append(query_ajuste)
        ajustes_m.children.append(insert_ajuste)
        ajustes_m.children.append(update_ajuste)
        ajustes_m.children.append(delete_ajuste)

        super_role = session.query(Rol).filter(Rol.nombre == 'SUPER ADMINISTRADOR').first()
        if super_role is None:
            super_role = Rol(nombre='SUPER ADMINISTRADOR', descripcion='Todos los permisos.')

        admin_role = session.query(Rol).filter(Rol.nombre == 'ADMINISTRADOR').first()
        if admin_role is None:
            admin_role = Rol(nombre='ADMINISTRADOR', descripcion='Solo permisos de administrador.')

        super_role.modulos.append(user_m)
        super_role.modulos.append(ajustes_m)
        super_role.modulos.append(query_ajuste)
        super_role.modulos.append(insert_ajuste)
        super_role.modulos.append(update_ajuste)
        super_role.modulos.append(delete_ajuste)

        session.add(super_role)
        session.add(admin_role)
        session.add(Ajuste(id=1, claveSecreta='SecretBackup'))

        session.commit()


from flask import Flask, request
import subprocess
# import json
app = Flask(__name__)

# ...
@app.route('/', methods=['POST'])
def process_json():
    if (request.headers.get('Authorization') == "Bearer 8801acb25f6ca38e5955540969770890"):
        if (request.headers.get('Content-Type') == 'application/json'):
            json = request.json

            tel_num = json['tel']
            flash = json['flash']
            msg = json['msg']

            print("Nummer: " + tel_num)
            print("Flash: " + flash)
            print("Nachricht: " + msg)

            tel_num = "-t " + tel_num
            flash = "-f " + flash
            msg = "-m " + "'" + msg + "'"

            filen = ("/home/sms/smssend/send_flash.sh" if flash == "true" else "/home/sms/smssend/send.sh")
            print(filen)
            # args = " -t " + tel_num + " -m " + "'" + msg + "'" + " -f " + flash
            # subprocess.call([filen + args])
            subprocess.call([filen, tel_num, msg, flash])
            return "OK"
        else:
            return 'Content-Type "' + request.headers.get('Content-Type') + '"not supported!'
    else:
        return "Unauthorized"

if __name__ == "__main__":
    app.run(host='0.0.0.0',port=80)


# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
"""
Userbot module to help you manage a group
"""

from asyncio import sleep

from telethon import functions
from telethon.errors import (
    BadRequestError,
    ImageProcessFailedError,
    PhotoCropSizeSmallError,
)
from telethon.errors.rpcerrorlist import UserAdminInvalidError, UserIdInvalidError
from telethon.tl.functions.channels import (
    EditAdminRequest,
    EditBannedRequest,
    EditPhotoRequest,
)
from telethon.tl.functions.messages import UpdatePinnedMessageRequest
from telethon.tl.functions.users import GetFullUserRequest
from telethon.tl.types import (
    ChatAdminRights,
    ChatBannedRights,
    MessageEntityMentionName,
    MessageMediaPhoto,
)

from userbot import *
from userbot.plugins.sql_helper.mute_sql import is_muted, mute, unmute
from mafiabot.utils import *
from userbot.cmdhelp import CmdHelp

# =================== CONSTANT ===================

PP_TOO_SMOL = "`TÊœÉ˜ É©É±ÊŒÊ›É˜ É©s too sÉ±ÊŒÉÉ`"
PP_ERROR = "`FÊŒÉ©ÉÊ‹Ê€É˜ wÊœÉ©ÉÉ˜ pÊ€ocÉ˜ssÉ©Å‹Ê› tÊœÉ˜ É©É±ÊŒÊ›É˜`"
NO_ADMIN = "`I ÊŒÉ± Å‹ot ÊŒÅ‹ ÊŒÉ—É±É©Å‹! CÊœÊ‹tÉ©Æ´ÊŒ sÊŒÉÊŒ`"
NO_PERM = "`I É—oÅ‹'t ÊœÊŒvÉ˜ sÊ‹Ê†Ê†É©cÉ©É˜Å‹t pÉ˜Ê€É±É©ssÉ©oÅ‹s! SÉ˜É— -_-`"
CHAT_PP_CHANGED = "`CÊœÊŒt PÉ©ctÊ‹Ê€É˜ CÊœÊŒÅ‹Ê›É˜É— SÊ‹ccÉ˜ssÊ†Ê‹ÉÉÆ´`"
INVALID_MEDIA = "`IÅ‹vÊŒÉÉ©É— É±É˜É—É©ÊŒ ExtÉ˜Å‹sÉ©oÅ‹`"

BANNED_RIGHTS = ChatBannedRights(
    until_date=None,
    view_messages=True,
    send_messages=True,
    send_media=True,
    send_stickers=True,
    send_gifs=True,
    send_games=True,
    send_inline=True,
    embed_links=True,
)

UNBAN_RIGHTS = ChatBannedRights(
    until_date=None,
    send_messages=None,
    send_media=None,
    send_stickers=None,
    send_gifs=None,
    send_games=None,
    send_inline=None,
    embed_links=None,
)

MUTE_RIGHTS = ChatBannedRights(until_date=None, send_messages=True)
UNMUTE_RIGHTS = ChatBannedRights(until_date=None, send_messages=False)

# ================================================

@bot.on(admin_cmd("setgpic$"))
@bot.on(sudo_cmd(pattern="setgpic$", allow_sudo=True))
@errors_handler
async def set_group_photo(gpic):
    if gpic.fwd_from:
        return
    if not gpic.is_group:
        await edit_or_reply(gpic, "`I É—oÅ‹'t tÊœÉ©Å‹Ä¸ tÊœÉ©s É©s ÊŒ Ê›Ê€oÊ‹p.`")
        return
    replymsg = await gpic.get_reply_message()
    chat = await gpic.get_chat()
    admin = chat.admin_rights
    creator = chat.creator
    photo = None
    if not admin and not creator:
        await edit_or_reply(gpic, NO_ADMIN)
        return
    if replymsg and replymsg.media:
        if isinstance(replymsg.media, MessageMediaPhoto):
            photo = await gpic.client.download_media(message=replymsg.photo)
        elif "image" in replymsg.media.document.mime_type.split("/"):
            photo = await gpic.client.download_file(replymsg.media.document)
        else:
            await edit_or_reply(gpic, INVALID_MEDIA)
    h1m4n5hu0p = None
    if photo:
        try:
            await gpic.client(
                EditPhotoRequest(gpic.chat_id, await gpic.client.upload_file(photo))
            )
            await edit_or_reply(gpic, CHAT_PP_CHANGED)
            h1m4n5hu0p = True
        except PhotoCropSizeSmallError:
            await edit_or_reply(gpic, PP_TOO_SMOL)
        except ImageProcessFailedError:
            await edit_or_reply(gpic, PP_ERROR)
        except Exception as e:
            await edit_or_reply(gpic, f"**EÊ€Ê€oÊ€ : **`{str(e)}`")
        if BOTLOG and h1m4n5hu0p:
            await gpic.client.send_message(
                BOTLOG_CHATID,
                "#GROUPPIC\n"
                f"GÊ€oÊ‹p pÊ€oÊ†É©ÉÉ˜ pÉ©c cÊœÊŒÅ‹Ê›É˜É— "
                f"CHAT: {gpic.chat.title}(`{gpic.chat_id}`)",
            )

@bot.on(admin_cmd("promote(?: |$)(.*)"))
@bot.on(sudo_cmd(pattern="promote(?: |$)(.*)", allow_sudo=True))
@errors_handler
async def promote(promt):
    if promt.fwd_from:
        return
    chat = await promt.get_chat()
    admin = chat.admin_rights
    creator = chat.creator
    if not admin and not creator:
        await edit_or_reply(promt, NO_ADMIN)
        return
    new_rights = ChatAdminRights(
        add_admins=False,
        invite_users=True,
        change_info=False,
        ban_users=True,
        delete_messages=True,
        pin_messages=True,
    )
    mafiaevent = await edit_or_reply(promt, "PÊ€oÉ±otÉ©Å‹Ê› PÉÊ‘ WÊŒÉ©t...")
    user, rank = await get_user_from_event(promt)
    if not rank:
        rank = "SÊŒÅ‹Ä¸É© WÊŒÊ€Ê€É©oÊ€s <3"
    if not user:
        return
    try:
        await promt.client(EditAdminRequest(promt.chat_id, user.id, new_rights, rank))
        await mafiaevent.edit("PÊ€oÉ±otÉ˜É— SÊ‹ccÉ˜ssÊ†Ê‹ÉÉÆ´ ! CÊœÊŒÉ KÊœÊ‹sÊœ HojÊŒ AÉ“ DÊœÊŒÅ‹Å‹o <3")
    except BadRequestError:
        await mafiaevent.edit(NO_PERM)
        return
    if BOTLOG:
        await promt.client.send_message(
            BOTLOG_CHATID,
            "#PROMOTE\n"
            f"USER: [{user.first_name}](tg://user?id={user.id})\n"
            f"CHAT: {promt.chat.title}(`{promt.chat_id}`)",
        )

@bot.on(admin_cmd("demote(?: |$)(.*)"))
@bot.on(sudo_cmd(pattern="demote(?: |$)(.*)", allow_sudo=True))
@errors_handler
async def demote(dmod):
    if dmod.fwd_from:
        return
    chat = await dmod.get_chat()
    admin = chat.admin_rights
    creator = chat.creator
    if not admin and not creator:
        await edit_or_reply(dmod, NO_ADMIN)
        return
    mafiaevent = await edit_or_reply(dmod, "DÉ˜É±otÉ©Å‹Ê› PÉÊ‘ WÊŒÉ©t...")
    rank = "SÊŒÅ‹Ä¸É© WÊŒÊ€Ê€É©oÊ€s <3"
    user = await get_user_from_event(dmod)
    user = user[0]
    if not user:
        return
    newrights = ChatAdminRights(
        add_admins=None,
        invite_users=None,
        change_info=None,
        ban_users=None,
        delete_messages=None,
        pin_messages=None,
    )
    try:
        await dmod.client(EditAdminRequest(dmod.chat_id, user.id, newrights, rank))
    except BadRequestError:
        await mafiaevent.edit(NO_PERM)
        return
    await mafiaevent.edit("DÉ˜É±otÉ˜É— SÊ‹ccÉ˜ssÊ†Ê‹ÉÉÆ´ ! NÉ©Ä¸ÊŒÉ BsÉ—Ä¸.")
    if BOTLOG:
        await dmod.client.send_message(
            BOTLOG_CHATID,
            "#DEMOTE\n"
            f"USER: [{user.first_name}](tg://user?id={user.id})\n"
            f"CHAT: {dmod.chat.title}(`{dmod.chat_id}`)",
        )

@bot.on(admin_cmd("ban(?: |$)(.*)"))
@bot.on(sudo_cmd(pattern="ban(?: |$)(.*)", allow_sudo=True))
@errors_handler
async def ban(bon):
    if bon.fwd_from:
        return
    chat = await bon.get_chat()
    admin = chat.admin_rights
    creator = chat.creator
    if not admin and not creator:
        await edit_or_reply(bon, NO_ADMIN)
        return
    user, reason = await get_user_from_event(bon)
    if not user:
        return
    mafiaevent = await edit_or_reply(bon, "BÊŒÅ‹Å‹É©Å‹Ê› tÊœÉ©s SÊ‹ÊŒÊ€ WÊŒÉ©t...")
    try:
        await bon.client(EditBannedRequest(bon.chat_id, user.id, BANNED_RIGHTS))
    except BadRequestError:
        await mafiaevent.edit(NO_PERM)
        return
    try:
        reply = await bon.get_reply_message()
        if reply:
            await reply.delete()
    except BadRequestError:
        await mafiaevent.edit("I ÊŒÉ©Å‹'t Ê›ot É±sÊ› É—É˜ÉÉ˜tÉ©Å‹Ê› Ê€É©Ê›Êœt. BÊ‹t stÉ©ÉÉ BÊŒÅ‹Å‹É˜É— !")
        return
    if reason:
        await mafiaevent.edit(f"{str(user.id)} É©s É“ÊŒÅ‹Å‹É˜É— !!\nRÉ˜ÊŒsoÅ‹ : {reason}")
    else:
        await mafiaevent.edit(f"{str(user.id)} É©s É“ÊŒÅ‹Å‹É˜É— !!")
    if BOTLOG:
        await bon.client.send_message(
            BOTLOG_CHATID,
            "#BAN\n"
            f"USER: [{user.first_name}](tg://user?id={user.id})\n"
            f"CHAT: {bon.chat.title}({bon.chat_id})",
        )

@bot.on(admin_cmd("unban(?: |$)(.*)"))
@bot.on(sudo_cmd(pattern="unban(?: |$)(.*)", allow_sudo=True))
@errors_handler
async def nothanos(unbon):
    if unbon.fwd_from:
        return
    chat = await unbon.get_chat()
    admin = chat.admin_rights
    creator = chat.creator
    if not admin and not creator:
        await edit_or_reply(unbon, NO_ADMIN)
        return
    mafiaevent = await edit_or_reply(unbon, "UÅ‹É“ÊŒÅ‹Å‹É©Å‹Ê› PÉÊ‘ WÊŒÉ©t...")
    user = await get_user_from_event(unbon)
    user = user[0]
    if not user:
        return
    try:
        await unbon.client(EditBannedRequest(unbon.chat_id, user.id, UNBAN_RIGHTS))
        await mafiaevent.edit("UÅ‹É“ÊŒÅ‹Å‹É˜É— SÊ‹ccÉ˜ssÊ†Ê‹ÉÉÆ´ ! CÊœÊŒÉ KÊœÊ‹sÊœ HojÊŒ AÉ“ DÊœÊŒÅ‹Å‹o <3")
        if BOTLOG:
            await unbon.client.send_message(
                BOTLOG_CHATID,
                "#UNBAN\n"
                f"USER: [{user.first_name}](tg://user?id={user.id})\n"
                f"CHAT: {unbon.chat.title}(`{unbon.chat_id}`)",
            )
    except UserIdInvalidError:
        await mafiaevent.edit("SoÊ€Ê€Æ´ I CÊŒÅ‹'t UÅ‹É“ÊŒÅ‹ !")

@command(incoming=True)
async def watcher(event):
    if event.fwd_from:
        return
    if is_muted(event.sender_id, event.chat_id):
        try:
            await event.delete()
        except Exception as e:
            LOGS.info(str(e))

@bot.on(admin_cmd("pin($| (.*))"))
@bot.on(sudo_cmd(pattern="pin($| (.*))", allow_sudo=True))
@errors_handler
async def pin(msg):
    if msg.fwd_from:
        return
    chat = await msg.get_chat()
    admin = chat.admin_rights
    creator = chat.creator
    if not admin and not creator:
        await edit_or_reply(msg, NO_ADMIN)
        return
    to_pin = msg.reply_to_msg_id
    if not to_pin:
        await edit_or_reply(msg, "RÉ˜pÉÆ´ to ÊŒ É±É˜ssÊŒÊ›É˜ to pÉ©Å‹ É©t.")
        return
    options = msg.pattern_match.group(1)
    is_silent = True
    if options.lower() == "loud":
        is_silent = False
    try:
        await msg.client(UpdatePinnedMessageRequest(msg.to_id, to_pin, is_silent))
    except BadRequestError:
        await edit_or_reply(msg, NO_PERM)
        return
    hmm = await edit_or_reply(msg, "PÉ©Å‹Å‹É˜É— SÊ‹ccÉ˜ssÊ†Ê‹ÉÉÆ´ !")
    user = await get_user_from_id(msg.sender_id, msg)
    if BOTLOG:
        await msg.client.send_message(
            BOTLOG_CHATID,
            "#PIN\n"
            f"ADMIN: [{user.first_name}](tg://user?id={user.id})\n"
            f"CHAT: {msg.chat.title}(`{msg.chat_id}`)\n"
            f"LOUD: {not is_silent}",
        )
    await sleep(3)
    try:
        await hmm.delete()
    except:
        pass

@bot.on(admin_cmd("kick(?: |$)(.*)"))
@bot.on(sudo_cmd(pattern="kick(?: |$)(.*)", allow_sudo=True))
@errors_handler
async def kick(usr):
    if usr.fwd_from:
        return
    chat = await usr.get_chat()
    admin = chat.admin_rights
    creator = chat.creator
    if not admin and not creator:
        await edit_or_reply(usr, NO_ADMIN)
        return
    user, reason = await get_user_from_event(usr)
    if not user:
        await edit_or_reply(usr, "CoÊ‹ÉÉ—Å‹'t Ê†É˜tcÊœ Ê‹sÉ˜Ê€.")
        return
    mafiaevent = await edit_or_reply(usr, "Kicking...")
    try:
        await usr.client.kick_participant(usr.chat_id, user.id)
        await sleep(0.5)
    except Exception as e:
        await mafiaevent.edit(NO_PERM + f"\n{str(e)}")
        return
    if reason:
        await mafiaevent.edit(
            f"KÉ©cÄ¸É˜É— [{user.first_name}](tg://user?id={user.id})!\nRÉ˜ÊŒsoÅ‹: {reason}"
        )
    else:
        await mafiaevent.edit(f"KÉ©cÄ¸É˜É— [{user.first_name}](tg://user?id={user.id})!")
    if BOTLOG:
        await usr.client.send_message(
            BOTLOG_CHATID,
            "#KICK\n"
            f"USER: [{user.first_name}](tg://user?id={user.id})\n"
            f"CHAT: {usr.chat.title}({usr.chat_id})\n",
        )

@bot.on(admin_cmd("undlt$"))
@bot.on(sudo_cmd(pattern="undlt$", allow_sudo=True))
async def _(event):
    if event.fwd_from:
        return
    if event.fwd_from:
        return
    c = await event.get_chat()
    if c.admin_rights or c.creator:
        a = await event.client.get_admin_log(
            event.chat_id, limit=5, edit=False, delete=True
        )
        deleted_msg = "DÉ˜ÉÉ˜tÉ˜É— É±É˜ssÊŒÊ›É˜ É©Å‹ tÊœÉ©s Ê›Ê€oÊ‹p :"
        for i in a:
            deleted_msg += "\nðŸ‘‰{}".format(i.old.message)
        await edit_or_reply(event, deleted_msg)
    else:
        await edit_or_reply(
            event, "YoÊ‹ Å‹É˜É˜É— ÊŒÉ—É±É©Å‹É©stÊ€ÊŒtÉ©vÉ˜ pÉ˜Ê€É±É©ssÉ©oÅ‹s É©Å‹ oÊ€É—É˜Ê€ to É—o tÊœÉ©s coÉ±É±ÊŒÅ‹É—"
        )
        await sleep(3)
        try:
            await event.delete()
        except:
            pass

async def get_user_from_event(event):
    if event.fwd_from:
        return
    args = event.pattern_match.group(1).split(" ", 1)
    extra = None
    if event.reply_to_msg_id:
        previous_message = await event.get_reply_message()
        user_obj = await event.client.get_entity(previous_message.sender_id)
        extra = event.pattern_match.group(1)
    elif args:
        user = args[0]
        if len(args) == 2:
            extra = args[1]
        if user.isnumeric():
            user = int(user)
        if not user:
            await event.edit("PÊŒss tÊœÉ˜ Ê‹sÉ˜Ê€'s Ê‹sÉ˜Ê€Å‹ÊŒÉ±É˜, É©É— oÊ€ Ê€É˜pÉÆ´ !")
            return
        if event.message.entities:
            probable_user_mention_entity = event.message.entities[0]

            if isinstance(probable_user_mention_entity, MessageEntityMentionName):
                user_id = probable_user_mention_entity.user_id
                user_obj = await event.client.get_entity(user_id)
                return user_obj
        try:
            user_obj = await event.client.get_entity(user)
        except (TypeError, ValueError):
            await event.edit("CoÊ‹ÉÉ— Å‹ot Ê†É˜tcÊœ É©Å‹Ê†o oÊ† tÊœÊŒt Ê‹sÉ˜Ê€.")
            return None
    return user_obj, extra

async def get_user_from_id(user, event):
    if event.fwd_from:
        return
    if isinstance(user, str):
        user = int(user)
    try:
        user_obj = await event.client.get_entity(user)
    except (TypeError, ValueError) as err:
        await event.edit(str(err))
        return None
    return user_obj

CmdHelp("admin").add_command(
       'setgpic', '<reply to image>', 'Changes the groups display picture'
).add_command(
        'promote', '<username/reply> <custom rank (optional)>',
        'Provides admins right to a person in the chat.'
).add_command(
        'demote', '<username/reply>', 'Revokes the person admin permissions    in the chat.'
).add_command(
        'ban', '<username/reply> <reason (optional)>', 'Bans the person off your chat.'
).add_command(
        'unban', '<username/reply>', 'Removes the ban from the person in the chat.'
).add_command(
        'mute', '<username/reply> <reason (optional)>', 'Mutes the person in the chat, works on admins too.'
).add_command(
        'unmute', '<username/reply>', 'Removes the person from the muted list.'
).add_command(
        'pin', '<reply> or .pin loud', 'Pins the replied message in Group'
).add_command(
        'kick', '<username/reply>', 'kick the person off your chat'
).add_command(
        'iundlt', None, 'display last 5 deleted messages in group.'
).add()


def hammingDistance(p, q):
    """
    Returns hamming distance between strings p and q
    """
    d = 0
    n = len(p)
    for i in range(n):
    	if p[i] != q[i]:
	    	d = d + 1
    return d


import math
import random
########## Parameters ##########
    # number of random initial points
n_generators = 10000
    # we choose fittest members of generators for population
n_population = 50
    # chance for every child to be mutated (swap (x, y))
mutation_rate = 0.01
    # to show how much of the population could be parents, RANK-based
selection_percentage = 30
    # number of iterations for each generator if it doesn't stop automatically
iteration = 50
current_iteration= iteration

########## Funcions ##########
    # Calculate ackley
def ackley(x, y):
    return -20.0 * math.exp(-0.2 * math.sqrt(0.5 * (x ** 2 + y ** 2))) - math.exp(0.5 * (math.cos(2 * math.pi * x) + math.cos(2 * math.pi * y))) + math.exp(1) + 20

    # To sort elements based on their ackley value
def fit_sort(elements):
    fit_list = []
    for i in elements:
        fit_list.append(ackley(i[0], i[1]))
    sorted_elements = [x for _,x in sorted(zip(fit_list, elements))]
    # now we have our elements sorted based on their value (in fit_list) in sorted elements.
    return sorted_elements

    # We choose "n_populatoin" fittest as the initial population
def make_population(elements, n):
    return fit_sort(elements)[:n]

    # we choose "selection_percentage" of the population as parents, and make children from the by combination and mutation
    # RANK-base
def parent_selection(elements):
    n = len(elements) * selection_percentage // 100
    parents = make_population(population, n)
    return parents

def value(element):
    for i in element:
        print(round(ackley(i[0], i[1]), 4), end=", ")
    print()

    # We combinate and mutate n_population children from parents selected for breeding
def combination_mutation(parents, n):
    children = []
    j = len(parents)
    while (len(children) != n):
        r1 = random.randint(0, j - 1)
        r2 = random.randint(0, j - 1)
        if (r1 != r2):
            x = parents[r1][0] + parents[r2][0] // 2
            y = parents[r1][1] + parents[r2][1] // 2
            if (random.random() < mutation_rate):
                x, y = y, x
            children.append([x, y])
    return children

    # We give each element a probability based on it's fitness, then we choose "npopulation" of them. (we don't survive a duplicate of an element)
    # RANK-based
def survival_selection(elements, n):
    mating_pool = []
    survived_elements = []
    elements = fit_sort(elements)
    j = len(elements)
    i = 0
    while (j):
        x = j * [elements[i]]
        mating_pool.extend(x)
        j = j - 1
        i = i + 1
    j = len(mating_pool)
    while (n):
        z = 0
        x = mating_pool[random.randint(0, j - 1)]
        survived_elements.append(x)
        while (x in mating_pool):
            mating_pool.remove(x)
            z = z + 1
        n = n - 1
        j = j - z
    return survived_elements

# Create "n_generators" randomly, -5 < x, y < 5
# we choose "n_population" best of them for initial populatoin.
generators = []
population = []
for i in range(n_generators):
    x = random.random() * 10 - 5
    y = random.random() * 10 - 5
    generators.append([x, y])

i = iteration
population = make_population(generators, n_population)
while (i):
    parents = parent_selection(population)
    children = combination_mutation(parents, n_population)
    population = survival_selection(population + children, n_population)
    i = i - 1
min_ = ackley(fit_sort(population)[0][0], fit_sort(population)[0][1])

print("Minimum for ackley with", n_population, "population, mutation rate of", mutation_rate, ", selection percentage of", selection_percentage, "after", iteration, "generations :", min_)


#旧版有道爬虫（没有加密的）
import urllib.request
import urllib.parse
import json
import time    #为了防止被网络识别为爬虫，应该访问有一个时间差，不能在短时间达到目标网站的访问阈值

while True:
    content = input('请输入需要翻译的内容(输入"q!"退出程序)：')
    if content == 'q!':
        break
    url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&sessionFrom=null'   #这个是旧版本有道翻译的URL，新版的有道是在translate_o?
    #1:通过修改headers来
    '''
    head = {}
    head['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0;\WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36'
    '''
    data = {}
    data['i'] = content
    data['from'] = 'AUTO'
    data['to'] = 'AUTO'
    data['smartresult'] = 'dict'
    data['client'] = 'fanyideskweb'
    data['salt'] = '1502762754306'
    data['sign'] = '556692b456d411821609d2d4c575b389'
    data['doctype'] = 'json'
    data['version'] = '2.1'
    data['keyfrom'] = 'fanyi.web'
    data['action'] = 'FY_BY_CLlCKBUTTON'
    data['typoResult'] = 'true'
    data = urllib.parse.urlencode(data).encode('utf-8')

    response = urllib.request.Request(url,data)     #1:如果前面加了head字典进去，这里也加了head进去
    response.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0;\WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36')  #2:在.Requset的后面动态添加headers，用这个方法：Request.add_header(key,value),.Requset里面不用加
    request = urllib.request.urlopen(response)
    html = request.read().decode('utf-8')
    # print(html)
    target = json.loads(html)
    print("翻译结果： %s" %(target['translateResult'][0][0]['tgt']))
    print(response.headers)   #顺便验证header是否加进去了
    time.sleep(5)


# coding: utf-8

"""
    openapi 3.1.0 sample spec
    sample spec for testing openapi functionality, built from json schema tests for draft2020-12  # noqa: E501
    The version of the OpenAPI document: 0.0.1
    Generated by: https://github.com/openapi-json-schema-tools/openapi-json-schema-generator
"""

import unittest

import unit_test_api
from unit_test_api.components.schema.prefixitems_validation_adjusts_the_starting_index_for_items import PrefixitemsValidationAdjustsTheStartingIndexForItems
from unit_test_api.configurations import schema_configuration

class TestPrefixitemsValidationAdjustsTheStartingIndexForItems(unittest.TestCase):
    """PrefixitemsValidationAdjustsTheStartingIndexForItems unit test stubs"""
    configuration = schema_configuration.SchemaConfiguration(
        disabled_json_schema_keywords={'format'}
    )

    def test_wrong_type_of_second_item_fails(self):
        # wrong type of second item
        with self.assertRaises((unit_test_api.ApiValueError, unit_test_api.ApiTypeError)):
            PrefixitemsValidationAdjustsTheStartingIndexForItems.validate(
                [
                    "x",
                    "y",
                ],
                configuration=self.configuration
            )

    def test_valid_items_passes(self):
        # valid items
        PrefixitemsValidationAdjustsTheStartingIndexForItems.validate(
            [
                "x",
                2,
                3,
            ],
            configuration=self.configuration
        )

if __name__ == '__main__':
    unittest.main()


import os
import cv2
import face_recognition
import numpy as np

########### INIT ################
path_faces = "ParickovaFaces"
# path_faces = "HBS_Faces"
path_fotos = "ParickovaFotos"
#path_fotos = "HBS_Fotos"
path_rating = "ParickovaRating"
#path_rating = "HBS_Rating"
######## FUNCTIONS ##############

def makeParickovaLists(path):
    parickovaFaces = []
    parickovaNames = []
    myList = os.listdir(path)
    for face in myList:
        curImg = cv2.imread(f"{path}/{face}")
        parickovaFaces.append(curImg)
        parickovaNames.append(str.split(face, sep=".")[0])
    return parickovaFaces, parickovaNames

def findParickovaEncodings(parickovaFaces):
    encodeList = []
    for img in parickovaFaces:
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        encodeImg = face_recognition.face_encodings(img)[0]
        encodeList.append(encodeImg)
    return encodeList

def makeFotoList(path):
    fotoFaceLoc = []
    fotoFaceEncode = []
    fotoNames = []
    fotoList = os.listdir(path)
    for foto in fotoList:
        fotoNames.append(foto)
        foto = face_recognition.load_image_file(f"{path}/{foto}")
        foto = cv2.cvtColor(foto, cv2.COLOR_BGR2RGB)
        faceLoc = face_recognition.face_locations(foto)
        encodeFoto = face_recognition.face_encodings(foto, faceLoc)
        fotoFaceLoc.append(faceLoc)
        fotoFaceEncode.append(encodeFoto)
    return fotoNames, fotoFaceLoc, fotoFaceEncode

############## CORE CALL ################
# search for faces, names and encodings of parickova members
parickovaFaces, parickovaNames = makeParickovaLists(path_faces)
parickovaEncode = findParickovaEncodings(parickovaFaces)

# search of location and encodings of faces in the pictures [picName.][pictureNr.][faceNr.]
parickovaFotosNames, parickovaFotosLoc, parickovaFotosEncode  = makeFotoList(path_fotos)

# searching, whether parickova members are on pictures.
for curPic, curEnc, curLoc in zip(parickovaFotosNames, parickovaFotosEncode, parickovaFotosLoc):
    img = cv2.imread(f"{path_fotos}/{curPic}")
    print("In", curPic, "are", len(curEnc), "faces")
    for i, loc in zip(curEnc, curLoc):
        sourceFoto = ""
        nameFolder = ""
        targetFoto = ""
        compareResult = face_recognition.compare_faces(parickovaEncode, i)
        faceDistance = face_recognition.face_distance(parickovaEncode, i)
        minIdx = np.argmin(faceDistance)
        if compareResult[minIdx] == True:
            print("There is:", parickovaNames[minIdx])
            cv2.putText(img, parickovaNames[minIdx], (loc[3], loc[2]), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 2)
            sourceFoto = os.path.join(path_fotos, curPic)
            nameFolder = (f"{path_rating}/{parickovaNames[minIdx]}")
            targetFoto = (f"{nameFolder}/{str.split(curPic, sep='.')[0]}_{parickovaNames[minIdx]}.jpg")
            print(f"source pic: {sourceFoto} dest pic: {targetFoto}")
            if os.path.isdir(nameFolder) == True:
                print(f"Folder {nameFolder} exists. Creating symlink from {sourceFoto} to {targetFoto}")
                os.link(sourceFoto, targetFoto)
            else:
                print(f"Folder {nameFolder} doesnt exists. Creating folder.")
                os.makedirs(nameFolder)
                print(f"Folder {nameFolder} created. Creating symlink.")
                os.link(sourceFoto, targetFoto)
        else:
            print("I dont know who is at", loc)
            cv2.rectangle(img, (loc[3], loc[0]), (loc[1], loc[2]), (0, 255, 0), 2)

    cv2.imwrite(f"{path_rating}/{str.split(curPic, sep='.')[0]}_rated.jpg", img)


import os
import tensorflow as tf
import numpy as np
from graph_nets.graphs import GraphsTuple
from graph_nets import utils_tf

class _BaseAgent(object):
    def __init__(self):
        self.ckpt_manager = None
        self.ckpt = None
        self.network_name = None
        self.checkpoint_timestamp = None

    def act(self, *args):
        pass

    def update(self, *args):
        pass

    def export(self, graph, method='xflowrl'):
        import taso
        import onnx

        onnx_model = taso.export_onnx(graph)
        path = f'./models/{method}_{self.network_name}/{self.checkpoint_timestamp}/{self.network_name}.onnx'
        os.makedirs(os.path.dirname(path), exist_ok=True)
        onnx.save(onnx_model, path)

    @staticmethod
    def state_xfer_masked(states, action_xfer):
        if isinstance(states, list):
            tuples = []
            masks = []
            for i, state in enumerate(states):
                xfer_id = int(action_xfer[i])

                xfer_graph_tuple = state["xfers"][xfer_id]
                xfer_graph_tuple = make_eager_graph_tuple(xfer_graph_tuple)
                location_mask = state["location_mask"][xfer_id]

                tuples.append(xfer_graph_tuple)
                masks.append(location_mask)
        else:
            xfer_id = int(action_xfer)

            xfer_graph_tuple = states["xfers"][xfer_id]
            xfer_graph_tuple = make_eager_graph_tuple(xfer_graph_tuple)
            location_mask = states["location_mask"][xfer_id]

            tuples = xfer_graph_tuple
            masks = location_mask

        return tuples, masks

    def save(self):
        """Saves checkpoint to path."""
        path = self.ckpt_manager.save()
        print("Saving model to path = ", path)

    def load(self):
        """
        Loads model from latest checkpoint. Note: due to eager execution, this can only be called once
        all sonnet modules have been called once, e.g. by executing an act. See example.
        """
        self.ckpt.restore(self.ckpt_manager.latest_checkpoint)
        if self.ckpt_manager.latest_checkpoint:
            print("Restoring model from path = {}".format(self.ckpt_manager.latest_checkpoint))
            self.ckpt.step.assign_add(1)
        else:
            print("Initializing from scratch.")

def make_eager_graph_tuple(graph_tuple: GraphsTuple):
    """
    Ensures the contents of one or more graph tuples are tf tensors.

    Args:
        graph_tuple (gn.graph.GraphsTuple): GraphsTuple instances.

    Returns:
        Tuple with each value converted to an eager tensor.
    """
    return graph_tuple.replace(
        edges=tf.convert_to_tensor(value=graph_tuple.edges, dtype=tf.float32),
        nodes=tf.convert_to_tensor(value=graph_tuple.nodes, dtype=tf.float32),
        senders=tf.convert_to_tensor(value=graph_tuple.senders, dtype=tf.int32),
        receivers=tf.convert_to_tensor(value=graph_tuple.receivers, dtype=tf.int32),
        n_node=tf.convert_to_tensor(value=graph_tuple.n_node, dtype=tf.int32),
        n_edge=tf.convert_to_tensor(value=graph_tuple.n_edge, dtype=tf.int32),
        globals=tf.convert_to_tensor(value=graph_tuple.globals, dtype=tf.float32)
    )

def zeros_graph(sample_graph, edge_size, node_size, global_size):
    """
    Utility to produce an empty graph.

    Returns:
        A graph with zero-dim features.
    """
    zeros_graphs = sample_graph.replace(nodes=None, edges=None, globals=None)
    zeros_graphs = utils_tf.set_zero_edge_features(zeros_graphs, edge_size)
    zeros_graphs = utils_tf.set_zero_node_features(zeros_graphs, node_size)
    zeros_graphs = utils_tf.set_zero_global_features(zeros_graphs, global_size)
    return zeros_graphs

def discount_all(values, decay, terminal):
    """
    Discounts sequences based on a decay value.

    Args:
        values: Sequence of values to discount.
        decay: Decay value to apply along the sequence.
        terminal: Indicating end of a subsequence.

    Returns:
        An array of shape values with discounted values.
    """
    discounted = []
    i = len(values) - 1
    prev_v = 0.0
    for v in reversed(values):
        # Arrived at new sequence, start over.
        if np.all(terminal[i]):
            prev_v = 0.0

        # Accumulate prior value.
        accum_v = v + decay * prev_v
        discounted.append(accum_v)
        prev_v = accum_v

        i -= 1
    return list(reversed(discounted))

def gae_helper(vf, reward, gamma, gae_lambda, terminals, sequence_indices):
    """
    Computes generalized advantage estimation.
    """
    deltas = []
    # Convert to array for simplicity.
    vf = vf.numpy()
    start_index = 0
    i = 0
    sequence_indices[-1] = True
    for _ in range(len(vf)):
        if np.all(sequence_indices[i]):
            # Compute deltas for this subsequence.
            # Cannot do this all at once because we would need the correct offsets for each sub-sequence.
            vf_slice = list(vf[start_index:i + 1])

            if np.all(terminals[i]):
                vf_slice.append(0)
            else:
                vf_slice.append(vf[i])
            adjusted_v = np.asarray(vf_slice)

            # +1 because we want to include i-th value.
            delta = reward[start_index:i + 1] + gamma * adjusted_v[1:] - adjusted_v[:-1]
            deltas.extend(delta)
            start_index = i + 1
        i += 1

    deltas = np.asarray(deltas)
    return tf.convert_to_tensor(value=discount_all(deltas, gamma * gae_lambda, terminals), dtype=tf.float32)


# -*- coding: utf-8 -*-

from keras.models import Model
from keras.layers import Input, Conv2D, Conv2DTranspose, MaxPooling2D, Concatenate
from keras.callbacks import ModelCheckpoint
from keras.optimizers import Adam
import numpy as np
import os
import matplotlib as mpl
import matplotlib.pyplot as plt
from datetime import datetime
import h5py

def get_srcnn_model():
    inputs = Input(shape=(None, None, 1))
    conv = Conv2D(128, (9, 9), padding='same', activation='relu')(inputs)
    conv = Conv2D(64, (3, 3), padding='same', activation='relu')(conv)
    outputs = Conv2D(1, (5, 5), padding='same', activation='linear')(conv)

    model = Model(inputs=[inputs], outputs=[outputs])
    # model.compile(optimizer=Adam(lr=0.0003), loss='mean_squared_error')
    model.compile(optimizer='adam', loss='mean_squared_error')

    return model

def get_unet_model():

    img_shape = (None, None, 1)

    inputs = Input(shape=img_shape)

    #64
    conv1 = Conv2D(32, (3, 3), activation='relu', padding='same')(inputs)
    conv1 = Conv2D(32, (3, 3), activation='relu', padding='same')(conv1)
    pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)

    # 32
    conv2 = Conv2D(64, (3, 3), activation='relu', padding='same')(pool1)
    conv2 = Conv2D(64, (3, 3), activation='relu', padding='same')(conv2)
    pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)

    # 16
    conv3 = Conv2D(128, (3, 3), activation='relu', padding='same')(pool2)
    conv3 = Conv2D(128, (3, 3), activation='relu', padding='same')(conv3)
    pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)

    # 8
    conv4 = Conv2D(256, (3, 3), activation='relu', padding='same')(pool3)
    conv4 = Conv2D(256, (3, 3), activation='relu', padding='same')(conv4)
    pool4 = MaxPooling2D(pool_size=(2, 2))(conv4)

    # 4
    conv5 = Conv2D(512, (3, 3), activation='relu', padding='same')(pool4)
    conv5 = Conv2D(512, (3, 3), activation='relu', padding='same')(conv5)

    deconv6 = Conv2DTranspose(256, (2, 2), strides=(2, 2), activation='relu', padding='same')(conv5)
    up6 = Concatenate(axis=-1)([deconv6, conv4])
    conv6 = Conv2D(256, (3, 3), activation='relu', padding='same')(up6)
    conv6 = Conv2D(256, (3, 3), activation='relu', padding='same')(conv6)

    deconv7 = Conv2DTranspose(128, (2, 2), strides=(2, 2), activation='relu', padding='same')(conv6)
    up7 = Concatenate(axis=-1)([deconv7, conv3])
    conv7 = Conv2D(128, (3, 3), activation='relu', padding='same')(up7)
    conv7 = Conv2D(128, (3, 3), activation='relu', padding='same')(conv7)

    deconv8 = Conv2DTranspose(64, (2, 2), strides=(2, 2), activation='relu', padding='same')(conv7)
    up8 = Concatenate(axis=-1)([deconv8, conv2])
    conv8 = Conv2D(64, (3, 3), activation='relu', padding='same')(up8)
    conv8 = Conv2D(64, (3, 3), activation='relu', padding='same')(conv8)

    deconv9 = Conv2DTranspose(32, (2, 2), strides=(2, 2), activation='relu', padding='same')(conv8)
    up9 = Concatenate(axis=-1)([deconv9, conv1])
    conv9 = Conv2D(32, (3, 3), activation='relu', padding='same')(up9)
    conv9 = Conv2D(32, (3, 3), activation='relu', padding='same')(conv9)

    outputs = Conv2D(1, (1, 1), activation='sigmoid')(conv9)

    model = Model(inputs=[inputs], outputs=[outputs])
    model.compile(optimizer='adam', loss='mean_squared_error')

    return model

loss_save_dir = 'weights_loss'
if not os.path.isdir(loss_save_dir):
    os.makedirs(loss_save_dir)

def train():

    # model = get_srcnn_model()
    model = get_unet_model()
    model.summary()

    f_train = h5py.File('../dataset/train.h5', 'r')
    f_val = h5py.File('../dataset/val.h5', 'r')

    data_train, label_train = f_train['data'], f_train['label']
    data_val, label_val = f_val['data'], f_val['label']

    train_on_batch = True

    if train_on_batch:
        f = file(os.path.join(loss_save_dir, 'metrics.csv'), 'w')

        iter_num = 0
        epoches = 10
        batch_size = 128
        save_model_step = 50

        ids_train = np.arange(0, len(data_train))

        for e in range(1, epoches+1):
            print('epoch ' + str(e))
            np.random.shuffle(ids_train)
            ids_train_batchs = np.array_split(ids_train, int((len(data_train)/batch_size) + 1))

            for ids_tr_batch in ids_train_batchs:

                ids_tr_batch = sorted(ids_tr_batch)
                loss_train_batch = model.train_on_batch(data_train[ids_tr_batch], label_train[ids_tr_batch])

                ids_val_batch = sorted(np.random.choice(len(data_val), batch_size, replace=False))
                loss_val_batch = model.test_on_batch(data_val[ids_val_batch], label_val[ids_val_batch])

                iter_num += 1

                print(str(datetime.now())+' iter ' + str(iter_num) + ', loss: ' + str(loss_train_batch) + ', val_loss: ' + str(loss_val_batch))

                metrics = str(iter_num) + ',' + str(loss_train_batch) + ',' + str(loss_val_batch)
                f.write(metrics)
                f.write('\n')
                f.flush()

                if (iter_num % save_model_step) == 0:
                    model.save(os.path.join(loss_save_dir, 'iter_' + str(iter_num) + '.h5'))

        f.close()
    else:
        loss_val_filepath = os.path.join(loss_save_dir, 'val_loss_e_{epoch:02d}_loss_{val_loss:.8f}.h5')
        loss_val_checkpoint = ModelCheckpoint(loss_val_filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='min')

        history = model.fit(data_train[:], label_train[:], batch_size=128, validation_data=(data_val[:], label_val[:]), callbacks=[loss_val_checkpoint], shuffle=True, nb_epoch=200, verbose=1)
        # srcnn_model.load_weights("m_model_adam.h5")

        print(history.history.keys())

        f = file(os.path.join(loss_save_dir, 'metrics.csv'), 'w')
        loss = history.history['loss']
        loss_val = history.history['val_loss']
        for i in range(len(loss)):
            f.write(str(i+1)+','+str(loss[i])+','+str(loss_val[i]))
            f.write('\n')
            f.flush()
        f.close()

    f_train.close()
    f_val.close()

def plot_graph():

    metrics = np.loadtxt(os.path.join(loss_save_dir, 'metrics.csv'), delimiter=',')

    mpl.rcParams['figure.figsize'] = [8.4, 4.8]
    mpl.rcParams['figure.dpi'] = 500
    mpl.rcParams['lines.linewidth'] = 0.7
    mpl.rcParams['axes.linewidth'] = 0.3

    # plot graph loss
    plt.figure('Graph loss')
    plt.title('Loss')
    plt.plot(metrics[:, 1])
    plt.plot(metrics[:, 2])
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.legend(['train', 'val'])
    plt.grid(True, linestyle='--')
    # plt.yticks(np.linspace(0., 0.2, 11))
    # plt.ylim(0., 0.2)
    # plt.xticks(np.linspace(0, 5000, 11))
    # plt.xlim(0, 5000)
    plt.savefig(os.path.join(loss_save_dir, 'graph_history_loss.png'))

if __name__ == "__main__":
    train()
    # plot_graph()


import tweepy;
from tkinter import *;

CONSUMER_KEY = 'consumer key'
CONSUMER_SECRET = 'consumer secrets'
ACCESS_KEY = 'access token'
ACCESS_SECRET = 'access token secret'

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)

user = api.me()
root = Tk()

#Create GUI
label1 = Label(root, text='Key Word')
E1 = Entry(root, bd=5)

label2 = Label(root, text='Tweets Number')
E2 = Entry(root, bd=5)

label3 = Label(root, text='Response')
E3 = Entry(root, bd=5)

label4 = Label(root, text='Reply')
E4 = Entry(root, bd=5)

label5 = Label(root, text='Retweet')
E5 = Entry(root, bd=5)

label6 = Label(root, text='Liked')
E6 = Entry(root, bd=5)

label7 = Label(root, text='Follow')
E7 = Entry(root, bd=5)

def getKeyWord():
    return E1.get()

def getTweetNum():
    return E2.get()

def getResponse():
    return E3.get()

def getReply():
    return E4.get()

def getRetweet():
    return E5.get()

def getLikes():
    return E6.get()

def getFollow():
    return E7.get()

#Follow everyone follow me
for follower in tweepy.Cursor(api.followers).items():
    follower.follow()
    print(f"Followed everyone that is following {user.name}")

#Favorite and retweet based on keyword
def twitterBot():
    search = getKeyWord()
    numberofTweets = int(getTweetNum())
    phrase = getResponse()
    reply = getReply()
    retweet = getRetweet()
    liked = getLikes()
    follow = getFollow()

    if retweet.lower() == 'yes':
        for tweet in tweepy.Cursor(api.search, search).items(numberofTweets):
            try:
                tweet.retweet()
                print('Retweeted')

            except tweepy.TweepError as exception:
                print(exception.reason)

            except StopIteration:
                    break

    if liked.lower() == 'yes':
        for tweet in tweepy.Cursor(api.search, search).items(numberofTweets):
            try:
                tweet.favorite()
                print('Tweet Liked')

            except tweepy.TweepError as exception:
                print(exception.reason)

            except StopIteration:
                    break

    if follow.lower() == 'yes':
        for tweet in tweepy.Cursor(api.search, search).items(numberofTweets):
            try:
                tweet.user.follow()
                print(f'@{tweet.user} followed')

            except tweepy.TweepError as exception:
                print(exception.reason)

            except StopIteration:
                    break

    #reply to user based on keyword
    if reply.lower() == 'yes':
        for tweet in tweepy.Cursor(api.search, search).items(numberofTweets):
            try:
                tweetID = tweet.user.id
                username = tweet.user.screen_name
                api.update_status(f"@ {username} {phrase}", in_reply_to_status_id = tweetID)
                print(f"Replied with {phrase}")

            except tweepy.TweepError as exception:
                print(exception.reason)

            except StopIteration:
                    break

submit = Button(root, text ="Submit", command = twitterBot)

label1.pack()
E1.pack()
label2.pack()
E2.pack()
label3.pack()
E3.pack()
label4.pack()
E4.pack()
label5.pack()
E5.pack()
label6.pack()
E6.pack()
label7.pack()
E7.pack()
submit.pack(side =BOTTOM)
root.mainloop()


import re
import os
import json
import config
from basic_class import table, column

tables = {}
indices = {}

class catalog_manager():
    global tables
    global indices

    def __init__(self):
        if os.path.exists(config.catalog_path):
            self.__load__()

    def create_table(self, t_name, statement):
        # find primary key
        pri_st = re.search('primary key *\(',statement).end()
        pri_ed = re.search('\)',statement[pri_st:]).start()
        primary_key = statement[pri_st:][:pri_ed].strip()

        # replace multiple spaces with single one
        statement = re.sub(' +', ' ', statement).replace('\n', '')
        statement = re.sub('[()]', '', statement)

        # getting attributes info
        atts = [x.strip().split(' ') for x in statement.split(',')]
        atts[0][:] = atts[0][2:]
        # print(atts)
        colu = []
        for attr in atts[:-1]:
            u = False
            name = attr[0]
            length = 0
            d_type = 'c'

            if "unique" in attr or primary_key in attr:
                u = True

            if "int" in attr[1]:
                d_type = 'i'
            elif "float" in attr[1]:
                d_type = 'f'
            elif "char"  in attr[1]:
                d_type = 'c'
                length = int(attr[1][4:])
            else:
                raise NameError("Catalog Module : Unknow datatype ", attr[1])

            colu.append(column(name, u, d_type, length))

        primary = -1
        for i, col in enumerate(colu):
            if primary_key == col.name:
                primary = i
                break

        if primary == -1:
            raise ValueError("Catalog Module : Primary Key, no such attribute ", primary_key)
        else:
            global tables
            tables[t_name] = table(t_name, colu, primary)
            # print(tables)

    def drop_table(self, table):
        tables.pop(table)

    def create_index(self, index_name, t_name, column):
        col_i = tables[t_name].get_index(column)

        if not tables[t_name].attributes[col_i].is_unique:
            raise ValueError("Catalog Module : Create index failed, {} is not unique".format(column))

        indices[index_name] = { "table" : t_name, "column" : col_i }

    def drop_index(self, index):
        indices.pop(index)

    def __store__(self):
        _tables = {}
        for t in tables.items():
            _def = {}
            _def["pri_k"] = t[1].primary
            _columns = {}
            for i in t[1].attributes:
                _columns[i.name] = (i.is_unique, i.d_type, i.length)

            _def["columns"] = _columns
            _tables[t[0]] = _def

        with open(config.catalog_path + "tables.json", "w") as f:
            f.writelines(json.dumps(_tables, indent=2))

        with open(config.catalog_path + "indices.json", "w") as f:
            global indices
            f.writelines(json.dumps(indices, indent=2))

    @staticmethod
    def __load__():

        with open(config.catalog_path + "tables.json", "r") as f:
            t = json.load(f)
            for tab in t.items():
                _table = table(tab[0], tab[1]["pri_k"])

                colu = []
                for _column in tab[1]["columns"].items():
                    colu.append(column(_column[0], _column[1][0], _column[1][1], _column[1][2]))

                _table.attributes = colu
                tables[tab[0]] = _table

        with open(config.catalog_path + "indices.json", "r") as f:
            i = json.load(f)
            for ind in i.items():
                indices[ind[0]] = ind[1]

    def select_check(self, _table, conditions, cols):
        # Check the attributes in SELECT clause
        # Where
        columns = [c.name for c in tables[_table].attributes]
        if conditions != '':
            lists = re.sub('and|or', ',', conditions).split(',')
            for i in lists:
                col_name = i.strip().split(' ')[0]
                if col_name not in columns:
                    raise AttributeError("Catalog Module : no such column {}".format(col_name))

        # Project
        if cols != '*':
            for i in cols.split(','):
                if i.strip() not in columns:
                    raise AttributeError("Catalog Module : no such column {}".format(col_name))

    def insert_check(self, _table, values):
        tab = tables[_table]
        if len(tab.attributes) != len(values):
            raise ValueError("Catalog Module : table '%s' has %d atts" % (_table, len(tab.attributes)))

        for i, att in enumerate(tab.attributes):

            if att.d_type == 'c' and len(values[i]) > att.length:
                raise ValueError("Catalog Module : table '{}' : column '{}' 's length "
                                 "can't be longer than {}.".format(_table, att.name, att.length))

            if att.is_unique:
                if att.d_type == 'i': value = int(values[i])

                elif att.d_type == 'f': value = float(values[i])

                else: value = values[i]

                # api.index_manager.check_unique(_table, i, value)

    def exist_table(self, _table, t):
        # check whether the table exists, and raise error according to 't'
        # t = True: check table duplication
        # t = False: check table existence
        global tables
        if _table in tables.keys() and t:
            raise ValueError("Catalog Module : table {} already exists".format(_table))

        elif _table not in tables.keys() and not t:
            raise ValueError("Catalog Module : table {} not exists".format(_table))

    def exist_index(self, _index, t_name="", column="", t=False):
        # check whether the table exists, and raise error according to 't'
        # t = True: check table duplication
        # t = False: check table existence
        if t:
            col_i = tables[t_name].get_index(column)

            for ind in indices.values():
                if col_i == ind["column"] and t_name == ind["table"]:
                    raise ValueError("Catalog Module : duplicate create, index {} already exists".format(ind))

        if _index in indices.keys() and t:
            raise ValueError("Catalog Module : index {} already exists".format(_index))

        elif _index not in indices.keys() and not t:
            raise ValueError("Catalog Module : index {} not exists".format(_index))

    def __finalize__(self):
        self.__store__()

if "__name__" == "__main__":
    statement = "table student (\
                sno char(8),\
                sname char(16) unique,\
                sage int,\
                sgender char(1),\
                primary key(sno)\
                );"

    a = catalog_manager()
    a.create_table(statement)
    print(tables)


import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

sns.set_style("ticks")
sns.set_palette("husl")

fig = plt.figure(1, figsize=(8,8))
fig.clf()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)

for pext in [100, 10, 0, -10, -100]:
	p = np.loadtxt("single-artery-pext-%s_results/A1_P.last" % (pext))
	q = np.loadtxt("single-artery-pext-%s_results/A1_Q.last" % (pext))
	a = np.loadtxt("single-artery-pext-%s_results/A1_A.last" % (pext))
	u = np.loadtxt("single-artery-pext-%s_results/A1_u.last" % (pext))

	ax1.plot(p[:,0], p[:,3]/133.332, label=pext)
	ax2.plot(q[:,0], q[:,3]*1e6)
	ax3.plot(a[:,0], np.sqrt(a[:,3]/np.pi)*1e3)
	ax4.plot(u[:,0], u[:,3])

ax1.set_xlabel("time (s)")
ax2.set_xlabel("time (s)")
ax3.set_xlabel("time (s)")
ax4.set_xlabel("time (s)")

ax1.set_ylabel("pressure (mmHg)")
ax2.set_ylabel("flow (ml/s)")
ax3.set_ylabel("lumen radius (mm)")
ax4.set_ylabel("velocity (m/s)")

ax1.legend(loc="best")

plt.tight_layout()

sns.despine()

plt.draw()
plt.show()


from distutils.core import setup

with open('requirements.txt') as req:
    content = req.readlines()

setup(
  name = 'djsw_wrapper',
  packages = ['djsw_wrapper'],
  version = '0.2.3.1',
  description = 'Allows to build REST API directly from Swagger schema',
  author = 'Alex Revin',
  author_email = 'lyssdod@gmail.com',
  url = 'https://github.com/ErintLabs/django-openapi-gen',
  download_url = 'https://github.com/ErintLabs/django-openapi-gen/archive/0.2.3.1.tar.gz',
  install_requires = [x.strip() for x in content],
  keywords = ['django', 'swagger', 'schema', 'django-rest-framework'],
  classifiers = [],
)


from flask import Flask, request, render_template, url_for
from database import fetch_all, fetch_id, add_element, delete_element, update_element, update_status
from datetime import datetime
app = Flask(__name__)

#RENDER HOME PAGE
@app.route("/")
def index():
    return render_template("index.html")

#FETCHS ALL CUSTOMERS/ORDERS DATA FROM DATABASE
@app.route("/fetch", methods=['post', 'get'])

def fetch():
    table = request.form.get('table-type')
    ids = request.form.get('search-bar')

    if ids:
        data = fetch_id(table, ids)
    else:
        data = fetch_all(table)

    return render_template("index.html", table=table, data=data, ids=ids)

#REDIRECTS TO CREATE NEW CUSTOMER PAGE
@app.route('/create-customer')
def customer_page():
    return render_template('create-customer.html')

#REDIRECTS TO CREATE NEW ORDER PAGE
@app.route('/create-order')
def order_page():
    return render_template('create-order.html')

#CREATES A NEW CUSTOMER
@app.route('/create-customer/<customers>/', methods=['POST'])
def create_customer(customers):

    name = request.form.get('name')
    address = request.form.get('address')
    phone = request.form.get('customer_phone')
    country = request.form.get('country')
    email = request.form.get('customer_email')

    customer_info = [name, address, phone, country, email]

    add_element(customers, customer_info)

    return render_template('index.html', table='customers')

#CREATES A NEW GLASS ORDER
@app.route('/create-order/<orders>/', methods=['POST'])
def create_order(orders):

    customer_id = request.form.get('customer_id')
    glass_config = request.form.get('glass_config')
    order_status = 'requested'

    orders_info = [customer_id, glass_config, order_status]

    add_element(orders, orders_info)

    return render_template('index.html', table='customers')

#DELETES A RECORD FROM THE DATABASE
@app.route('/delete', methods=['POST'])
def delete():

    table = request.form.get('table-delete')
    customer_id = request.form.get('id-delete')

    delete_element(table, customer_id)

    return render_template('index.html', table='customers')

#REDIRECTS TO UPDATE CUSTOMERS PAGE
@app.route('/update', methods=['get'])
def update():

    return render_template('update-customer.html')

#RETRIEVES CUSTOMER DATA TO UPDATE
@app.route('/update/fetch', methods=['post'])
def fetch_customer_info():

    table = 'customers'
    ids = request.form.get('customer_id_upd')

    data = fetch_id(table, ids)

    return render_template('update-customer.html', data=data, ids=ids)

#UPDATES CUSTOMER DATA
@app.route('/update/record', methods=['POST'])
def update_userInfo():
    ids = request.form.get('customer_id')
    name = request.form.get('name')
    address = request.form.get('address')
    phone = request.form.get('customer_phone')
    country = request.form.get('country')
    email = request.form.get('customer_email')

    customer_info = [name, address, phone, country, email]

    update_element('customers', customer_info, ids)

    return render_template('index.html')

#UPDATES ORDER STATUS
@app.route('/update-order', methods=['POST'])
def update_order_status():
    ids = request.form.get('id-order')
    order_status = request.form.get('new-status')

    update_status(order_status, ids)

    return render_template('index.html')

if __name__ == '__main__':
    app.run()


import click
import yaml
import os

def write_head(file):
    pass

def appendValue(values, base_value=""):
    string = ""
    if isinstance(values, dict):
        itr = values.items()
        islist = False
    elif isinstance(values, list):
        itr = enumerate(values)
        islist = True

    for item, value in itr:
        if isinstance(values[item], dict) and values[item] is not {}:
            if islist:
                string += appendValue(values[item], base_value=f"{base_value}[{item}].")
            else:
                string += appendValue(values[item], base_value=f"{base_value}{item}.")
        elif isinstance(values[item], list) and len(values[item]) > 0:
            string += appendValue(values[item], base_value=f"{base_value}{item}")
        else:
            if values[item] == "":
                values[item] = '""'
            string += f" {base_value}{item} | ... | `{values[item]}` \n"
    return string

@click.command()
@click.argument("chart", type=click.Path(exists=True))
@click.option("-o", "--output", default="README.md", show_default=True)
def cli(chart, output):
    values_path = os.path.join(chart, "values.yaml")
    if not os.path.isfile(values_path):
        raise click.BadParameter(
            "There is no values.yaml in this folder", param=chart, param_hint="INPUT"
        )

    with open(values_path, "r") as values_file:
        values = yaml.load(values_file, Loader=yaml.FullLoader)

    val = """
Parameter | Description | Default
--- | --- | ---
"""
    val += appendValue(values)

    click.echo(val)


import ogre.renderer.OGRE as ogre
import math

class Scrubber:
    def __init__(self, scrubberNum, engine, pos = ogre.Vector3(0, 0, 0)):
        self.default = ogre.Vector3(10000, 10000, 10000) #Vector
        self.position = pos
        self.sceneManager = engine.gfxMgr.sceneManager
        self.engine = engine
        self.velocity = ogre.Vector3(0, 0, 0)
        self.node = ''
        self.area = 0
        self.playerMoved = False
        self.move = False
        self.heading = 0
        self.scrubVelFactor = 40
        self.scrubEntity = "Scrubber" + str(scrubberNum) #Need a number passed in to create the right entity.
        self.mesh = "scrubberFinalOriented.mesh"
        self.scaleFactor = 5
        self.velocity = ogre.Vector3(0,0,0)
        self.stopPosOne = ogre.Vector3(0, 0, 0)
        self.stopPosTwo = ogre.Vector3(0, 0, 0)
        self.oneTwoDirection = False
        self.inProgressMovement = False
        self.tempPos = ogre.Vector3(0, 0, 0)
        self.playerCollideCounter = 0

        #Bounding Box Points
        self.point1 = ogre.Vector3(0, 0, 0)
        self.point2 = ogre.Vector3(0, 0, 0)
        self.point3 = ogre.Vector3(0, 0, 0)
        self.point4 = ogre.Vector3(0, 0, 0)
        self.defualtHeight = 3
        self.init()
        pass

    def init(self):
        self.ent = self.sceneManager.createEntity(self.scrubEntity, self.mesh)
        node = self.sceneManager.getRootSceneNode().createChildSceneNode(self.scrubEntity + 'node', self.position)
        node.attachObject(self.ent)
        self.node = node
        self.node.scale(self.scaleFactor, self.scaleFactor, self.scaleFactor)
        #print "Generated a scrubber at:" + str(self.position)
        pass

    def reset(self):
        self.position = self.default
        self.move = False
        pass

    def playerCollideCheck(self):
        self.boolPoint1 = self.inAreaScruber(self.engine.gameMgr.player.point1)
        self.boolPoint2 = self.inAreaScruber(self.engine.gameMgr.player.point2)
        self.boolPoint3 = self.inAreaScruber(self.engine.gameMgr.player.point3)
        self.boolPoint4 = self.inAreaScruber(self.engine.gameMgr.player.point4)

        if self.boolPoint1 or self.boolPoint2 or self.boolPoint3 or self.boolPoint4:
            return True
        else:
            return False

    def moveSet(self, pos = ogre.Vector3(0, 0, 0)):
        self.velocityTemp = ogre.Vector3(0, 0, 0)
        #print "Printing TempPos: " + str(self.tempPos)

        if (self.playerMoved == True and self.move == False):
            if(self.collide(ogre.Vector3(self.position.x + 50, self.position.y, self.position.z)) == True):
                self.tempPos = ogre.Vector3(self.position.x + 50, self.position.y, self.position.z)
                self.heading = math.radians(0)
                self.move = True
            elif(self.collide(ogre.Vector3(self.position.x - 50, self.position.y, self.position.z)) == True):
                self.tempPos = ogre.Vector3(self.position.x - 50, self.position.y, self.position.z)
                self.heading = math.radians(180)
                self.move = True
            elif(self.collide(ogre.Vector3(self.position.x, self.position.y, self.position.z + 50)) == True):
                self.tempPos = ogre.Vector3(self.position.x, self.position.y, self.position.z + 50)
                self.heading = math.radians(270)
                self.move = True
            elif(self.collide(ogre.Vector3(self.position.x, self.position.y, self.position.z - 50)) == True):
                self.tempPos = ogre.Vector3(self.position.x, self.position.y, self.position.z - 50)
                self.heading = math.radians(90)
                self.move = True
        elif(self.playerMoved == True and self.move == True):
            self.node.resetOrientation()
            self.node.yaw(self.heading)
            self.speed = self.scrubVelFactor
            self.velocityTemp.x = math.cos(-self.heading) * self.speed
            self.velocityTemp.z = math.sin(-self.heading) * self.speed
            self.velocity = ogre.Vector3(self.velocityTemp.x, 0, self.velocityTemp.z)
            self.testPosx = math.fabs(self.position.x - self.tempPos.x)
            self.testPosz = math.fabs(self.position.z - self.tempPos.z)
            if(self.collide(self.position) == False):
                self.move = False
        pass

    def tick(self, dt):
        self.scrubCalcBound()
        self.moveSet()
        self.position = self.position + self.velocity * dt
        self.node.position = self.position

        self.projectDistance = math.sqrt(pow((self.engine.gameMgr.player.pos.x - self.position.x),2) + pow((self.engine.gameMgr.player.pos.z - self.position.z), 2))

        #pow((self.engine.gameMgr.player.pos.y - self.projectilePos.y),2)

        if(self.playerCollideCheck() == True or self.projectDistance <= 10):
            self.velocityTemp = ogre.Vector3(0, 0, 0)
            self.velocityTemp.x = math.cos(-self.engine.gameMgr.player.heading) * -3000
            self.velocityTemp.z = math.sin(-self.engine.gameMgr.player.heading) * -3000
            self.engine.gameMgr.player.vel = ogre.Vector3(self.velocityTemp.x, self.engine.gameMgr.player.vel.y, self.velocityTemp.z)
            self.playerCollideCounter = 10

        if(self.playerCollideCounter > 0):
            self.playerCollideCounter -= 1

    def scrubCalcBound(self):
        self.depth = 40
        self.width = 40
        self.point1 = ogre.Vector3(self.position.x + self.width, self.position.y + 30, self.position.z)
        self.point2 = ogre.Vector3(self.position.x, self.position.y + 30, self.position.z - self.depth)
        self.point3 = ogre.Vector3(self.position.x - self.width, self.position.y + 30, self.position.z)
        self.point4 = ogre.Vector3(self.position.x, self.position.y + 30, self.position.z + self.depth)

    def inAreaScruber(self, checkVect = ogre.Vector3(0, 0, 0)): #checkVect can be the position of the player.
        if(checkVect.x >= self.point3.x):
            if(checkVect.x <= self.point1.x):
                if(checkVect.z <= self.point4.z):
                    if(checkVect.z >= self.point2.z):
                        return True
        return False

    def collide(self, checkPos):
        self.index = len(self.engine.entityMgr.platEntList)
        for self.counter in range(0, self.index):
            self.boolPos = self.engine.entityMgr.platEntList[self.counter].inAreaPlatScrub(checkPos)
            self.bool1 = self.engine.entityMgr.platEntList[self.counter].inAreaPlatScrub(checkPos)
            self.bool2 = self.engine.entityMgr.platEntList[self.counter].inAreaPlatScrub(checkPos)
            self.bool3 = self.engine.entityMgr.platEntList[self.counter].inAreaPlatScrub(checkPos)
            self.bool4 = self.engine.entityMgr.platEntList[self.counter].inAreaPlatScrub(checkPos)

            if self.boolPos and self.bool1 and self.bool2 and self.bool3 and self.bool4:
                return True
        return False


from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from django.conf import settings

urlpatterns = patterns('wizardcms.views',
        url(r'search/(.+)/$', 'default.global_search', name='wizardcms-globalsearch'),
        url(r'search/?P<keyword>(.+)/$', 'default.global_search', name='wizardcms-globalsearch'),
        url(r'search/$', 'default.global_search', name='wizardcms-globalsearch'),
        url(r'page/(\d+).html$', 'pages.show', name='wizardcms-page-view'),
        url(r'page/(\d+),([a-z0-9-]+).html$', 'pages.show', name='wizardcms-page-view'),
        url(r'(?P<slug>[a-z]+[a-z0-9-\/]+).html$', 'pages.viewslug', name='wizardcms-page-view'),
        url(r'([a-z]+[a-z0-9-]+)/$', 'pages.listslug', name='wizardcms-page-list'),
        url(r'pages/(\d+)/$', 'pages.list', name='wizardcms-page-list'),
        url(r'^$', direct_to_template, kwargs=dict(template='wizardcms/index.html'), name='wizardcms-homepage'),
        )