bl_info = {
    "name": "Rigging Tools",
    "author": "Wayne Wu",
    "version": (2, 3, 1),
    "blender": (2, 75, 0),
    "location": "View3D > Tools",
    "description": "Rigging Tools",
    "warning": "The addon still in progress! Make a backup!",
    "wiki_url": "https://tangentanimation.sharepoint.com/wiki/Pages/Rigging%20Tool.aspx",
    "category": "Tangent"}

import bpy
from bpy.types import Panel, Operator, PropertyGroup
import bone_tools
import mesh_tools

class ArmatureLayerGUI(Panel):
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'TOOLS'
    bl_category = 'TA - Rigging'
    bl_label = "Armature Layers"

    @classmethod
    def poll(cls, context):
        return context.object and context.object.type == 'ARMATURE'

    def draw(self, context):
        layout = self.layout

        arm = context.active_object.data
        layout.prop(arm, "pose_position", expand=True)

        col = layout.column()
        col.label(text="Layers:")
        col.prop(arm, "layers", text="")
        col.label(text="Protected Layers:")
        col.prop(arm, "layers_protected", text="")

class ExceptionsProperty(PropertyGroup):
    """
    A property class for exception
    """
    exception = bpy.props.StringProperty(name="Exception", default = "")
    index = bpy.props.IntProperty(name="Index")

class BONE_ToolProperty(PropertyGroup):
    bpy.types.Object.bone_change_prefix = bpy.props.BoolProperty(name = "Change Prefix", description= "Check this to allow changing the prefix of the bones", default = False)
    bpy.types.Object.bone_old_prefix = bpy.props.StringProperty(name = "Old Prefix", default = "ctl.")
    bpy.types.Object.bone_new_prefix = bpy.props.StringProperty(name = "New Prefix", default = "acc.")
    bpy.types.Object.bone_new_scale = bpy.props.FloatProperty(name = "Scale", default = 1.5)
    bpy.types.Object.boneshape_apply = bpy.props.BoolProperty(name = "Assign", description ="Assign bone shape if selected, otherwise will remove bone shape for the selected bones", default = False)
    bpy.types.Object.bone_show_wireframe = bpy.props.BoolProperty(name = "Wireframe", description = "Bone is drawn as wireframe", default = True)
    bpy.types.Object.boneshape_shape_name = bpy.props.StringProperty(name = "Shape name")
    try:
        bpy.utils.register_class(ExceptionsProperty) #Need to find a way around this
    except:
        pass
    bpy.types.Object.bone_exceptions = bpy.props.CollectionProperty(type = ExceptionsProperty)
    bpy.types.Object.bone_deform_enable = bpy.props.BoolProperty(name = "Enable", description = "Will enable deform for selected bones if checked, otherwise will remove", default = False)
    bpy.types.Object.bone_source = bpy.props.StringProperty(name = "Source Bone")
    bpy.types.Object.bone_stretch_volume = bpy.props.EnumProperty(
        items = [('VOLUME_XZX', 'XZX', "volume_xzx"), ('VOLUME_X', "X", "volume_x"),('VOLUME_Z','Z', "volume_z"), ('NO_VOLUME','NO VOLUME', "no_volume")],
        name = "Stretch To Volume"
        )

class BONE_ToolsGUI(Panel):
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'TOOLS'
    bl_category = 'TA - Rigging'
    bl_label = "Bone Tools"

    @classmethod
    def poll(cls, context):
        return context.object and context.object.type == 'ARMATURE'

    def draw(self, context):
        layout = self.layout
        col = layout.column()

        ################################BOX1#########################
        row = col.row(align = True)
        box = row.box()
        row = box.row(align = True)
        col2 = row.column(align = True)
        row = col2.row(align = True)
        row.label("Bone Attributes (Based on Selection)")
        row = col2.row(align = True)
        row.operator("object.bone_lock", text = "Lock", icon = 'LOCKED')
        row.operator("object.bone_unlock", text = "Unlock", icon = 'UNLOCKED')
        row = col2.row(align = True)
        row.operator("object.bone_flip", text = "Flip", icon = 'FULLSCREEN_ENTER' )
        row.operator("object.bone_set_xzy", text = "Set XZY", icon = 'NDOF_TURN')

        row = box.row(align = True)
        row.alignment = 'LEFT'
        row.prop(context.object, "bone_deform_enable")
        if bpy.context.object.bone_deform_enable:
            row.operator("object.bone_deform", text = "Enable Deform", icon = 'ZOOMIN')
        else:
            row.operator("object.bone_deform", text = "Remove Deform", icon = 'X')
        row = box.row(align = True)
        col2 = row.column(align = False)
        i = 0
        while i < len(bpy.context.object.bone_exceptions):
            col2.prop(context.object.bone_exceptions[i], "exception", icon = 'GROUP_BONE')
            i = i + 1 #First Exception
        row = col2.row(align = True)
        row.operator("object.add_bone_exception", text="Add Exception")
        row.operator("object.remove_bone_exception", text = "", icon = "X")

        ###################################BOX2##########################
        row = col.row(align = True)
        box = row.box()
        col2 = box.column()
        row = col2.row()
        row.label("Bone Parenting (Based on Selection)")
        row = col2.row(align = True)
        row.prop(context.object, "bone_change_prefix")
        if bpy.context.object.bone_change_prefix:
            row = col2.row(align = True)
            row.prop(context.object, "bone_old_prefix" )
            row = col2.row(align = True)
            row.prop(context.object, "bone_new_prefix")
        row = col2.row(align = True)
        row.prop(context.object, "bone_new_scale")
        row = col2.row(align = True)
        row.operator("object.parent_bones", text = "Create Parent Bones", icon = 'CONSTRAINT_BONE')
        row = col2.row()
        row.separator()
        #Section 3
        row = col2.row()
        row.label("Bone Shape (Based on Selection)")
        row = col2.row(align = True)
        row.prop(context.object, "boneshape_apply")
        if bpy.context.object.boneshape_apply:
            row.prop(context.object, "bone_show_wireframe")
            row = col2.row(align = True)
            row.prop_search(context.object, "boneshape_shape_name", bpy.context.scene, 'objects', text = "Shape", icon = 'OBJECT_DATA')
        row = col2.row(align = True)
        if bpy.context.object.boneshape_apply:
            row.operator("object.bone_shape", text = "Assign Bone Shape", icon = 'ZOOMIN' )
        else:
            row.operator("object.bone_shape", text = "Remove Bone Shape", icon = 'X')

        #####################################BOX3###############################
        row = col.row()
        box = row.box()
        col2 = box.column(align = True)
        col2.label("Bone Constraints (Based on Selection)")
        row = col2.row(align = True)
        row.alignment = 'EXPAND'
        row.label(icon = 'CONSTRAINT_BONE')
        row.operator("object.mute_bone_constraints", text = "Mute", icon = "RESTRICT_VIEW_ON")
        row.operator("object.unmute_bone_constraints", text = "Unmute", icon = "RESTRICT_VIEW_OFF")
        col2 = box.column()
        col2.label(text="Stretch To")
        row = col2.row(align = True)
        row.label(text ="RESET")
        row.operator("object.reset_stretch_all", text = "All")
        row.operator("object.reset_stretch_selected", text = "Selected")
        row = col2.row(align = True)
        row.alignment = 'EXPAND'
        row.prop_menu_enum(context.object, "bone_stretch_volume", text = bpy.context.object.bone_stretch_volume)
        #row.prop(context.object, "bone_stretch_volume")
        row.operator("object.stretch_volume_change_all", text = "All")
        row.operator("object.stretch_volume_change_selected", text = "Selected")
        row = col.row()

        ########################################BOX4#############################
        if bpy.context.selected_pose_bones:
            row = col.row(align = False)
            box = row.box()
            box.prop_search(context.object, "bone_source", bpy.context.object.pose, 'bones', text="Source", icon = 'BONE_DATA')
            box.operator("object.copy_driver", text = "Copy Constraint Drivers", icon = "GHOST")

class BONE_AddException(Operator):
    bl_idname = "object.add_bone_exception"
    bl_description = "Add exception"
    bl_label = "Add_Exception"
    bl_options = {'UNDO'}

    def invoke(self, context, event):
        new_exception = bpy.context.object.bone_exceptions.add()
        i = len(bpy.context.object.bone_exceptions) - 1
        new_exception.index = i
        return{'FINISHED'}

class BONE_RemoveException(Operator):
    bl_idname = "object.remove_bone_exception"
    bl_description = "Remove the last exception"
    bl_label = "Remove Exception"
    bl_options = {'UNDO'}

    def invoke(self, context, event):
        index = len(bpy.context.object.bone_exceptions) - 1
        bpy.context.object.bone_exceptions.remove(index)
        return{'FINISHED'}

class BONE_Flip(Operator):
    bl_idname = "object.bone_flip"
    bl_label = "Flip Bones"
    bl_description = "Flip the selected bones head to tail, tail to head"
    bl_option = {'UNDO'}
    def invoke (self, context, event):
        bone_tools.bone_flip(compile_bone_exceptions())
        return {'FINISHED'}

class BONE_Deform(Operator):
    bl_idname = "object.bone_deform"
    bl_label = "Enable Deform Bone to selected"
    bl_description = "Enable/Disable Bone Deform for the selected bones"
    bl_option = {'UNDO'}

    @classmethod
    def poll(cls, context):
        return bpy.context.selected_pose_bones

    def invoke (self, context, event):
        if bpy.context.active_object.mode != 'POSE':
            bpy.ops.object.mode_set(mode='POSE')

        for item in bpy.context.selected_pose_bones:
            if not item.name.startswith(compile_bone_exceptions()):
                if bpy.context.object.bone_deform_enable:
                    item.bone.use_deform = True
                else:
                    item.bone.use_deform = False

        return {'FINISHED'}

class BONE_Lock(Operator):
    bl_idname = "object.bone_lock"
    bl_label = "Lock Bone Transformations"
    bl_description = "Lock the transformations of the selected bones"
    bl_option = {'UNDO'}

    def invoke (self, context, event):
        bone_tools.bone_lock(compile_bone_exceptions(), True)
        return {'FINISHED'}

class BONE_Unlock(Operator):
    bl_idname = "object.bone_unlock"
    bl_label = "Unlock Bone Transformations"
    bl_description = "Unlock the transformations of the selected bones"
    bl_option = {'UNDO'}

    def invoke (self, context, event):
        bone_tools.bone_lock(compile_bone_exceptions(), False)
        return {'FINISHED'}

class BONE_Parenting(Operator):
    bl_idname = "object.parent_bones"
    bl_label = "Parent_Bone"
    bl_description = "Create a parented bones at the same spot with given scale"
    bl_option = {'UNDO'}

    def invoke (self, context, event):
        obj = bpy.context.object
        bone_tools.bone_parenting(obj.bone_change_prefix, obj.bone_new_prefix, obj.bone_old_prefix, obj.bone_new_scale)
        return {'FINISHED'}

class BONE_Shape(Operator):
    bl_idname = "object.bone_shape"
    bl_label = "Remove_Assign_BoneShape"
    bl_description = "Assign/Remove Custom Bone Shape to selected bones"
    bl_option = {'UNDO'}

    def invoke (self, context, event):
        shape_name = bpy.context.object.boneshape_shape_name
        if bpy.context.object.boneshape_apply:
            if not shape_name:
                self.report({'ERROR'}, "No Shape Name Entered")
            else:
                bone_tools.bone_shape(shape_name, bpy.context.object.bone_show_wireframe)
        else:
            bone_tools.bone_shape()
        return {'FINISHED'}

class BONE_SetXZY(Operator):
    bl_idname = "object.bone_set_xzy"
    bl_label = "Set_XZY"
    bl_description = "Set rotation mode to XZY for all bones in the selected objects"
    bl_option = {'UNDO'}

    def invoke (self, context, event):

        for item in bpy.context.object.pose.bones:
            if not item.name.startswith(compile_bone_exceptions()):
                item.rotation_mode = 'XZY'
        return {'FINISHED'}

