# Programmer: Jesse Chisholm
# Program: Static Simple PostScript (CptS 355 HW6)
#
# Description: This is a compiler for a variation on the PostScript programming language. This
#              variation has most of the non-graphical language features of PostScript except that
#              there are no dictionary commands like dictz begin and end. Instead, the language
#              is dynamically scoped by default (with an optional flag to behave as if statically
#              scoped), so that the dictionary stack is handled by the compiler instead of the user.
#              Floating point numbers are not currently supported in SSPS.
#
# How to use: Run the command "python ssps.py [flags] input-filename" or "python3 [flags] ssps.py input-filename",
#             depending on how python is installed on your system. The program defaults with debug mode off and
#             static mode off.
#
#             Optional Flags:
#                    -x : Run in debug mode, producing detailed debugging output while interpreting the program code.
#                    -s : Run in static mode, running the program as if SSPS is statically scoped.
#                    -d : Run in dynamic mode, running the program code as if SSPS is dynamically scoped.

# -------------------------\
# Operand Stack Operations |
# -------------------------/

def op_push(operand):
    """
    Push operand onto the operand stack.
    Throws an error if the operand is a float.
    """
    if is_float(operand):
        error("op_push", "float argument encountered", [operand])
    op_stack.append(operand)

def op_pop():
    """
    Remove and return top of the operand stack.
    Throws an error if the operand stack is empty.
    """
    if is_empty(op_stack):
        error("op_pop", "empty operand stack")
    return op_stack.pop()

def dup_op():
    """
    Duplicates the top operand on the operand stack.
    """
    debug("***dup_op performed***")
    debug("Operand Stack (Before): " + str(op_stack)[1:-1])
    val = op_pop()
    dup = val
    op_push(val)
    op_push(dup)
    debug("Operand Stack (After): " + str(op_stack)[1:-1])
    debug()

def exch_op():
    """
    Swaps the top two operands on the operand stack.
    """
    debug("***exch_op performed***")
    debug("Operand Stack (Before): " + str(op_stack)[1:-1])
    second = op_pop()
    first = op_pop()
    op_push(second)
    op_push(first)
    debug("Operand Stack (After): " + str(op_stack)[1:-1])
    debug()

def stack_op():
    """
    Prints contents of operand and dictionary stacks.
    """
    print("==============")

    op_stack.reverse()
    for operand in op_stack:
        print(operand)
    op_stack.reverse()

    print("==============")

    dict_stack.reverse()
    index = len(dict_stack) - 1
    for (d, link) in dict_stack:
        print("----", index, "---- ", end="")
        if static:
            print(link, "----", end="")
        print()
        for (k, v) in d.items():
            print(k, " [", v, "]", sep="")
        index -= 1
    dict_stack.reverse()

    print("==============")

def top_op():
    """
    Pops operand off of operand stack and prints it.
    """
    print(op_pop())

# ----------------------\
# Arithmetic Operations |
# ----------------------/

def add_op():
    """
    Takes two operands from the operand stack,
    performs an integer addition operation,
    and pushes the integer result to the operand stack.
    Throws an error if any operand is not an integer.
    """
    debug("***add_op performed***")
    debug("Operand Stack (Before): " + str(op_stack)[1:-1])
    second = op_pop()
    first = op_pop()
    if is_int(first) and is_int(second):
        op_push(first + second)
    else:
        error("add_op", "non-int operand encountered", [first, second])
    debug("Operand Stack (After): " + str(op_stack)[1:-1])
    debug()

def sub_op():
    """
    Takes two operands from the operand stack,
    performs an integer subtraction operation,
    and pushes the integer result to the operand stack.
    Throws an error if any operand is not an integer.
    """
    debug("***sub_op performed***")
    debug("Operand Stack (Before): " + str(op_stack)[1:-1])
    second = op_pop()
    first = op_pop()
    if is_int(first) and is_int(second):
        op_push(first - second)
    else:
        error("sub_op", "non-int operand encountered", [first, second])
    debug("Operand Stack (After): " + str(op_stack)[1:-1])
    debug()

def mul_op():
    """
    Takes two operands from the operand stack,
    performs an integer multiplication operation,
    and pushes the integer result to the operand stack.
    Throws an error if any operand is not an integer.
    """
    debug("***mul_op performed***")
    debug("Operand Stack (Before): " + str(op_stack)[1:-1])
    second = op_pop()
    first = op_pop()
    if is_int(first) and is_int(second):
        op_push(first * second)
    else:
        error("mul_op", "non-int operand encountered", [first, second])
    debug("Operand Stack (After): " + str(op_stack)[1:-1])
    debug()

