import random  # for random module

# Global variable Player Stats
global health
global strength
global magic
global luck
health = 5
strength = 5
magic = 5
luck = 5 # Invisible Stat

# Frequently Reused Functions

def stats():  # prints stats
    print(f"Your Stats \nHealth: {health} \nStrength: {strength} \nMagic: {magic}\n")
def default():  # If an invalid answer is given. Player is punished and moves on
    global magic
    global health
    global strength
    health -= 2
    magic -= 2
    strength -= 2
    print(
        "You were so overwhelmed that you accidentally discharged an explosion spell. \n It blew you a few feet in the air. You land painfully on your back. You are alive, but you lose 2 points for all Stats. \n ")
    stats()
    health_0()
    luck_roll_neg()
def click_enter():  # Let's player know to click enter to continue
    enter = input("Press [Enter] to Continue. \n")

# If Health is at 0, terminate program
def health_0():
    if health <= 0:
        print(f"Your Health is at {health}. You can not Continue. Game Over!")
        quit()
#Luck Rolls - Add into events
def luck_roll_50():
    global luck
    luck_stat = random.randint(-2, 2)
    luck += luck_stat
def luck_roll_neg():
    global luck
    luck_stat = random.randint(-2, 0)
    luck += luck_stat
def luck_roll_pos():
    global luck
    luck_stat = random.randint(1, 2)
    luck += luck_stat

#Default Settings Above
########################################################################################################################
# Horse/Griffin
def horse_griffin():
    global health
    global strength
    global magic
    click_enter()
    answer_1 = input(
        "You must find a way of getting to Miss GoldenDragon's house. "
        "\nDo you summon a griffin with magic or call on a horse carriage? Enter Griffin or Horse. \n ")

    if answer_1.lower().strip() != "griffin" and answer_1.lower().strip() != "horse":
        health -= 3
        print(
            f"You raise your wand and shout out '{answer_1}'! "
            f"\nUnfortunately that was not a valid spell and you summoned a grumpy griffin. It claws at you. You lose 3 Health.\n ")
        click_enter()
        stats()
        luck_roll_neg()
        health_0()
        print(
            "You call for a horse carriage instead and it takes you to the edge of the Dark Forest. "
            "\nNo matter how much money you offer the driver refuses to take you through the forest. "
            "\nSomething about insurance premiums being too high to cover trips through the Dark Forest.\n")
    elif answer_1.lower().strip() == "griffin":
        health -= 2
        print(
            "You raise your wand up to summon a griffin. "
            "\nYour magic is too low and you summoned a grumpy griffin. "
            "\nIt claws at you. You lose 2 Health.\n")
        click_enter()
        stats()
        luck_roll_neg()
        health_0()
        print(
            "You end up calling a the horse carriage instead. The horse carriage arrives and it takes you to the edge of the Dark Forest. "
            "\nNo matter how much money you offer the driver refuses to take you through the forest. "
            "\nSomething about insurance premiums being too high to cover trips through the Dark Forest.\n")
    elif answer_1.lower().strip() == "horse":
        print(
            "The horse carriage arrives and it takes you to the edge of the Dark Forest. No matter how much money you offer the driver refuses to take you through the forest. "
            "\nSomething about insurance premiums being too high to cover trips through the Dark Forest.\n")
        click_enter()
        stats()
        health_0()
        luck_roll_pos()
########################################################################################################################
# Fairies Event
def magic_fairies():  # Checks with the current Magic stat and runs if statements
    global magic
    global health
    global strength
    if magic >= 9:
        magic += 2
        print(
            "You quickly casted a sleep spell on the fairies. They fall down around you like falling leaves. You tiptoe away from the pile of snoring fairies. \nYou gain 2 Magic from this. \n")
        click_enter()
        stats()
        health_0()
        luck_roll_pos()
    elif magic >= 5 and magic <= 8:
        health -= 1
        magic += 1
        print(
            "You can only recall the lightning spell. You zapped them with a shot from your wand. It worked! \nBut only for a few moments. \nThey quickly recover and flew towards you. You managed to run away with a scraped knee. \nYou lose 1 Health and gain 1 Magic. \n")
        click_enter()
        stats()
        health_0()
        luck_roll_50()
    else:
        health -= 3
        magic -= 1
        strength -= 1
        print(
            "You anxiously try to recall any spell to fight the fairies. You yell out a random spell. \n BOOM \nIt blew up in your face. Fortunately it also blasted the fairies away. \nYou lose 3 Health, 1 Magic and 1 Strength. \n ")
        click_enter()
        stats()
        health_0()
        luck_roll_50()
def strength_fairies():  # Checks Stats
    global magic
    global health
    global strength
    if strength >= 9:
        strength += 2
        print(
            "You break off a branch from a tree and start swatting the fairies with all your might. \nThe fairies were stunned by your ferocity that they quickly clear the area. You got a good arm workout from swinging the branch. \nYou gain 2 Strength. \n")
        click_enter()
        stats()
        health_0()
        luck_roll_pos()
    elif strength >= 5 and strength <= 8:
        health -= 1
        strength += 1
        print(
            "You break off a branch from a tree and start swatting the fairies. \nThey screeched angrily at you. \nYou lost your nerve and started running away. You tripped on tree roots and branches scratched you, but you escaped. \nYou lost 1 Health and gained 1 Strength. \n ")
        click_enter()
        stats()
        health_0()
        luck_roll_50()
    else:
        health -= 3
        strength -= 2
        print(
            "You tried to break off a tree branch to swat the fairies with. \nYou are too weak. The fairies are upon you. Pulling at your clothes and hair. Scratching at your eyes. \nYou run blindly through the forest, hitting tree trunks, tripping on roots and scratched by branches. You managed to get away from them. \nYou lost 3 Health and 2 Strength. \n ")
        click_enter()
        stats()
        health_0()
        luck_roll_50()
def fairies():
    click_enter()
    print("You encounter a swarm of fairies. Fairies are mischievous and like to mess with humans. "
          "\nYou would like to avoid them if you can, but they blocked the your path through the forest. \n")
    while True:
        answer_2 = input("What do you do? Do you run away, use magic or fight? Enter Run, Magic or Fight. \n")
        if answer_2.lower().strip() == "run":
            print("You died trying to run away. \n")
            quit()
        elif answer_2.lower().strip() == "magic":
            magic_fairies()
            break
        elif answer_2.lower().strip() == "fight":
            strength_fairies()
            break
        else:
            continue
########################################################################################################################
# Hole Event
def hole_event():
    global health
    global strength
    global magic
    click_enter()
    hole_flip = random.randint(1,3)
    print("After an hour of walking, you fell into a hole! \n")
    click_enter()
    if hole_flip == 1:
        health += 5
        magic += 5
        print("You fell into a dwarve's dwelling. They are in the middle of renovating their home. "
              "\nThey are extremely apologetic and give you a Health and Magic potion for your trouble. Your Health and Magic went up by 5.\n")
        click_enter()
        stats()
        health_0()
        luck_roll_pos()
    else:
        health -= 3
        strength -= 3
        print("You fell into a Cannabal's trap! The crazed human hasn't eaten human flesh in weeks. "
              "\nYou barely escape with your life. You were injured during your escape. You lose 3 Health and 1 Strength. \n")
        click_enter()
        stats()
        luck_roll_50()
        health_0()
########################################################################################################################
# Mermaids Event
def magic_mermaids():  # Checks with the current Magic stat and runs if statements
    global magic
    global health
    global strength
    if magic >= 9:
        magic += 2
        print(
            "You quickly casted a lightning spell on the mermaids. They are stunned and sink below the waters. "
            "\nYou gain 2 Magic from this. \n")
        click_enter()
        stats()
        health_0()
        luck_roll_pos()
    elif magic >= 5 and magic <= 8:
        health -= 1
        magic += 1
        print(
            "In the spur of the moment you can only recall the vine spell. You grew vines over the water's surface. "
            "The vines entangle the mermaids \nBut only for a few moments. "
            "\nThey claw and bite through the vines and swim towards you. "
            "You managed to flee, but you got hurt in the process. \nYou lose 1 Health and gain 1 Magic. \n")
        click_enter()
        stats()
        luck_roll_50()
        health_0()
    else:
        health -= 3
        magic -= 1
        strength -= 1
        print(
            "You anxiously try to recall any spell to fight the mermaids. You yell out a random spell. \n BOOM \nIt blew up in your face. Fortunately it also scared the mermaids away. \nYou lose 3 Health, 1 Magic and 1 Strength. \n ")
        click_enter()
        stats()
        luck_roll_50()
        health_0()
def strength_mermaids():  # Checks Stats
    global magic
    global health
    global strength
    if strength >= 9:
        strength += 2
        print(
            "You pick up a fist-sized rock and accurately slung it at one of the mermaid's head. It got hit and disappeared under the surface \n You aim more rocks at them. The mermaids were stunned by your aim. They quickly clear the area. You got a good arm workout. \nYou gain 2 Strength. \n")
        click_enter()
        stats()
        health_0()
        luck_roll_pos()
    elif strength >= 5 and strength <= 8:
        health -= 1
        strength += 1
        print(
            "You pick up a rock and started to throw it at the mermaids. You missed. \nThey smile maliciously as they swim towards you. \nYou lost your nerve and started running away. You tripped on a rock during your escape. \nYou lost 1 Health and gained 1 Strength. \n ")
        click_enter()
        stats()
        luck_roll_50()
        health_0()
    else:
        health -= 3
        strength -= 2
        print(
            "You tried to pick up a big rock \nYou are too weak. The mermaids are quicker than you thought. They began pulling at your clothes to drag you into the water. \nYou fought with all your might against their claw-like hands. You managed to get away from them. \nYou lost 3 Health and 2 Strength. \n ")
        click_enter()
        stats()
        luck_roll_50()
        health_0()
def mermaids():
    click_enter()
    print("You reached a lake. It has been a hot and humid day. You decide to wade into the lake to cool off and have a sip. "
          "\nsplash\n"
          "From the center of the lake, a school of mermaids emerge. "
          "They are swimming quickly towards you.\n")
    while True:
        answer_4 = input(
            "What do you do? Do you run away, use magic or fight? Enter Run, Magic or Fight. \n")
        if answer_4.lower().strip() == "run":
            print("You died trying to run away. \n")
            quit()
        elif answer_4.lower().strip() == "magic":
            magic_mermaids()
            break
        elif answer_4.lower().strip() == "fight":
            strength_mermaids()
            break
        else:
            continue