class BONE_MuteConstraints(Operator):

    bl_idname = "object.mute_bone_constraints"
    bl_label = "Mute_Bone_Constraints"
    bl_description = "Mute constraints on the selected bone"
    bl_option = {'UNDO'}

    def invoke (self, context, event):
        bone_tools.mute_bone_constraint(True)
        return {'FINISHED'}

class BONE_UnmuteConstraints(Operator):

    bl_idname = "object.unmute_bone_constraints"
    bl_label = "Unmute_Bone_Constraints"
    bl_description = "Unmute constraints on the selected bone"
    bl_option = {'UNDO'}

    def invoke (self, context, event):
        bone_tools.mute_bone_constraint(False)
        return {'FINISHED'}

class BONE_CopyConstraintDriver(Operator):
    bl_idname = "object.copy_driver"
    bl_label = "Copy Drivers after copying constraints"
    bl_description = "Copy source bone's constraint drivers to selected bones"
    bl_option = {'UNDO'}

    @classmethod
    def poll(cls, context):
        return bpy.context.object.bone_source

    def invoke (self, context, event):
        bone_tools.copy_driver(bpy.context.object.bone_source)
        return {'FINISHED'}

class BONE_ResetStretchAll(Operator):
    bl_idname = "object.reset_stretch_all"
    bl_label = "Reset_Stretch_All"
    bl_description = "Reset stretch to constraint to all pose bones"
    bl_option = {'UNDO'}

    def invoke (self, context, event):
        bone_tools.reset_stretch_constraint('ALL')
        return {'FINISHED'}

class BONE_ResetStretchSelected(Operator):
    bl_idname = "object.reset_stretch_selected"
    bl_label = "Reset Stretch Selected"
    bl_description = "Reset stretch to constraint to selected pose bones"
    bl_option = {'UNDO'}

    @classmethod
    def poll(cls, context):
        return context.selected_pose_bones

    def invoke (self, context, event):
        bone_tools.reset_stretch_constraint()
        return {'FINISHED'}

class BONE_StretchVolumeChangeAll(Operator):
    bl_idname = "object.stretch_volume_change_all"
    bl_label = "Stretch_Volume_Change_All"
    bl_description = "Change Stretch To Constriant's Volume to all bones"
    bl_option = {'UNDO'}

    def invoke (self, context, event):
        bone_tools.change_stretch_volume(bpy.context.object.bone_stretch_volume,'ALL')
        return {'FINISHED'}

class BONE_StretchVolumeChangeSelected(Operator):
    bl_idname = "object.stretch_volume_change_selected"
    bl_label = "Stretch_Volume_Change_Selected"
    bl_description = "Change Stretch To Constriant's Volume to selected bones"
    bl_option = {'UNDO'}

    @classmethod
    def poll(cls, context):
        return context.selected_pose_bones

    def invoke (self, context, event):
        bone_tools.change_stretch_volume(bpy.context.object.bone_stretch_volume)
        return {'FINISHED'}

class Mesh_ToolsProperties(PropertyGroup):
    class DriverSettings(PropertyGroup):
        driver_target = bpy.props.StringProperty(name = "Driver Target")
        driver_target_datapath = bpy.props.StringProperty(name = "Driver Target Datapath")
        driver_subtarget = bpy.props.StringProperty(name = "Driver Target Subtarget")
        driver_datapath = bpy.props.StringProperty(name = "Datapath")
        driver_expression = bpy.props.StringProperty(name = "Expression", default = "-var+1")

    try:
        bpy.utils.register_class(DriverSettings)
    except: pass

    bpy.types.Scene.driver_settings = bpy.props.PointerProperty(type = DriverSettings)

class MESH_ToolsGUI(Panel):
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'TOOLS'
    bl_category = 'TA - Rigging'
    bl_label = "Mesh Tools"

    #*TODO Create a pointer property to point to these
    bpy.types.Object.weight_mirror_side = bpy.props.EnumProperty(
        items = [('LEFT', 'L', "left"), ('RIGHT', 'R', "right")],
        name = "Source Side"
        )

    def draw(self, context):
        layout = self.layout
        col = layout.column()
        row = col.row(align = True)
        row.label(text="Modifiers")

        row = col.row(align = True)
        row.operator("object.mesh_remove_modifiers", text = "Remove Modifiers", icon = "X")

        row = col.row(align = True)
        row.operator("object.mesh_add_dummy", text = "Add Dummy Modifier", icon = "POSE_DATA")
        row = col.row(align = True)
        row.operator("object.lock_transformations", text = "Transformation", icon = 'LOCKED').lock = True
        row.operator("object.lock_transformations", text = "Transformation", icon = 'UNLOCKED').lock = False
        row = col.row(align = True)
        row.label(text="Vertex Groups")
        row = col.row()
        row.label("Source Side:")
        row.prop(context.object, "weight_mirror_side", text = "Source Side", expand = True)
        row = col.row()
        row.operator("object.weight_mirror", text = "Weight Mirror", icon = 'WPAINT_HLT')
        row = col.row() #Small Gap

        box = col.box()
        col2 = box.column(align = True)
        col2.label(text="Cycles Render")
        row = col2.row(align = True)
        row.alignment = 'LEFT'
        row.label(text="Ray Visibility", icon = "SEQ_CHROMA_SCOPE")
        row.operator("object.ray_viz_on", text = "ON")
        row.operator("object.ray_viz_off", text = "OFF")

        row = col.row()
        box = row.box()
        row = box.row()
        col2 = row.column(align = True)
        col2.label("Create Driver: Target")
        col2.prop_search(context.scene.driver_settings, "driver_target", context.scene, "objects", text = "Object", icon = 'OBJECT_DATA')
        if context.scene.driver_settings.driver_target:
            obj = context.scene.objects[context.scene.driver_settings.driver_target]
            if obj.type == 'ARMATURE':
                col2.prop_search(context.scene.driver_settings, "driver_subtarget", obj.pose, "bones", text = "Bone", icon = 'BONE_DATA')
            col2.prop(context.scene.driver_settings, "driver_target_datapath", text = "Datapath", icon = 'RNA')
            col2.prop(context.scene.driver_settings, "driver_expression", text = "Expression")
        row = box.row(align = True)
        row.prop(context.scene.driver_settings, "driver_datapath", text = "Datapath", icon = 'RNA')
        row.operator("object.create_driver", text = "Create Driver", icon = 'ZOOMIN')

class MESH_RemoveModifiers(Operator):
    bl_idname = "object.mesh_remove_modifiers"
    bl_label = "Remove the modifiers and particle systems"
    bl_description = "Remove all modifiers and all particle systems"
    bl_option = {'UNDO'}

    @classmethod
    def poll(cls, context):
        return context.object and context.object.type == 'MESH'

    def invoke (self, context, event):
        mesh_tools.remove_modifiers()
        return {'FINISHED'}

class MESH_LockTransformation(Operator):
    bl_idname = "object.lock_transformations"
    bl_label = "lock_transformations_selected_mesh"
    bl_description = "Lock Transformations for selected objects"
    bl_option = {'UNDO'}

    lock = bpy.props.BoolProperty(name = "state")
    def invoke (self, context, event):
        mesh_tools.lock_objects(self.lock)
        return {'FINISHED'}

class MESH_AddDummy(Operator):
    bl_idname = "object.mesh_add_dummy"
    bl_description = "Add Simple Deform Modifier to the end of the selected object's modifier stack"
    bl_label = "Character_Add_Dummy"
    bl_options = {'UNDO'}

    def invoke(self, context, event):
        mesh_tools.put_dummy()

        return {"FINISHED"}

class MESH_ObjectRayVizOff(Operator):
    bl_idname = "object.ray_viz_off"
    bl_label = "Object_Ray_Viz_off"
    bl_options = {'UNDO'}

    @classmethod
    def poll(cls, context):
        return context.object and context.object.type == 'MESH'

    def invoke(self, context, event):
        mesh_tools.object_ray_viz(False)

        return {"FINISHED"}

class MESH_ObjectRayVizOn(Operator):
    bl_idname = "object.ray_viz_on"
    bl_label = "Object_Ray_Viz_on"
    bl_options = {'UNDO'}

    @classmethod
    def poll(cls, context):
        return context.object and context.object.type == 'MESH'

    def invoke(self, context, event):
        mesh_tools.object_ray_viz(True)

        return {"FINISHED"}

class MESH_WeightMirroring(Operator):
    bl_idname = "object.weight_mirror"
    bl_label = "Mirror Weight across the X Axis"
    bl_options = {'UNDO'}

    @classmethod
    def poll(cls, context):
        return context.object and context.object.type == 'MESH'

    def invoke(self, context, event):
        weight = mesh_tools.WeightMirroring(bpy.context.object.weight_mirror_side)
        weight.execute()
        return {"FINISHED"}

class OBJ_CreateDriver(Operator):
    bl_idname = "object.create_driver"
    bl_label = "Create Drivers"
    bl_description = "Create the same driver on the selected meshes"
    bl_options = {'UNDO'}

    @classmethod
    def poll(cls, context):
        settings = context.scene.driver_settings
        return (
            context.object
            and context.object.mode == 'OBJECT'
            and settings.driver_target_datapath
            and settings.driver_datapath)

    def execute(self, context):
        settings = context.scene.driver_settings
        for obj in bpy.context.selected_objects:
            self.create_driver(
                obj,
                settings.driver_datapath,
                settings.driver_expression,
                settings.driver_target_datapath,
                settings.driver_target,
                settings.driver_subtarget)

        return {'FINISHED'}

    def invoke(self, context, event):
        return self.execute(context)

    def create_driver(self, obj, data_path, expression, custom_prop_name, target_id, subtarget = None):
        new_driver = obj.driver_add(data_path)
        new_driver.driver.expression = expression
        try:
            var = new_driver.driver.variables[0]
        except:
            var = new_driver.driver.variables.new()
        var.name = "var"
        target = var.targets[0]
        target.id = bpy.context.scene.objects[target_id]
        if subtarget:
            target.bone_target = subtarget
        target.data_path = custom_prop_name

class CLEAN_ToolsGUI(Panel):
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'TOOLS'
    bl_category = 'TA - Rigging'
    bl_label = "Clean Up Tools"

    bpy.types.Scene.clear_action_name = bpy.props.StringProperty(name = "Clear Action Name")

    def draw(self, context):
        layout = self.layout
        col = layout.column()
        row = col.row(align = True)
        row.label(icon = 'LINKED')
        row.operator("object.character_remove_dependencies", text = "Clear Dependencies", icon = 'X')
        row = col.row(align = True)
        row.label(icon= 'SPLITSCREEN')
        row.operator("screen.delete_none_default", text = "Delete Screens", icon = 'X')
        row = col.row(align = True)
        row.prop_search(context.scene, "clear_action_name", bpy.data, "actions", text = "Action")
        row.operator("action.clear_action", text = "Remove", icon = "X")

class CLEAN_RemoveDependency(Operator):
    bl_idname = "object.character_remove_dependencies"
    bl_label = "Character_Remove_Dependencies"
    bl_description = "Remove all dependencies at the rig level"
    bl_options = {"UNDO"}

    def invoke(self, context, event):
        error_list = self.remove_dependencies()
        if error_list:
            for error in error_list:
                self.report({'ERROR'}, error)
        return {"FINISHED"}

    def remove_dependencies(self):
        """
        Remove all dependencies at the armature level
        """
        error=[]
        for armature in bpy.data.armatures:
            if armature.name.startswith('rig'):
                try:
                    armature.animation_data
                except:
                    print("ERROR: no animation data(driver)")
                else:
                    try:
                        for d in armature.animation_data.drivers:
                            if d.data_path.endswith('.hide') or d.data_path.endswith('.bbone_in') or d.data_path.endswith('.bbone_out'):
                                try:
                                    armature.driver_remove(d.data_path)
                                    #print("%s removed" %d.data_path)
                                except TypeError: #driver path is broken
                                    for var in d.driver.variables:
                                        d.driver.variables.remove(var)
                                    try:
                                        d.data_path = 'bones[\"ctl.god.C\"].hide'      #change data_path target to ctl.god.C so that it's deletable
                                    except:
                                        print("No such datapath")
                                        break
                                    else:
                                        armature.driver_remove(d.data_path)
                            else:
                                error.append("Driver(Armature %s) pointed to %s will not be removed" %(armature.name, d.data_path))
                    except AttributeError:
                        print("No driver")
                    for layer in armature.layers:
                       layer = True
                    try:
                        for b in bpy.data.objects[armature.name].pose.bones:
                            b.bone.hide = False
                    except KeyError:
                        pass
                    i = 0
                    while (i < 32):
                        if 7 < i < 16 or i > 23:
                            armature.layers[i] = False
                        i = i + 1

        for obj in bpy.data.objects:
            if obj.name.startswith('rig'):
                try:
                    for d in obj.animation_data.drivers:
                        if not d.is_valid:
                            error.append("Driver(Object %s) Datapath %s is broken" %(obj.name, d.data_path))
                except AttributeError:
                    pass
        return error