def div_op():
    """
    Takes two operands from the operand stack,
    performs an integer division operation,
    and pushes the integer result to the operand stack.
    Throws an error if any operand is not an integer,
    or if dividing by zero.
    """
    debug("***div_op performed***")
    debug("Operand Stack (Before): " + str(op_stack)[1:-1])
    second = op_pop()
    first = op_pop()
    if is_int(first) and is_int(second):
        if second != 0:
            op_push(first // second)
        else:
            error("div_op", "dividing by zero", [first, second])
    else:
        error("div_op", "non-int operand encountered", [first, second])
    debug("Operand Stack (After): " + str(op_stack)[1:-1])
    debug()

# ----------------------\
# Comparison Operations |
# ----------------------/

def eq_op():
    """
    Takes two operands from the operand stack,
    performs an integer or boolean equality comparison,
    and pushes the boolean result to the operand stack.
    Throws an error if the operands are not either
    both booleans or both integers.
    """
    debug("***eq_op performed***")
    debug("Operand Stack (Before): " + str(op_stack)[1:-1])
    second = op_pop()
    first = op_pop()
    if is_int(first) and is_int(second):
        op_push(first == second)
    elif is_bool(first) and is_bool(second):
        op_push(first == second)
    else:
        error("eq_op", "non-matching operand types encountered", [first, second])
    debug("Operand Stack (After): " + str(op_stack)[1:-1])
    debug()

def lt_op():
    """
    Takes two operands from the operand stack,
    performs an integer less-than comparison,
    and pushes the boolean result to the operand stack.
    Throws an error if any operand is not an integer.
    """
    debug("***lt_op performed***")
    debug("Operand Stack (Before): " + str(op_stack)[1:-1])
    second = op_pop()
    first = op_pop()
    if is_int(first) and is_int(second):
        op_push(first < second)
    else:
        error("lt_op", "non-int operand encountered", [first, second])
    debug("Operand Stack (After): " + str(op_stack)[1:-1])
    debug()

def gt_op():
    """
    Takes two operands from the operand stack,
    performs an integer greater-than comparison,
    and pushes the boolean result to the operand stack.
    Throws an error if any operand is not an integer.
    """
    debug("***gt_op performed***")
    debug("Operand Stack (Before): " + str(op_stack)[1:-1])
    second = op_pop()
    first = op_pop()
    if is_int(first) and is_int(second):
        op_push(first > second)
    else:
        error("gt_op", "non-int operand encountered", [first, second])
    debug("Operand Stack (After): " + str(op_stack)[1:-1])
    debug()

# -------------------\
# Boolean Operations |
# -------------------/

def and_op():
    """
    Takes two operands from the operand stack,
    performs a boolean 'and' operation,
    and pushes the boolean result to the operand stack.
    Throws an error if any operand is not a boolean.
    """
    debug("***and_op performed***")
    debug("Operand Stack (Before): " + str(op_stack)[1:-1])
    second = op_pop()
    first = op_pop()
    if is_bool(first) and is_bool(second):
        op_push(first and second)
    else:
        error("and_op", "non-bool operand encountered", [first, second])
    debug("Operand Stack (After): " + str(op_stack)[1:-1])
    debug()

def or_op():
    """
    Takes two operands from the operand stack,
    performs a boolean 'or' operation,
    and pushes the boolean result to the operand stack.
    Throws an error if any operand is not a boolean.
    """
    debug("***or_op performed***")
    debug("Operand Stack (Before): " + str(op_stack)[1:-1])
    second = op_pop()
    first = op_pop()
    if is_bool(first) and is_bool(second):
        op_push(first or second)
    else:
        error("or_op", "non-bool operand encountered", [first, second])
    debug("Operand Stack (After): " + str(op_stack)[1:-1])
    debug()

def not_op():
    """
    Takes one operand from the operand stack,
    performs a boolean 'not' operation,
    and pushes the boolean result to the operand stack.
    Throws an error if the operand is not a boolean.
    """
    debug("***not_op performed***")
    debug("Operand Stack (Before): " + str(op_stack)[1:-1])
    value = op_pop()
    if is_bool(value):
        op_push(not value)
    else:
        error("not_op", "non-bool operand encountered", [value])
    debug("Operand Stack (After): " + str(op_stack)[1:-1])
    debug()

# -------------\
# Conditionals |
# -------------/

def if_op():
    """
    Takes a boolean and a code array from the operand stack,
    and only interprets the code array if the boolean is True.
    """
    debug("***if_op performed***")
    debug("Operand Stack (Before): " + str(op_stack)[1:-1])
    if_code = op_pop()
    boolean = op_pop()
    if is_bool(boolean):
        if boolean:
            interpret(if_code)
    else:
        error("if_op", "non-bool operand encountered", [boolean])
    debug("Operand Stack (After): " + str(op_stack)[1:-1])
    debug()

def if_else_op():
    """
    Takes a boolean and two code arrays from the stack,
    only interprets the first code array if the boolean is True,
    and only interprets the second code array if the boolean is False.
    """
    debug("***if_else_op performed***")
    debug("Operand Stack (Before): " + str(op_stack)[1:-1])
    else_code = op_pop()
    if_code = op_pop()
    boolean = op_pop()
    if is_bool(boolean):
        if boolean:
            interpret(if_code)
        else:
            interpret(else_code)
    else:
        error("if_else_op", "non-bool operand encountered", [boolean])
    debug("Operand Stack (After): " + str(op_stack)[1:-1])
    debug()

# ----------------------\
# Dictionary Operations |
# ----------------------/

def is_in_dict(d, name):
    """
    Checks if the dictionary d contains the key name.
    Returns True if the key is found, False otherwise.
    """
    return name in d

def get_from_dict(d, name):
    """
    Returns the value associated with the key name in dictionary d.
    Throws an error if key does not exist in d.
    """
    if is_in_dict(d, name):
        return d[name]
    # May be unnecessary to ever throw this error, but why not just in case.
    error("get_from_dict", "name not found", [name])

def add_to_dict(d, name, value):
    """
    Adds the name-value association pair to dictionary d.
    """
    d[name] = value

# ----------------------------\
# Dictionary Stack Operations |
# ----------------------------/

def dict_push(d, link):
    """
    Push dictionary d with access link onto the dictionary stack.
    """
    dict_stack.append((d, link))

def dict_pop():
    """
    Remove and return top of the dictionary stack.
    Throws an error if the dictionary stack is empty.
    """
    if is_empty(dict_stack):
        error("dict_pop", "empty dictionary stack")
    return dict_stack.pop()

def def_op():
    """
    Takes a name and a value from the operand stack,
    gets the top dictionary d from the dictionary stack,
    adds the name-value association to d,
    and pushes d back on the dictionary stack.
    Throws an error if the name is formatted incorrectly.
    """
    debug("***def_op performed***")
    debug("Operand Stack (Before): " + str(op_stack)[1:-1])
    debug("Top Dictionary and Link (Before): " + str(dict_stack[-1])[1:-1])
    value = op_pop()
    name = op_pop()
    if not is_name(name):
        error("def_op", "trying to define non-name", [name])
    (d, link) = dict_pop()
    add_to_dict(d, name[1:], value)
    dict_push(d, link)
    debug("Operand Stack (After): " + str(op_stack)[1:-1])
    debug("Top Dictionary and Link (After): " + str(dict_stack[-1])[1:-1])
    debug()

def get_link(name):
    """
    Searches for the name in each dictionary on the dictionary stack,
    starting with the top dictionary working down.
    If the name is found in any dictionary, returns the positive index of the
    dictionary that contains the name.
    Throws error if the name is not found in any dictionary.
    """
    index = 0
    dict_stack.reverse()
    for (d, link) in dict_stack:
        if is_in_dict(d, name):
            dict_stack.reverse()
            return len(dict_stack) - index - 1
        index += 1
    error("get_link", "name is undefined", [name])

def lookup(name):
    """
    If the name is found in or below the current scope, returns the value of the name.
    Follows static links if static, goes top-down if dynamic.
    Throws error if the name is not found in or below the current scope.
    """
    if static:
        index = -1
        while True:
            (d, link) = dict_stack[index]
            debug("Current dictionary: " + str(d))
            debug("Static link: " + str(link))
            if is_in_dict(d, name):
                return get_from_dict(d, name)
            else:
                if not is_int(link):
                    error("lookup", "name is undefined in current static scope", [name])
                if index == link:
                    error("lookup", "infinite loop", [name])
                debug("Following static link to index " + str(link) + "...")
                index = link
    else:
        link = get_link(name)
        debug("Following dynamic links, the name \"" + str(name) + "\" was found at index " + str(link))
        if not is_int(link):
            error("lookup", "name is undefined in current dynamic scope", [name])
        (d, link) = dict_stack[link]
        return get_from_dict(d, name)

# ----------------\
# Other Functions |
# ----------------/

def debug(message="", sep=" ", end="\n"):
    """
    Debugging output, only prints if debugging is enabled.
    """
    if debugging:
        print(message, sep, end)

def is_bool(value):
    """
    Helper function that checks if value is a boolean.
    Returns True if value is boolean, False if not.
    """
    return type(value) is bool

def is_int(value):
    """
    Helper function that checks if value is an integer.
    Returns True if value is an integer, False if not.
    """
    return type(value) is int

def is_float(value):
    """
    Helper function that checks if value is a float.
    Returns True if value is an float, False if not.
    """
    return type(value) is float

def is_string(value):
    """
    Helper function that checks if value is a string.
    Returns True if value is an string, False if not.
    """
    return type(value) is str

def is_dict(value):
    """
    Helper function that checks if value is a dictionary.
    Returns True if value is an dict, False if not.
    """
    return type(value) is dict

def is_name(value):
    """
    Helper function that checks if value is a /name.
    Returns True if value is a /name, False if not.
    """
    if not is_string(value):
        return False
    if value[0] != '/':
        return False
    return True

def is_empty(stack):
    """
    Helper function that checks if a stack is empty.
    Returns True if the stack is empty, False if not.
    """
    return len(stack) < 1

def error(criminal, crime, accomplices=[]):
    """
    Prints semi-detailed error message and exits program.
    """
    print("Error in ", criminal, ": ", crime, ".", sep="")
    if accomplices != []:
        print("Problem Arguments: ", str(accomplices)[1:-1])
    op_stack.reverse()
    dict_stack.reverse()
    print("SPS Operand Stack: ", str(op_stack)[1:-1])
    print("SPS Dictionary Stack: ", str(dict_stack)[1:-1])
    dict_stack.reverse()
    op_stack.reverse()
    print("Exiting program.")
    sys.exit()

def condense(code):
    """
    Tokenize code string and, additionally, condense outermost code arrays
    from code into singular token strings with curly braces included.
    """
    tokens = re.findall("/?[a-zA-Z][a-zA-Z0-9_]*|[-]?[0-9]+|[}{]+|%.*|[^ \t\n]", code)
    if '{' not in code:
        return tokens
    count = 0
    code_arr = ""
    res = []
    for token in tokens:
        if count != 0:
            if token == '{':
                count += 1
            if token == '}':
                count -= 1
            if count == 0:
                res.append('{' + code_arr[:-1] + '}')
                code_arr = ""
            else:
                code_arr += token + " "
        else:
            if token == '{':
                count += 1
            else:
                res.append(token)
    return res

def interpret(code):
    """
    Takes a string of an SPS program as an argument, tokenizes it,
    and for each token, performs the appropriate SPS action accordingly.
    """
    debug("=======================Interpreting Code=======================")
    debug("Code: \"" + code + "\"")
    debug("Operand stack: " + str(op_stack)[1:-1])
    debug("Dictionary stack: " + str(dict_stack)[1:-1])
    debug("Top dictionary: " + str(dict_stack[-1])[1:-1])
    debug()

    # Tokenize and condense the code.
    tokens = condense(code)
    for token in tokens:
        # Handling operations....
        if token == "add":
            add_op()
        elif token == "sub":
            sub_op()
        elif token == "mul":
            mul_op()
        elif token == "div":
            div_op()
        elif token == "eq":
            eq_op()
        elif token == "lt":
            lt_op()
        elif token == "gt":
            gt_op()
        elif token == "and":
            and_op()
        elif token == "or":
            or_op()
        elif token == "not":
            not_op()
        elif token == "if":
            if_op()
        elif token == "ifelse":
            if_else_op()
        elif token == "dup":
            dup_op()
        elif token == "exch":
            exch_op()
        elif token == "stack":
            stack_op()
        elif token == "=":
            top_op()
        elif token == "pop":
            op_pop()
        elif token == "def":
            def_op()
        # ...handling pushing bools and code arrays.
        elif token == "true":
            op_push(True)
        elif token == "false":
            op_push(False)
        elif token[0] == '{':
            op_push(token[1:-1])
        else:
            # Could now be an integer, /name or name lookup; if int, push the int.
            try:
                num = int(token)
                op_push(num)
            except ValueError:
                # Could now be a /name or a name lookup; if /name, push the /name.
                if is_name(token):
                    op_push(token)
                else:
                    debug("***Name lookup***")
                    debug("Name being looked up: \"" + token + "\"")
                    debug("Dictionary stack: " + str(dict_stack)[1:-1])

                    # lookup name and receive code.
                    code = lookup(token)

                    debug("Code found: \"" + str(code) + "\"")
                    debug()

                    # Create dummy link if dynamic.
                    # Using scientific number of the beast for the lols.
                    link = 666
                    if static:
                        debug("***Getting Link***")
                        debug("Name being looked up: \"" + token + "\"")
                        debug("Dictionary stack: " + str(dict_stack)[1:-1])

                        # Get link before interpreting if static.
                        link = get_link(token)

                        debug("Link made: index " + str(link))
                        debug()

                    # Recursively interpret the string version of the code received.
                    dict_push({}, link)
                    interpret(str(code))
                    dict_pop()

# ----------------\
# Main Code Block |
# ----------------/

if __name__ == "__main__":

    import sys
    import re

    # Our operand and dictionary stacks, as well as static and debugging flags.
    global op_stack
    global dict_stack
    global static
    global debugging
    op_stack = []
    dict_stack = [({}, None)]
    static = False
    debugging = False

    # Gather command line arguments and filename in clean format.
    args = ""
    filename = ""
    for arg in sys.argv:
        if arg[0] == '-':
            for c in arg[1:]:
                args += c
        else:
            filename = arg

    # Set static and debugging flags based on command line arguments.
    for c in args:
        if c == 's':
            static = True
        elif c == 'd':
            static = False
        elif c == 'x':
            debugging = True
        else:
            print("Command line argument '", c, "' not recognized. Skipping...", sep="")

    # Open file passed in via command line, store file's lines as one code string.
    lines = []
    try:
        lines = open(filename).readlines()
    except IOError:
        error("reading file", "file does not exist", [filename])
    program = ""
    for line in lines:
        program += line[:-1] + " "

    # Finally, interpret the program code, and cross your fingers...
    interpret(program)


class Solution:
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        sList = s.split()
        # for index in range(len(sList)):
        #     sList[index] = sList[index][::-1]
        # s = ' '.join(sList)
        # print(s)
        resuly = []
        for item in sList:
            resuly.append(item[::-1])
        s = ' '.join(resuly)
        print(s)
        return s

s = "Let's take LeetCode contes"
sol = Solution()
sol.reverseWords(s)


import maya.cmds as cmds
from constants import MAX_TIME, MIN_TIME
import logPoses
import poseLibrary

class CreateBuild:
    curvesLocationDict = None
    curvesRotationDict = None

    def moveCurves(self):
        """
        :summary: creates class variables for dictionaries from the the pose data created by user nurb movement
        :parameter: none
        :return: nothing
        """
        CreateBuild.curvesLocationDict = logPoses.findPoseInformation.PosesDictMove
        CreateBuild.curvesRotationDict = logPoses.findPoseInformation.PosesDictRot

class Play:
    frameNum = 10
    preSet = None

    def __init__(self):
        reset()
        Play.frameNum = cmds.intSlider("frameNum", query=True, value=True)
        cmds.playbackOptions(minTime='0sec', maxTime=str(Play.frameNum/30.0) + 'sec')
        cmds.select(all=True)
        cmds.cutKey(time=(0, MAX_TIME), cl=True)
        cmds.select(clear=True)
        self.deltaScaleArms = cmds.floatSliderGrp("deltaScaleArms", query=True, value=True)
        self.deltaScaleLegs = cmds.floatSliderGrp("deltaScaleLegs", query=True, value=True)
        self.deltaScaleCore = cmds.floatSliderGrp("deltaScaleCore", query=True, value=True)

        self.PoseOneScale = cmds.intSlider("Pose_One_Length", query=True, value=True)
        self.PoseTwoScale = cmds.intSlider("Pose_Two_Length", query=True, value=True)
        self.PoseThreeScale = cmds.intSlider("Pose_Three_Length", query=True, value=True)
        self.PoseFourScale = cmds.intSlider("Pose_Four_Length", query=True, value=True)

        self.default = cmds.radioButton('default', query=True, select=True)

    def forwardsRig(self):
        """
        :summary: rests all the data for the user data animations, resets the timeline length, resets the data, and plays the clip
        :return: nothing
        """
        Frames.frameCount = 5 + self.PoseOneScale + self.PoseTwoScale + self.PoseThreeScale + self.PoseFourScale
        Play().stop()
        cmds.playbackOptions(minTime='0sec', maxTime=str(Frames.frameCount/30.0) + 'sec')
        LoadClips().loadRig()
        LoadClips().runRig()
        cmds.play(forward=True)

    def forwardsPreSetClip(self):
        """
        :summary: rests all the data for the ik data animations, resets the timeline length, resets the data, and plays the clip
        :return: nothing
        """
        clip_move, clip_rot = LoadClips().loadPreSet()
        Frames.frameCount = len(clip_move["arms"].keys()) + 1
        Play().stop()
        cmds.playbackOptions(minTime='0sec', maxTime=str(Frames.frameCount / 30.0) + 'sec')
        LoadClips().runPreSet(clipsDictMove=clip_move, clipsDictRot=clip_rot)
        cmds.play(forward=True)

    def stop(self):
        """
        :summary: stops the time slider
        :return: nothing
        """
        cmds.play(state=False)

class LoadClips(Play):
    def loadRig(self):
        """
        :summary: collects the user created pose data formatted from another script and separates it out into separate dictionaries
        :return: nothing
        """
        LoadClips.PoseOneTranslate = CreateBuild.curvesLocationDict["Pose_One"]
        LoadClips.PoseTwoTranslate = CreateBuild.curvesLocationDict["Pose_Two"]
        LoadClips.PoseThreeTranslate = CreateBuild.curvesLocationDict["Pose_Three"]
        LoadClips.PoseFourTranslate = CreateBuild.curvesLocationDict["Pose_Four"]

        LoadClips.PoseOneRotation = CreateBuild.curvesLocationDict["Pose_One"]
        LoadClips.PoseTwoRotation = CreateBuild.curvesLocationDict["Pose_Two"]
        LoadClips.PoseThreeRotation = CreateBuild.curvesLocationDict["Pose_Three"]
        LoadClips.PoseFourRotation = CreateBuild.curvesLocationDict["Pose_Four"]

    def runRig(self):
        """
        :summary: takes the user data collected from the nurbs handles and puts in on the timeline
        :parameter: none
        :return: nothing
        """
        newTime = 1
        for nurbs, location in LoadClips.PoseOneTranslate.items():
            Clips().PosesTranslate(startTime=newTime, endtime=newTime + self.PoseOneScale, value=location, joint=nurbs)
        newTime += (1 + self.PoseOneScale)
        for nurbs, location in LoadClips.PoseTwoTranslate.items():
            Clips().PosesTranslate(startTime=newTime, endtime=newTime + self.PoseTwoScale, value=location, joint=nurbs)
        newTime += (1 + self.PoseTwoScale)
        for nurbs, location in LoadClips.PoseThreeTranslate.items():
            Clips().PosesTranslate(startTime=newTime, endtime=newTime + self.PoseThreeScale, value=location, joint=nurbs)
        newTime += (1 + self.PoseThreeScale)
        for nurbs, location in LoadClips.PoseFourTranslate.items():
            Clips().PosesTranslate(startTime=newTime, endtime=newTime + self.PoseFourScale, value=location, joint=nurbs)

        newTime = 1
        for nurbs, location in LoadClips.PoseOneRotation.items():
            Clips().PosesRotate(startTime=newTime, endtime=newTime + self.PoseOneScale, value=location, joint=nurbs)
        newTime += (1 + self.PoseOneScale)
        for nurbs, location in LoadClips.PoseTwoRotation.items():
            Clips().PosesRotate(startTime=newTime, endtime=newTime + self.PoseTwoScale, value=location, joint=nurbs)
        newTime += (1 + self.PoseTwoScale)
        for nurbs, location in LoadClips.PoseThreeRotation.items():
            Clips().PosesRotate(startTime=newTime, endtime=newTime + self.PoseThreeScale, value=location, joint=nurbs)
        newTime += (1 + self.PoseThreeScale)
        for nurbs, location in LoadClips.PoseFourRotation.items():
            Clips().PosesRotate(startTime=newTime, endtime=newTime + self.PoseFourScale, value=location, joint=nurbs)

    def loadPreSet(self):
        """
        :summary: depending on the boolean a function returning pose data is chosen
        :parameter: none
        :return: dictionaries of translation and rotation data
        """
        if self.default == True:
            return poseLibrary.default()

    def runPreSet(self, clipsDictMove, clipsDictRot):
        """
        :summary: load clips on the timeline from ik data
        :param clipsDictMove: a dictionary of all the translation data for all the poses for all the nurbs handles
        :param clipsDictRot: a dictionary of all the rotation data for all the poses for all the nurbs handles
        :return: nothing
        """
        newTime = 0
        for key, nurbsList in clipsDictMove["arms"].items():
            newTime += 1
            for nurbs, location in nurbsList.items():
                Clips().PosesTranslate(startTime=newTime, endtime=newTime,
                                       value=valuesList(location[0], location[1], location[2], self.deltaScaleArms), joint=nurbs)
        newTime = 0
        for key, nurbsList in clipsDictMove["legs"].items():
            newTime += 1
            for nurbs, location in nurbsList.items():
                Clips().PosesTranslate(startTime=newTime, endtime=newTime,
                                       value=valuesList(location[0], location[1], location[2], self.deltaScaleLegs), joint=nurbs)
        newTime = 0
        for key, nurbsList in clipsDictMove["core"].items():
            newTime += 1
            for nurbs, location in nurbsList.items():
                Clips().PosesTranslate(startTime=newTime, endtime=newTime,
                                       value=valuesList(location[0], location[1], location[2], self.deltaScaleCore), joint=nurbs)
        newTime = 0
        for key, nurbsList in clipsDictRot["arms"].items():
            newTime += 1
            for nurbs, location in nurbsList.items():
                Clips().PosesRotate(startTime=newTime, endtime=newTime,
                                       value=valuesList(location[0], location[1], location[2], self.deltaScaleArms), joint=nurbs)
        newTime = 0
        for key, nurbsList in clipsDictRot["legs"].items():
            newTime += 1
            for nurbs, location in nurbsList.items():
                Clips().PosesRotate(startTime=newTime, endtime=newTime,
                                       value=valuesList(location[0], location[1], location[2], self.deltaScaleLegs), joint=nurbs)
        newTime = 0
        for key, nurbsList in clipsDictRot["core"].items():
            newTime += 1
            for nurbs, location in nurbsList.items():
                Clips().PosesRotate(startTime=newTime, endtime=newTime,
                                       value=valuesList(location[0], location[1], location[2], self.deltaScaleCore), joint=nurbs)

class Clips:
    """
    :summary: created keyed from on the timeline for rotation or translation
    :param startTime: what time the pose should start
    :param endtime: what time the pose should end
    :param joint: the joint (or nurbs handle or ik handle) that is being moved or rotated
    :param value: a list of x, y, z values in the pose of "joint"
    :return: a time for the next pose (not always needed)
    """
    def PosesTranslate(self, startTime, endtime, joint, value):
        cmds.setKeyframe(joint, attribute='translateX', t=(Frames().calcFrames()[startTime], Frames().calcFrames()[endtime]), v=value[0])
        cmds.setKeyframe(joint, attribute='translateY', t=(Frames().calcFrames()[startTime], Frames().calcFrames()[endtime]), v=value[1])
        cmds.setKeyframe(joint, attribute='translateZ', t=(Frames().calcFrames()[startTime], Frames().calcFrames()[endtime]), v=value[2])
        return startTime + 2

    def PosesRotate(self, startTime, endtime, joint, value):
        cmds.setKeyframe(joint, attribute='rotateX', t=(Frames().calcFrames()[startTime], Frames().calcFrames()[endtime]), v=value[0])
        cmds.setKeyframe(joint, attribute='rotateY', t=(Frames().calcFrames()[startTime], Frames().calcFrames()[endtime]), v=value[1])
        cmds.setKeyframe(joint, attribute='rotateZ', t=(Frames().calcFrames()[startTime], Frames().calcFrames()[endtime]), v=value[2])
        return startTime + 2

def reset():
    """
    :summary: sets the time slider on the timeline to 0
    :parameter: none
    :return: nothing
    """
    cmds.currentTime(0, edit=True)

class Frames:
    """
    :summary: converts the amount of frames needed into units of time based on the number of frames on the timeline
    :parameter: none
    :return: a list of frames
    """
    frameCount = MIN_TIME

    def calcFrames(self):
        returnList = []
        for x in range(Frames.frameCount):
            returnList.append((Play.frameNum/Frames.frameCount)*x)
        return returnList

def valuesList(X, Y, Z, percent):
    """
    :param X: x translation or rotation
    :param Y: y translation or rotation
    :param Z: z translation or rotation
    :param percent: scale value
    :return: list of the new x, y, z coordinates with the scale applied
    """
    return [(X*percent), (Y*percent), (Z*percent)]

class RotatePos:
    """
    :summary: rotates an object around a point and converts that matrix into x, y, z values
    :param x: x rotation value
    :param y: y rotation value
    :param z: z rotation value
    :param object: the object to be rotated
    :param parent: the parent x, y, z position
    """
    def __init__(self, x, y, z, object, parent):
        #self.parent = {"posX": 0, "posY": 0, "posZ": 0,}
        self.parent = parent
        self.object = object
        self.rotX = x
        self.rotY = y
        self.rotZ = z

    def xformRot(self):
        cmds.rotate(self.rotX, self.rotY, self.rotZ, self.object,
                    pivot=(self.parent["posX"], self.parent["posY"], self.parent["posZ"]))
        location = cmds.xform(self.object, query=True, bb=True)
        cmds.rotate(0, 0, 0, self.object, pivot=(self.parent["posX"], self.parent["posY"], self.parent["posZ"]))

        return [(location[0] + location[3])/2.0, (location[1] + location[4])/2.0, (location[2] + location[5])/2.0]


import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-5, 5)
# print(x)
y = 1 / ( 1 + np.exp(-x) )
# print(y)