########################################################################################################################
#Granny Event
#Granny Event
def rps_game():
    rock = '''
        _______
    ---'   ____)
          (_____)
          (_____)
          (____)
    ---.__(___)
    '''

    paper = '''
        _______
    ---'   ____)____
              ______)
              _______)
             _______)
    ---.__________)
    '''

    scissors = '''
        _______
    ---'   ____)____
              ______)
           __________)
          (____)
    ---.__(___)
    '''

    images = [rock, paper, scissors]

    number_games = input("Granny asks 'How many times do you want to play "
                         "Rock, Paper, Scissors?'\n")

    for turns in range(1, int(number_games) + 1):
        player_turn = int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors. \n"))
        if player_turn >= 3 or player_turn < 0:
            print(" You didn't follow the directions! Pick 0, 1 or 2 only! You lose! \n")
        else:
            print(images[player_turn])

            computer_turn = random.randint(0, 2)

            print("Granny chose:")
            print(images[computer_turn])

            if player_turn == computer_turn:
                print("Its a draw!")
                click_enter()
            elif player_turn == 0 and computer_turn == 1:
                print("Paper beats Rock! You lose!")
                click_enter()
            elif player_turn == 0 and computer_turn == 2:
                print("Rock beats Scissors! You win!")
                click_enter()
            elif player_turn == 1 and computer_turn == 0:
                print("Paper beats Rock! You win!")
                click_enter()
            elif player_turn == 1 and computer_turn == 2:
                print("Scissors beats Paper! You lose!")
                click_enter()
            elif player_turn == 2 and computer_turn == 0:
                print("Rock beats Scissors! You lose!")
                click_enter()
            elif player_turn == 2 and computer_turn == 1:
                print("Scissors beats Paper! You win!")
                click_enter()
def guess_number():
    # This is a guess the number game.
    import random
    number_games = input("Granny asks 'How many times do you want to play "
                         "Guess The Number'\n")

    for turns in range(1, int(number_games) + 1):
        secretNumber = random.randint(1, 20)
        print("Granny says, 'I am thinking of a number between 1 and 20.'\n")

        # Ask the player to guess 6 times.
        for guessesTaken in range(1, 7):
            print("Take a guess, dearie")
            guess = int(input())

            if guess < secretNumber:
                print("Aww shucks, your guess is low.")
            elif guess > secretNumber:
                print("Sweetie, your guess is too high.")
            else:
                break  # This condition is the correct guess!

        if guess == secretNumber:
            print("Good job dearie! You guessed my number in " + str(guessesTaken) + " guesses!\n")
            click_enter()
        else:
            print("Naw. The number I was thinking of was " + str(secretNumber))
            click_enter()
def granny_event():
    global health
    global strength
    global magic
    click_enter()
    play_or_not = input("A granny appears from out of the bushes. She looks lonely."
                       "Would you like to play some games with me dearie? \nEnter 'Y' for yes, 'N' for no \n")
    if play_or_not.lower().strip() == 'y':
        which_game = input("Oh goodie. What game would you like to play? "
                           "\nRock, Paper, Scissors or Guess the Number?"
                           "\nEnter 1 for Rock, Paper, Scissors. Enter 2 for Guess the Number. \n")
        if which_game == '1':
            rps_game()
        elif which_game == '2':
            guess_number()
        else:
            guess_number()
        print("Thank you for keeping me company dearie. Here, have a cookie."
          "\nYou eat the cookie and gained 5 Health, 5 Magic, and 5 Strength. \n")
        health += 5
        magic += 5
        strength += 5
        click_enter()
        stats()
        health_0()
        luck_roll_pos()

    else:
        print("'I'll get out of your hair', said Granny as she hobbled away. \n")
        health_0()
        luck_roll_neg()
########################################################################################################################
# Plants Event
def magic_plant():  # Checks with the current Magic stat and runs if statements
    global magic
    global health
    global strength
    if magic >= 9:
        magic += 2
        print(
            "You remember that plants are weak against fire. "
            "You shot fireballs from your wand. The plants caught on fire and burned to ash."
            "\nYou gain 2 Magic from this. \n")
        click_enter()
        stats()
        health_0()
        luck_roll_pos()
    elif magic >= 5 and magic <= 8:
        health -= 1
        magic += 1
        print(
            "You vaguely remember that plants are weak against fire. "
            "But you forget the fire spell. "
            "You manage to conjure up some rabbits to distract the plants as you escaped. "
            "\nYou lose 1 Health and gain 1 Magic. \n")
        click_enter()
        stats()
        luck_roll_50()
        health_0()
    else:
        health -= 3
        magic -= 1
        strength -= 1
        print(
            "In your panic, you forgot all your spells and wave your wand frantically at the plant. "
            " Your wand shoots out some sparks and you managed to set both the plants and yourself on fire."
            " You get away and smothered the flames."
            "\nYou lose 3 Health, 1 Magic and 1 Strength. \n ")
        click_enter()
        stats()
        luck_roll_50()
        health_0()
def strength_plant():  # Checks Stats
    global magic
    global health
    global strength
    if strength >= 9:
        strength += 2
        print(
            "You tear the vines apart with your bare hands. "
            "The plants recoil and withdraw their vines. "
            "\nYou gain 2 Strength. \n")
        click_enter()
        stats()
        luck_roll_pos()
    elif strength >= 5 and strength <= 8:
        health -= 1
        strength += 1
        print(
            "You attempt to tear the vines apart with your hands."
            " But you are too weak. The vines nearly overpower you."
            "\nYou manage to wiggle out of its grasp.\nYou lost 1 Health and gained 1 Strength. \n ")
        click_enter()
        stats()
        luck_roll_50()
        health_0()
    else:
        health -= 3
        strength -= 2
        print(
            "You attempt to tear the vines apart with your hands."
            " But you are too weak."
            "\n It pulls you towards its mouth. In your struggle, you dropped a pepper bomb into its mouth."
            "\n It retches and tosses you aside."
            "\nYou lost 3 Health and 2 Strength. \n ")
        click_enter()
        stats()
        luck_roll_50()
        health_0()
def plant():
    print("You took a closer inspection of one of the plant's vines."
        "It starts to move! It's a man-eating plant! \n")
    while True:
        answer_3 = input("What do you do? Do you run away, use magic or fight? Enter Run, Magic or Fight. \n")
        if answer_3.lower().strip() == "run":
            print("You died trying to run away. \n")
            quit()
        elif answer_3.lower().strip() == "magic":
            magic_plant()
            break
        elif answer_3.lower().strip() == "fight":
            strength_plant()
            break
        else:
            continue
def plant_event_50():
    global health
    global strength
    global magic
    plant_flip = random.randint(1,2)
    print("You approach a bush of brightly colored plants. "
          "They look familiar so you take a closer look. \n")
    click_enter()
    if plant_flip == '1':
        health += 5
        magic += 5
        strength += 5
        print("You recognize the plants upon a closer inspection! "
              "It is very rare plant that boosts your all stats! "
              "\nYour Health,Magic and Strength went up by 5.\n")
        click_enter()
        stats()
        luck_roll_pos()
    else:
        luck_roll_50()
        plant()
########################################################################################################################
# Mushrooms 50
def mushroom_event():
    global health
    global strength
    global magic
    click_enter()
    mushroom_flip = random.randint(1,3)
    print("All of a sudden a giant mushroom is rushing at you! \n")
    click_enter()
    if mushroom_flip == 1:
        health += 5
        magic += 5
        print("Lucky you! It was a magic mushroom! Your Health and Magic went up by 5.\n")
        click_enter()
        stats()
        health_0()
        luck_roll_pos()
    else:
        health -= 5
        strength -= 3
        print("Oh no! It was a cursed mushroom! It collides into you. You lose 5 Health and 3 Strength. \n")
        click_enter()
        stats()
        luck_roll_50()
        health_0()
########################################################################################################################
# Lake 50
def lake_event():
    global health
    global strength
    global magic
    click_enter()
    lake_flip = random.randint(1,3)
    print("You stop by a lake to refill your canteen. "
          "From the distant side of the lake you can vaguely see a silvery horse. "
          "\nIt is trotting accross the water's surface to you.")
    click_enter()
    if lake_flip == 1:
        health += 5
        magic += 5
        print("As it gets closer you can see the glow of its horn."
              "It's a unicorn! It blesses and purifies the lake water. \nYour Health and Magic went up by 5.\n")
        click_enter()
        stats()
        health_0()
        luck_roll_pos()
    else:
        health -= 3
        strength -= 3
        print("You see that it is a beautiful horse. It invites you to ride on it."
              "\nYou put your hands out to touch it. When it grabs you and starts dragging you under the water. "
              "\n Its a Kelpie!"
              "\nYou stun it with a spell and escape, but you lose 3 Health and 3 Strength. \n")
        click_enter()
        stats()
        luck_roll_50()
        health_0()
########################################################################################################################
# Treasure Chest 50
def treasure_chest_50():
    global health
    global strength
    global magic
    click_enter()
    chest_flip = random.randint(1,3)
    print("You stop by an ancient tree to rest. "
          "The giant tree has a big hollow above your head. "
          "You curiously peeked in and see a dusty treasure chest. \n")
    click_enter()
    if chest_flip == 1:
        health += 5
        magic += 5
        print("You shrug and decide to open the chest."
              "The top creaks open and a bright light blinds you. "
              "\nThere is nothing in the chest, but your Health and Magic went up by 5.\n")
        click_enter()
        stats()
        health_0()
        luck_roll_pos()
    else:
        health -= 3
        strength -= 3
        print("You shrug and decide to open the chest."
              "\nYou barely touched the top of the chest when it opens its fanged mouth. "
              "\nIts a Mimic!"
              "\nIt bites down on your hand. "
              "You managed to stun it with a spell and escape, but you lose 3 Health and 3 Strength. \n")
        click_enter()
        stats()
        luck_roll_50()
        health_0()
########################################################################################################################
# Slimes
# Slimes Event
def magic_slimes():  # Checks with the current Magic stat and runs if statements
    global magic
    global health
    global strength
    if magic >= 9:
        magic += 2
        print(
            "Slimes are weak against fire. You blast fireballs at the the slimes. "
            "They melt away into puddles. \nYou gain 2 Magic from this. \n")
        click_enter()
        stats()
        health_0()
        luck_roll_pos()
    elif magic >= 5 and magic <= 8:
        health -= 1
        magic += 1
        print(
            "You can only recall the lightning spell. You zapped them with a shot from your wand. It worked! "
            "\nBut only for a few moments. "
            "\nThey quickly recover and bounce towards you. You managed to run away with a scraped knee. "
            "\nYou lose 1 Health and gain 1 Magic. \n")
        click_enter()
        stats()
        health_0()
        luck_roll_50()
    else:
        health -= 3
        magic -= 1
        strength -= 1
        print(
            "You anxiously try to recall any spell to fight the slimes. "
            "You yell out a random spell. "
            "\n BOOM \n"
            "It blew up in your face. Fortunately it also blasted the slimes into nothing. "
            "\nYou lose 3 Health, 1 Magic and 1 Strength. \n ")
        click_enter()
        stats()
        health_0()
        luck_roll_50()