class CLEAN_ClearAction(Operator):
    bl_idname = "action.clear_action"
    bl_label = "Clear_action"
    bl_description = "Clear all users in an action and remove it"
    bl_options = {'UNDO'}

    def execute(self, context):

        action = bpy.data.actions[bpy.context.scene.clear_action_name]
        action.user_clear()
        bpy.data.actions.remove(action)

        return {'FINISHED'}

    def invoke(self, context, event):
        return self.execute(context)

class CLEAN_DeleteScreens(Operator):
    bl_idname = "screen.delete_none_default"
    bl_label = "Delete_None_Default"
    bl_description = "Delete None Default screens"
    bl_options = {'UNDO'}

    def execute(self, context):

        default_screens = [
            "3D View Full",
            "Animation",
            "Composition",
            "Default",
            "Game Logic",
            "Motion Tracking",
            "Scripting",
            "UV Editing",
            "Video Editing",
            ]

        i = 0
        while(i<len(bpy.data.screens)):
            bpy.ops.screen.screen_set(delta = 1)
            if bpy.context.screen.name not in default_screens:
                bpy.ops.screen.delete()
            i = i + 1
        bpy.context.window.screen = bpy.data.screens["Default"]
        return {'FINISHED'}

    def invoke(self, context, event):
        return self.execute(context)

def compile_bone_exceptions():

    strings = []
    try:
        bpy.context.object.bone_exceptions
    except:
        pass
    else:
        for b in bpy.context.object.bone_exceptions:
            strings.append(b.exception)
    if not strings:
        #string is empty
        strings.append("\t\t\t")
    str = tuple(strings)
    return str

def register():
    bpy.utils.register_module(__name__)

def unregister():
    bpy.utils.unregister_module(__name__)

if __name__ == "__main__":
    register()


from PIL import Image
import qrcode

sl = 100
def QR_area(image, pos):                       # tìm các pixel ở đó chứa mã QR
    size = image.size[0]
    QR_area = []
    for i in range(size):
        QR_area.append([])
        for j in range(size):
            QR_area[i].append(0)
    for i in range(size):
        for j in range(size):
            if (i < 120) or (i >= (size - 120)) or (j < 120) or (j >= (size - 120)):
                QR_area[i][j] = 1
                continue
            if (i >= 120 and j >= 120 and i < 360 and j < 360):
                QR_area[i][j] = 1
                continue
            if (i >= (size - 360) and j >= 120 and i < (size - 120) and j < 360):
                QR_area[i][j] = 1
                continue
            if (i >= 120 and j >= (size - 360) and i < 360 and j < (size - 120)):
                QR_area[i][j] = 1
                continue
            if (i % 30 == 10 and j % 30 == 10):
                for a in range(10):
                    for b in range(10):
                        QR_area[i + a][j + b] = 1

    for i in pos:
        for j in pos:
            if (i == 6 and j == pos[-1]) or (j == 6 and i == pos[-1])\
                or (i == 6 and j == 6):
                continue
            else:
                for a in range(150):
                    for b in range(150):
                        QR_area[10*(3*(i-2)+12)+a][10*(3*(j-2)+12)+b] = 1
    return QR_area

def QR_fromtext(txt,ver=5,err_crt = qrcode.constants.ERROR_CORRECT_H):         # Sinh ảnh QR nhị phân từ text
    qr = qrcode.QRCode(version = ver,error_correction = err_crt,box_size=3)
    qr.add_data(txt)
    qr.make(fit=True)
    img_qr = qr.make_image()
    img_size = img_qr.size[0] - 24

    img_frame = img_qr
    for x in range(0,img_size):
        for y in range(0,img_size):
            if x < 24 and (y < 24 or y > img_size-25):
                continue
            if x > img_size-25 and (y < 24 ):
                continue
            if (x%3 ==1 and  y%3 == 1):
                if (img_frame.getpixel((x+12,y+12)) == 0):
                    continue
            img_frame.putpixel((x+12,y+12),(255))
    pos = qrcode.util.pattern_position(qr.version)
    img_qr2 = qr.make_image()
    for i in pos:
        for j in pos:
            if (i == 6 and j == pos[-1]) or (j == 6 and i == pos[-1])\
                or (i == 6 and j == 6):
                continue
            else:
                rect = (3*(i-2)+12,3*(j-2)+12,3*(i+3)+12,3*(j+3)+12)
                img_tmp = img_qr2.crop(rect)
                img_frame.paste(img_tmp,rect)

    img_res = Image.new("RGBA",(img_frame.size[0]*10,img_frame.size[1]*10),(0,0,0,0))
    img_res = img_res.convert('1')
    img_frame = img_frame.resize((img_frame.size[0]*10,img_frame.size[1]*10), Image.NEAREST)
    img_res.paste(img_frame,(0,0),img_frame)
    return img_res, pos


# -*- encoding: utf-8 -*-
'''
@项目名称：   txsp.py
@更新时间：   2022/07/29 21:42:49
@版本号  ：   1.0
@环境变量：   txspCookie 福利中心抓取Cookie
@更新内容：   福利中心任务
'''

import json
import os
from time import sleep
import requests

COOKIE_NAME = "txspCookie"

class User:

    def __init__(self, cookie, index=1) -> None:
        self.cookie = cookie
        self.valid = True
        self.index = index

    def get(self, url, header=None):
        headers = {
            "Content-Type": "application/json",
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Mobile/11A465 QQLiveBrowser/8.5.95 AppType/UN WebKitCore/WKWebView iOS GDTTangramMobSDK/4.370.6 GDTMobSDK/4.370.6 cellPhone/iPhone 12",
            "referer": "https://fuli.v.qq.com/",
            "origin": "https://fuli.v.qq.com/",
            "cookie": self.cookie
        }
        if(header):
            headers.update(header)
        try:
            res = requests.get(url, headers=headers)
            return res.json()
        except Exception as e:
            print("GET异常：{0}".format(str(e)))
            return None

    def post(self, url, body='', header=None):
        headers = {
            "Content-Type": "application/json",
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Mobile/11A465 QQLiveBrowser/8.5.95 AppType/UN WebKitCore/WKWebView iOS GDTTangramMobSDK/4.370.6 GDTMobSDK/4.370.6 cellPhone/iPhone 12",
            "referer": "https://fuli.v.qq.com/",
            "origin": "https://fuli.v.qq.com/",
            "accept-encoding":"gzip, deflate, br",
            "connection":"keep-alive",
            "cookie": self.cookie
        }
        if(header):
            headers.update(header)
        # 捕获异常
        try:
            res = requests.post(url, data=body, headers=headers)
            return res.json()
        except Exception as e:
            print("POST异常：{0}".format(str(e)))
            return None

    def vipInfo(self):
        url = "https://vip.video.qq.com/fcgi-bin/comm_cgi?name=spp_SVipInfo&cmd=1&source_scene=4&otype=xjson"
        rjson = self.get(url=url)
        if(not rjson):
            self.valid = False
            return
        if("msg" not in rjson):
            self.valid = True
            self.nickname = rjson['nick']
            self.vipInfo = rjson["hlw"]
            print("用户昵称：",self.nickname)
            if(self.vipInfo['vip']):
                print("VIP状态：有效")
            else:
                print("VIP状态：过期")
            print("VIP等级：",self.vipInfo['level'])
            print("VIP经验：",self.vipInfo['score'])
        else:
            self.valid = False
            print("获取账号信息失败：",rjson["msg"])

    def welfareCenter(self,onlyCoin = False):
        url = "https://pbaccess.video.qq.com/activity/welfare_center/v2/queryUserActivityNew"
        body = {"activity_id":1001}
        rjson = self.post(url=url,body=json.dumps(body))
        if(not rjson):
            return
        if("msg" not in rjson):
            self.coin = rjson['data']['asset_info']['coin']
            if(onlyCoin):
                print(f"账号[{self.nickname}]：{self.coin}")
                return
            print("福利金币：",self.coin)

            tasks = rjson['data']['task_info']
            print("")
            if(len(tasks['watch_video_info']['watch_video_record'])>=2):
                print("任务[播放视频]已完成")
            else:
                print("任务[播放视频]未完成")
                self.taskWatch()
            if(len(tasks['browse_info']['browse_record'])>=2):
                print("任务[浏览商店]已完成")
            else:
                print("任务[浏览商店]未完成")
                self.taskBrowse()
            print(f"任务[好友助力]进度：{tasks['help_share_info']['help_share_count']}/{tasks['help_share_info']['help_share_limit']}")
            if(tasks['help_share_info']['help_share_count'] != tasks['help_share_info']['help_share_limit']):
                self.needHelp = True
                self.shareCode = rjson['data']['vuid_encoded']
            else:
                self.needHelp = False
        else:
            print("获取福利中心信息失败：",rjson['msg'])

    def taskBrowse(self):
        url = "https://pbaccess.video.qq.com/activity/platform/gateway/v2/browse"
        body = {"activity_id":"1001","browse_page":"caochangdi","task_group_id":"4"}
        rjson = self.post(url,body=json.dumps(body))

        if(rjson['err_msg'] == "success"):
            print("任务[浏览商店]执行成功")
        else:
            print("任务[浏览商店]执行失败：",rjson['err_msg'])

    def taskWatch(self):
        url = "https://pbaccess.video.qq.com/activity/platform/gateway/v2/WatchVideo"
        body = {"activity_id":"1001","vid":"mzc00200p51jpn7","task_group_id":"1"}
        rjson = self.post(url,body=json.dumps(body))

        if(rjson['err_msg'] == "success"):
            print("任务[播放视频]执行成功")
        else:
            print("任务[播放视频]执行失败：",rjson['err_msg'])

    def signInfo(self):
        url = "https://pbaccess.video.qq.com/activity/platform/gateway/v2/querySignInfo"
        body = {"activity_id":"1001","task_group_id":5}
        rjson = self.post(url=url,body=json.dumps(body))
        if(not rjson):
            return
        if(not rjson['err_msg']):
            if(rjson['data']['is_sign']):
                print("今日已签到")
            else:
                print("今日未签到")
                self.signIn()
        else:
            print("获取签到信息失败：",rjson['err_msg'])

    def signIn(self):
        url = "https://pbaccess.video.qq.com/activity/platform/gateway/v2/signPlay"
        body = {"activity_id":"1001","task_group_id":5}
        rjson = self.post(url=url,body=json.dumps(body))
        if(not rjson):
            return
        if(rjson['err_msg'] == "success"):
            print(f"签到成功：+{rjson['data']['reward_count']}金币")
        else:
            print("签到失败：",rjson['err_msg'])

    def shareHelp(self, users):
        if(not self.valid):
            return
        for user in users:
            if(user.cookie == self.cookie):
                continue
            if(not user.valid or not user.needHelp):
                continue
            url = "https://pbaccess.video.qq.com/activity/platform/gateway/v2/helpShare"
            body = {"activity_id":"1001","task_group_id":2,"sponsor_id":user.shareCode}
            rjson = self.post(url=url,body=json.dumps(body))
            if(not rjson):
                continue
            if(rjson['err_msg'] == "success"):
                print(f"[{self.nickname}]->[{user.nickname}]助力成功")
            else:
                print(f"[{self.nickname}]->[{user.nickname}]助力失败：{rjson['err_msg']}")
            sleep(2)

    def run(self):
        print(f"======账号[{self.index}]======")
        self.vipInfo()
        if(self.valid):
            print("\n>>>福利中心")
            self.welfareCenter()
            print("")
            self.signInfo()
        print("\n")