plt.plot(x, y)
plt.grid(axis='y')
plt.title('Logistic Function')
plt.ylabel('Y')
plt.xlabel('X')
plt.show()


import argparse
import os
import json
import re

import torch
from pytorch_pretrained_bert import BertAdam

from utils import UnitAlphabet, LabelAlphabet
from model import PhraseClassifier
from misc import fix_random_seed
from utils import corpus_to_iterator, Procedure, split_long_passage, GPU_ID

from flask import Flask, request, jsonify, make_response
from flask_cors import CORS
app = Flask(__name__)
CORS(app)

def predict_a_long_text(text, model, batch_size, src_info=None):
    '''text: 一段长长的文字...'''
    sentence_segs = split_long_passage(text)
    material = [{'sentence': str(list(sent)), 'labeled entities':str([])} for sent in sentence_segs]
    test_loader = corpus_to_iterator(None, batch_size, False, material=material)
    ans = Procedure.test_for_cluener(model, test_loader, allow_conflit=True)
    return ans

def predict_for_clue_submit(args, model):
    fix_random_seed(args.random_state)
    test_loader = corpus_to_iterator(os.path.join(args.data_dir, "test.json"), args.batch_size, False)
    ans = Procedure.test_for_cluener(model, test_loader, True)
    with open(os.path.join(args.check_dir, 'cluener_predict.json'), 'w', encoding='utf8') as f:
        for jobj in ans:
            f.write(json.dumps(jobj, ensure_ascii=False) + '\n')