def strength_slimes():  # Checks Stats
    global magic
    global health
    global strength
    if strength >= 9:
        strength += 2
        print(
            "You break off a thick branch from a tree and start smashing the slimes with all your might. "
            "\nThe slimes were obliterated by your might. "
            "You got a good arm workout from swinging the branch. \nYou gain 2 Strength. \n")
        click_enter()
        stats()
        health_0()
        luck_roll_pos()
    elif strength >= 5 and strength <= 8:
        health -= 1
        strength += 1
        print(
            "You break off a branch from a tree and start whacking at the slimes. "
            "\nYour blows bounce off their slimey surface. "
            "\nYou lost your nerve and started running away. Luckily slimes don't have great vision, so you escaped easily. "
            "\nYou lost 1 Health and gained 1 Strength. \n ")
        click_enter()
        stats()
        health_0()
        luck_roll_50()
    else:
        health -= 3
        strength -= 2
        print(
            "You tried to break off a tree branch to smash the slimes. \nYou are too weak. The slimes are upon you. "
            "They surround you and bounce on you. "
            "\nYou run blindly through the forest, hitting tree trunks, tripping on roots and scratched by branches. "
            "You managed to get away from them. \nYou lost 3 Health and 2 Strength. \n ")
        click_enter()
        stats()
        health_0()
        luck_roll_50()
def slimes():
    click_enter()
    print("You encounter a herd of bouncing slimes. Slimes are a low-level monster."
        "\nBut you are not an adventurer, so you would like to avoid them if you can. "
        "\nBut the slimes blocked the your path through the forest. \n")
    while True:
        answer_2 = input("What do you do? Do you run away, use magic or fight? Enter Run, Magic or Fight. \n")
        if answer_2.lower().strip() == "run":
            print("You died trying to run away. \n")
            quit()
        elif answer_2.lower().strip() == "magic":
            magic_slimes()
            break
        elif answer_2.lower().strip() == "fight":
            strength_slimes()
            break
        else:
            continue
########################################################################################################################
# Goblins
# Goblins Event
def magic_goblins():  # Checks with the current Magic stat and runs if statements
    global magic
    global health
    global strength
    if magic >= 9:
        magic += 2
        print(
            "Goblins love gold. You shoot an illusion spell on some butterflies. "
            "The butterflies appear to be made of gold. The goblins chase after the gold butterflies. "
            "\nYou gain 2 Magic from this. \n")
        click_enter()
        stats()
        health_0()
        luck_roll_pos()
    elif magic >= 5 and magic <= 8:
        health -= 1
        magic += 1
        print(
            "Goblins love gold. You take out some of your gold coins. "
            "You zapped the coins with a flying spell. The goblins are distracted by the flying coins! "
            "\nBut only for a few moments. Your spell wasn't strong enough and the coins fell down. "
            "\nThe goblins grab the coins and start running towards you. You managed to run away. "
            "\nYou lose 1 Health and gain 1 Magic. \n")
        click_enter()
        stats()
        health_0()
        luck_roll_50()
    else:
        health -= 3
        magic -= 1
        strength -= 1
        print(
            "You anxiously try to recall any spell to fight the goblins. "
            "You yell out a random spell. "
            "\n BOOM \n"
            "It blew up in your face. Fortunately it also blasted the goblins away. "
            "\nYou lose 3 Health, 1 Magic and 1 Strength. \n ")
        click_enter()
        stats()
        health_0()
        luck_roll_50()
def strength_goblins():  # Checks Stats
    global magic
    global health
    global strength
    if strength >= 9:
        strength += 2
        print(
            "You grab a goblin and begin swinging it around like a club. "
            "\nThe goblins are thoroughly thrashed. They run off scared and bruised. "
            "You got a good arm workout from swinging goblins. \nYou gain 2 Strength. \n")
        click_enter()
        stats()
        health_0()
        luck_roll_pos()
    elif strength >= 5 and strength <= 8:
        health -= 1
        strength += 1
        print(
            "You swing your fists at the goblins. "
            "\nYou miss most of your swings. But when your fists hit a goblin you sent it flying. "
            "\nThe goblins eventually gave up fighting you."
            "\nYou lost 1 Health and gained 1 Strength. \n")
        click_enter()
        stats()
        health_0()
        luck_roll_50()
    else:
        health -= 3
        strength -= 2
        print(
            "You swing your fists at the goblins \nYou are too weak. The goblins are upon you. "
            "They surround you and start clawing at you. "
            "\nYou run blindly through the forest, hitting tree trunks, tripping on roots and scratched by branches. "
            "You managed to get away from them. \nYou lost 3 Health and 2 Strength. \n ")
        click_enter()
        stats()
        health_0()
        luck_roll_50()
def goblins():
    click_enter()
    print("You encounter a group of goblins. Goblins are stupid, but they can overwhelm you."
    "\nYou are not an adventurer, so you would like to avoid them if you can. "
    "\nBut the goblins blocked the your path through the forest. ")
    while True:
        answer_2 = input(
            "\nWhat do you do? Do you run away, use magic or fight? Enter Run, Magic or Fight. \n")
        if answer_2.lower().strip() == "run":
            print("You died trying to run away. \n")
            quit()
        elif answer_2.lower().strip() == "magic":
            magic_goblins()
            break
        elif answer_2.lower().strip() == "fight":
            strength_goblins()
            break
        else:
            continue
########################################################################################################################
# Witch's Tea House
def magic_witch():  # Checks with the current Magic stat and runs if statements
    global magic
    global health
    global strength
    if magic >= 9:
        magic += 2
        print(
            "A witch knows a lot of spells. She would know more than you."
            "But you are younger and have quicker reflexes. You shot a fireball at her wand. "
            "\nIt burned away to ash. The witch horrified ran out the back door. "
            "\nYou gain 2 Magic from this. \n")
        click_enter()
        stats()
        health_0()
        luck_roll_pos()
    elif magic >= 5 and magic <= 8:
        health -= 1
        magic += 1
        print(
            "A witch knows a lot of spells. She would know more than you."
            "But you are younger and have quicker reflexes. You shot a fireball at her wand. "
            "But you missed and blasted a supporting beam."
            "\nShe is angry that you caught her off guard and zaps some spells at you."
            "\nSome spells burned as it hissed by you. "
            "A supporting beam fell on her and you escaped the burning tea shop."
            "\nYou lose 1 Health and gain 1 Magic. \n")
        click_enter()
        stats()
        health_0()
        luck_roll_50()
    else:
        health -= 3
        magic -= 1
        strength -= 1
        print(
            "You anxiously try to recall any spell to fight the witch. "
            "You yell out a random spell. "
            "\n BOOM \n"
            "It blew up in your face. Fortunately it also blasted the witch away. "
            "\nYou lose 3 Health, 1 Magic and 1 Strength. \n ")
        click_enter()
        stats()
        health_0()
        luck_roll_50()
def strength_witch():  # Checks Stats
    global magic
    global health
    global strength
    if strength >= 9:
        strength += 2
        print(
            "A witch knows a lot of spells. She would know more than you."
            "But you are younger and have quicker reflexes. You lunge at her and side-stepped her spells."
            "You snapped her wand and threw her out of the tea shop. \nYou gain 2 Strength. \n")
        click_enter()
        stats()
        health_0()
        luck_roll_pos()
    elif strength >= 5 and strength <= 8:
        health -= 1
        strength += 1
        print(
            "A witch knows a lot of spells. She would know more than you."
            "But you are younger and have quicker reflexes. You lunge at her. "
            "You got hit by one of her spells. It burned, but you continue until you successfully snapped her wand."
            "\nYou lost 1 Health and gained 1 Strength. \n ")
        click_enter()
        stats()
        health_0()
        luck_roll_50()
    else:
        health -= 3
        strength -= 2
        print(
            "You attempt to rush at the witch to snap her wand. "
            "\nYou are too slow. The witch saw your plan and she jumped back. "
            "She threw a flurry of spells at you. Most missed, but a few met their mark."
            "\nShe accidentally set herself on fire and was momentarily distracted."
            "\nYou jump through a window and ran through the forest. "
            "\nYou managed to get away from the witch. \nYou lost 3 Health and 2 Strength. \n ")
        click_enter()
        stats()
        health_0()
        luck_roll_50()
def witch():
    click_enter()
    print("You reached a tea shop in a clearing. "
        "Its been such a hot day and you see that the shop offers boba milk tea."
        "\nYou eagerly enter the shop to order a refreshing drink."
        "\nA witch cackles from behind the counter and zaps the door shut. Its a trap! \n")
    while True:
        answer_2 = input("What do you do? Do you run away, use magic or fight? Enter Run, Magic or Fight. \n")
        if answer_2.lower().strip() == "run":
            print("You died trying to run away. \n")
            quit()
        elif answer_2.lower().strip() == "magic":
            magic_witch()
            break
        elif answer_2.lower().strip() == "fight":
            strength_witch()
            break
        else:
            continue
########################################################################################################################
def got_sugar():
    click_enter()
    print("Miss GoldenDragon gives you a cup of sugar and generously teleports you home.")
def too_weak():
    click_enter()
    if luck > 0:
        got_sugar()
        print("You arrive safely home. But the whole journey has been so tiring."
              " You took a nap and woke up the next day. "
              "You rush and managed to put together a respectable tea party.")
    else:
        no_luck()
def best_ending():
    click_enter()
    print("You arrive safely home with your cup of sugar. You feel surprisingly refreshed despite your journey. "
          "\nYou baked the most delicious and moist cake. A royal did show up! "
          "\nYou shared your adventures to get the cup of sugar. "
          "\nYou impressed them so much that they offer to publish your adventures in a novel. "
          "\nYour novel is an instant success and with your profits you open up a bakery called 'Cup o' Sugar'."
          "\nThe End")
def good_ending():
    click_enter()
    print("You arrive safely home. You are a bit tired, but you go ahead and bake your cake. "
          "\nThe next day you tea party went well. No rumored royal showed up."
          "\nYour reputation goes up for your delicious cake and you are invited to more tea parties."
          "\nThe End")
def burnt_cake():
    click_enter()
    print("You arrive safely home. But you are so tired. You still went forward and baked a cake."
          "\nBut you fell asleep and the cake was burnt! "
          "You decide to serve it anyway, hiding the burnt blackness with plenty of whipped cream. "
          "\nThe tea party was a moderate success, though much cake was left uneaten.")
def walk_home():
    click_enter()
    if strength >= 10 and health >= 10:
        print("You walk yourself safely home. "
                "You are frustrated that you didn't get your sugar."
                " But you made do with store-bought baked goods. "
                "You managed to have a respectable, but mediocre tea party.")
        quit()
    elif strength < 10 and health < 10:
        print("You attempt to walk back, but you are too weak to travel. You are stuck and miss the tea party.\n")
        quit()
    else:
        print("You attempt to walk back, but you are too weak to travel. You are stuck and miss the tea party.\n")
def no_luck():
    click_enter()
    magic_walk = input("You knock and knock, but it appears that no one was home. "
            "Do you use magic to get home or walk? Enter 'M' for magic or 'W' for walk. \n")
    if magic_walk.lower().strip() == "m":
        if magic >= 15:
            print("You teleport yourself safely home. "
                    "You are frustrated that you didn't get your sugar."
                    " But you made do with store-bought baked goods. "
                    "You managed to have a respectable, but mediocre tea party.")
        else:
            print("Your teleportation spell failed.")
            walk_home()
    elif magic_walk.lower().strip() == "w":
            walk_home()