def initEnv():
    env = os.environ
    if(COOKIE_NAME in env):
        cookies = env[COOKIE_NAME]
        if(cookies.find("&")):
            return cookies.split("&")
    return []

if __name__ == "__main__":
    cookies = initEnv()
    users = []
    index = 1
    for cookie in cookies:
        users.append(User(cookie, index))
        index +=1
    for user in users:
        try:
            user.run()
        except Exception as e:
            print("运行异常：", str(e))

    print("\n======福利助力======")
    for user in users:
        user.shareHelp(users)

    print("\n======账号总览======")
    for user in users:
        if(user.valid):
            user.welfareCenter(True)


import os
import numpy as np
from astropy.io import fits
from astropy.table import Table
from astropy import units as u
from astropy.coordinates import SkyCoord

def create_sweepfile_dict(listdir = ['/global/project/projectdirs/cosmo/data/legacysurvey/dr9/north/sweep/9.0', '/global/project/projectdirs/cosmo/data/legacysurvey/dr9/south/sweep/9.0']):
    '''Creates dictionary of sweep files containing path, min
    and max ra and dec for the block.

    Parameters
    ----------
    listdir : list of str, optional
        list of directory paths to search for sweep files.
        defaults to dr9 north and south sweeps

    Returns
    -------
    files : dict
        A dictionary w/ filename for keys.
        Every key maps to another dictionary containing
        'min_ra' 'max_ra' 'min_dec' 'max_dec' and 'path'
    '''
    files = {}
    for dir in listdir:
        for dirname, __, filenames in os.walk(dir):

            for filename in filenames:
                block = filename[6:-5]

                if block[6].isdigit():

                    min_ra = int(block[:3])
                    min_dec = int(block[4:7])
                    if block[3] == 'm':
                        min_dec = int('-'+str(min_dec))

                    max_ra = int(block[8:11])
                    max_dec = int(block[12:])
                    if block[-4] == 'm':
                        max_dec = int('-'+str(max_dec))

                    files[filename]={'min_ra':min_ra, 'max_ra':max_ra, 'min_dec': min_dec, 'max_dec':max_dec, 'path':os.path.join(dirname, filename)}
    return files

def find_host_galaxy_file(files,ra, dec):
    '''Matches transient to corresponding host sweep file by
    finding which block it is in.

    Parameters
    ----------
    files : dict
        A dictionary w/ filename for keys.
        Every key maps to another dictionary containing
        'min_ra' 'max_ra' 'min_dec' 'max_dec' and 'path'
    ra : float
        pseudo-host ra for observed transient
    dec : float
        pseudo-host dec for observed transient

    Returns
    -------
    path : str or nan
        full path of the matching sweep file.
        Returns nan if no match is found.
    '''
    for i in files.keys():
         if ra>=files[i]['min_ra'] and ra<=files[i]['max_ra'] and dec>=files[i]['min_dec'] and dec<=files[i]['max_dec']:
            return files[i]['path']
         else: continue

    return float(np.NaN)

def find_ID_RA_DEC_lists_in_brick(brick_path):
    '''Finds lists of OBJID, RA, DEC

    Parameters
    ----------
    sweepfile_path : str
        A sweep file path to extract objects from.

    Returns
    -------
    OBJID_RA_DEC : list of 3 lists
        List of 3 lists corresponding to objid, ra, dec respectiveliy
        of all objects in the brick sweep file.
    '''
    hdus = fits.open(brick_path)
    data = Table(hdus[1].data)
    return [list(data['OBJID']), list(data['RA']), list(data['DEC'])]

def find_redshift(obj_list, path, ra, dec):

    '''Finds Spectroscopic and Photometric redshift and Standard Deviation
       NOTE: - Spectroscopic Redshift will be -99.0 if it does not exist
             - I the associated photo-z file does not exist, returns a tuple
               of type nan

    Parameters
    ----------
    onj_list : list of 3 lists
        List of 3 lists corresponding to objid, ra, dec respectiveliy
        of all objects in the brick sweep file.
    sweepfile_path : str
        A sweep file path associated with the matching brick.
    ra : float
        pseudo-host ra for observed transient
    dec : float
        pseudo-host dec for observed transient

    Returns
    -------
     z_spec, z_photo_mean, z_photo_err: tuple
        A tuple containing spectroscopic redshift, mean of photometric redshift,
        and photometric redshift standard deviation respectively of the matching
        object within the sweep file.
    '''
    c = SkyCoord(ra*u.degree, dec*u.degree)
    catalog = SkyCoord(obj_list[1]*u.degree, obj_list[2]*u.degree)
    idx, d2d, d3d = c.match_to_catalog_3d(catalog)
    obj_id = obj_list[0][idx]

    sweep_pz = path.replace('9.0', '9.0-photo-z').replace('.fits', '-pz.fits')

    if os.path.exists(sweep_pz):
        hdus = fits.open(sweep_pz)
        redshift_data = Table(hdus[1].data)
        try:
            assert redshift_data['OBJID'][idx] == obj_id, 'object ID does not match'
            z_spec, z_photo_mean, z_photo_err = (redshift_data['Z_SPEC'][idx],redshift_data['Z_PHOT_MEAN'][idx], redshift_data['Z_PHOT_STD'][idx])
            return (z_spec, z_photo_mean, z_photo_err)
        except AssertionError as msg:
            print(msg)
    else:
        print(os.path.exists(sweep_pz))
    return (np.NaN, np.NaN, np.NaN)

def do_all(ra, dec):
    files = create_sweepfile_dict()
    path = find_host_galaxy_file(files, ra, dec)
    obj_lists = find_ID_RA_DEC_lists_in_brick(path)
    z_spec, z_photo_mean, z_photo_err = find_redshift(obj_lists, path, ra, dec)
    return {'z_spec': z_spec, 'mean': z_photo_mean,'err': z_photo_err}


import torch
import torch.nn as nn
import itertools
from util.image_pool import ImagePool
from .base_model import BaseModel
from . import networks
import numpy as np
import cv2
from util import util
from util.saver import save_images
from torch.nn import functional as F
import gc
import random