@app.route('/', methods=['POST', 'GET'])
def predict_service():
    try:
        text = request.values.get('text')
        if not text:
            raise Exception("使用post方法且text字段不能为空！")

        ########## 模型预测
        results = predict_a_long_text(text, model, batch_size=args.batch_size)

        ret = {
            'result': results,
            'code' : 200
        }
    except Exception as e:
        from traceback import print_exc
        print_exc()
        ret = {
            'code': 500,
            'message': str(e)
        }
    return jsonify(ret)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()

    parser.add_argument("--data_dir", "-dd", type=str, required=True)
    parser.add_argument("--check_dir", "-cd", type=str, required=True)
    parser.add_argument("--resource_dir", "-rd", type=str, required=True)
    parser.add_argument("--random_state", "-rs", type=int, default=0)
    parser.add_argument("--epoch_num", "-en", type=int, default=40)
    parser.add_argument("--batch_size", "-bs", type=int, default=16)

    parser.add_argument("--negative_rate", "-nr", type=float, default=0.7)
    parser.add_argument("--warmup_proportion", "-wp", type=float, default=0.1)
    parser.add_argument("--hidden_dim", "-hd", type=int, default=256)
    parser.add_argument("--dropout_rate", "-dr", type=float, default=0.1)
    parser.add_argument("--cache_dir", "-cache", type=str, default='resource/bert')

    args = parser.parse_args()
    print(json.dumps(args.__dict__, indent=True), end="\n\n")

    checkpoint_path = os.path.join(args.check_dir, "model.pt")
    model = torch.load(checkpoint_path, map_location='cpu')
    model = model.cuda(GPU_ID) if torch.cuda.is_available() else model.cpu()
    app.run(debug=False, host='0.0.0.0', port=16060)
    # predict_for_clue_submit(args, model)


T = int(input())
for i in range(T):
    N = int(input())
    s = input()
    for j in range(1, N):
        if j != int(s[j*2-2]):
            print(j)
            break
    else:
        print(N)


#! /usr/bin/env python3
import os
import os.path

import javalang

from plantuml_composer import Root
from plantuml_composer import Class
from plantuml_composer import Package

def walk_java_files(path):
    for root, dirs, files in os.walk(path):
        for fn in files:
            if not fn.endswith(".java"):
                continue

            yield os.path.join(root, fn)

class Mapper:
    def __init__(self):
        self.packages = {}
        self.classes = []
        self.root = Root()

    def map(self, path: str):
        for path in walk_java_files(path):
            with open(path) as f:
                content = f.read()

            fn = os.path.basename(path)
            tree = javalang.parse.parse(content)

            if tree.package.name in self.packages:
                package = self.packages[tree.package.name]
            else:
                package = Package(tree.package.name)
                self.packages[tree.package.name] = package

            for cls in tree.types:
                class_item = Class(cls.name)
                if class_item not in package:
                    package.add(class_item)

        self._store_packages()

    def _store_packages(self):
        for package in self.packages.values():
            self.root.add(package)

            up_package_name = self.up_in_dot_notation(package.name)
            if up_package_name in self.packages:
                up_package = self.packages[up_package_name]

                if package not in up_package:
                    up_package.add(package)

    def up_in_dot_notation(self, path):
        tokens = path.split(".")
        if len(tokens) == 1:
            return None

        tokens.pop()
        return ".".join(tokens)

    def save_to(self, path: str):
        with open(path, "wt") as f:
            f.write(self.root.to_str())

mapper = Mapper()
mapper.map("../../")
mapper.save_to("structure.plantuml")


class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        def search(node, r, c):
            if 'word' in node:  # A complete word has been found
                word = node.pop('word')
                found.append(word)
                remove(word)  # Remove word from trie
            if 0 <= r < m and 0 <= c < n and board[r][c]:
                char = board[r][c]
                board[r][c] = None  # Marked as visited
                for dr, dc in directions:
                    row, col = r + dr, c + dc
                    if char in node:
                        search(node[char], row, col)
                board[r][c] = char  # Restore to original state

        def remove(word):
            node, parents = trie, []
            for char in word:
                parents.append(node)
                node = node[char]
            for i in range(len(parents) - 1, -1, -1):
                if node == {}:
                    parents[i].pop(word[i])
                    node = parents[i]
                else:  # Parents are shared by other words
                    break

        m, n = len(board), len(board[0])
        trie, found, directions = {}, [], [(0, 1), (0, -1), (1, 0), (-1, 0)]
        for word in words:  # Store all words in trie format
            node = trie
            for char in word:
                node = node.setdefault(char, {})
            node['word'] = word  # e.g. word = 'oath', trie = {'o': {'a': {'t': {'h': {'word': 'oath'}}}}}
        for r in range(m):
            for c in range(n):
                if len(found) < len(words):
                    search(trie, r, c)
        return found


n=input().split(',')

for i in range(len(n)):
    n[i]=int(n[i])
res=True
if n[2]>n[0]:
    res=False
elif n[1]>n[3]:
    res=False
print(res)


test = {
  'name': 'pow',
  'points': 1,
  'suites': [
    {
      'cases': [
        {
          'code': r"""
          scm> (pow 2 5)
          6f066a5ea36822ee02b13277317ad7a8
          # locked
          """,
          'hidden': False,
          'locked': True
        },
        {
          'code': r"""
          scm> (pow 10 3)
          6c3e2b869b5d3b4719b4c97396caa474
          # locked
          """,
          'hidden': False,
          'locked': True
        },
        {
          'code': r"""
          scm> (pow 3 3)
          b5547241e8be8001f620abf9f066b80c
          # locked
          """,
          'hidden': False,
          'locked': True
        }
      ],
      'scored': True,
      'setup': r"""
      scm> (load 'hw04)
      """,
      'teardown': '',
      'type': 'scheme'
    }
  ]
}


import socket
import scapy
import time

from scapy.all import *
from scapy.layers.inet import *
from scapy.layers.l2 import *

n_send = 100
tar = ['www.zhihu.com']
my_extra_ip = '152.136.160.194'
my_intra_ip = '172.21.0.52'
bind_if_name = 'eth0'

z_payload = b''
for i in range(0, 520):
    z_payload += struct.pack('B', 0)

for t in tar:
    ip = socket.getaddrinfo(t, None)[0][4][0]

    send_list = [IP(src=my_intra_ip, dst=ip, id=i) / ICMP() for i in range(0, n_send)]

    pkts = sniff(filter="icmp and src " + ip,
                         iface=bind_if_name, count=n_send, timeout=2, started_callback=
                         lambda: send(send_list, iface=bind_if_name, verbose=False))

    print(len(pkts))

    ipids = []
    for pk in pkts:
        ipids.append(pk[1].fields['id'])

    ipid_next = 0
    for i in range(1, n_send):
        # print(ipids[i])
        if ipids[i] - ipids[i - 1] >= 2:
            print(' ---- ' + str(ipids[i]))
            ipid_next += 1

    print(ipid_next)


def format_name(f_name,l_name):
    #this is Docstring format with three double quote
    """
    Take a fist and last name and format it to return the title case version of the name
    :param param1: this is a first param
    :param param2: this is a second para
    :returns: this is a description of what is returned
    """
    if f_name=="" or l_name=="":
        return "You don't provide valid inputs"
    formated_f_name = f_name.title()
    formated_l_name = l_name.title()
    return f"{formated_f_name} {formated_l_name}"

firstname = input("what is your first name?")
lastname = input("what is your last name?")
formated_string = format_name(firstname,lastname)
print(formated_string) #formated_string variable with return result by invoked format_name


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

from cms.utils.i18n import get_current_language
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.template import RequestContext
from django.test import RequestFactory
from django.utils.html import strip_tags

try:
    from django.utils.encoding import force_unicode
except ImportError:
    from django.utils.encoding import force_text as force_unicode

def get_request(language=None):
    """
    Returns a Request instance populated with cms specific attributes
    """
    request_factory = RequestFactory()
    request = request_factory.get('/')
    request.session = {}
    request.LANGUAGE_CODE = language or settings.LANGUAGE_CODE
    request.current_page = None
    request.user = AnonymousUser()
    return request

def get_text_from_placeholder(placeholder, language=None, request=None):
    """
    Returns rendered and strippet text from given placeholder
    """
    if not placeholder:
        return ''
    if not language:
        language = get_current_language()
    if not request:
        request = get_request(language)

    bits = []
    plugins = placeholder.cmsplugin_set.filter(language=language)
    for base_plugin in plugins:
        instance, plugin_type = base_plugin.get_plugin_instance()
        if instance is None:
            continue
        bits.append(instance.render_plugin(context=RequestContext(request)))
    return force_unicode(strip_tags(' '.join(bits)))