def final_stat_check():
    if health <= 5 and strength <= 0:
        too_weak()
    elif luck >= 15:
        got_sugar()
        best_ending()
    elif luck >= 6 and luck <= 10:
        got_sugar()
        good_ending()
    elif luck >= 0:
        got_sugar()
        burnt_cake()
    else:
        no_luck()

def whole_game():
    global health
    global strength
    global magic
    global luck
    health = 5
    strength = 5
    magic = 5
    luck = 5  # Invisible Stat
    horse_griffin()
    list_events = [fairies, goblins, granny_event, hole_event, lake_event, mermaids,
                   mushroom_event, plant_event_50, slimes, treasure_chest_50, witch]  # List of events
    while list_events != 0:  # To continue through list
        if magic >= 25:
            print("You suddenly remembered the teleportation spell. "
                  "You teleport yourself to Miss GoldenDragon's door.")
            break
        elif list_events == []:  # If list is empty to break out of loop
            break
        events = random.randint(0, len(list_events) - 1)  # Random number for index of stat_events list
        list_events[events]()  # This will call the function
        list_events.remove(list_events[events])  # Removes the event that was selected
    click_enter()
    print("You arrive at Miss GoldenDragon's door.")
    final_stat_check()

# Introduction

print("\n\nJourney to Miss GoldenDragon\n\n")
click_enter()
print(
    "You are hosting a tea party tomorrow with the upper echelons of society. "
    "\nWealthy wives, aristocratic ladies and there was even a rumor of one of the royals attending. "
    "\nYou intend to bake a cake to impress them all! But you do not have enough sugar! "
    "Your nearest neighbor is Miss GoldenDragon pass the Dark Forest on top of the mountain. "
    "\nYou must journey to borrow a cup of sugar!\n")
click_enter()
stats()
# Testing
# 1. While loop restart
# 2. assigning numbers to events and randomizing the events

while True:
    whole_game()
    restart = input("Do you want to restart? Enter 'Y' for yes or 'N' for No.")
    if restart.lower().strip() == 'n':
        quit()
    elif restart.lower().strip() == 'y':
        continue


k = int(input())
word = input()
decode = ""
for i in range(len(word)):
    shift = 3 * (i + 1) + k
    pos = ord(word[i]) - ord('A') - shift
    while pos < 0:
        pos += 26
    decode += chr(ord('A') + pos)
print(decode)


# -*- coding: utf-8 -*-
"""
Created on Fri Jan 12 12:28:28 2018

@author: XPS 13 9350
"""