class MXResnetModel(BaseModel):
    """
    This class implements the CycleGAN model, for learning image-to-image translation without paired data.

    The model training requires '--dataset_mode unaligned' dataset.
    By default, it uses a '--netG resnet_9blocks' ResNet generator,
    a '--netD basic' discriminator (PatchGAN introduced by pix2pix),
    and a least-square GANs objective ('--gan_mode lsgan').

    CycleGAN paper: https://arxiv.org/pdf/1703.10593.pdf
    """
    @staticmethod
    def modify_commandline_options(parser, is_train=True):
        """Add new dataset-specific options, and rewrite default values for existing options.

        Parameters:
            parser          -- original option parser
            is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.

        Returns:
            the modified parser.

        For CycleGAN, in addition to GAN losses, we introduce lambda_A, lambda_B, and lambda_identity for the following losses.
        A (source domain), B (target domain).
        Generators: G_A: A -> B; G_B: B -> A.
        Discriminators: D_A: G_A(A) vs. B; D_B: G_B(B) vs. A.
        Forward cycle loss:  lambda_A * ||G_B(G_A(A)) - A|| (Eqn. (2) in the paper)
        Backward cycle loss: lambda_B * ||G_A(G_B(B)) - B|| (Eqn. (2) in the paper)
        Identity loss (optional): lambda_identity * (||G_A(B) - B|| * lambda_B + ||G_B(A) - A|| * lambda_A) (Sec 5.2 "Photo generation from paintings" in the paper)
        Dropout is not used in the original CycleGAN paper.
        """
        parser.set_defaults(no_dropout=True)  # default CycleGAN did not use dropout
        if is_train:
        #     parser.add_argument('--lambda_A', type=float, default=10.0, help='weight for cycle loss (A -> B -> A)')
        #     parser.add_argument('--lambda_B', type=float, default=10.0, help='weight for cycle loss (B -> A -> B)')
        #     parser.add_argument('--lambda_identity', type=float, default=0.5, help='use identity mapping. Setting lambda_identity other than 0 has an effect of scaling the weight of the identity mapping loss. For example, if the weight of the identity loss should be 10 times smaller than the weight of the reconstruction loss, please set lambda_identity = 0.1')
            parser.add_argument('--show_cam', type=bool, default=True, help='show cam')
            parser.add_argument('--show_acc', type=bool, default=True, help='show acc for C_A and C_B')
        parser.add_argument('--n_classes', type=int, default=2, help='how many class')
        return parser

    def __init__(self, opt):
        """Initialize the CycleGAN class.

        Parameters:
            opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions
        """
        BaseModel.__init__(self, opt)
        # specify the training losses you want to print out. The training/test scripts will call <BaseModel.get_current_losses>
        self.loss_names = ['C', 'C_A', 'C_B']
        # specify the images you want to save/display. The training/test scripts will call <BaseModel.get_current_visuals>
        self.opt = opt
        self.only_early_late = 'onlyEarlyLate' in self.opt.name

        visual_names_A = []
        visual_names_B = []
        if self.opt.show_cam:
            visual_names_A.append('cam_A')
            visual_names_B.append('cam_B')

        self.visual_names = visual_names_A + visual_names_B  # combine visualizations for A and B
        # specify the models you want to save to the disk. The training/test scripts will call <BaseModel.save_networks> and <BaseModel.load_networks>.
        self.model_names = []
        self.model_names.append('C')

        # define networks (both Generators and discriminators)
        # The naming is different from those used in the paper.
        # Code (vs. paper): G_A (G), G_B (F), D_A (D_Y), D_B (D_X)
        self.netC = networks.define_C(1, opt.ndf, opt.netC,
                                        opt.n_layers_D, opt.norm, opt.init_type, opt.init_gain, self.gpu_ids,
                                        opt.n_classes)

        if self.isTrain:
            # self.criterionCE = networks.CELoss().to(self.device)
            # self.criterionCE = networks.CELoss(dataset_mode=opt.dataset_mode, n_classes=opt.n_classes,
            #                                    lambda_ce_A=self.opt.lambda_ce_A, lambda_ce_B=self.opt.lambda_ce_B,
            #                                    device=self.device).to(self.device)
            self.criterionCE = networks.CELoss(dataset_mode=opt.dataset_mode, n_classes=opt.n_classes,
                                               lambda_ce_A=self.opt.lambda_ce_A, lambda_ce_B=self.opt.lambda_ce_B,
                                               device=self.device).to(self.device)
            # initialize optimizers; schedulers will be automatically created by function <BaseModel.setup>.
            self.optimizer = torch.optim.Adam(itertools.chain(self.netC.parameters()), lr=opt.lr, betas=(opt.beta1, 0.999))
            self.optimizers.append(self.optimizer)

        if self.opt.netC == 'inception':
            if self.isTrain:
                self.netC.train()
            else:
                self.netC.eval()

        self.features_blobs = []

    def set_input(self, input):
        """Unpack input data from the dataloader and perform necessary pre-processing steps.

        Parameters:
            input (dict): include the data itself and its metadata information.

        The option 'direction' can be used to swap domain A and domain B.
        """
        # for n classes

        AtoB = self.opt.direction == 'AtoB'
        if self.isTrain | self.opt.test_for_traindata:
            bs = len(input['train_A_paths'])
            self.train_A_label = torch.tensor(0).expand(bs).to(self.device)
            self.test_A_label = torch.tensor(0).expand(bs).to(self.device)
            self.train_B_label = torch.tensor(1).expand(bs).to(self.device)
            self.test_B_label = torch.tensor(1).expand(bs).to(self.device)

            self.real_A = input['train_A' if AtoB else 'train_B'].to(self.device)
            self.real_B = input['train_B' if AtoB else 'train_A'].to(self.device)
            if not self.only_early_late:
                self.real1_A = self.real_A[:,0:3,:,:]
                self.real1_B = self.real_B[:,0:3,:,:]
            else:
                self.real2_A = self.real_A[:,0,:,:].unsqueeze(1)
                self.real2_B = self.real_B[:,0,:,:].unsqueeze(1)
                self.real3_A = self.real_A[:,1,:,:].unsqueeze(1)
                self.real3_B = self.real_B[:,1,:,:].unsqueeze(1)

            # self.image_paths = input['A_paths' if AtoB else 'B_paths']
            # by Gloria for test
            self.image_paths_A = input['train_A_paths' if AtoB else 'train_B_paths']
            self.image_paths_B = input['train_B_paths' if AtoB else 'train_A_paths']

            self.test_A = input['test_A' if AtoB else 'test_B'].to(self.device)
            self.test_B = input['test_B' if AtoB else 'test_A'].to(self.device)
            if not self.only_early_late:
                self.test1_A = self.test_A[:,0:3,:,:]
                self.test1_B = self.test_B[:,0:3,:,:]
            else:
                self.test2_A = self.test_A[:,0,:,:].unsqueeze(1)
                self.test2_B = self.test_B[:,0,:,:].unsqueeze(1)
                self.test3_A = self.test_A[:,0,:,:].unsqueeze(1)
                self.test3_B = self.test_B[:,0,:,:].unsqueeze(1)
            # self.image_paths = input['A_paths' if AtoB else 'B_paths']
            # by Gloria for test
            self.test_image_paths_A = input['test_A_paths' if AtoB else 'test_B_paths']
            self.test_image_paths_B = input['test_B_paths' if AtoB else 'test_A_paths']
            # for n classes
            if self.opt.n_classes > 2:
                self.train_B_label = input['train_B_label'].to(self.device)
        else:
            bs = len(input['test_A_paths'])
            self.test_A_label = torch.tensor(0).expand(bs).to(self.device)
            self.test_B_label = torch.tensor(1).expand(bs).to(self.device)

            self.real_A = input['test_A' if AtoB else 'test_B'].to(self.device)
            self.real_B = input['test_B' if AtoB else 'test_A'].to(self.device)
            if not self.only_early_late:
                self.real1_A = self.real_A[:, 0:3, :, :]
                self.real1_B = self.real_B[:, 0:3, :, :]
            else:
                self.real2_A = self.real_A[:,0,:,:].unsqueeze(1)
                self.real2_B = self.real_B[:,0,:,:].unsqueeze(1)
                self.real3_A = self.real_A[:,1,:,:].unsqueeze(1)
                self.real3_B = self.real_B[:,1,:,:].unsqueeze(1)
            # self.image_paths = input['A_paths' if AtoB else 'B_paths']
            # by Gloria for test
            self.image_paths_A = input['test_A_paths' if AtoB else 'test_B_paths']
            self.image_paths_B = input['test_B_paths' if AtoB else 'test_A_paths']
            # for n classes
            if self.opt.n_classes > 2:
                self.test_B_label = input['test_B_label'].to(self.device)

    def forward(self):
        """Run forward pass; called by both functions <optimize_parameters> and <test>."""

    def backward(self):
        """Calculate the loss for generators G_A and G_B"""

        self.loss_C_A = 0
        self.loss_C_B = 0
        self.loss_C = 0
        if self.opt.netC == 'inception':
            self.logit, _ = self.netC(self.real)
        else:
            self.logit1 = self.netC(self.real2_A, self.real3_A)
            self.logit2 = self.netC(self.real2_B, self.real3_B)
            self.loss_C_A += 2 * self.criterionCE(self.logit1, target_label=self.train_A_label)
            self.loss_C_B += 2 * self.criterionCE(self.logit2, target_label=self.train_B_label)

        # self.loss_C = self.criterionCE(self.logit, self.train_label)
        self.loss_C = self.loss_C_A + self.loss_C_B
        self.loss_C.backward()

    def optimize_parameters(self, epoch):
        """Calculate losses, gradients, and update network weights; called in every training iteration"""
        # forward
        self.forward()      # compute fake images and reconstruction images.

        # G_A and G_B
        self.optimizer.zero_grad()  # set G_A and G_B's gradients to zero
        self.backward()  # calculate gradients for G_A and G_B
        self.optimizer.step()  # update G_A and G_B's weights

    def train_acc(self):

        size_A = np.shape(self.logit1)[0]
        size_B = np.shape(self.logit2)[0]
        total = size_A + size_B
        labels = torch.cat((self.train_A_label, self.train_B_label), 0).long()

        # for C_A : logit AB and logit BB
        outputs_A = torch.cat((self.logit1,self.logit2), 0)
        _, predicted = torch.max(outputs_A.data, 1)     # 每一行的最大值，即batch中每个样本的最大值
        correct = predicted.eq(labels.data).sum()
        self.train_C_acc = 100. * correct / total

        self.train_C_A_acc = self.train_C_acc
        self.train_C_B_acc = self.train_C_acc

    def test_acc(self):

        if self.isTrain:
            size_A = np.shape(self.test2_A)[0]
            size_B = np.shape(self.test2_B)[0]

            logit1 = self.netC(self.test2_A, self.test3_A)
            logit2 = self.netC(self.test2_B, self.test3_B)

            total = size_A + size_B
            labels = torch.cat((self.train_A_label, self.train_B_label), 0).long()
        else:
            size_A = np.shape(self.real2_A)[0]
            size_B = np.shape(self.real2_B)[0]

            logit1 = self.netC(self.real2_A, self.real3_A)
            logit2 = self.netC(self.real2_B, self.real3_B)

            total = size_A + size_B
            labels = torch.cat((self.test_A_label, self.test_B_label), 0).long()

        # for C_A : logit AB and logit BB
        outputs_A = torch.cat((logit1, logit2), 0)
        _, predicted_A = torch.max(outputs_A.data, 1)  # 每一行的最大值，即batch中每个样本的最大值
        correct_A = predicted_A.eq(labels.data).sum()
        self.test_C_acc = 100. * correct_A / total

        correct_B = correct_A
        correct = correct_A
        predicted_B = predicted_A
        predicted = predicted_A

        if self.opt.accs_or_logits == 'accs':
            return correct_A, correct_B, correct
        else:
            # return outputs1_A, outputs1_B, outputs1
            if self.opt.n_classes > 2:
                return predicted_A, predicted_B, predicted, labels.data
            else:
                return predicted_A, predicted_B, predicted


"""
quakestats

Computes some basic statistics for earthquakes in a USGS data feed.
The desired feed is specified using severity level and period.
Severity level can be "significant", "4.5", "2.5", "1.0", "all".
Period can be "hour", "day", "week", "month".

Usage: quakestats [options] <level> <period>

Options:

  -h --help   Show this help
"""

import statistics
from docopt import docopt
from quakefeeds import QuakeFeed

def main():
    args = docopt(__doc__)

    level = args["<level>"]
    period = args["<period>"]

    feed = QuakeFeed(level, period)

    mean_magnitude = statistics.mean(feed.magnitudes)
    median_magnitude = statistics.median(feed.magnitudes)
    mean_depth = statistics.mean(feed.depths)
    median_depth = statistics.median(feed.depths)

    print(len(feed), "events processed.")
    print("Mean magnitude   = {:.1f}".format(mean_magnitude))
    print("Median magnitude = {:.1f}".format(median_magnitude))
    print("Mean depth       = {:.1f} km".format(mean_depth))
    print("Median depth     = {:.1f} km".format(median_depth))


# Akansha Vashisth, Nov 2018
#
# This script visualizes the distributions of training data features.
# For visualization, it uses histograms to identify better predictors from our data set.
# Argument variables of the script are an input data file and
# visualization plots of training data distributions.
#
# Dependencies: argparse, pandas, seaborn, matplotlib
#
# Usage: python scripts/eda.py results/breast_cancer_new.csv img/plot

# package import for parsing arguments
import argparse
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

# variable for parsing
parser = argparse.ArgumentParser()

# adding argument for input file
parser.add_argument('input_file')
parser.add_argument('output_file')
args = parser.parse_args()

def main():

    # read the data
    data = pd.read_csv(args.input_file)

    # split the data
    data1 = data[data.Classification==1]
    data2 = data[data.Classification==2]

    # Visualize the features
    feature_cols = data.columns.values[:-1]
    number = range
    for idx,item in enumerate(feature_cols):
        sns_data1 = sns.distplot(data1[item].dropna(),kde = False, label="Healthy controls")
        sns_data2 = sns.distplot(data2[item].dropna(),kde = False, label="Patient")
        sns_data1.set_title(item)
        sns_data1.set_ylabel("Count")
        sns_data1.set_xlabel(item)
        plt.legend()
        plt.savefig(args.output_file+str(idx+1)+'.png')
        plt.close()

# call main function
if __name__ == "__main__":
    main()


# Python - Database - sqlite

import sqlite3

def databaseFunction(db_name):
    conn = sqlite3.connect(db_name)
    print(f" {db_name} database connected")

    tableScript = "create table mytable (name text, age int, mobile int) "

    conn.execute(tableScript)
    print(f"table created")

    insertData = "insert into mytable values('Alex', 28, 652312)"

    conn.execute(insertData)
    print(f"data inserted")

    conn.commit()
    conn.close()

def insertData(tableName):
    conn = sqlite3.connect("sample.db")

    #conn.execute(f"create table {tableName} (name text, age int) ")

    conn.execute(f"insert into mytable values('Tom', 35, 454556)")

    conn.commit()
    conn.close()

choice = input("do you want to create a database? if yes type a name or just press enter  ")

if len(choice) > 1:
    databaseFunction(choice + ".db")

def getData(tableName):
    conn = sqlite3.connect("sample.db")

    selectScript = f"select * from {tableName}"

    cursor = conn.execute(selectScript)

    for rows in cursor:
       print(f"{rows[0]} - {rows[1]} - {rows[2]} ")
       #print(len(rows))

    conn.close()

tableName = "mytable"

#insertData(tableName)

def updateData():
    conn = sqlite3.connect("sample.db")

    conn.execute(f"update mytable set age=32 where name = 'Alex'")

    conn.commit()
    conn.close()

def deleteData():
    conn = sqlite3.connect("sample.db")

    conn.execute(f"delete from mytable where name = 'Alex'")

    conn.commit()
    conn.close()

getData(tableName)

deleteData()

getData(tableName)

#DML - Insert Data, Modify/Update Data, Delete Data
#CRUD - Create/Insert, Read/Select, Update/Modify, Delete


import yaml
import yamale
import pprint
import jsbeautifier

pp = pprint.PrettyPrinter(indent=4)
def pretty_print(*args, **kwargs):
    pp.pprint(*args, **kwargs)

def update_recursive(target, src):
    for k, v in src.items():
        if type(v) == dict:
            if k not in target:
                target[k] = {}
            update_recursive(target[k], src[k])
        else:
            target[k] = v

def load_configs():
    with open('dialects/typescript.yaml') as f:
        configs = {}
        features = {}
        for config in yaml.load_all(f):
            for root in config.keys():
                if root.startswith('feature '):
                    features[' '.join(root.split(' ')[1:])] = config[root]
                else:
                    configs[root] = config[root]
    return configs, features

def load_config(lang, *features):
    features = set(features)
    configs, config_features = load_configs()

    def build_dep_order(lang):
        if lang not in configs:
            raise Exception("invalid language target '%s'"%lang)
        config = configs[lang]
        deps = config['inheirit'] if 'inheirit' in config else []
        if type(deps) != list:
            deps = [deps]
        dep_order = []
        for dep in reversed(deps):
            dep_order += build_dep_order(dep)
        dep_order += [lang]
        return dep_order

    # build lang dependencies in order
    config = {}
    for dep in build_dep_order(lang):
        # print("Adding dep %s"%dep)
        update_recursive(config, configs[dep])
        # pretty_print(config)

    # add feature deps
    for feature in features:
        # print("adding feature %s"%feature)
        update_recursive(config, config_features[feature])
        # pretty_print(config)
    return config