"""add unique constraint

Revision ID: 49bb5a76c589
Revises: 17615e42022c
Create Date: 2018-03-04 09:49:13.381590

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '49bb5a76c589'
down_revision = '17615e42022c'
branch_labels = None
depends_on = None

def upgrade():
    conn = op.get_bind()
    conn.execute(
        sa.sql.text(
            """
            ALTER TABLE stocks ADD CONSTRAINT stocks_label_uq UNIQUE (label);
            """
        )
    )

def downgrade():
    conn = op.get_bind()
    conn.execute(
        sa.sql.text(
            """
            ALTER TABLE stocks DROP CONSTRAINT stocks_label_uq;
            """
        )
    )


# Instalar " pip install mysql-connector-python "
import threading

import mysql.connector

'''importar a biblioteca selenium'''
from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

# CONEXÃO COM O WHATSAPP
def conexao():
    '''ESPERA ATE COM QUE O ELEMENTO SIDE SEJA ENCONTRADO NA TELA'''
    while (len(driver.find_elements(By.ID, 'side')) < 1):
        time.sleep(1)  # "padrão 1"
    else:
        print('QR-COD ABERTO')
        time.sleep(1)  # "padrão 2"

def main():
    while (1):
        # PEGA AS NOVAS MENSAGENS
        '''BUSCA NOVAS MENSAGENS  '''
        bolinha_notificacao = driver.find_elements(By.CLASS_NAME, '_1pJ9J')
        '''CONFERE A QUANTIDADE DE MENSAGEM'''
        quantidade_bolinha_notificacao = len(bolinha_notificacao)
        if quantidade_bolinha_notificacao > 0:
            time.sleep(1)
            for bolinhas_encontrada in bolinha_notificacao:
                time.sleep(1)
                # MENSAGEM ENCONTRADA CLICAR
                bolinhas_encontrada.click()
                element2 = driver.find_element(By.XPATH, '//*[@id="main"]/div[2]/div/div[2]/div[3]')
                element2.send_keys(Keys.ESCAPE)
                time.sleep(2)
#================================================================================

if __name__ == "__main__":
    site = "https://web.whatsapp.com"
    driver = webdriver.Chrome()
    driver.get(site)
    conexao()
    main()


import datetime
import json
import logging
import os
import psutil
import sys
import time
import threading
import msgpack

from .metrics import get_process_memory, get_process_cpu, get_gpu_metrics
from .utilities import get_offline_directory, create_file

logger = logging.getLogger(__name__)

HEARTBEAT_INTERVAL = 60
POLLING_INTERVAL = 20
MAX_BUFFER_SEND = 5000

def update_processes(parent, processes):
    """
    Create an array containing a list of processes
    """
    for child in parent.children(recursive=True):
        if child not in processes:
            processes.append(child)
    if parent not in processes:
        processes.append(parent)
    return processes

class Worker(threading.Thread):
    def __init__(self, metrics_queue, events_queue, shutdown_event, uuid, run_name, url, headers, mode, pid, resources_metrics_interval):
        threading.Thread.__init__(self)
        self._parent_thread = threading.current_thread()
        self._metrics_queue = metrics_queue
        self._events_queue = events_queue
        self._shutdown_event = shutdown_event
        self._run_name = run_name
        self._uuid = uuid
        self._url = url
        self._headers = headers
        self._headers_mp = headers.copy()
        self._headers_mp['Content-Type'] = 'application/msgpack'
        self._mode = mode
        self._directory = os.path.join(get_offline_directory(), self._uuid)
        self._start_time = time.time()
        self._processes = []
        self._resources_metrics_interval = resources_metrics_interval
        self._pid = pid
        if pid:
            self._processes = update_processes(psutil.Process(pid), [])
        logger.debug('Worker thread started')

    def heartbeat(self):
        """
        Send a heartbeat
        """
        if self._mode == 'online':
            from .api import put
            put(f"{self._url}/api/runs/heartbeat", self._headers, {'name': self._run_name})
        else:
            create_file(f"{self._directory}/heartbeat")

    def post(self, endpoint, data):
        """
        Send the supplied data
        """
        if self._mode == 'online':
            from .api import post
            post(f"{self._url}/api/{endpoint}", self._headers_mp, data=data, is_json=False)
        else:
            unique_id = time.time()
            filename = f"{self._directory}/{endpoint}-{unique_id}"
            try:
                with open(filename, 'w') as fh:
                    json.dump(data, fh)
            except Exception as err:
                logger.error('Got exception writing offline update for %s: %s', endpoint, str(err))

    def run(self):
        """
        Loop sending heartbeats, metrics and events
        """
        last_heartbeat = 0
        last_metrics = 0
        collected = False
        while True:
            # Collect metrics if necessary
            if time.time() - last_metrics > self._resources_metrics_interval and self._processes:
                if self._pid:
                    self._processes = update_processes(psutil.Process(self._pid), self._processes)
                cpu = get_process_cpu(self._processes)
                if not collected:
                    # Need to wait before sending metrics, otherwise first point will have zero CPU usage
                    collected = True
                else:
                    memory = get_process_memory(self._processes)
                    gpu = get_gpu_metrics(self._processes)
                    if memory is not None and cpu is not None:
                        data = {}
                        data['step'] = 0
                        data['run'] = self._run_name
                        data['values'] = {'resources/cpu.usage.percent': cpu,
                                          'resources/memory.usage': memory}
                        if gpu:
                            for item in gpu:
                                data['values'][item] = gpu[item]
                        data['time'] = time.time() - self._start_time
                        data['timestamp'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
                        try:
                            self._metrics_queue.put(data, block=False)
                        except:
                            pass
                    last_metrics = time.time()

            # Send heartbeat if necessary
            if time.time() - last_heartbeat > HEARTBEAT_INTERVAL:
                try:
                    self.heartbeat()
                except:
                    pass
                last_heartbeat = time.time()

            # Send metrics
            buffer = []
            while not self._metrics_queue.empty() and len(buffer) < MAX_BUFFER_SEND:
                item = self._metrics_queue.get(block=False)
                buffer.append(item)
                self._metrics_queue.task_done()

            if buffer:
                logger.debug('Sending metrics')
                try:
                    if self._mode == 'online': buffer = msgpack.packb(buffer, use_bin_type=True)
                    self.post('metrics', buffer)
                except Exception as err:
                    logger.error(str(err))
                buffer = []

            # Send events
            buffer = []
            while not self._events_queue.empty() and len(buffer) < MAX_BUFFER_SEND:
                item = self._events_queue.get(block=False)
                buffer.append(item)
                self._events_queue.task_done()

            if buffer:
                logger.debug('Sending events')
                try:
                    if self._mode == 'online': buffer = msgpack.packb(buffer, use_bin_type=True)
                    self.post('events', buffer)
                except Exception as err:
                    logger.error(str(err))
                buffer = []

            if self._shutdown_event.is_set() or not self._parent_thread.is_alive():
                if self._metrics_queue.empty() and self._events_queue.empty():
                    logger.debug('Ending worker thread')
                    sys.exit(0)
            else:
                counter = 0
                while counter < POLLING_INTERVAL and not self._shutdown_event.is_set() and self._parent_thread.is_alive():
                    time.sleep(1)
                    counter += 1


import numpy as np
from sklearn.utils import shuffle
from .utils import encode

class ADALINEClassifier:
    def __init__(self):
        self.avg_error = []
        self.W = None

    def fit(self, X, y, alpha=0.001, epoches=10):
        Y = encode(y) # Encode labels into binary matrix
        Y = 2*Y - 1 # Transform 0 to -1

        # Init weight matrix
        self.W = 0.1*np.random.randn(Y.shape[1], X.shape[1])
        for _ in range(epoches):
            error_lis = []
            X, Y = shuffle(X, Y, random_state=100)
            for i in range(X.shape[0]):
                x = X[i, :]
                y_pred = self.W.dot(x)
                error = Y[i, :] - y_pred.T

                # Normalize x vector
                x_norm = x/np.linalg.norm(X[0, :])

                # Update the weights
                delta = np.outer(error, x_norm)
                self.W = self.W + alpha*delta
                error_lis.append(sum(error**2))
            self.avg_error.append(sum(error_lis)/len(X))

    def predict(self, X):
        Y_score = self.W.dot(X.T)
        y_pred = np.argmax(Y_score, 0)
        return y_pred


# 29. A fábrica WK produz uma quantidade de automóveis por dia e deseja fazer um
# levantamento sobre essa produção. Escreva um programa em Python que leia a
# quantidade de automóveis produzida diariamente, enquanto não for digitado um número
# negativo. Ao final o programa deve mostrar na tela a quantidade total de automóveis
# produzida, a quantidade de dias que foi considerada (ou seja, é a quantidade de números
# digitados), e a quantidade média de carros produzida por dia.

def somador(lista):
    soma = 0
    for n in lista:
        soma += n
    return soma

automoveis = []
qntAutomoveis = int(input("Digite a quantidade de automóveis produzidos: "))

while qntAutomoveis >= 0:
    automoveis.append(qntAutomoveis)
    qntAutomoveis = int(input("Digite a quantidade de automóveis produzidos: "))

print(f"Foram produzidos {somador(automoveis)} automovéis em {len(automoveis)} dias")
print(f"Média de automoveis por dia foi: {(somador(automoveis)/len(automoveis)):.2f}")

Senai/Lista de atividade/Lista 3 - Loops/ex29.py


## @package Read raklida datasets
import sys
import os
import h5py
import pandas as pd
import numpy as np
import rasterio

class raklida_import:
    def __init__(self, args):
        """ configure output """
        ## command line arguments
        self.args = args
        ## configuration of parameter properties
        self.conf = {
            'raklida_messungen' : {
                'parameters' : {
                   'ETP' : {'id':8, 'decimals':2, 'dtype':'int32', 'to_hdf' : True},
                   'GRV' : {'id':30, 'decimals':2, 'dtype':'int32', 'to_hdf' : True}
                }
            },
            'raklida_referenz' : {
                 'parameters' : {
                   'RRK' :{'id':10, 'decimals':2, 'dtype':'int32', 'to_hdf' : True},
                   'TM0' : {'id':9, 'decimals':2, 'dtype':'int32', 'to_hdf' : True}
                }
            },
            'raklida_wettreg66' : {
                 'parameters' : {
                   'ETP' :{'id':8, 'decimals':2, 'dtype':'int32', 'to_hdf' : True},
                   'RRK' : {'id':10, 'decimals':2, 'dtype':'int32', 'to_hdf' : True},
                   'TM0' : {'id':9, 'decimals':2, 'dtype':'int32', 'to_hdf' : True}
                }
            },
            'raklida_referenz_derived' : {
                'parameters' : {
                    'pi_summer' : {'id':6, 'decimals':2, 'dtype':'int32', 'to_hdf' : True},
                    'pi_winter' : {'id':7, 'decimals':2, 'dtype':'int32', 'to_hdf' : True}
                }
            },
            'raklida_wettreg66_derived' : {
                'parameters' : {
                    'pi_summer' : {'id':6, 'decimals':2, 'dtype':'int32', 'to_hdf' : True},
                    'pi_winter' : {'id':7, 'decimals':2, 'dtype':'int32', 'to_hdf' : True}
                }
            }
        }

    ## @brief Read asc files
    #
    # @param src, string : source folder
    # @return dbf_list, list: list of files
    def read_asc(self, src):
        print('--> read raklida asc files')
        files = []

        # get raklida asc files
        if 'Raklida' in src:
            for r, d, f in os.walk(src):
                for file in f:
                    if '.asc' in file:
                        if not 'lock' in file: # exlude locked files
                            if not '.txt' in file:
                                files.append(os.path.join(r, file))

        if len(files) > 0:
            print('OK, found %d asc files' % len(files))
            #for i in files:
            #    print(i)
        else:
            sys.exit('ERROR: No asc files found')

        return files

    ## @brief read asc into pandas dataframe
    #
    # @param args, dict: dictionary of arguments
    # @returns stacked_df: pandas dataframe
    def read_as_pandas(self, args):
        print('--> read asc into pandas dataframe')
        # placeholder
        df_all = {}
        u_pnames = []
        # read raklida area dataset
        try:
            raklida_area = h5py.File(args['src_folder'] + '/raklida_gis/raklida.h5', 'r')
            raklida_ds = np.flipud(np.array(raklida_area['Band1'])).flatten().astype(float)
            raklida_ds[raklida_ds<0] = np.nan
        except:
            sys.exit("ERROR: " + str(sys.exc_info()))
        # get unique parameters
        for f in args['asc_files']:
            pname, idparam = self.get_parameter_from_fname(args, f)
            if not pname in u_pnames:
                u_pnames.append(pname)
        print('>>>>> parameters', u_pnames)

        # loop over parameter names
        for pname in u_pnames:
            #if pname == 'TM0':
            # create a key in dict if not exists
            if not pname in df_all.keys():
                df_all[pname] = pd.DataFrame()
            df_raklida = pd.DataFrame()
            next_year = 2100
            # initialize df_stacked
            df_stacked = pd.DataFrame({'id':raklida_ds})
            df_stacked = df_stacked[df_stacked['id'].notna()]
            # read csv file
            args['asc_files'] = sorted(args['asc_files'])
            #print('--> asc_files: ', args)

            for f in args['asc_files']:
                if not '.xml' in f:
                    if pname in f:
                        print('reading by rasterio', f)
                        # get year and month from filename
                        year, month = self.get_year_month_from_fname(f)

                        print(year, next_year)

                        #handle missing years
                        if next_year < year:
                            next_year = year + 1
                            # reinitialize df_stacked
                            df_stacked = pd.DataFrame({'id':raklida_ds})
                            df_stacked = df_stacked[df_stacked['id'].notna()]
                            print('*****************', str(year))
                            print(f)

                        raster = rasterio.open(f).read(1).flatten() # read file by rasterio
                        # get nodata value
                        nodata = self.get_nodata_value_from_asc(f)
                        raster[raster == nodata] = np.nan
                        # loop over one year
                        if year <= next_year:
                            if year != next_year and month != 'dec':
                                # stack data into pandas dataframe
                                print(raklida_ds.shape)
                                print(raster.shape)
                                print(month)

                                df = pd.DataFrame({'id':raklida_ds, 'value':raster}).rename(columns={'value':month})
                                df = df[df['id'].notna()]
                                df_stacked['year'] = year
                                df_stacked = pd.merge(df_stacked, df, how='left', on='id')
                                print(df_stacked.shape)
                            elif year != next_year and  month == 'dec':
                                # stack data of one year into pandas dataframe
                                df = pd.DataFrame({'id':raklida_ds, 'value':raster}).rename(columns={'value':month})
                                df = df[df['id'].notna()]
                                df_stacked['year'] = year
                                df_stacked = pd.merge(df_stacked, df, how='left', on='id')
                                # add df_stacked (one complete year) to df_all
                                frames = [df_raklida, df_stacked]
                                df_raklida = pd.concat(frames)
                                print(df_raklida.shape, df_stacked.shape)
                                print('df_raklida.shape: ', df_raklida.shape)
                                #sys.exit()
                                if df_raklida.shape[1] > 14:
                                    print(df_stacked)
                                    sys.exit('ERROR: shape not correct')
                            else:
                                # reinitialize df_stacked
                                df_stacked = pd.DataFrame({'id':raklida_ds})
                                df_stacked = df_stacked[df_stacked['id'].notna()]
                                df = pd.DataFrame({'id':raklida_ds, 'value':raster}).rename(columns={'value':month})
                                df = df[df['id'].notna()]
                                df_stacked['year'] = year
                                df_stacked = pd.merge(df_stacked, df, how='left', on='id')
                                print('##### ', str(year))
                                #break
                                #print(df_stacked)
                            next_year = year + 1

                        #if next_year == 2023:
                        #    break

                    #break
                df_all[pname] = df_raklida
                #break
                #print(df_all)
                #sys.exit()
        return df_all

    ## @brief Get nodata value
    #
    # @param file, string
    # @returns nodata, float
    def get_nodata_value_from_asc(self, file):
        print('--> get nodata value from file')
        nodata = None
        file = open(file, 'r')
        for line in file.readlines():
            if 'nodata_value' in line:
                nodata = float((line.split(' '))[2])
                break
        file.close()
        if nodata == None:
            sys.exit('ERROR: Missing nodata value in asc file', file)

        return nodata

    ## @brief Get year and month from filename
    #
    # @param filename: string
    # @returns year, month: integer
    def get_year_month_from_fname(self, file):
        print('--> get year and month from filename')
        year, month = None, None
        months = {1:'jan', 2:'feb', 3:'mar', 4:'apr', 5:'may', 6:'jun', 7:'jul', 8:'aug', 9:'sep', 10:'oct', 11:'nov', 12:'dec'}

        yearmonth = file.split('.')[0].split('_')[-1]
        year = int(yearmonth[0:4])

        if int(yearmonth[4:6]) in range(1,13):
            month = int(yearmonth[4:6])

        if year == None or month == None:
            sys.exit('ERROR: Missing year or month')

        return year, months[month]

    ## @brief Get parameter name and id from filename
    #
    # @param filename: string
    # @returns pname, id: integer
    def get_parameter_from_fname(self, args, file):

        #print ('---> : file :',file)
        #print ('---> : conf :',str(self.conf[args['data_type']]['parameters']))

        #print('--> get parameter name and id from filename')
        pname, idparam = None, None
        for p in self.conf[args['data_type']]['parameters']:
            if p in file:
                idparam = self.conf[args['data_type']]['parameters'][p]['id']
                pname = p

        if pname == None or idparam == None:
            sys.exit('ERROR: Missing parameter name or parameter id')

        return pname, idparam

    ## @brief Save parameters as hdf5
    #
    # @param df, pandas DataFrame
    def transform_as_hdf(self, args, dict):
        print('--> transform data to hdf5')
        print(dict.keys())
        # loop over each parameter
        for p in dict.keys():
            if self.conf[args['data_type']]['parameters'][p]['to_hdf'] == True:
                # get dataset for a parameter
                df = dict[p]
                print('parameter --> ', p)
                start_year = df['year'].min()
                last_year = df['year'].max()
                print('start year', start_year)
                print('last year', last_year)
                for y in range(int(start_year),int(last_year)+1):
                    print(y)
                    # get data for one year
                    df_year = df.loc[df['year'] == y]
                    # reorganize data to final structure: index, values_block_0[]
                    df_final = pd.DataFrame(columns=['index','values_block_0'])
                    df_final['index'] = df_year['id']
                    df_final['values_block_0'] = df_year[df_year.columns[2:]].apply(
                        lambda x: ' '.join(x.astype(str)),
                        axis=1
                    )
                    df_final = df_final.set_index('index')

                    print(df_final.dtypes)
                    # save as hdf5
                    path = self.args['dst_folder'] + '/' + str(self.args['scenario_id']) + '/' + str(self.conf[args['data_type']]['parameters'][p]['id']) + '/'
                    if not os.path.exists(path):
                        os.makedirs(path)
                    fn = str(self.args['scenario_id']) + '_' + str(self.conf[args['data_type']]['parameters'][p]['id']) + '_' + str(y) + '.h5'
                    print(path + fn)
                    #sys.exit()
                    try:
                        df_final[['values_block_0']].to_hdf(path + fn, key='table' , mode='w', format='table', complevel=9)
                    except:
                        sys.exit("ERROR: " + str(sys.exc_info()))

    ## @brief create derived parameters and store them into a pandas dataframe
    #
    # @param args, dict: dictionary of arguments
    # @returns stacked_df: pandas dataframe
    def create_derived_parameters(self, args):
        print('--> Create derived parameters')
        df = {}
        # loop over derived parameters to create
        for p in self.conf[args['data_type']]['parameters']:
            if p == 'pi_summer' and self.conf[args['data_type']]['parameters'][p]['to_hdf'] == True:
                print('+++')
                df['pi_summer'] = self.derive_pi_summer(args)

            if p == 'pi_winter' and self.conf[args['data_type']]['parameters'][p]['to_hdf'] == True:
                print('+++')
                df['pi_winter'] = self.derive_pi_winter(args)

        if len(df) == 0:
            sys.exit('ERROR: dataframe creation failed')

        return df

    ## @brief Derive pi_summer
    #
    # sum of parameters 12, 13, 25, 26, 27, 28, 29
    def derive_pi_summer(self, args):
        print('--> Derive pi_summer')
        ds = {}
        # loop over files
        src = args['src_folder'] + '/' + str(args['scenario_id']) + '/10/'
        print('--> src', src)
        for r, d, f in os.walk(src):
            for file in f:
                df = pd.DataFrame()
                # get year from fname
                year = file.split('.')[0].split('_')[-1]
                print(year)

                try:
                     # read parameters for one year# read the h5 file
                    df_10 = pd.read_hdf(args['src_folder'] + '/' + str(args['scenario_id']) + '/10/' + str(args['scenario_id']) + '_10_' + str(year) + '.h5', key='table').reset_index()
                    # set integer type for column, set nan values
                    df_10['index'] = df_10['index'].astype('float').replace(-99999, np.nan)
                    # get a column for each month
                    df_10[['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']] = df_10.values_block_0.str.split(expand=True,).astype(float).replace(-99999, np.nan)
                    # remove column values_block_0
                    df_10 = df_10.drop(columns=['values_block_0'])
                    # create sum of flows
                    decimals = self.conf[args['data_type']]['parameters']['pi_summer']['decimals']
                    df['index'] = df_10['index']
                    df['jan'] = 0
                    df['feb'] = 0
                    df['mar'] = 0
                    df['apr'] = df_10['apr'].round(decimals)
                    df['may'] = df_10['may'].round(decimals)
                    df['jun'] = df_10['jun'].round(decimals)
                    df['jul'] = df_10['jul'].round(decimals)
                    df['aug'] = df_10['aug'].round(decimals)
                    df['sep'] = df_10['sep'].round(decimals)
                    df['oct'] = 0
                    df['nov'] = 0
                    df['dec'] = 0
                    ds[str(year)] = df
                except:
                    print("ERROR: ")

        return ds

    ## @brief Derive pi_winter
    #
    # sum of parameters 12, 13, 25, 26, 27, 28, 29
    def derive_pi_winter(self, args):
        print('--> Derive pi_winter')
        ds = {}
        # loop over files
        src = args['src_folder'] + '/' + str(args['scenario_id']) + '/10/'
        print('--> src', src)
        for r, d, f in os.walk(src):
            for file in f:
                df = pd.DataFrame()
                # get year from fname
                year = file.split('.')[0].split('_')[-1]
                print(year)

                try:
                    # read parameters for one year# read the h5 file
                    df_10 = pd.read_hdf(args['src_folder'] + '/' + str(args['scenario_id']) + '/10/' + str(args['scenario_id']) + '_10_' + str(year) + '.h5', key='table').reset_index()
                    # set integer type for column, set nan values
                    df_10['index'] = df_10['index'].astype('float').replace(-99999, np.nan)
                    # get a column for each month
                    df_10[['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']] = df_10.values_block_0.str.split(expand=True,).astype(float).replace(-99999, np.nan)
                    # remove column values_block_0
                    df_10 = df_10.drop(columns=['values_block_0'])
                    # create sum of flows
                    decimals = self.conf[args['data_type']]['parameters']['pi_winter']['decimals']
                    df['index'] = df_10['index']
                    df['jan'] = df_10['jan'].round(decimals)
                    df['feb'] = df_10['feb'].round(decimals)
                    df['mar'] = df_10['mar'].round(decimals)
                    df['apr'] = 0
                    df['may'] = 0
                    df['jun'] = 0
                    df['jul'] = 0
                    df['aug'] = 0
                    df['sep'] = 0
                    df['oct'] = df_10['oct'].round(decimals)
                    df['nov'] = df_10['nov'].round(decimals)
                    df['dec'] = df_10['dec'].round(decimals)
                    # assign dataframe to dictionary
                    ds[str(year)] = df
                except:
                    print("ERROR: ")

        return ds

    ## @brief Save derived parameters
    def save_derived_parameters(self, args, df):
        print('--> Save derived parameters')
        for p in df:
            print('===>>', p)
            if df[p] != None:
                for y in df[p]:
                    print(y)
                    df_year = df[p][str(y)]
                    # reorganize data to final structure: index, values_block_0[]
                    df_final = pd.DataFrame(columns=['index','values_block_0'])
                    df_final['index'] = df_year['index']
                    df_final['values_block_0'] = df_year[df_year.columns[1:]].apply(
                        lambda x: ' '.join(x.astype(str)),
                        axis=1
                    )
                    df_final = df_final.set_index('index')
                    #print(df_final)
                    print(df_final.dtypes)
                    # save as hdf5
                    path = self.args['dst_folder'] + str(self.args['scenario_id']) + '/' + str(self.conf[args['data_type']]['parameters'][p]['id']) + '/'
                    if not os.path.exists(path):
                        os.makedirs(path)
                    fn = str(self.args['scenario_id']) + '_' + str(self.conf[args['data_type']]['parameters'][p]['id']) + '_' + str(y) + '.h5'
                    print(path + fn)
                    #sys.exit()
                    try:
                        df_final[['values_block_0']].to_hdf(path + fn, key='table' , mode='w', format='table')
                    except:
                        sys.exit("ERROR: " + str(sys.exc_info()))


import random
print('Number Guessing Game')

randnum = random.randint(1,9)
chances = 0
print('Guess any number between 1 to 9!')

#While loop to count the number of chances
while chances < 5:

    guess = int(input('Enter your guessed number!'))

    # Compare the user entered number with the number to be guessed

    if guess == randnum:
        # If number entered by user is same as the generated
        # number by randint function then break from loop using loop
        # control statement "break"
        print('Congratulations! You guessed the number!')
        break

    elif guess > randnum:
        print('Your guess was too high! Guess a number lower than', guess)

    else:
        print('Your guess was too low! Guess a number higher than',guess)

        chances+=1

    # Check whether the user guessed the correct number
    if not chances < 5:
        print('You Lose! The number was',randnum)


import pandas as pd

# with pd.option_context('display.max_rows', None, 'display.max_columns', None):
#     print(result.head(20))
#
# s = result['Monkey']
# for i in set(s):
#     print(i)
# print(result.shape)
# print(len(set(s)))
#
# with open("monkeys.txt", 'w') as f:
#     for s in list(set(s)):
#         f.write(str(s) + '\n')

def read_csv(filename):
    dic = {}
    with open(filename) as f:
        lines = f.read().splitlines()
        for line in lines:
            x = line.split(",")
            dic[str(x[0])] = x[1]
    return dic


from appJar import gui
import utils

app = gui("Mon TP Python")

def showSubWindow(button):
    app.showSubWindow(button)

def exo1_exec():
    try:
        num1 = int(app.getEntry("one_num1"))
        num2 = int(app.getEntry("one_num2"))
        if(utils.divisible(num1, num2)):
            app.setLabel("one_result",
                         str(num1)+" est divisible par "+str(num2))
        else:
            app.setLabel("one_result",
                         str(num1)+" n'est pas divisible par "+str(num2))
    except TypeError:
        app.setLabel("one_result", "Un champ est vide!")

def exo2_exec():
    try:
        num = int(app.getEntry("two_num"))
        result = utils.divisors(num)
        resultStr = utils.arrayToStr(result)
        app.setLabel("two_result", resultStr)
    except TypeError:
        app.setLabel("two_result", "Un champ est vide!")

def exo3_exec():
    result = utils.evenNumbers()
    resultStr = utils.arrayToStr(result)
    app.setLabel("three_result", resultStr)

def exo4_exec():
    try:
        u = int(app.getEntry("four_num1"))
        q = int(app.getEntry("four_num2"))
        result = utils.geometricSuite(u, q)
        resultStr = utils.arrayToStr(result)
        app.setLabel("four_result", resultStr)
    except TypeError:
        app.setLabel("four_result", "Un champ est vide!")

def exo5_exec():
    try:
        num = int(app.getEntry("five_num"))
        result = utils.toBinary(num)
        app.setLabel("five_result", str(num)+" en binaire fait "+result)
    except TypeError:
        app.setLabel("five_result", "Un champ est vide!")

# Main Windows
app.addLabel("title", "Quel exercice voulez-vous tester?")
app.addButton("Exercice 1: Divisibilité", showSubWindow)
app.addButton("Exercice 2: Diviseurs", showSubWindow)
app.addButton("Exercice 3: Nombres pairs", showSubWindow)
app.addButton("Exercice 4: Suite géométrique", showSubWindow)
app.addButton("Exercice 5: Décimal à Binaire", showSubWindow)

# Exercice 1
app.startSubWindow("Exercice 1: Divisibilité", modal=True)
app.addLabel("one_num1_label", "Nombre 1 :")
app.addNumericEntry("one_num1")
app.addLabel("one_num2_label", "Nombre 2 :")
app.addNumericEntry("one_num2")
app.addNamedButton("Lancer", "one_run", exo1_exec)
app.addEmptyLabel("one_result")
app.stopSubWindow()

# Exercice 2
app.startSubWindow("Exercice 2: Diviseurs", modal=True)
app.addLabel("two_num_label", "Nombre :")
app.addNumericEntry("two_num")
app.addNamedButton("Lancer", "two_run", exo2_exec)
app.addEmptyLabel("two_result")
app.stopSubWindow()

# Exercice 3
app.startSubWindow("Exercice 3: Nombres pairs", modal=True)
app.addNamedButton("Lancer", "three_run", exo3_exec)
app.addEmptyLabel("three_result")
app.stopSubWindow()

# Exercice 4
app.startSubWindow("Exercice 4: Suite géométrique", modal=True)
app.addLabel("four_num1_label", "u(0) :")
app.addNumericEntry("four_num1")
app.addLabel("four_num2_label", "Raison :")
app.addNumericEntry("four_num2")
app.addNamedButton("Lancer", "four_run", exo4_exec)
app.addEmptyLabel("four_result")
app.stopSubWindow()

# Exercice 5
app.startSubWindow("Exercice 5: Décimal à Binaire", modal=True)
app.addLabel("five_num_label", "Nombre :")
app.addNumericEntry("five_num")
app.addNamedButton("Lancer", "five_run", exo5_exec)
app.addEmptyLabel("five_result")
app.stopSubWindow()

app.go()


# %%
import pickle
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.distance import pdist
from scipy.cluster.hierarchy import dendrogram, linkage
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
import os.path as osp
import argparse
import scipy.stats
import pandas as pd
import seaborn as sns

plt.rcParams["font.sans-serif"] = ["SimHei"]  # 用来正常显示中文标签
plt.rcParams["axes.unicode_minus"] = False  # 用来正常显示负号

#%%
clippredpkl_file = '/mnt/liying.cibr.ac.cn_Data_Temp/multiview_9/chenxf/00_BehaviorAnalysis-seq2seq/SexAge/DayAll20230828/All-DecSeq/FWPCA0.00_P100_en3_hid30_epoch300-decSeqPC0.9_svm2allAcc0.96_kmeansK2use-43_fromK1-20_K100.clippredpkl'
beh_project_dir = osp.dirname(clippredpkl_file)
clippreddata = pickle.load(open(clippredpkl_file, "rb"))
assert {
    "ncluster",
    "ntwin",
    "cluster_labels",
    "embedding",
    "embedding_d2",
    "clipNames",
    "cluster_names",
} <= clippreddata.keys()
# %% 载入数据
feat_data = clippreddata["embedding"]  # nsample x nfeat

# start from 1. The 0 is nonsocial
kmeans_label = clippreddata["cluster_labels"]
n_kmeans = clippreddata["ncluster"]
cluster_names = clippreddata['cluster_names']
assert kmeans_label.min() == 1

def get_pearsonr(xs, ys, embedding):
    return np.array([scipy.stats.pearsonr(embedding[x], embedding[y])[0] for x, y in zip(xs, ys)])

n_each_class = 200
n_blockin = 4
clusterlabel = clippreddata["cluster_labels"] # kmeans_data['labels'] + 1
assert clusterlabel.min()==1 and clusterlabel.max()==n_kmeans
uni_id, uni_c = np.unique(clusterlabel, return_counts=True)
np.random.seed(1000)

n_each_class = np.min([uni_c.min()//2, 200])

id_ego_choose_each_class = np.zeros((len(uni_id)+1, n_each_class, n_blockin), dtype=int)
id_partner_choose_each_class = np.zeros_like(id_ego_choose_each_class)
id_nchoose_each_class = np.zeros_like(id_ego_choose_each_class)
for i in uni_id:
    id_list = np.where(clusterlabel==i)[0]

    id_choose = np.stack([np.random.choice(id_list, n_blockin*2, replace=True) for _ in range(n_each_class)])
    id_ego_choose_each_class[i] = id_choose[...,  :n_blockin]
    id_partner_choose_each_class[i] = id_choose[...,  n_blockin:]

    id_list = np.where(clusterlabel!=i)[0]
    id_nchoose = np.stack([np.random.choice(id_list, n_blockin, replace=True) for _ in range(n_each_class)])
    id_nchoose_each_class[i] = id_nchoose

df = pd.DataFrame(columns=['r', 'group', 'cluster'])
df_list = []
for i in uni_id:
    xego = id_ego_choose_each_class[i]
    xpartner = id_partner_choose_each_class[i]
    yother = id_nchoose_each_class[i]
    rs_intra = [get_pearsonr(xego_, xpartner_, feat_data).mean() for (xego_, xpartner_) in zip(xego, xpartner)]
    rs_inter = [get_pearsonr(xego_, yother_, feat_data).mean() for (xego_, yother_) in zip(xego, yother)]
    df1 = pd.DataFrame(zip(rs_intra, ['intra']*n_each_class, np.zeros((n_each_class,), dtype=int)+i))
    df2 = pd.DataFrame(zip(rs_inter, ['inter']*n_each_class, np.zeros((n_each_class,), dtype=int)+i))
    df_list.extend([df1, df2])

df = pd.concat(df_list)
df.columns = ['r', 'group', 'cluster']
df_mean = df.groupby(by=['group', 'cluster']).agg('median').reset_index()
df_mean.loc[(df_mean['group'] =='intra'), 'cluster'] -= 1.2
df_mean.loc[(df_mean['group'] =='inter'), 'cluster'] -= 0.8

plt.figure(figsize= (20,8))
palette = ['#a4cee4', '#e6e6e6']
sns.violinplot(data=df, x='cluster', y='r', scale='count',
               palette=palette, cut = 5,
               inner=None, hue='group')

plt.plot(df_mean['cluster'].values, df_mean['r'].values, 'wo', markeredgecolor='k')
plt.xlim(-0.5, n_kmeans - 0.5)
plt.ylim(-1, 1)
plt.yticks([-1, -0.5, 0, 0.5, 1])
plt.ylabel('Correlation coefficient')
outfig = osp.join(beh_project_dir, 'violinplot_cluster_similarity_plot.pdf')
plt.savefig(outfig)
#%%
K = len(uni_id)
matrix = np.zeros((K,K))
for i in range(K):
    for j in range(K):
        xego = id_ego_choose_each_class[i+1][...,0]
        xpartner = id_partner_choose_each_class[j+1][...,0]
        matrix[i, j] = get_pearsonr(xego, xpartner, feat_data).mean()

matrix_mirror = (matrix + matrix.T)/2

leaf_labels = [
    f"[{leaf+1:>2}] {label.rstrip()}" for leaf, label in enumerate(cluster_names)
]

df_matrix_mirror = pd.DataFrame(matrix_mirror, columns=np.arange(1,K+1), index=np.arange(1,K+1))
df_matrix_mirror = pd.DataFrame(matrix_mirror, columns=np.arange(1,K+1), index=leaf_labels)
sns.clustermap(df_matrix_mirror, cmap="vlag", vmin=-1, vmax=1,
               xticklabels=1,yticklabels=1,
               method='complete',
               figsize=(11,8) )
outfig = osp.join(osp.dirname(clippredpkl_file), "dendrogram_heatmap_similiar.pdf")
plt.savefig(outfig, bbox_inches="tight")

dist = pdist(matrix_mirror)
linkage_matrix = linkage(dist,
                         method='complete',
                         )

fig, ax = plt.subplots(figsize=(4, 14))
plt.rcParams["font.family"] = "Arial"
dendrogram_result = dendrogram(
    linkage_matrix,
    ax=ax,
    labels=leaf_labels,
    orientation="left",
    color_threshold=0,
    above_threshold_color="k",
)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["left"].set_visible(False)
ax.set_ylim(ax.get_ylim()[::-1])
plt.xticks([])
plt.yticks(fontsize=14)

outfig = osp.join(osp.dirname(clippredpkl_file), "dendrogram_similiar.pdf")
plt.savefig(outfig, bbox_inches="tight")


# -*- coding: utf-8 -*-
# © 2015 ClearCorp
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

from openerp import models
from openerp.report import report_sxw

class StockMoveOder(report_sxw.rml_parse):
    def __init__(self, cr, uid, name, context):
        super(StockMoveOder, self).__init__(cr, uid, name, context=context)
        self.localcontext.update({
            'get_data': self.get_data,
            'cr': cr,
            'uid': uid,
        })

    def get_data(self, cr, uid, data):
        product_product_obj = self.pool.get('product.product')
        sale_line_obj = self.pool.get('sale.order.line')
        sale_obj = self.pool.get('sale.order')
        purchase_line_obj = self.pool.get('purchase.order.line')
        purchase_obj = self.pool.get('purchase.order')
        product_ids = data['form']['product_ids']
        stock_location = data['form']['stock_location'][0]
        product_lines_to_print = []

        for product_id in product_ids:
            product = product_product_obj.browse(self.cr,
                                                 self.uid, product_id,
                                                 context=self.localcontext)[0]
            sale_line_ids = sale_line_obj.search(self.cr,
                                                 self.uid,
                                                 [('product_id',
                                                   '=',
                                                   product_id),
                                                  ('state',
                                                   '=',
                                                   'sale')]
                                                 )
            sale_order_ids = sale_obj.search(
                self.cr,
                self.uid,
                [('order_line',
                  'in',
                  sale_line_ids)]
                )
            sale_orders = sale_obj.browse(self.cr, self.uid, sale_order_ids)
            sale_orders_list = []
            purchase_line_ids = purchase_line_obj.search(self.cr,
                                                         self.uid,
                                                         [('product_id',
                                                           '=',
                                                           product_id),
                                                          ('state',
                                                           '=',
                                                           'sale')]
                                                         )
            purchase_order_ids = purchase_obj.search(self.cr,
                                                     self.uid,
                                                     [('order_line',
                                                       'in',
                                                       purchase_line_ids)]
                                                     )
            purchase_orders = purchase_obj.browse(self.cr, self.uid,
                                                  purchase_order_ids,
                                                  context=self.localcontext)
            for sale_order in sale_orders:
                sale_product_quantity = 0.0
                for sale_order_line in sale_order.order_line:
                    if sale_order_line.product_id.id == product_id:
                        sale_product_quantity += \
                            sale_order_line.product_uom_qty
                for picking in sale_order.picking_ids:
                    for move in picking.move_lines:
                        if move.product_id.id == product_id and \
                                move.location_id.id == stock_location and \
                                move.state == 'done':
                            sale_product_quantity -= \
                                move.product_uom_qty
                if sale_product_quantity != 0.0:
                    sale_order_line_dict = {'sale': sale_order.name,
                                            'quantity': sale_product_quantity,
                                            }
                    sale_orders_list.append(sale_order_line_dict)
            context = {'location': stock_location}
            line = {
                'name': product.name,
                'product': product,
                'qyt_available':
                    product_product_obj._product_available(
                        self.cr, self.uid, [product_id], field_names=None,
                        arg=False,  context=context)
                    [product_id]['qty_available'],
                'virtual_available':
                    product_product_obj._product_available(
                        self.cr, self.uid, [product_id], field_names=None,
                        arg=False,  context=context)
                    [product_id]['virtual_available'],
                'product_lines': [],
                }
            # is product are in purchase
            purchase_orders_list = []
            for purchase_order in purchase_orders:
                purchase_product_quantity = 0.0
                for purchase_order_line in purchase_order.order_line:
                    if purchase_order_line.product_id.id == product_id:
                        purchase_product_quantity +=\
                            purchase_order_line.product_qty
                for picking in purchase_order.picking_ids:
                    for move in picking.move_lines:
                        if move.product_id.id == product_id and\
                                move.location_dest_id.id == stock_location and\
                                move.state == 'done':
                            purchase_product_quantity -=\
                                move.product_uom_qty
                if purchase_product_quantity != 0.0:
                    purchase_order_line_dict = {
                        'purchase': purchase_order.name,
                        'quantity': purchase_product_quantity,
                        }
                    purchase_orders_list.append(purchase_order_line_dict)
            product_lines = [sale_orders_list, purchase_orders_list]
            line['product_lines'] = product_lines
            product_lines_to_print.append(line)
        return product_lines_to_print

class ReportStockMoveOrder(models.AbstractModel):
    _name = 'report.stock_move_report.report_stock_move_order'
    _inherit = 'report.abstract_report'
    _template = 'stock_move_report.report_stock_move_order'
    _wrapped_report_class = StockMoveOder


# ðŸš¨ Don't change the code below ðŸ‘‡
print("Welcome to Python Pizza Deliveries!")
size = input("What size pizza do you want? S, M, or L ")
add_pepperoni = input("Do you want pepperoni? Y or N ")
extra_cheese = input("Do you want extra cheese? Y or N ")
# ðŸš¨ Don't change the code above ðŸ‘†

#Write your code below this line ðŸ‘‡
print("Welcome to Python Pizza Deliveries!")
Size = input("What size pizza do you want? S, M or L ")
Peperoni = input("Do you want peperoni? Y or N")
Cheese = input("Do you want extra cheese? Y or N")

if Size == "S":
    total_tamanho = 15
elif Size == "M":
    total_tamanho = 20
else:
    total_tamanho = 25
if Peperoni == "Y" and Size == "S":
    total_peperoni = 2
elif Peperoni == "Y" and Size == "M" or "L":
    total_peperoni = 3
else:
    total_peperoni = 0
if Cheese == "Y":
    total_cheese = 1
else:
    total_cheese = 0
total = total_tamanho + total_peperoni + total_cheese
print("Your final bill is: ${}.".format(total))


from airflow import DAG
from airflow.operators.python import PythonOperator
from datetime import datetime
import boto3
from airflow.models import Variable
from datetime import datetime
import time

def executar_emr(steps, emr_client, cluster_id):
    action = emr_client.add_job_flow_steps(JobFlowId=cluster_id, Steps=steps)
    return action

def main():
    cluster_id = 'j-1IEGGW7IQ8XQO'
    env = 'dev'
    arquivo_config = 's3://customer-intelligences/{}/jobs/config/config.json'.format(env)
    data_atualizacao = '08/01/2022'

    solux_trusted = [
        {
            'Name': 'Solux-Trusted',
            'ActionOnFailure': 'CANCEL_AND_WAIT',
            'HadoopJarStep': {
                'Jar': 'command-runner.jar',
                'Args': ['spark-submit',
                            '--deploy-mode', 'cluster',
                            's3://customer-intelligences/{}/jobs/BI03DJ11.py'.format(env),
                            '--env', env,
                            '--data_atualizacao',data_atualizacao,
                            '--arquivo_config', arquivo_config]
            }
        }
    ]

    emr_client = boto3.client('emr', region_name = 'us-east-1')

    solux_trusted = executar_emr(solux_trusted, emr_client, cluster_id)

with DAG(dag_id="emr_exec_2_dag",
         start_date=datetime(2022,1,1),
         schedule_interval=None,
         catchup=False) as dag:

    task1 = PythonOperator(
            task_id="emr_exec",
            python_callable=main)

task1