class Solution:
    def trap(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        length=len(height)
        if length<=2:
            return 0
        top=height.index(max(height))
        if top>=length-2:
            return self.left_trap(height[:top+1])
        elif top<=1:
            return self.right_trap(height[top:])
        else:
            return self.left_trap(height[:top+1])+self.right_trap(height[top:])
    def left_trap(self,height):
        low=0
        high=0
        temp=0
        water=0
        for i in range(len(height)):
            if height[i]>0:
                low=i
                high=i
                break;
        start=high
        for i in range(start,len(height)):
            if height[i]>=height[high]:
                if i!=high:
                    high=i
                    water+=(high-low-1)*height[low]-temp
                    temp=0
                    low=high
            else:
                temp+=height[i]
        return water

    def right_trap(self,height):
        low=len(height)-1
        high=len(height)-1
        temp=0
        water=0
        for i in range(len(height)-1,-1,-1):
            if height[i]>0:
                low=i
                high=i
                break;
        start=high
        for i in range(start,-1,-1):
            if height[i]>=height[high]:
                if i!=high:
                    high=i
                    water+=(low-high-1)*height[low]-temp
                    temp=0
                    low=high
            else:
                temp+=height[i]
        return water


from sqlalchemy import CHAR, ForeignKey, String
from sqlalchemy.orm import relationship

from giges.db import db
from giges.models.mixins import UUIDMixin

class Ritual(db.Model, UUIDMixin):

    name = db.Column(
        String,
        nullable=False,
        unique=True,
        index=True,
        doc="Name of the ritual",
    )
    team_id = db.Column(
        CHAR(36),
        ForeignKey(
            "team.id",
            deferrable=True,
            initially="DEFERRED",
            name="ritual_team_fk",
        ),
    )

    logs_url = db.Column(
        String,
        nullable=True,
        index=True,
        doc="The Bahamut section for the logs",
    )
    meeting_url = db.Column(
        String,
        nullable=True,
        index=False,
        doc="The URL for the virtual meeting place",
    )
    team = relationship("Team", back_populates="rituals")


from models import db, Ingredient, Restaurant, Dish, Rating
import peewee
import sqlite3

def data_test():
    db.connect()
    return db.create_tables([Ingredient, Restaurant, Dish, Rating])

def data_writer():
    db.connect()

    restaurants = [["Vilacidro", 1992, "16:00", "23:00"], ["Zaika", 2005, "14:00", "23:00"], ["MySnacks", 2005, "12:00", "23:00"]]

    dishes = [["Bambino pizza Maria", 1, 6000, "Tomaten"], ["Bambino pizza Italiana", 1, 6000, "Kaas"], ["Classic Burger", 2, 7500, "Rundvlees hamburger"], ["BBQ pulled chicken burger", 2, 9750, "Pulled Chicken"], ["Zak patat", 3, 4000, "Aardappel"], ["Franse Frietjes", 3, 2000, "Aardappel"]]

    ingredients = [["Tomaten", True, True, True], ["Kaas", True, False, False], ["Rosbief", False, False, True], ["Gorgonzola", True, False, False], ["Paprika", True, True, True], ["Artisjokken", True, True, True], ["Rundvlees hamburger", False, False, False], ["Sla", True, True, True], ["Rode ui", True, True, True], ["Augurk", True, True, True], ["Zaika Burgersaus", True, False, False], ["Pulled Chicken", False, False, False], ["Cheddar", True, False, False], ["Aardappel", True, True, True]]

    ratings = [[1, 8, "Super!"], [1, 9, "Geweldig!"], [1, 10, "Top!"], [2, 6, "Moah"], [2, 5, "Oke"], [2, 6, "Moah"], [3, 2, "Booeee"], [3, 4, "Bleh"], [3, 5, "Bleh"]]

    for restaurant_name in restaurants:
        Restaurant.create(name = restaurant_name[0], open_since = restaurant_name[1], opening_time = restaurant_name[2], closing_time = restaurant_name[3])

    # for dish_name in dishes:
       # Dish.create(name = dish_name[0], served_at = dish_name[1], price_in_cents = dish_name[2], ingredients = dish_name[3])

    for ingredient_name in ingredients:
        Ingredient.create(name = ingredient_name[0], is_vegetarian = ingredient_name[1], is_vegan = ingredient_name[2], is_glutenfree = ingredient_name[3])

    for number in ratings:
        Ingredient.create(restaurant = number[0], rating = number[1], comment = number[2])


from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (
        QApplication, QWidget,
        QHBoxLayout, QVBoxLayout,
        QGroupBox, QButtonGroup, QRadioButton,
        QPushButton, QLabel)
from random import shuffle, randint

class Question():
    def __init__(self, question, right_answer, wrong1, wrong2, wrong3):
        self.question = question
        self.right_answer = right_answer
        self.wrong1 = wrong1
        self.wrong2 = wrong2
        self.wrong3 = wrong3

question_list = []
question_list.append(Question('Государственный язык Бразилии', 'Португальский', 'Бразильский', 'Испанский', 'Итальянски'))
question_list.append(Question('Без какой составляющей компьютер сможет функционировать?', 'Видеокарта', 'Процессор', 'Оперативная память', 'Блок питания'))
question_list.append(Question('Какая видеокарта мощнее?', 'RTX 3090', 'RTX 3060', 'RTX 1050', 'RTX 750 TI'))
question_list.append(Question('Какой страны не существует?', 'Грекистан', 'Бразилия', 'Китай', 'Россия'))
question_list.append(Question('Какой самый сильный злодей в игре Star Wars?', 'Дарт Молл', 'Дарт Вейдер', 'Граф Дуку', 'Дарт Сидиус'))
question_list.append(Question('Что такое H2O?', 'Вода', 'Кислород', 'Водород', 'Углекислый газ'))
question_list.append(Question('Кто из богатырей сказал:"А ловко ты это придумал"?', 'Добрыня Никитич', 'Алеша Попович', 'Илья Муромец', 'Никита Кожемяк'))
question_list.append(Question('Какое оружие в Cs Go убивает с одной пули в тело?', 'AWP', 'Desert Eagle', 'AK-47', 'Glock-18'))
question_list.append(Question('Первый Президент России', 'Ельцин', 'Путин', 'Медведев', 'Горбачев'))
question_list.append(Question('Человек известный как Маэстро', 'Панасенков', 'Величайший', 'Легендарный', 'Залетный'))
question_list.append(Question('Любимый Президент Сан Саныча','Обэмэ', 'Путин', 'Лукашонок', 'Зеленка'))
question_list.append(Question('Из какой игры популярный мем АМОГУС?', 'Among Us', 'Clash Royale', 'Brawl Stars', 'Subway Surfers'))
question_list.append(Question('Какая была разборка?', 'Питерская', 'Минская', 'Московская', 'Краснодарская'))
question_list.append(Question('Как зовут Водилу у которого бочек потик?', 'Ярик', 'Саша', 'Славик', 'Димон'))
question_list.append(Question('Какого камня нет в море?', 'Сухого', 'Мокрого', 'Черного', 'Разноцветного'))
question_list.append(Question('Самый дорогой скин на Glock-18', 'Градиент', 'Глазки', 'Дух', 'Ядерный сад'))
question_list.append(Question('Кто идет домой?', 'Русские', 'Французы', 'Немцы', 'Англичане'))

#Добавить 15-20 вопросов
app = QApplication([])

btn_OK = QPushButton('Ответить')
lb_Question = QLabel('Самый сложный вопрос в мире!')

RadioGroupBox = QGroupBox("Варианты ответов")

rbtn_1 = QRadioButton('Вариант 1')
rbtn_2 = QRadioButton('Вариант 2')
rbtn_3 = QRadioButton('Вариант 3')
rbtn_4 = QRadioButton('Вариант 4')

RadioGroup = QButtonGroup()
RadioGroup.addButton(rbtn_1)
RadioGroup.addButton(rbtn_2)
RadioGroup.addButton(rbtn_3)
RadioGroup.addButton(rbtn_4)

layout_ans1 = QHBoxLayout()
layout_ans2 = QVBoxLayout()
layout_ans3 = QVBoxLayout()
layout_ans2.addWidget(rbtn_1)
layout_ans2.addWidget(rbtn_2)
layout_ans3.addWidget(rbtn_3)
layout_ans3.addWidget(rbtn_4)

layout_ans1.addLayout(layout_ans2)
layout_ans1.addLayout(layout_ans3)
RadioGroupBox.setLayout(layout_ans1)

AnsGroupBox = QGroupBox("Результат теста")
lb_Result = QLabel('прав ты или нет?')
lb_Correct = QLabel('ответ будет тут!')
layout_res = QVBoxLayout()
layout_res.addWidget(lb_Result, alignment=(Qt.AlignLeft | Qt.AlignTop))
layout_res.addWidget(lb_Correct, alignment=Qt.AlignHCenter, stretch=2)
AnsGroupBox.setLayout(layout_res)

layout_line1 = QHBoxLayout()
layout_line2 = QHBoxLayout()
layout_line3 = QHBoxLayout()

layout_line1.addWidget(lb_Question, alignment=(Qt.AlignHCenter | Qt.AlignVCenter))
layout_line2.addWidget(RadioGroupBox)
layout_line2.addWidget(AnsGroupBox)
AnsGroupBox.hide()

layout_line3.addStretch(1)
layout_line3.addWidget(btn_OK, stretch=2) # кнопка должна быть большой
layout_line3.addStretch(1)
layout_card = QVBoxLayout()

layout_card.addLayout(layout_line1, stretch=2)
layout_card.addLayout(layout_line2, stretch=8)
layout_card.addStretch(1)
layout_card.addLayout(layout_line3, stretch=1)
layout_card.addStretch(1)
layout_card.setSpacing(5) # пробелы между содержимым

# ----------------------------------------------------------
# Виджеты и макеты созданы, далее - функции:
# ----------------------------------------------------------

def show_result():
    ''' показать панель ответов '''
    RadioGroupBox.hide()
    AnsGroupBox.show()
    btn_OK.setText('Следующий вопрос')

def show_question():
    ''' показать панель вопросов '''
    RadioGroupBox.show()
    AnsGroupBox.hide()
    btn_OK.setText('Ответить')
    RadioGroup.setExclusive(False) # сняли ограничения, чтобы можно было сбросить выбор радиокнопки
    rbtn_1.setChecked(False)
    rbtn_2.setChecked(False)
    rbtn_3.setChecked(False)
    rbtn_4.setChecked(False)
    RadioGroup.setExclusive(True)

answers = [rbtn_1, rbtn_2, rbtn_3, rbtn_4]

def ask(q: Question):
    shuffle(answers)
    answers[0].setText(q.right_answer)
    answers[1].setText(q.wrong1)
    answers[2].setText(q.wrong2)
    answers[3].setText(q.wrong3)
    lb_Question.setText(q.question)
    lb_Correct.setText(q.right_answer)
    show_question()
def show_correct(res):
    lb_Result.setText(res)
    show_result()

def check_answer():
    if answers[0].isChecked():
        show_correct('Правильно!')
        window.score += 1
        print('Статистика\n-Всего вопросов:', window.total, '\nПравильных ответов:', window.score)
        print('Рейтинг:', (window.score/window.total*100), '%')
    else:
        if answers[1].isChecked() or answers[2].isChecked() or answers[3].isChecked():
            show_correct('Неверно!')
            print('Рейтинг:', (window.score/window.total*100), '%')

def next_question():
    window.total += 1
    print('Статистика\n-Всего вопросов:', window.total, '\nПравильных ответов:', window.score)
    cur_question = randint(0, len(question_list) - 1)
    q = question_list[cur_question]
    ask(q)

def click_ok():
    if btn_OK.text() == 'Ответить':
        check_answer()
    else:
        next_question()

window = QWidget()
window.setLayout(layout_card)
window.setWindowTitle('PradaCard') #изменить  название прораммы
btn_OK.clicked.connect(click_ok)
window.score = 0
window.total = 0
next_question()
window.show()
app.exec()


from typing import Any, Dict

from app.app import db

Model: Any = db.Model

class Camera(Model):
    __tablename__ = 'cameras'

    Name = db.Column(db.String(10), unique=True)
    images = db.relationship('Image', backref='camera', lazy=True)

    @classmethod
    def from_dict(cls, camera_dict: Dict[str, Any]) -> 'Camera':
        return cls(
            Name=camera_dict['Name']
        )

    def to_dict(self) -> Dict[str, Any]:
        to_dict = super().to_dict()
        to_dict.update(
            {
                'Name': self.Name
            }
        )
        return to_dict

    def update_from_dict(self, camera_dict: Dict[str, Any]) -> None:
        super().update_from_dict(camera_dict)
        if 'Name' in camera_dict:
            self.Name = camera_dict['Name']

class ProductType(Model):
    __tablename__ = 'product_types'

    Name = db.Column(db.String(4), unique=True)
    images = db.relationship('Image', backref='product_type', lazy=True)

    @classmethod
    def from_dict(cls, type_dict: Dict[str, Any]) -> 'ProductType':
        return cls(
            Name=type_dict['Name']
        )

    def to_dict(self) -> Dict[str, Any]:
        to_dict = super().to_dict()
        to_dict.update(
            {
                'Name': self.Name
            }
        )
        return to_dict

    def update_from_dict(self, type_dict: Dict[str, Any]) -> None:
        super().update_from_dict(type_dict)
        if 'Name' in type_dict:
            self.Name = type_dict['Name']

class Image(Model):
    __tablename__ = 'images'

    Name = db.Column(db.String(31), unique=True)
    URL = db.Column(db.Text)
    Sol = db.Column(db.Integer, nullable=False)
    DetatchedLabel = db.Column(db.Boolean)
    CameraID = db.Column(
        db.Integer,
        db.ForeignKey('cameras.ID'),
        nullable=False,
    )
    ProductTypeID = db.Column(
        db.Integer,
        db.ForeignKey('product_types.ID'),
        nullable=False,
    )

    @classmethod
    def from_dict(cls, image_dict: Dict[str, Any]) -> 'Image':
        return cls(
            Name=str(image_dict['Name']),
            URL=str(image_dict['URL']),
            Sol=int(image_dict['Sol']),
            DetatchedLabel=bool(image_dict['DetatchedLabel']),
            CameraID=int(image_dict['CameraID']),
            ProductTypeID=int(image_dict['ProductTypeID']),
        )

    def to_dict(self) -> Dict[str, Any]:
        to_dict = super().to_dict()
        to_dict.update(
            {
                'Name': self.Name,
                'URL': self.URL,
                'Sol': self.Sol,
                'DetatchedLabel': self.DetatchedLabel,
                'CameraID': self.CameraID,
                'camera': self.camera.to_dict(),
                'ProductTypeID': self.ProductTypeID,
                'product_type': self.product_type.to_dict(),
            }
        )
        return to_dict

    def update_from_dict(self, image_dict: Dict[str, Any]) -> None:
        super().update_from_dict(image_dict)
        if 'Name' in image_dict:
            self.Name = image_dict['Name']
        if 'URL' in image_dict:
            self.URL = image_dict['URL']
        if 'Sol' in image_dict:
            self.Sol = image_dict['Sol']
        if 'DetatchedLabel' in image_dict:
            self.DetatchedLabel = image_dict['DetatchedLabel']
        if 'CameraID' in image_dict:
            self.CameraID = image_dict['CameraID']
        if 'ProductTypeID' in image_dict:
            self.ProductTypeID = image_dict['ProductTypeID']


import subprocess

import tator

def test_video_clips(host, token, project, video):

    # Run the example.
    cmd = [
        'python3',
        'examples/video_clips.py',
        '--host', host,
        '--token', token,
        '--video_id', str(video),
        '--file_path', '/tmp/asdf',
    ]
    subprocess.run(cmd, check=True)


# random agent on Taxi-v2
import gym

env = gym.make("Taxi-v2")

P = env.env.P
# P[s][a] contains array of tuples.
# each of them is in form of (p, next_s, r, done)
# where "p" is the transition probability of
# going from "s" to "next_s" with action "a" getting "r" reward;
# "done" denotes whether the episode is finished or not.

observation = env.reset()
score = 0
# since random agent might not be able to finish the game, I used for with 1000 steps instead of while True
for _ in range(1000):
    # env.reset() gives the initial position of taxi and state is a number between 0 and 499
    state = env.reset()
    # env.render() renders the map with current state
    env.render()
    # action is a number between 0 and 5. your task is to replace this random action with your own policy
    action = env.action_space.sample()  # your agent here (this takes random actions)
    # env.step() takes the game to the next state and returns next_state, reward, done, info.
    state, reward, done, info = env.step(action)

    score += reward
    if done:
        state = env.reset()
        break
print("score: ", score)
env.close()


import os
import tweepy

def get():
    with open(os.path.join(os.path.dirname(__file__), "template.html")) as f:
        return f.read()

def post(screen_name=""):
    CK = os.getenv("TW_CK")
    CS = os.getenv("TW_CS")
    AT = os.getenv("TW_AT")
    AS = os.getenv("TW_AS")
    auth = tweepy.OAuthHandler(CK, CS)
    auth.set_access_token(AT, AS)
    try:
        api = tweepy.API(auth)
        user = api.get_user(screen_name=screen_name)
        output = "ID: {}".format(user.id)
    except Exception as e:
        print(e)
        if screen_name == "":
            output = ""
        else:
            output = "何かがおかしい。<br>" + str(e)
    return {"output": output}

if __name__ == "__main__":
    print(post("laddge"))


from flask import jsonify, request
from app.models import Pharmaceutical_info, Token
from app import db

def updatePharmaceuticalInfo():
    '''update pharmaceutical info record'''
    data = request.get_json()
    token = request.headers['TOKEN']
    id=int(data['id'])

    t=Token.query.filter_by(token=token).first()

    is_expired=t.status

    if data:
        if id in data and id is not None:
            if token and is_expired == 'active':

                if Pharmaceutical_info.query.filter_by(id=id).first() is not None:
                    pharmaceutical_info = Pharmaceutical_info(
                        list_of_excipients=data['list_of_excipients'],
                        storage_conditions=data['storage_conditions'],
                        nature_content_ofContainer=data['treatment'],
                        instruction_for_handling=data['instruction_for_handling'],
                        instruction_for_disposal=data['instruction_for_disposal'],
                        text_revision_date=data['text_revision_date'],
                        drug_id=data['drug_id']
                            )
                    db.session.add(pharmaceutical_info)
                    db.session.commit()

                else:
                    return jsonify('Drug pharmaceutical info record specified does not exist'),500
            else:
                return jsonify('no token provided or token has expired'),500
        else:
            return jsonify('No pharmaceutical info id provided'),500
    return jsonify('Provide new pharmaceutical info records for update'),500


import numpy as np
import cv2
from matplotlib import pyplot as plt
import random
from PIL import Image

img = Image.open('original.jpg')

img1 = cv2.imread('original.jpg')
img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)

h, w, _ = img1.shape
print('width: ', w)
print('height:', h)

count = 0
w1 = w2 = int(w/20)
h1 = h2 = int(h/10)
w2 = w3 = w2 - 5
h2 = h3 = h2 - 5
countpixel = 0