def generate(config, names, state, actions):
    syntax = config['syntax']
    # print(list(config.keys()))
    type_conv = config['types']['decl']
    type_conv = { k: v.strip() for k, v in type_conv.items() }

    def format_type(t):
        if type(t) == dict:
            return type_conv['dict'].replace('...', ', '.join([
                '%s: %s'%(k, format_type(v))
                for k, v in t.items()
            ]))
        if type(t) == list:
            return type_conv['list'].replace('...', ', '.join(
                map(format_type, t)))
        if t in type_conv:
            return type_conv[t]
        return t

    def gen_interface(name, members):
        return (syntax['interface-decl'].strip()
            .replace('$name', name)
            .replace('$body', ' '.join([
                syntax['interface-elem'].strip()
                    .replace('$name', name)
                    .replace('$type', format_type(type))
                    for name, type in members.items()
                ])))

    def gen_enum(name, elements):
        return (syntax['enum']['decl'].strip()
            .replace('$type', name)
            .replace('$body', ' '.join([
                (syntax['enum']['decl_elem_0']
                if i == 0 else
                syntax['enum']['decl_elem'])
                    .strip()
                    .replace('$elem', elem)
                for i, elem in enumerate(elements)
            ])))

    def gen_fcn(name, params, return_type, body):
        return (syntax['fcn-signatures'].strip()
            .replace('$name', name)
            .replace('$params', ', '.join([
                syntax['type-signatures'].strip()
                    .replace('$var', name)
                    .replace('$type', format_type(type))
                for name, type in params.items()
            ]))
            .replace('$return-type', return_type)
            .replace('$body', body))

    def printjs(js):
        print(js)
        # print(jsbeautifier.beautify(js))

    printjs(gen_interface(names['StateType'], state))
    for name, action in actions.items():
        elem = 'ACTION_ELEM'
        params = { 'type': syntax['enum']['decl_type']
            .replace('$type', names['ActionEnumType'])
            .replace('$elem', elem)
        }
        params.update(action['params'])
        printjs(gen_interface(name, params))
    printjs(gen_enum(names['ActionEnumType'], [
        action for action in actions.keys()
    ]))
    for name, action in actions.items():
        printjs(gen_fcn(name, action['params'], name+'Action',
            syntax['action-ctor-body'].strip()
                .replace('$type', name+'Action')
                .replace('$elem', 'ACTION_ELEM')
                .replace('$params', ', '.join(action['params'].keys()))
            ))

    State, Actions = names['StateType'], names['ActionEnumType']

    def build_action(name, result):
        # print(name, result)
        if type(result) == dict:
            for key, expr in result.items():
                return (config['action-extensions'][key].strip()
                    .replace('$var', name)
                    .replace('$expr', expr))
        return str(result)

    State, Action = names['StateType'], names['ActionEnumType']
    printjs(gen_fcn('reducer', { 'state': State, 'action': Action }, State,
        syntax['enum']['match'].strip()
            .replace('$expr', 'state.type')
            .replace('$body', ' '.join([
                syntax['enum']['match-case'].strip()
                    .replace('$type', 'ActionType')
                    .replace('$elem', 'ACTION_ELEM')
                    .replace('$expr', syntax['reducer-state-return'].strip()
                        .replace('$cases', ''.join([
                            syntax['reducer-state-var'].strip()
                                .replace('$var', name)
                                .replace('$expr', build_action(name, result))
                            for name, result in action['reduce'].items()
                        ])))
                for action_name, action in actions.items()
            ])
        )))

if __name__ == '__main__':
    # load_config()
    for options in [
        [ 'typescript' ],
        [ 'typescript', 'typescript-enums' ],
        [ 'javascript' ],
    ]:
        print()
        print(options)
        generate(load_config(*options),
            { 'StateType': 'FooState', 'ActionEnumType': 'FooActions' },
            { 'foo': 'string', 'bar': [{ 'a': 'number', 'b': 'string' }] },
            {
                'add pillows': { 'params': { 'a': 'number' }, 'reduce': { 'foo': { 'append': 'fubar' } } },
                'add more pillows': { 'params': { 'a': 'number' }, 'reduce': { 'foo': '"fubar"' } },
            }
        )
    # pretty_print(load_config('typescript', 'string-enums'))


from functools import reduce
from os import write
from pickle import FALSE
import pronouncing
from nltk.tokenize import word_tokenize
import re
import string
import prosodic
prosodic.config['print_to_screen'] = 0
prosodic.config['en_TTS_ENGINE'] = 1

METER_LIMIT = 5
METER_LINE_LIMIT = 120 # The longer the line the longer it takes to analyze, so let's just skip them for speed

PHONEME_TO_TYPE = dict({(k,v[0]) for (k,v) in pronouncing.cmudict.phones()})

TYPE_TO_PHONEMES = {}
for k in set([i for i in PHONEME_TO_TYPE.values()]):
    TYPE_TO_PHONEMES[k] = [v for v in PHONEME_TO_TYPE if PHONEME_TO_TYPE[v]==k]

def alliterates(phoneme1, phoneme2):
    if(not(phoneme1 and phoneme2)):
        return False
    return phoneme1.split()[0] == phoneme2.split()[0]

def alliteration_and_assonance(tokens, phoneme_list, window_size):
    alliterations = []
    assonances = []
    window_size = min(len(tokens),window_size)-1
    for i in range(1,len(tokens)):
        for j in range(-min(window_size,i), 0):
            (po,pb) = (phoneme_list[i+j], phoneme_list[i])
            t = (tokens[i+j], tokens[i])
            if(any([alliterates(o,b) for o in po for b in pb])):
                alliterations.append(t)
            for o in po:
                for b in pb:
                    (vo, vb) = tuple(map(lambda ps: [p for p in ps.split() if p[:-1] in TYPE_TO_PHONEMES['vowel'] and int(p[-1]) >0],(o,b)))
                    if len(set(vo).intersection(set(vb))):
                        assonances.append(t)

    return (alliterations,assonances)

def estimate_syllables(word):
    approx = int(.6 + len(word)/3.2)
    _range = max(3, int(len(word)/3))
    return [ max(1, (i - int(_range/2)  + approx)) for i in range(_range)]

def is_haiku(tokens, phoneme_list):
    if(len(tokens)>17):
        return False

    all_syllables = []

    for (i,phs) in enumerate(phoneme_list):
        syllables = set([pronouncing.syllable_count(ph) for ph in phs])
        syllables = syllables if len(syllables) > 0 else estimate_syllables(tokens[i])
        syllables = list(set(syllables))
        all_syllables.append(syllables)

    possible_total_syllables = reduce(lambda x,y: [ i+n for i in x for n in y], all_syllables,[0])

    return 17 in set(possible_total_syllables)

def get_stresses(line):
    text = prosodic.Text(line)
    text.parse(meter='default_english')
    parses = text.bestParses()
    stresses = []
    for parse in parses:
        if parse is None:
            continue
        meter = ""
        for pos in parse.positions:
            val = pos.meterVal
            if val == "w":
                meter += "0" # I just prefer this representation
            elif val == "s":
                meter += "1"
        stresses.append(meter)
    return stresses

def stresses_to_meter(stresses):
    meter_table = {
        "01": "Iambic",
        "10": "Trochaic",
        "11": "Spondaic",
        "001": "Anapestic",
        "100": "Dactylic",
        "010": "Amphibrachic",
        "00": "Pyrrhic"
    }
    '''
    This is an ambiguous state machine, let's use the following flags:
    0: No meter found.
    n: End of state, found n copies.
    -n: End of state, go back n, also move pointer back n
    In all cases, simply grab the correct one from the table
    '''
    meter_tree = {
        "0": {
            "0": {
                "0": { # 00, third 0 is second set of 00. This could be done with -1 but let us continue for speed
                    "0": 2,
                    "1": 0 # Found 00 01 which is not a valid consistent meter
                },
                "1": 1 # Must be 001
            },
            "1": {
                "0": { # Ambiguous, need next token
                    "0": -1, # You could expand this state but that's ugly (010 010)
                    "1": 2
                },
                "1": 0
            }
        },
        "1": {
            "0": {
                "0": 1,
                "1": {
                    "0": 2,
                    "1": 0
                }
            },
            "1": {
                "0": 0,
                "1": {
                    "0": 0,
                    "1": 2
                }
            }
        }
    }
    count_table = {
        1: "monometer",
        2: "dimeter",
        3: "trimeter",
        4: "tetrameter",
        5: "pentameter",
        6: "hexameter",
        7: "heptameter",
        8: "octameter"
    }
    pointer = 0
    stack = ""
    counter = 0
    sub_tree = meter_tree
    while pointer < len(stresses) and counter == 0:
        val = stresses[pointer]
        if val == "2":
            val = "1"
        stack += val
        sub_tree = sub_tree[val]
        if not isinstance(sub_tree, dict): # We have found a leaf
            if sub_tree == 0:
                return None
            elif sub_tree < 0:
                pointer += sub_tree
                add = abs(sub_tree)
            else:
                add = sub_tree
                pointer += 1
            counter += add
            stack = stack[:(add//2)+1]
        else:
            pointer += 1
    if counter == 0 or len(stresses) % len(stack) != 0:
        return None
    else: # We have found a pattern, now to see if it repeats
        patt_pointer = 0
        while pointer < len(stresses):
            val = stresses[pointer]
            req = stack[patt_pointer]
            if val != req:
                return None
            pointer += 1
            patt_pointer += 1
            if patt_pointer >= len(stack):
                counter += 1
                patt_pointer = 0
    style = meter_table[stack]
    foot = counter
    if foot in count_table:
        foot = count_table[foot]
    return style + " " + str(foot)

def get_meter(poem):
    meters = []
    lines = poem.splitlines()
    if len(lines) < 2:
        return None
    for line in lines[:METER_LIMIT]:
        if len(line) <= METER_LINE_LIMIT:
            stresses = get_stresses(line)
            line_meters = []
            for stress in stresses:
                meter = stresses_to_meter(stress)
                line_meters.append(meter)
            meters.append(line_meters)
    scores = {}
    for meter in meters:
        for line_meter in meter:
            if line_meter in scores:
                scores[line_meter] += 1
            else:
                scores[line_meter] = 1
    scores = sorted(scores.items(), key=lambda x:x[1], reverse=True)
    return scores

def get_styles(poem, window_size=4):
    poem = re.sub(r"(\w+)-(\w+)",r"\1 \2",poem)
    tokens = [token for token in word_tokenize(poem) if not re.match(r"[^\w]+", token)]
    phonemes_for_tokens = [pronouncing.phones_for_word(t) for t in tokens]

    (alliterations, assonances) = alliteration_and_assonance(tokens, phonemes_for_tokens, window_size)

    meter = get_meter(poem)
    main_meter = None
    if meter:
        main_meter = meter[0][0]
        if main_meter is None and len(meter) > 1: # If it can't analyze most of the lines properly
            main_meter = meter[1][0]

    return {
        "form":{
            "is_haiku": is_haiku(tokens, phonemes_for_tokens),
        },
        "rhyme": {
            "alliteration": len(alliterations)/max(1,len(tokens)),
            "assonance": len(assonances)/max(1,len(tokens))
        },
        "meter": {
            "main": main_meter,
            "all": meter
        }
    }


import cv2, sys

# Print the HSV value of the pixel just clicked
def mouse_event(event, x, y, _, __):
    if event == cv2.EVENT_LBUTTONUP:
        pixel_value = frameGray[y,x]
        print(f"({x:3},{y:3}) -> {pixel_value}")

# Camera number can be given as a command line argument
# Note that camera number may change by rebooting or re-connection!
cap = cv2.VideoCapture(cv2.CAP_DSHOW+2 if len(sys.argv) == 1 else int(sys.argv[1]))

# Set frame size; for Logicool C270n, allowed values include
# 640x480, 320x240 and 160x120.
# High-resolution images require more processing cost.
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 320);
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 240);

# Prepare a window for the original image
cv2.namedWindow('src', cv2.WINDOW_NORMAL)
cv2.setMouseCallback('src', mouse_event)
cv2.moveWindow('src', 120,0)
cv2.resizeWindow('src',320,240)

# Another window for the transformed image
cv2.namedWindow('circles', cv2.WINDOW_NORMAL)
cv2.moveWindow('circles', 460,0)
cv2.resizeWindow('circles', 320,240)

while True:
    # (1) カメラからの入力画像1フレームをframeに格納
    _, frame = cap.read()
    frameGray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # (2)ハフ変換のための前処理（画像を平滑化しないと誤検出が出やすい）
    frameGray = cv2.GaussianBlur(frameGray, (11,11), 0)

    # (3)ハフ変換による円の検出と検出した円の描画
    h, w = frameGray.shape
    circles = cv2.HoughCircles(frameGray, cv2.HOUGH_GRADIENT,
              dp=1, minDist=3, param1=20, param2=70, minRadius=10, maxRadius=max(h,w))
    if circles is not None:
        circles = circles.squeeze(axis=0)
        for i in range(0, min(3, len(circles))):
            p = circles[i]
            cv2.circle(frame, (int(p[0]),int(p[1])), 4, (0,255,0), -1, 8, 0)
            cv2.circle(frame, (int(p[0]),int(p[1])), int(p[2]), (0,0,255), 6-2*i, 8, 0)

    # (4) 検出結果表示用のウィンドウを確保し表示する
    cv2.imshow('circles', frame)
    cv2.imshow('src', frameGray)

    # Press 'q' in the frame window to exit loop
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# cap.release()
# cv2.destroyAllWindows()


import itertools

# price: (dmg, armor)
weapons = {
    8:  (4, 0),  # dagger
    10: (5, 0),  # shortsword
    25: (6, 0),  # warhammer
    40: (7, 0),  # longsword
    74: (8, 0),  # greataxe
}

armors = {
    0:   (0, 0),  # nothin, yo
    13:  (0, 1),  # leather
    31:  (0, 2),  # chain
    53:  (0, 3),  # splint
    75:  (0, 4),  # banded
    102: (0, 5),  # plate
}

rings = {
    0:   (0, 0),    # nothin, yo
    25:  (1, 0),    # damage 1
    50:  (2, 0),    # damage 2
    100: (3, 0),    # damage 3
    20:  (0, 1),    # def 1
    40:  (0, 2),    # def 2
    80:  (0, 3),    # def 3
}

class Combatant:
    def __init__(self, name, hp, dmg, armor):
        self.name = name
        self.hp = hp
        self.damage = dmg
        self.armor = armor

    def hit(self, other):
        damage = (self.damage - other.armor)
        other.hp -= max(damage, 1)

    def is_dead(self):
        return self.hp <= 0

def player_wins_sim(player, boss):
    for turn in itertools.cycle([(player, boss), (boss, player)]):
        attacker, victim = turn
        attacker.hit(victim)
        if victim.is_dead():
            return attacker == player

    raise RuntimeError('unreachable!')

best = None
worst = None
bossargs = ['boss', 100, 8, 2]

for wcost, wtup in weapons.items():
    for acost, atup in armors.items():
        all_rings = itertools.chain(rings.items(), [(0, (0, 0))])

        for ring1, ring2 in itertools.combinations(all_rings, 2):
            cost = wcost + acost + ring1[0] + ring2[0]
            damage = wtup[0] + ring1[1][0] + ring2[1][0]
            armor = atup[1] + ring1[1][1] + ring2[1][1]

            boss = Combatant(*bossargs)
            player = Combatant('player', 100, damage, armor)

            if player_wins_sim(player, boss):
                if not best or best > cost:
                    best = cost
            else:
                if not worst or worst < cost:
                    worst = cost

print(f'part 1: {best}')
print(f'part 2: {worst}')


import os
import pandas as pd
from pyterrier.measures import *
import pyterrier as pt
import sys

from utils import chunk_based_on_number

from functools import partial

from CAsTutils import loadIndex, loadQueries, loadQrels

import numpy as np

os.environ['JAVA_HOME'] = '../../../../SOFTWARE/jdk-11.0.11'

'''
import neuralcoref
nlp = spacy.load("en_core_web_sm")

neuralcoref.add_to_pipe(nlp)
doc_with_coref = nlp(v)
print(doc_with_coref)
new_conv_coref = doc_with_coref._.coref_resolved
new_doc_coref = nlp(new_conv_coref)
new_utt_list = list(new_doc_coref.sents)

print(new_utt_list)
'''

if not pt.started():
    pt.init(boot_packages=["com.github.terrierteam:terrier-prf:-SNAPSHOT"])

queries = loadQueries("original")
qrels = loadQrels()

queries_resolved = loadQueries("resolved")

from allennlp_models import pretrained
from allennlp.predictors.predictor import Predictor
#predictor = Predictor.from_path(
#            "https://storage.googleapis.com/allennlp-public-models/coref-model-2018.02.05-allennlpv1.0.tar.gz")
predictor = pretrained.load_predictor("coref-spanbert")
#"https://storage.googleapis.com/allennlp-public-models/coref-model-2018.02.05-allennlpv1.0.tar.gz"

import spacy

#nlp = spacy.load("en_core_web_sm")

n_perms = 5
t2perm = {}
with open("../../../data/class_perms.txt", "r") as F:
    for l in F.readlines():
        topic, permutations = l.strip().split("\t")
        permutations = eval(permutations)
        t2perm[topic] = [sorted(permutations[0])] + permutations[1:n_perms]

def convert_topic_permutations(ds, t2perm):
    permutations = t2perm[ds['topic'].values[0]]
    order = {i:e for e, i in enumerate(sorted(permutations[0]))}
    for e, p in enumerate(permutations):
        newOrder = [order[i] for i in p]
        queries = ds.iloc[newOrder]

        print(queries)

        v = " | ".join(queries['query'].values)
        doc = predictor.coref_resolved(v)
        new_utt_list = doc.split(" | ")

        for e2, u in enumerate(new_utt_list):
            if u!=queries_resolved[queries_resolved['topic']==ds['topic'].values[0]]['query'].values[newOrder[e2]]:
                print(f"{u} - {queries_resolved[queries_resolved['topic']==ds['topic'].values[0]]['query'].values[newOrder[e2]]}")

queries.groupby(['topic']).apply(convert_topic_permutations, t2perm)


from django.urls import path
from . import views
from .views import ListToonsView, ThisToonsView

urlpatterns = [
    path('', views.index, name='index'),
    path('all/', views.alltoons, name='alltoons'),
    path('all/<toon>', views.thistoon, name='thistoon'),
    path('api/', ListToonsView.as_view(), name="toons-all"),
    path('api/<toon>', ThisToonsView.as_view(), name="toon")

]


import subprocess
import shutil
import os
# from . models import Question, Testcase
from subprocess import STDOUT, check_output
from celery import shared_task

def execute(code, tc, language):
    copy_run_py(language)
    copy_code(code)
    copy_input(tc)
    run = subprocess.run("python code/run.py", shell=True)

    return get_output_files()

def runCode(que, code, language):
    TCs = Testcase.objects.filter(que=que).order_by('pk')
    TC_Status = []
    outputList = []
    for tc in TCs:
        output, err, rc = execute(code, tc, language)
        if rc != 0:
            TC_Status.append("RE")
        elif compare(output, tc):
            TC_Status.append("AC")
        else:
            TC_Status.append("WA")

    return TC_Status

def compare(output, tc):
    try:
        with open(tc.tc_output.path, "r") as correct_output:
            x = correct_output.read().strip()
            return output.strip() == x
    except:
        return False

def create_containers():
    for i in range(6):
        try:
            os.makedirs(f"containers/container_{i}/")
        except:
            pass
    for i in range(6):
        container_path = f"{os.getcwd()}\\containers\\container_{i}"
        subprocess.run(f"docker run --name container_{i} -v {container_path}:src\ python", shell=True)

def copy_run_py(language):
    src = "run.py"
    dst = f"code/run.py"
    shutil.copyfile(src, dst)
    file1 = open(dst, "a")  # append mode
    file1.write(f"\nrun_{language}()")
    file1.close()

def copy_code(code):
    file_path = "code/code.py"
    with open(file_path, 'w+') as file:
        file.write(code)
        file.close()

def copy_input(tc):
    dst = "code/input.txt"
    src = tc.tc_input.path
    shutil.copy(src, dst)

def get_output_files():
    output = open("code/output.txt").read()
    err = open("code/err.txt").read()
    rc = open("code/returnCode.txt").read()
    return output, err, int(rc)

#my
import os,pathlib,subprocess
from django.conf import settings
project_name = "Clash_RC_2"
directory = os.path.join(settings.BASE_DIR,"User_Data")

def make_dir(user):
    print("inside make_dir",directory)
    # project_name = "Clash_RC_2"
    # directory = pathlib.Path(f"./{project_name}/User_Data/{username}")
    # if not directory.exists():
    #     directory.mkdir()
    #     return 1
    user_folder = pathlib.Path(f"{directory}/{user}")  #to check directory is present or not
    #if not it will create it
    if not user_folder.exists():
        user_folder.mkdir()

def make_code_file(language,code,ip_text,user):
    if language == "py":
        code_file = open(f"{directory}/{user}/code.{language}","w")
        code_file.write(code)
        code_file.close()
        text_file = open(f"{directory}/{user}/ip_text_file.txt","w")
        text_file.write(ip_text.replace('\n',""))
        text_file.close()
        return run_code_file(user,language)

def run_code_file(user,language):
    if (language == "py"):
        code_file_path = pathlib.Path(f"{directory}/{user}/code.py")
        text_file = pathlib.Path(f"{directory}/{user}/ip_text_file.txt")
        cmd = f"python {code_file_path} <{text_file}"
        op = subprocess.run(cmd,shell=True,text=True,capture_output=True)
        # print(op)
        # print(op.stdout)
        # print(op.stderr)
        code_op_text_file = open(f"{directory}/{user}/op_text.txt","w")
        if op.returncode !=1:
            code_op_text_file.write(op.stdout)
        else:
            code_op_text_file.write(op.stderr)

        code_op_text_file.close()

        if (compare_answer(user)):
            return True
        else:
            return False

directory_questions = os.path.join(settings.BASE_DIR,"Question_Data")

def compare_answer(user):
    with open(f'{directory_questions}/question_op/Q1_1_op.txt', 'r') as f1, open(f"{directory}/{user}/op_text.txt", 'r') as f2:
    # Read the contents of each file into memory
        file1_contents = f1.readlines()
        file2_contents = f2.readlines()
        print(file1_contents)
        print(file2_contents)

    # Compare the contents of the files
    if file1_contents == file2_contents:
        print("The files are the same")
        return True
    else:
        print("The files are different")
        return False

    # try:
    #     with open(f'{directory_questions}/question_op/Q1_1_op.txt', "r") as correct_output:
    #         x = correct_output.read().strip()
    #         y = f"{directory}/{user}/op_text.txt"
    #         print(x,y)
    #         if y.strip() == x :
    #             print("same file")
    #             return True
    #         else:
    #             print("diff file")
    #             return False
    # except:
    #     return False

#dev

import subprocess,os
import time
codeRunnerPath = os.path.abspath("Code_Runner")
print(codeRunnerPath,"dddddddddddddddddddddkkkkkkkkkkkkkkkkkkkkkkkk")
def run_python():
    code_path = f"{codeRunnerPath}/code.py"
    tc_path = f"{codeRunnerPath}/input.txt"
    # x = open(tc_path,"r")
    # y = open(code_path,"r")
    # print(x.read(),y.read())
    er=open(f'{codeRunnerPath}/error.txt','w+')
    rc=open(f'{codeRunnerPath}/status.txt','w+')
    out=open(f'{codeRunnerPath}/output.txt','w+')
    # run = subprocess.run(f"python {code_path} <{tc_path}", text=True, shell=True, capture_output=True,timeout=1)
    st =time.time()
    try:
        run = subprocess.run(f"python {code_path} <{tc_path}", text=True, shell=True, capture_output=True,timeout=1)
    except subprocess.TimeoutExpired:
        print("enter in exept blockhhhhhhhhhhhhhhhhhhhkkhk")
    et = time.time()
    print("time foe execution  : ",et-st)

    # print(run)
    # print(run.stdout)
    # print(run.stderr)
    # print(run.returncode)

    out.write(run.stdout)
    er.write(run.stderr)
    rc.write(str(run.returncode))
    er.close()
    rc.close()
    out.close()