for y in range(0, 10):
    h2 = h2 + (h1*y)
    for x in range(0, 20):
        img1[h2,w2] = (255, 0, 0)
        countpixel = countpixel + 1
        w2 = w2 + w1
        if x==19:
            h2 = h3
            w2 = w3

img1 = Image.fromarray(img1) #conversion

print(countpixel)

plt.figure(num='DEADPIXEL Failure - Configuration 3')
plt.subplot(121),plt.imshow(img),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(img1),plt.title('DEADPIXEL - Configuration 3')
plt.xticks([]), plt.yticks([])
plt.show()


#!/usr/bin/env python3
import csv
import glob
import os
import json

us_states_and_territories = [
    "Alabama",
    "Alaska",
    "Arizona",
    "Arkansas",
    "California",
    "Colorado",
    "Connecticut",
    "Delaware",
    "Florida",
    "Georgia",
    "Hawaii",
    "Idaho",
    "Illinois",
    "Indiana",
    "Iowa",
    "Kansas",
    "Kentucky",
    "Louisiana",
    "Maine",
    "Maryland",
    "Massachusetts",
    "Michigan",
    "Minnesota",
    "Mississippi",
    "Missouri",
    "Montana",
    "Nebraska",
    "Nevada",
    "New Hampshire",
    "New Jersey",
    "New Mexico",
    "New York",
    "North Carolina",
    "North Dakota",
    "Ohio",
    "Oklahoma",
    "Oregon",
    "Pennsylvania",
    "Rhode Island",
    "South Carolina",
    "South Dakota",
    "Tennessee",
    "Texas",
    "Utah",
    "Vermont",
    "Virginia",
    "Washington",
    "West Virginia",
    "Wisconsin",
    "Wyoming",
    "District of Columbia",
    "Puerto Rico",
    "Virgin Islands",
    "Guam",
    "American Samoa",
    "Northern Mariana Islands",
]

def country(row):
    if "Country/Region" in row:
        return row["Country/Region"]
    return row["Country_Region"]

def setcountry(row, val):
    if "Country/Region" in row:
        row["Country/Region"] = val
    else:
        row["Country_Region"] = val

def state(row):
    if "Province/State" in row:
        return row["Province/State"]
    return row["Province_State"]

def toint(n):
    try:
        return int(n)
    except ValueError:
        return 0

# process modifies the data table data in-place, given data file daily
def process(data, daily, date):
    # the daily file (at least recently) has the data broken down very
    # granularly, so the first thing we'll do is sum it up before we add it to
    # the total data
    dailydata = {}
    for row in daily:
        if country(row) == "Mainland China":
            setcountry(row, "China")

        if state(row) and country(row) == "US":
            # skip all regions that are not states or territories
            if state(row) not in us_states_and_territories:
                continue
            displayname = f"{state(row)}, {country(row)}"
        else:
            displayname = f"{country(row)}"

        dailydata.setdefault(displayname, {}).setdefault("confirmed", []).append(
            toint(row["Confirmed"])
        )
        dailydata[displayname].setdefault("deaths", []).append(toint(row["Deaths"]))
        dailydata[displayname].setdefault("recovered", []).append(
            toint(row["Recovered"])
        )

        # Because we treat the US specially, we also need to sum up our national rows:
        if country(row) == "US":
            displayname = "United States"
            dailydata.setdefault(displayname, {}).setdefault("confirmed", []).append(
                toint(row["Confirmed"])
            )
            dailydata[displayname].setdefault("deaths", []).append(toint(row["Deaths"]))
            dailydata[displayname].setdefault("recovered", []).append(
                toint(row["Recovered"])
            )

    for name, today in dailydata.items():
        try:
            data.setdefault(name, {}).setdefault("confirmed", []).append(
                sum(today["confirmed"])
            )
            data[name].setdefault("deaths", []).append(sum(today["deaths"]))
            data[name].setdefault("recovered", []).append(sum(today["recovered"]))
        except:
            print("failed summing row", name, today)
            raise

def main():
    datadir = "jhudata/csse_covid_19_data/csse_covid_19_daily_reports/"
    data = {}
    dates = []
    # it's important to read this in sorted order
    for fname in list(sorted(glob.glob(datadir + "*.csv"))):
        with open(fname, encoding="utf-8-sig") as dailyfile:
            # Grab the date from the filename, like "03-24-2020", and append it
            # to the dates array
            date = fname.split("/")[-1].split(".")[0]
            dates.append(date)

            daily = csv.DictReader(dailyfile)
            process(data, daily, date)

    for key in data:
        data[key]["displayName"] = key

    envelope = {"dates": dates, "data": data}
    for region in data.values():
        # if there are dates where we have data, but this region does not yet,
        # prepend zeros so we have a data point for every date
        region["confirmed"] = [0] * (len(dates) - len(region["confirmed"])) + region[
            "confirmed"
        ]
        region["deaths"] = [0] * (len(dates) - len(region["deaths"])) + region["deaths"]
        region["recovered"] = [0] * (len(dates) - len(region["recovered"])) + region[
            "recovered"
        ]

    # json.dump(envelope, open("data.json", "w"), indent=2)
    json.dump(envelope, open("data.json", "w"))

if __name__ == "__main__":
    main()


import datetime

name = str(input('Name: '))
c = int(input('Age: '))

e = int(input("Number: "))

def years(age):
    d = datetime.date.today().year
    a = d+(100-c)

    for i in range(e):
        print("You're gonna be 100 yrs old the year:", a)
    return(a)

def main():
    return

if __name__ == '__main__':
    main()

years(c)

"""
name = input("Enter you name: ")
age = int(input("Enter your age: "))

x = 100 - age # user will be 100 year old in x years
y = 2019 + x # user will be 100 years old in this year

print(name + " You will turn 100 in " + str(y))
"""


#!/usr/bin/env python
from brownie import accounts,SimpleStorage

def test_deploy():
    # Arrage
    account = accounts[0]
    # Act
    simple_storage = SimpleStorage.deploy({"from":account})
    starting_value = simple_storage.get()
    excepted = 777
    # Assert
    assert excepted == starting_value


# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import absolute_import
import os

from salt.utils import parsers
from salt.utils.verify import verify_env, verify_files
from salt.config import _expand_glob_path
import salt.cli.caller

class SaltCall(parsers.SaltCallOptionParser):
    '''
    Used to locally execute a salt command
    '''

    def run(self):
        '''
        Execute the salt call!
        '''
        self.parse_args()

        if self.config['verify_env']:
            verify_env([
                    self.config['pki_dir'],
                    self.config['cachedir'],
                ],
                self.config['user'],
                permissive=self.config['permissive_pki_access'],
                pki_dir=self.config['pki_dir'],
            )
            if not self.config['log_file'].startswith(('tcp://',
                                                       'udp://',
                                                       'file://')):
                # Logfile is not using Syslog, verify
                verify_files(
                    [self.config['log_file']],
                    self.config['user']
                )

        if self.options.file_root:
            # check if the argument is pointing to a file on disk
            file_root = os.path.abspath(self.options.file_root)
            self.config['file_roots'] = {'base': _expand_glob_path([file_root])}

        if self.options.pillar_root:
            # check if the argument is pointing to a file on disk
            pillar_root = os.path.abspath(self.options.pillar_root)
            self.config['pillar_roots'] = {'base': _expand_glob_path([pillar_root])}

        if self.options.local:
            self.config['file_client'] = 'local'
        if self.options.master:
            self.config['master'] = self.options.master

        # Setup file logging!
        self.setup_logfile_logger()

        caller = salt.cli.caller.Caller.factory(self.config)

        if self.options.doc:
            caller.print_docs()
            self.exit(os.EX_OK)

        if self.options.grains_run:
            caller.print_grains()
            self.exit(os.EX_OK)

        caller.run()


#!/usr/bin/env python3
import unittest
from vec2 import Vec2
from person import Person
from unittest.mock import patch

class TestVec2(unittest.TestCase):
    def test_add(self):
        a = Vec2(5, 3)
        a.add(Vec2(3, 7))
        self.assertEqual(a.x, 8)
        self.assertEqual(a.y, 10)

    def test_scale(self):
        a = Vec2(5, -2)
        a.scale(4)
        self.assertEqual(a.x, 20)
        self.assertEqual(a.y, -8)

    def test_divide(self):
        a = Vec2(15, -6)
        a.divide(3)
        self.assertEqual(a.x, 5)
        self.assertEqual(a.y, -2)

    def test_divide_zero(self):
        a = Vec2(15, -6)
        with self.assertRaises(ValueError):
            a.divide(0)

class TestPerson(unittest.TestCase):
    def test_fetch(self):
        with patch('person.requests.get') as mocked_get:
            mocked_get.return_value.ok = True
            mocked_get.return_value.text = "{ \"age\": 20 }"

            marco = Person("marco2")
            self.assertEqual(marco.name, "marco2")
            self.assertEqual(marco.age, 20)
            mocked_get.assert_called_with("https://api.agify.io/?name=marco2")

            mocked_get.return_value.ok = False
            polo = Person("polo")
            self.assertEqual(polo.name, "polo")
            self.assertEqual(polo.age, None)
            mocked_get.assert_called_with("https://api.agify.io/?name=polo")

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


import json
import logging
import os
from typing import Dict

import lib.configs
from lib.activelearning import Last
from lib.infers.deepgrow_pipeline import InferDeepgrowPipeline
from lib.infers.vertebra_pipeline import InferVertebraPipeline

import monailabel
from monailabel.interfaces.app import MONAILabelApp
from monailabel.interfaces.config import TaskConfig
from monailabel.interfaces.datastore import Datastore
from monailabel.interfaces.tasks.infer_v2 import InferTask
from monailabel.interfaces.tasks.scoring import ScoringMethod
from monailabel.interfaces.tasks.strategy import Strategy
from monailabel.interfaces.tasks.train import TrainTask
from monailabel.scribbles.infer import GMMBasedGraphCut, HistogramBasedGraphCut
from monailabel.tasks.activelearning.first import First
from monailabel.tasks.activelearning.random import Random

# bundle
from monailabel.tasks.infer.bundle import BundleInferTask
from monailabel.tasks.train.bundle import BundleTrainTask
from monailabel.utils.others.class_utils import get_class_names
from monailabel.utils.others.generic import get_bundle_models, strtobool
from monailabel.utils.others.planner import HeuristicPlanner

logger = logging.getLogger(__name__)

class MyApp(MONAILabelApp):
    def __init__(self, app_dir, studies, conf):
        self.model_dir = os.path.join(app_dir, "model")

        configs = {}
        for c in get_class_names(lib.configs, "TaskConfig"):
            name = c.split(".")[-2].lower()
            configs[name] = c

        configs = {k: v for k, v in sorted(configs.items())}

        # Load models from app model implementation, e.g., --conf models <segmentation_spleen>
        models = conf.get("models")
        if not models:
            print("")
            print("---------------------------------------------------------------------------------------")
            print("Provide --conf models <name>")
            print("Following are the available models.  You can pass comma (,) seperated names to pass multiple")
            print(f"    all, {', '.join(configs.keys())}")
            print("---------------------------------------------------------------------------------------")
            print("")
            exit(-1)

        models = models.split(",")
        models = [m.strip() for m in models]
        invalid = [m for m in models if m != "all" and not configs.get(m)]
        if invalid:
            print("")
            print("---------------------------------------------------------------------------------------")
            print(f"Invalid Model(s) are provided: {invalid}")
            print("Following are the available models.  You can pass comma (,) seperated names to pass multiple")
            print(f"    all, {', '.join(configs.keys())}")
            print("---------------------------------------------------------------------------------------")
            print("")
            exit(-1)

        # Use Heuristic Planner to determine target spacing and spatial size based on dataset+gpu
        spatial_size = json.loads(conf.get("spatial_size", "[48, 48, 32]"))
        target_spacing = json.loads(conf.get("target_spacing", "[1.0, 1.0, 1.0]"))
        self.heuristic_planner = strtobool(conf.get("heuristic_planner", "false"))
        self.planner = HeuristicPlanner(spatial_size=spatial_size, target_spacing=target_spacing)

        # app models
        self.models: Dict[str, TaskConfig] = {}
        for n in models:
            for k, v in configs.items():
                if self.models.get(k):
                    continue
                if n == k or n == "all":
                    logger.info(f"+++ Adding Model: {k} => {v}")
                    self.models[k] = eval(f"{v}()")
                    self.models[k].init(k, self.model_dir, conf, self.planner)
        logger.info(f"+++ Using Models: {list(self.models.keys())}")

        # Load models from bundle config files, local or released in Model-Zoo, e.g., --conf bundles <spleen_ct_segmentation>
        self.bundles = get_bundle_models(app_dir, conf, conf_key="bundles") if conf.get("bundles") else None

        super().__init__(
            app_dir=app_dir,
            studies=studies,
            conf=conf,
            name=f"MONAILabel - Radiology ({monailabel.__version__})",
            description="DeepLearning models for radiology",
            version=monailabel.__version__,
        )

    def init_datastore(self) -> Datastore:
        datastore = super().init_datastore()
        if self.heuristic_planner:
            self.planner.run(datastore)
        return datastore

    def init_infers(self) -> Dict[str, InferTask]:
        infers: Dict[str, InferTask] = {}

        #################################################
        # Models
        #################################################
        for n, task_config in self.models.items():
            c = task_config.infer()
            c = c if isinstance(c, dict) else {n: c}
            for k, v in c.items():
                logger.info(f"+++ Adding Inferer:: {k} => {v}")
                infers[k] = v

        #################################################
        # Bundle Models
        #################################################
        if self.bundles:
            for n, b in self.bundles.items():
                i = BundleInferTask(b, self.conf)
                logger.info(f"+++ Adding Bundle Inferer:: {n} => {i}")
                infers[n] = i

        #################################################
        # Scribbles
        #################################################
        infers.update(
            {
                "Histogram+GraphCut": HistogramBasedGraphCut(
                    intensity_range=(-300, 200, 0.0, 1.0, True),
                    pix_dim=(2.5, 2.5, 5.0),
                    lamda=1.0,
                    sigma=0.1,
                    num_bins=64,
                    labels=task_config.labels,
                ),
                "GMM+GraphCut": GMMBasedGraphCut(
                    intensity_range=(-300, 200, 0.0, 1.0, True),
                    pix_dim=(2.5, 2.5, 5.0),
                    lamda=5.0,
                    sigma=0.5,
                    num_mixtures=20,
                    labels=task_config.labels,
                ),
            }
        )

        #################################################
        # Pipeline based on existing infers
        #################################################
        if infers.get("deepgrow_2d") and infers.get("deepgrow_3d"):
            infers["deepgrow_pipeline"] = InferDeepgrowPipeline(
                path=self.models["deepgrow_2d"].path,
                network=self.models["deepgrow_2d"].network,
                model_3d=infers["deepgrow_3d"],
                description="Combines Clara Deepgrow 2D and 3D models",
            )

        #################################################
        # Pipeline based on existing infers for vertebra segmentation
        # Stages:
        # 1/ localization spine
        # 2/ localization vertebra
        # 3/ segmentation vertebra
        #################################################
        if (
            infers.get("localization_spine")
            and infers.get("localization_vertebra")
            and infers.get("segmentation_vertebra")
        ):
            infers["vertebra_pipeline"] = InferVertebraPipeline(
                task_loc_spine=infers["localization_spine"],  # first stage
                task_loc_vertebra=infers["localization_vertebra"],  # second stage
                task_seg_vertebra=infers["segmentation_vertebra"],  # third stage
                description="Combines three stage for vertebra segmentation",
            )
        logger.info(infers)
        return infers

    def init_trainers(self) -> Dict[str, TrainTask]:
        trainers: Dict[str, TrainTask] = {}
        if strtobool(self.conf.get("skip_trainers", "false")):
            return trainers
        #################################################
        # Models
        #################################################
        for n, task_config in self.models.items():
            t = task_config.trainer()
            if not t:
                continue

            logger.info(f"+++ Adding Trainer:: {n} => {t}")
            trainers[n] = t

        #################################################
        # Bundle Models
        #################################################
        if self.bundles:
            for n, b in self.bundles.items():
                t = BundleTrainTask(b, self.conf)
                if not t or not t.is_valid():
                    continue

                logger.info(f"+++ Adding Bundle Trainer:: {n} => {t}")
                trainers[n] = t

        return trainers

    def init_strategies(self) -> Dict[str, Strategy]:
        strategies: Dict[str, Strategy] = {
            "random": Random(),
            "first": First(),
            "last": Last(),
        }

        if strtobool(self.conf.get("skip_strategies", "true")):
            return strategies

        for n, task_config in self.models.items():
            s = task_config.strategy()
            if not s:
                continue
            s = s if isinstance(s, dict) else {n: s}
            for k, v in s.items():
                logger.info(f"+++ Adding Strategy:: {k} => {v}")
                strategies[k] = v

        logger.info(f"Active Learning Strategies:: {list(strategies.keys())}")
        return strategies

    def init_scoring_methods(self) -> Dict[str, ScoringMethod]:
        methods: Dict[str, ScoringMethod] = {}
        if strtobool(self.conf.get("skip_scoring", "true")):
            return methods

        for n, task_config in self.models.items():
            s = task_config.scoring_method()
            if not s:
                continue
            s = s if isinstance(s, dict) else {n: s}
            for k, v in s.items():
                logger.info(f"+++ Adding Scoring Method:: {k} => {v}")
                methods[k] = v

        logger.info(f"Active Learning Scoring Methods:: {list(methods.keys())}")
        return methods

"""
Example to run train/infer/batch infer/scoring task(s) locally without actually running MONAI Label Server

More about the available app methods, please check the interface monailabel/interfaces/app.py

"""

def main():
    import argparse
    import shutil
    from pathlib import Path

    from monailabel.utils.others.generic import device_list, file_ext

    os.putenv("MASTER_ADDR", "127.0.0.1")
    os.putenv("MASTER_PORT", "1234")

    logging.basicConfig(
        level=logging.INFO,
        format="[%(asctime)s] [%(process)s] [%(threadName)s] [%(levelname)s] (%(name)s:%(lineno)d) - %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
        force=True,
    )

    home = str(Path.home())
    studies = f"{home}/Dataset/Radiology"

    parser = argparse.ArgumentParser()
    parser.add_argument("-s", "--studies", default=studies)
    parser.add_argument("-m", "--model", default="segmentation")
    parser.add_argument("-t", "--test", default="batch_infer", choices=("train", "infer", "batch_infer"))
    args = parser.parse_args()

    app_dir = os.path.dirname(__file__)
    studies = args.studies
    conf = {
        "models": args.model,
        "preload": "false",
    }

    app = MyApp(app_dir, studies, conf)

    # Infer
    if args.test == "infer":
        sample = app.next_sample(request={"strategy": "first"})
        image_id = sample["id"]
        image_path = sample["path"]

        # Run on all devices
        for device in device_list():
            res = app.infer(request={"model": args.model, "image": image_id, "device": device})
            # res = app.infer(
            #     request={"model": "vertebra_pipeline", "image": image_id, "device": device, "slicer": False}
            # )
            label = res["file"]
            label_json = res["params"]
            test_dir = os.path.join(args.studies, "test_labels")
            os.makedirs(test_dir, exist_ok=True)

            label_file = os.path.join(test_dir, image_id + file_ext(image_path))
            shutil.move(label, label_file)

            print(label_json)
            print(f"++++ Image File: {image_path}")
            print(f"++++ Label File: {label_file}")
            break
        return

    # Batch Infer
    if args.test == "batch_infer":
        app.batch_infer(
            request={
                "model": args.model,
                "multi_gpu": False,
                "save_label": True,
                "label_tag": "original",
                "max_workers": 1,
                "max_batch_size": 0,
            }
        )

        # app.batch_infer(
        #     request={
        #         "model": "pipeline",
        #         "multi_gpu": False,
        #         "save_label": True,
        #         "label_tag": "original",
        #         "max_workers": 1,
        #         "max_batch_size": 0,
        #     }
        # )

        return

    # Train
    app.train(
        request={
            "model": args.model,
            "max_epochs": 10,
            "dataset": "Dataset",  # PersistentDataset, CacheDataset
            "train_batch_size": 1,
            "val_batch_size": 1,
            "multi_gpu": False,
            "val_split": 0.1,
        },
    )

if __name__ == "__main__":
    # export PYTHONPATH=~/Projects/MONAILabel:`pwd`
    # python main.py
    main()


from odoo import _, api, fields, models
from odoo.exceptions import ValidationError

class MrpProduction(models.Model):
    _inherit = "mrp.production"

    def _default_mo_type_id(self):
        return self.env["manufacturing.order.type"].search(
            ["|", ("company_id", "=", False), ("company_id", "=", self.company_id.id)],
            limit=1,
        )

    mo_type_id = fields.Many2one(
        comodel_name="manufacturing.order.type",
        string="Type",
        ondelete="restrict",
        domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]",
        default=lambda self: self._default_mo_type_id(),
    )

    @api.onchange("product_id")
    def onchange_product_id(self):
        super().onchange_product_id()
        mo_type_id = self.product_id.mo_type_id or self.product_id.categ_id.mo_type_id
        if mo_type_id:
            self.mo_type_id = mo_type_id

    @api.onchange("mo_type_id")
    def _onchange_mo_type_id(self):
        for order in self:
            if order.mo_type_id.picking_type_id:
                order.picking_type_id = order.mo_type_id.picking_type_id

    @api.model
    def create(self, vals):
        if vals.get("name", "/") == "/" and vals.get("mo_type_id"):
            mo_type = self.env["manufacturing.order.type"].browse(vals["mo_type_id"])
            if mo_type.sequence_id:
                vals["name"] = mo_type.sequence_id.next_by_id()
        return super().create(vals)

    @api.constrains("company_id", "mo_type_id")
    def _check_mo_type_company(self):
        for rec in self:
            if rec.company_id != rec.mo_type_id.company_id:
                raise ValidationError(
                    _("Document's company and type's company mismatch")
                )

    @api.onchange("company_id")
    def check_company(self):
        self.mo_type_id = False