def run_cpp():
    code_path = f"{codeRunnerPath}/code.cpp"
    tc_path = f"{codeRunnerPath}/input.txt"
    # x = open(tc_path,"r")
    # y = open(code_path,"r")
    # print(x.read(),y.read())
    er=open(f'{codeRunnerPath}/error.txt','w+')
    rc=open(f'{codeRunnerPath}/status.txt','w+')
    out=open(f'{codeRunnerPath}/output.txt','w+')
    # run = subprocess.run(f"python {code_path} <{tc_path}", text=True, shell=True, capture_output=True)
    run = subprocess.run(['g++', '-o', f"{codeRunnerPath}/code", f"{code_path}"], capture_output=True, text=True)
    # print(run)
    if run.returncode != 0:
        rc.write(str(run.returncode))
        rc.close()
        er.write(run.stderr)
        er.close()
        print('Compilation failed. Errors written to errors.txt.')
    else:
        with open(f"{tc_path}", "r") as input_file:
            program_result = subprocess.run([f"{codeRunnerPath}/./code"],stdin=input_file, capture_output=True, text=True)
            out.write(program_result.stdout)
            er.write(program_result.stderr)
            rc.write(str(run.returncode))
            rc.close()
            er.close()
            out.close()

def run_c():
    code_path = f"{codeRunnerPath}/code.c"
    tc_path = f"{codeRunnerPath}/input.txt"
    # x = open(tc_path,"r")
    # y = open(code_path,"r")
    # print(x.read(),y.read())
    er=open(f'{codeRunnerPath}/error.txt','w+')
    rc=open(f'{codeRunnerPath}/status.txt','w+')
    out=open(f'{codeRunnerPath}/output.txt','w+')
    # run = subprocess.run(f"python {code_path} <{tc_path}", text=True, shell=True, capture_output=True)
    run = subprocess.run(['gcc', '-o', f"{codeRunnerPath}/code", f"{code_path}"], capture_output=True, text=True)
    # print(run)
    if run.returncode != 0:
        rc.write(str(run.returncode))
        rc.close()
        er.write(run.stderr)
        er.close()
        print('Compilation failed. Errors written to errors.txt.')
    else:
        with open(f"{tc_path}", "r") as input_file:
            program_result = subprocess.run([f"{codeRunnerPath}/./code "],stdin=input_file, capture_output=True, text=True)
            out.write(program_result.stdout)
            er.write(program_result.stderr)
            rc.write(str(run.returncode))
            rc.close()
            er.close()
            out.close()

#ruuner utils
import subprocess
import shutil
import os
from .models import Question, Testcases
from subprocess import STDOUT, check_output
# from celery import shared_task
codeRunnerPath = os.path.abspath("Code_Runner")
# codeRunnerPath="Clash_RC_2/Code_Runner"
runnerPath = os.path.dirname(__file__)
print(codeRunnerPath,"dddjjjjjjjjjjjjjjjjjjjjjjjjjjjjj")

ErrorCodes={
  "AC": 0,
  "WA": 1,
  "CE": 2,
  "RE": 3,
  "MLE":4,
  "TLE":5,
}

def execute(code, tc, language):
    copy_run_py(language)
    copy_code(code,language)
    copy_input(tc)
    run = subprocess.run(f"python {codeRunnerPath}/code_run.py", shell=True)

    return get_output_files()

def runCode(que_num, code, language,btn_click_status,user_test):             #btn_click_status true = submit and false = run
    TC_Status = []
    # print("fffffffffff",user_test)
    if (btn_click_status==0):
        output, err, rc = execute_run(code, user_test, language)
        print("ge output files",output,"type ",err,rc)

        if int(rc) !=0:
            print("enter in if")
            TC_Status.append(err)
        else:
            print("enter in else")
            TC_Status.append(output)
        print("in run code for run clicke",TC_Status)
        return TC_Status

    TCs = Testcases.objects.filter(q_id=que_num).order_by('t_id')
    # print("TEst casesinside runcode ",TCs)
    outputList = []
    for tc in TCs:

        output, err, rc = execute(code, tc, language)
        # print("op",output,"err",err,"status",rc,"value of compare",compare(output, tc))
        if int(rc) != 0:
            TC_Status.append("RE")
        elif compare(output, tc):
            TC_Status.append("AC")
        else:
            TC_Status.append("WA")
    print("see list of status ",TC_Status)
    return TC_Status

def compare(output, tc):
    try:
        with open(tc.t_op.path, "r") as correct_output:
            x = correct_output.read().strip()
            # print("actual : ",x,"user : ",output)
            return output.strip() == x
    except:
        return False

def copy_run_py(language):
    src = f"{runnerPath}/runner.py"
    dst = f"{codeRunnerPath}/code_run.py"
    print(src,"\n",dst,"\nsdsssssssddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd")
    shutil.copyfile(src, dst)
    file1 = open(dst, "a")  # append mode
    file1.write(f"\nrun_{language}()")
    file1.close()

def copy_code(code,language):
    if (language=="python"):
        file_path = f"{codeRunnerPath}/code.py"
    elif (language=="cpp"):
        file_path = f"{codeRunnerPath}/code.cpp"
    elif (language=="c"):
        file_path = f"{codeRunnerPath}/code.c"
    with open(file_path, 'w+') as file:
        file.write(code)
        file.close()

def copy_input(tc):
    dst = f"{codeRunnerPath}/input.txt"
    src = tc.t_ip.path
    shutil.copy(src, dst)

def get_output_files():
    output = open(f"{codeRunnerPath}/output.txt").read()
    err = open(f"{codeRunnerPath}/error.txt").read()
    rc = open(f"{codeRunnerPath}/status.txt").read()
    print("ge output files",output,"type ",err,rc)
    return output, err, rc

#when run clicke
def copy_test_input(tc):
    # print("dfddddddddd",tc)
    dst = open(f"{codeRunnerPath}/input.txt","w")
    dst.write(tc)
    dst.close()

def execute_run(code, tc, language):
    copy_run_py(language)
    copy_code(code,language)
    copy_test_input(tc)
    run = subprocess.run(f"python {codeRunnerPath}/code_run.py", shell=True)

    return get_output_files()

#To detect error
# import os
codeRunnerPath = os.path.abspath("testsubprocess")
# codeRunnerPath="Clash_RC_2/Code_Runner"

#It will give current file path
#And our other files are in same folder
FilePath = os.path.dirname(__file__)
print("File Path ",FilePath)

#File in which users code is present
PythonFile = f"{FilePath}/code.py"
CppFile = f"{FilePath}/code.cpp"
CFile = f"{FilePath}/code.c"
#File in which ip testcase is present
ip_file_path = f"{FilePath}/input.txt"
with open(ip_file_path, 'r') as f:
    ip_contents = f.read()

import subprocess
import signal,resource
import psutil,re

ceErrors = [ "SyntaxError:","NameError:","TypeError:","ImportError:","IndentationError:","LogicError:"]
reErrors = ["ZeroDivisionError:","IndexError:","KeyError:","AttributeError:","ValueError:","RuntimeError","StopIteration","RecursionError","OSError"]
#"MemoryError"

#Timeout Signal
TimeoutLimit = 1
def set_time_limit(time_limit):
    def signal_handler(signum, frame):
        raise TimeoutError
    signal.signal(signal.SIGALRM, signal_handler)
    signal.alarm(time_limit)

MemoryLimit = 256 * 1024 * 1024
def set_memory_limit():
    # resource.setrlimit(resource.RLIMIT_CPU, (TimeoutLimit, TimeoutLimit))
    resource.setrlimit(resource.RLIMIT_AS, (MemoryLimit, MemoryLimit))

def execute_user_code(lang):
    try:
        set_time_limit(TimeoutLimit)

        process = RunByLang(lang)

        # # wait for the command to finish and get the stdout and stderr
        stdout, stderr = process.communicate()
        CopyFilesToTxt(stdout,stderr)
        ListOfReturn =stderr.decode().strip().split()
        print(ListOfReturn)
        # signal.alarm(0)

        # check for any errors in stderr
        if process.returncode != 0:
            process.kill()
            if any(error in ListOfReturn for error in ceErrors):
                return "CE"
            elif any(error in ListOfReturn for error in reErrors):
                return "RE"
            elif "MemoryError" in ListOfReturn:
                return "MLE"
            else:
                return "WA"
        else:
            if (process.returncode == 0):
                return "AC"
            else:
                return "WA"
    except TimeoutError:
        # handle timeout error
        process.kill()
        stdout, stderr = process.communicate()
        CopyFilesToTxt(stdout,stderr)

        # stderr = process.stderr.read()
        ListOfReturn =stderr.decode().strip().split()
        # s[s.index("File")] = "ddddd"
        # print("index ",ListOfReturn)
        # print("inside 1timeout ",str(stderr.decode()).split())
        if ("MemoryError" in ListOfReturn):
            print("present MLE")
            return "MLE"

        return "TLE"

def CopyFilesToTxt(stdout,stderr,rCode):
    err=open(f'{FilePath}/error.txt','w+')
    out=open(f'{FilePath}/output.txt','w+')
    # rCode=open(f'{FilePath}/status.txt','w+')

    out.write(stdout.decode().strip())
    err.write(stderr.decode().strip())
    # rCode.write(rCode)

def RunByLang(lang):
    if (lang == "py"):
        process = subprocess.Popen(['python3', f'{PythonFile}'],stdin=ip_contents,stdout=subprocess.PIPE, stderr=subprocess.PIPE,preexec_fn=set_memory_limit)
        return process
    elif (lang == "cpp"):
        process = subprocess.Popen(['g++', '-o', f"{FilePath}/code", f"{CppFile}"],stdout=subprocess.PIPE, stderr=subprocess.PIPE,preexec_fn=set_memory_limit )
        if (process.returncode != 0):
            return process
        process = subprocess.Popen([f"{FilePath}/./code"],stdin=ip_contents,stdout=subprocess.PIPE, stderr=subprocess.PIPE,preexec_fn=set_memory_limit )
        return process

# test the function with a sample command
command = ['python3', f'{PythonFile}']
result = execute_user_code(command)
print("result   ",result)

import subprocess,os
import time

codeRunnerPath = os.path.abspath("Code_Runner")
# codeRunnerPath="Clash_RC_2/Code_Runner"
runnerPath = os.path.dirname(__file__)
print(codeRunnerPath,"sssssssssssss",runnerPath)

def run_with_popen(language):
    # File path for coderunner
    code_path = f"{codeRunnerPath}/code.py"
    # tc_path = f"{codeRunnerPath}/input.txt"

    # Location for ip.txt file
    tc_path = open(f'{codeRunnerPath}/input.txt','r')

    #Locations for error output file
    er=open(f'{codeRunnerPath}/error.txt','w+')
    rc=open(f'{codeRunnerPath}/status.txt','w+')
    out=open(f'{codeRunnerPath}/output.txt','w+')

    st =time.time()
    cmd = f"python3 {code_path}"

    # run = subprocess.Popen(cmd,stdin=tc_path,stderr=subprocess.PIPE,stdout=subprocess.PIPE,shell=True,text=True)
    run = subprocess.Popen(cmd,stdin=tc_path,stderr=er,stdout=out,shell=True,text=True)
    run.wait()

    et = time.time()
    print("time foe execution  : ",et-st)

    # print(run)
    print(run.returncode)
    """ in popen if we piped stdin out then we not need to communicate op will save at specified place
        if not piped then use communicate"""

run_with_popen()