from flask_restful import Resource, reqparse
from flask_jwt_extended import (
    jwt_required,
    jwt_optional,
    get_jwt_claims,
    get_jwt_identity,
    fresh_jwt_required
)

from model import Item, Store

class ItemResource(Resource):
    parser = reqparse.RequestParser()
    parser.add_argument(
        'price',
        type=float,
        required=True,
        help='This field cannot be left blank.'
    )
    parser.add_argument(
        'store_id',
        type=int,
        required=True,
        help='Every item needs a store id.'
    )

    @jwt_required
    def get(self, name):
        item = Item.find_by_name(name)
        if item:
            return {'item': item.json()}
        else:
            return {'message': 'item not found'}, 404

    @fresh_jwt_required
    def post(self, name):
        if Item.find_by_name(name):
            return {'message': 'item already exists'}

        data = ItemResource.parser.parse_args()

        if Store.find_by_id(data['store_id']) is None:
            return {'message': 'invalid store_id'}

        item = Item(name, data['price'], data['store_id'])
        try:
            item.persist()
        except Exception:
            return {'message': 'error occurred while creating item'}, 500
        else:
            return item.json(), 201

    @jwt_required
    def delete(self, name):
        claims = get_jwt_claims()
        if not claims['is_admin']:
            return {'message': 'Admin privilege required.'}, 401

        item = Item.find_by_name(name)
        if item is None:
            return {'message': 'item does not exist'}, 400

        try:
            item.delete()
        except Exception:
            return {'message': 'error occurred while deleting item'}, 500
        else:
            return {'message': 'item deleted'}

    def put(self, name):
        data = ItemResource.parser.parse_args()

        item = Item.find_by_name(name)
        if item is None:
            item = Item(name, data['price'], data['store_id'])
        else:
            item.price = data['price']
            item.store_id = data['store_id']

        item.persist()
        return item.json(), 201

class ItemListResource(Resource):

    @jwt_optional
    def get(self):
        user_id = get_jwt_identity()
        items = Item.find_all()
        if user_id:
            return {'items': [item.json() for item in items]}, 200

        return {
            'items': [item.name for item in items],
            'message': 'More data available if you log in.'
        }, 200


import asyncio
import dbus_next
from dbus_next.aio import MessageBus
import socket
import enum
import logging
import common

class BtConnectionRole(enum.Enum):
    Master = 1
    Slave = 2
    NotConnected = 3

class BtClient(object):
    BT_CONTROL_PORT = 17  # Service port - control port specified in the bluetooth HID specification
    BT_INTERRUPT_PORT = 19  # Service port - interrupt port specified in the bluetooth HID specification

    @staticmethod
    async def create_via_address(address):
        client = BtClient(address)
        await client._connect_to_dbus_service()
        return client

    @staticmethod
    async def create_via_device_object_path(device_object_path):
        address = BtClient.get_mac_address_from_devie_object_path(device_object_path)
        client = BtClient(address)
        await client._connect_to_dbus_service()
        return client

    @staticmethod
    def get_mac_address_from_devie_object_path(device_object_path):
        return device_object_path[-17:].replace("_",":")

    @staticmethod
    def get_device_object_path_from_mac_address(device_object_path):
        return "/org/bluez/hci0/dev_" + device_object_path.replace(":","_")

    def __init__(self, address):
        self._address = address
        self._device_object_path = BtClient.get_device_object_path_from_mac_address(self._address)
        self._is_alive = True
        self._stop_event = False
        self._is_connected = False
        self._is_bluez_connected = True
        self._control_socket = None
        self._interrupt_socket = None
        self._loop = asyncio.get_event_loop()
        self._message_queue = asyncio.Queue()
        self._task = None
        self._bt_master_task = None
        self._bt_check_alive_task = None

    @property
    def address(self):
        return self._address

    @property
    def object_path(self):
        return self._device_object_path

    @property
    def name(self):
        return self._name

    @property
    def is_alive(self):
        if self._task:
            return not self._task.done()
        else:
            return False

    @property
    def is_connected(self):
        return self._is_connected

    @property
    def info(self):
        info_dict = {}
        info_dict["name"] = self.name
        info_dict["address"] = self.address
        info_dict["isConnected"] = self.is_connected
        return info_dict

    def connect(self):
        if not self._task or self._task.done():
            self._stop_event = False
            self._task = asyncio.create_task(self._run())

    def accept_connection(self, control_socket, interrupt_socket):
        if not self._task or self._task.done():
            self._control_socket = control_socket
            self._interrupt_socket = interrupt_socket
            self._stop_event = False
            self._task = asyncio.create_task(self._run())

    async def _establish_socket_connection(self):
        if self._control_socket and self._interrupt_socket:
            logging.debug(f"{self.name}: Incoming socket connection from {self.name} ({self.address})")
            self._handle_state_at_successfull_connection()
        else:
            logging.debug(f"{self.name}: Establish socket connection to {self.name} ({self.address})")
            try:
                self._control_socket = socket.socket(
                    socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_L2CAP)
                await self._loop.run_in_executor(None, lambda: self._control_socket.connect((self.address, self.BT_CONTROL_PORT)))
                self._control_socket.setblocking(False)
                self._interrupt_socket = socket.socket(
                    socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_L2CAP)
                await self._loop.run_in_executor(None, lambda: self._interrupt_socket.connect((self.address, self.BT_INTERRUPT_PORT)))
                self._interrupt_socket.setblocking(False)
                self._handle_state_at_successfull_connection()
            except Exception as e:
                logging.error(f"{self.name}: Exception during connect: {e}")
                self._disconnect()
        if self._is_connected:
            self._enshure_bt_master()
            self._checking_connection_state_periodically()

    def _handle_state_at_successfull_connection(self):
        self._message_queue = asyncio.Queue()
        self._is_connected = True

    def _disconnect(self):
        if self._control_socket:
            self._control_socket.close()
            self._control_socket = None
        if self._interrupt_socket:
            self._interrupt_socket.close()
            self._interrupt_socket = None
        self._is_connected = False

    def stop(self):
        self._stop_event = True

    async def join(self):
        await self._task

    async def _connect_to_dbus_service(self):
        self._bluez_obj = None
        while not self._bluez_obj:
            try:
                self._dbus = await MessageBus(bus_type=dbus_next.BusType.SYSTEM).connect()
                introspection = await self._dbus.introspect(
                    "org.bluez", self._device_object_path)
                self._bluez_obj = self._dbus.get_proxy_object(
                    "org.bluez", self._device_object_path, introspection)
                self._bluez_itf = self._bluez_obj.get_interface("org.bluez.Device1")
                self._bluez_props = self._bluez_obj.get_interface("org.freedesktop.DBus.Properties")
                logging.debug(f"{self._address}: D-Bus bluez object connected")
                self._name = await self._bluez_itf.get_name()
                logging.debug(f"{self._address}: Name resolves to {self._name}")
                self._bluez_props.on_properties_changed(self._on_properties_changed)
            except dbus_next.DBusError:
                logging.warning(f"{self._address}: D-Bus bluez object available - reconnecting...")
                await asyncio.sleep(5)

    def _on_properties_changed(self, interface_name, changed_properties, invalidated_properties):
        for changed, variant in changed_properties.items():
            logging.debug(f'{self._name}: D-Bus bluez property changed: {changed} - {variant.value}')
            if changed == "Connected":
                self._is_bluez_connected = variant.value

    async def _run(self):
        if self._stop_event: return
        await self._establish_socket_connection()
        if self._is_connected:
            logging.info(f"\033[0;32m{self.name}: Connection established ({self.address})\033[0m")
        while self._is_connected and not self._stop_event:
            message = ""
            try:
                message = await asyncio.wait_for(self._message_queue.get(), timeout=2)
                await self._loop.sock_sendall(self._interrupt_socket, bytes(message))
                self._message_queue.task_done()
            except asyncio.QueueEmpty:
                pass
            except asyncio.TimeoutError:
                pass
            except socket.error:
                logging.error(f"{self._name}: Socket error during send")
                self._disconnect()
            except:
                logging.error(f"{self._name}: Message could not be sed: {message}")
                raise

        logging.info(f"\033[0;31m{self.name}: Connection terminated - client closed ({self.address})\033[0m")
        self._disconnect()

    def _enshure_bt_master(self):
        if not self._bt_master_task or self._bt_master_task.done():
            self._bt_master_task = asyncio.create_task(self._switch_to_master())

    async def _switch_to_master(self):
        logging.info(f"{self._name}: Enshure connection role {BtConnectionRole.Master.name}")
        connection_role = await self._get_connection_role()
        while (connection_role == BtConnectionRole.Slave) and not self._stop_event:
            try:
                await common.System.exec_cmd(f"hcitool sr {self._address} MASTER")
            except Exception as exc:
                logging.debug(f"{self._name}: Connection role switch exception: {exc}")
            await asyncio.sleep(2)
            connection_role = await self._get_connection_role()
        logging.info(f"{self._name}: Connection role is {connection_role.name}")

    def _checking_connection_state_periodically(self):
        if not self._bt_check_alive_task or self._bt_check_alive_task.done():
            self._bt_check_alive_task = asyncio.create_task(self._send_periodic_alive_messages())

    async def _send_periodic_alive_messages(self):
        logging.debug(f"{self._name}: Sending periodic messages to check connection state started")
        while self._is_connected and not self._stop_event:
            await asyncio.sleep(4)
            # sending an empty message to check if socket connection is still alive
            self.send(bytes([0, 0, 0, 0]))
        logging.debug(f"{self._name}: Sending periodic messages to check connection state stopped")

    async def _get_connection_role(self):
        returncode, stdout, stderr = await common.System.exec_cmd("hcitool con")
        for line in stdout.decode("utf-8").splitlines():
            if line.find(self._address) >= 0:
                if line.find("SLAVE") >= 0:
                    return BtConnectionRole.Slave
                if line.find("MASTER") >= 0:
                    return BtConnectionRole.Master
        return BtConnectionRole.NotConnected

    def send(self, message):
        if self._is_connected:
            self._message_queue.put_nowait(message)


import c_a_parameters_bible as pb
import sqlite3
from sqlite3 import Error

conn = sqlite3.connect(pb.BIBLE_ID + '/f_c_db_'+pb.BIBLE_ID+'.sqlite')
cur = conn.cursor()
cur.execute(''' SELECT book,token, count(*) as 'count' FROM wordtokens GROUP BY book,token ORDER by 1,3 desc; ''')

old_book = ""
token_count = 0
line = ""
for row in cur:
	book = row[0]
	token = row[1]
	count = row[2]

	if(old_book != book):
		token_count = 0
		old_book = book
		print(line)
		line = book + "\t"
	else:
		token_count += 1
		if(token_count<4):
			line = line + token + "(" + str(count) + ")"  + "\t\t"
conn.commit()
conn.close()