'''
Task:
when given any separation of a plane into contiguous regions and producing a figure called a map, no more than four colors are required to color the regions of the map so that no two adjacent regions have the same color. Two regions are called adjacent if they share a common boundary that is not a corner, where corners are the points shared by three or more regions. For our model we will use a grid with square cells.
You are given a regional map as a grid (matrix). There are N countries located on this map. Each country has a number from 0 to N-1. Two cells are adjacent if they have a common edge. Each country has one or more cells that are connected. Thus you can move between any cells of the country X just using for this adjacent cells.
Each cell is marked by the number of its designated country.
You should "color" a map with 4 colors. All of the cells comprising one country should be one color. Adjacent cells of various countries should not have the same color.
The result should be represented as a sequence of numbers 1,2,3 or 4. Each element shows the color of its country matching the index. For example, the 0th element shows the color of country 0. So the result should have N elements.
'''

##### Precondition: Country numbers are in sequence from 0 to N-1
import random

COLORS = 4	# Total number of colors
MAX_STEPS = 1000

class Node(object):
	'''
	Represents a 'country' in the map graph.
	'''
	def __init__(self, node_id = None, color_assignment = None, adjacents = None, map_positions = None):
		self.node_id = node_id
		self.color_assignment = color_assignment	# Store color assignment
		self.adjacents = adjacents 					# Store list of adjacent nodes or countries
		self.map_positions = map_positions			# Store list of locations occupied by this node in the map

def map_to_graph(tup_map):
	'''
	Converts map (tuple of tuples) to a graph (network of nodes).
	'''
	# Get the number of unique countries in the region
	# 	- Flatten map, get unique countries
	flat_map = [val for tup in tup_map for val in tup]
	unique_regions = []
	for val in flat_map:
		if val not in unique_regions:
			unique_regions.append(val)

	# Create empty graph with correct number of regions
	graph = [Node(node_id = n, color_assignment = None, adjacents = [], map_positions = []) for n in xrange(0, len(unique_regions))]

	# Populate map positions for each node (map positions a particular country occupies)
	# Also populate adjecent regions for each node
	for r in xrange(0, len(tup_map)):
		for c in xrange(0, len(tup_map[r])):
			graph[tup_map[r][c]].map_positions.append((r,c))
			neighbors = get_neighbors(tup_map, (r,c))
			for neighbor in neighbors:
				if neighbor not in graph[tup_map[r][c]].adjacents:
					graph[tup_map[r][c]].adjacents.append(neighbor)

	return graph

def get_neighbors(tup_map, loc):
	'''
	Given a position, get any neighboring regions to that position that are different
	 from the given region.
	'''
	region = tup_map[loc[0]][loc[1]]
	coords = [(loc[0] - 1, loc[1]), (loc[0] + 1, loc[1]), (loc[0], loc[1] + 1), (loc[0], loc[1] - 1)]
	neighbors = []
	for c in coords:
		valid_location = (c[0] >= 0 and c[0] < len(tup_map)) and (c[1] >= 0 and c[1] < len(tup_map[0]))
		if valid_location and tup_map[c[0]][c[1]] != region and tup_map[c[0]][c[1]] not in neighbors:
			neighbors.append(tup_map[c[0]][c[1]])
	return neighbors

def conflicts(node, color, graph):
	'''
	The CONFLICTS function counts the number of constraints violated by a particular value,
	 given the rest of the current assignment.
	'''
	conflicts = 0
	adjacent_colors = [graph[region].color_assignment for region in node.adjacents]
	for adj_color in adjacent_colors:
		if color == adj_color:
			conflicts += 1
	return conflicts

def print_node(node):
	print("Node ID: " + str(node.node_id))
	print("Color: " + str(node.color_assignment))
	print("Adjacent Nodes: " + str(node.adjacents))
	print("Map Positions: " + str(node.map_positions))

def constraint_satisfaction_search(tup_map):
	'''
	Given a map (a tuple of tuples), returns colored graph such that no adjacent regions are
	 the same color.
	'''
	# Step 1: Map -> Graph
	graph = map_to_graph(tup_map)

	# Step 2: Assign Colors randomly
	for node in graph:
		node.color_assignment = random.randint(0, COLORS - 1)

	# print("=== BEFORE ===")
	# for node in graph:
	# 	print("===============")
	# 	print_node(node)
	# 	print("Conflicts for node %d: %d" % (node.node_id, conflicts(node, node.color_assignment, graph)))

	# Step 3: Begin Local search
	# - Repeat
	#	- Get all constraint violations
	# 	- If constraints (no violations) are met => return current assignments
	# 	- Select a random node with a constraint violation
	# 	- Select color assignment that minimizes conflicts
	#	- Set node's color assignment to selected color
	steps = 0
	while (steps < MAX_STEPS):
		naughty_nodes = []
		# Get all constraint violations
		for node in graph:
			if conflicts(node, node.color_assignment, graph) != 0:
				naughty_nodes.append(node.node_id)
		# If no violations, return current assignments
		if len(naughty_nodes) == 0:
			# print("=== AFTER ===")
			# print("Number of steps: " + str(steps))
			# for node in graph:
			# 	print("===============")
			# 	print_node(node)
			# 	print("Conflicts for node %d: %d" % (node.node_id, conflicts(node, node.color_assignment, graph)))
			return graph
		# Select a random node with a constraint violation
		lucky_winner = naughty_nodes[random.randint(0, len(naughty_nodes) - 1)]
		# Select color assignment for lucky_winner that minimizes conflicts
		min_conflict_color = (-1, -1) # Color, conflicts
		for c in xrange(0, COLORS):
			num_conflicts = conflicts(graph[lucky_winner], c, graph)
			if min_conflict_color[0] == -1:
				min_conflict_color = (c, num_conflicts)
			elif min_conflict_color[1] > num_conflicts:
				min_conflict_color = (c, num_conflicts)
		# Set node's color assignment to selected color
		graph[lucky_winner].color_assignment = min_conflict_color[0]
		steps += 1
	return None

def color_map(region):
	graph = constraint_satisfaction_search(region)
	while graph == None:
		graph = constraint_satisfaction_search(region)
	return [node.color_assignment + 1 for node in graph]

if __name__ == "__main__":
	#These "asserts" using only for self-checking and not necessary for auto-testing
	assignment = color_map(((7,4,4,4,),(7,0,1,5,),(7,2,3,5,),(6,6,6,5,),))
	print(str(assignment))


"""

TODO: Exit out of all demon programs when quit
TODO: Check the characters position before it moves or performs certain actions.
TODO: Integrate the BUY function into the shops.

"""

import pathlib as pathlib
import textwrap as textwrap

from app.main import world, enemies, command_parser, config, npcs, combat, events

verbs = config.verbs
stances = config.stances
action_history = []
wrapper = textwrap.TextWrapper(width=config.TEXT_WRAPPER_WIDTH)

def do_action(action_input, character=None):
    action_history.insert(0,action_input)
    if not character:
        events.game_event(game_event_text="No character loaded. You will need to create a new character or load an existing character.")
        return
    if len(action_input) == 0:
        events.game_event("")
        return
    kwargs = command_parser.parser(action_input)
    return DoActions.do_action(kwargs['action_verb'], character, **kwargs).action_result

class DoActions:
    def __init__(self, character, **kwargs):
        self.character = character
        self.action_result = {"room_change": {"room_change_flag":  False,
                                              "old_room":  None,
                                              "new_room":  None},
                              "character_output":  None,
                              "room_output":  {},
                              "area_output":  None,
                              "status_window":  None}

    do_actions = {}

    @classmethod
    def register_subclass(cls, action):
        """Catalogues actions in a dictionary for reference purposes"""
        def decorator(subclass):
            cls.do_actions[action] = subclass
            return subclass
        return decorator

    @classmethod
    def do_action(cls, action, character, **kwargs):
        """Method used to initiate an action"""
        if action not in cls.do_actions:
            events.game_event("I am sorry, I did not understand.")
            return
        return cls.do_actions[action](character, **kwargs)

    def update_room(self, old_room_number, new_room_number):
        self.action_result['room_change']['room_change_flag'] = True
        self.action_result['room_change']['old_room'] = old_room_number
        self.action_result['room_change']['new_room'] = new_room_number
        return

    def update_character_output(self, character_output_text):
        self.action_result['character_output'] = character_output_text

    def update_room_output(self, room_output_text):
        self.action_result['room_output'] = room_output_text

    def update_area_output(self, area_output_text):
        self.action_result['area_output'] = area_output_text

    def update_status(self, status_text):
        self.action_result['status_window'] = status_text

@DoActions.register_subclass('ask')
class Ask(DoActions):
    """\
    Certain npcs have information that is valuable for you. The ASK verb allows you to interact with these npcs
    and obtain that information.

    Usage:
    ASK <npc> about <subject>\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        if character.check_round_time():
            return
        if character.is_dead():
            return
        elif not kwargs['direct_object']:
            events.game_event("Who are you trying to ask?")
            return
        elif not kwargs['indirect_object']:
            events.game_event("What are you trying to ask about?")
            return
        else:
            for npc in character.room.npcs:
                if set(npc.handle) & set(kwargs['direct_object']):
                    npc.ask_about(object=kwargs['indirect_object'])
                    return
            else:
                events.game_event("That doesn't seem to do any good.")

@DoActions.register_subclass('attack')
class Attack(DoActions):
    """\
    ATTACK allows you to engage in combat with an enemy. Provided you are not in round time, ATTACK swings
    the weapon in your right hand (or your bare fist if there is no weapon) at the enemy. You will not be able
    to attack anyone other than enemies.

    Usage:
    ATTACK <enemy> : Engages an enemy and begins combat.\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        if character.check_round_time():
            return
        if character.is_dead():
            return
        if kwargs['direct_object']:
            character.target = kwargs['direct_object']
        if not character.target:
            events.game_event("Who are you going to attack? You do not have a target.")
            return
        else:
            for npc in character.room.npcs:
                if set(npc.handle) & set(character.target):
                    events.game_event("{} will probably not appreciate that.".format(npc.name))
                    return
            enemy_found = False
            for enemy in character.room.enemies:
                if set(enemy.handle) & set(character.target):
                    enemy_found = True
                    combat.melee_attack_enemy(character, enemy)
                    return
            if not enemy_found:
                events.game_event("{} is not around here.".format(kwargs['direct_object']))
                return

@DoActions.register_subclass('attribute')
class Attributes(DoActions):
    """\
    ATTRIBUTES allows you to view various attributes\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        events.game_event('''
Attribute:  {}
            '''.format(character.attack_strength_base))

@DoActions.register_subclass('buy')
class Buy(DoActions):
    """\
    BUY enables you to purchase an item from a shop.

    Usage:

    BUY <#>:  Finalize purchase of the selected item.\
    """

    def __init__(self, character, **kwargs):

        if character.check_round_time():
            return
        if character.is_dead():
            return
        if not character.check_position_to_move():
            return

        if character.room.is_shop == False:
            events.game_event("You can't seem to find a way to order anything here.")
            return
        if character.room.shop_filled == False:
            events.game_event("You will need to ORDER first.")
            return
        if character.room.shop.in_shop == False:
            events.game_event("You have exited the shop. You will need to ORDER again.")
            return
        if character.get_dominant_hand_inv() is not None:
            events.game_event("You will need to empty your right hand first.")
            return
        character.set_dominant_hand_inv(character.room.shop.buy_item(number=kwargs['number_1']))

@DoActions.register_subclass('drop')
class Drop(DoActions):
    """\
    DROP sets an object within your environment. This verb works the same as PUT <item>.

    Usage:
    DROP <item> : Places an item within an environment.
    DROP <item> in <object/item> : Will put an item within an object or within another item if that object or item
    is a container and if that object or item has enough room within it.
    DROP <item> on <object/item> : Will put an item on top of an object or on top of another item if that object
    or item is stackable.\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        if character.check_round_time():
            return
        if character.is_dead():
            return
        elif not kwargs['direct_object']:
            events.game_event("I'm sorry, I could not understand what you wanted.")
            return
        elif character.get_dominant_hand_inv() is None:
            events.game_event("You do not have that item in your hand")
            return
        elif not set(character.get_dominant_hand_inv().handle) & set(kwargs['direct_object']):
            events.game_event("You do not have that item in your right hand.")
            return
        else:
            character.room.items.append(character.get_dominant_hand_inv())
            events.game_event("You drop " + character.get_dominant_hand_inv().name)
            character.set_dominant_hand_inv(item=None)
            character.print_status()
            return

@DoActions.register_subclass('east')
@DoActions.register_subclass('e')
class East(DoActions):
    """\
    Moves you east, if you can move in that direction.\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        if character.check_round_time():
            return
        if character.is_dead():
            return
        if not character.check_position_to_move():
            return
        if world.tile_exists(x=self.character.location_x + 1, y=self.character.location_y, area=self.character.area):
            if character.room.shop_filled == True:
                if character.room.shop.in_shop == True:
                    character.room.shop.exit_shop()
            old_room = self.character.room.room_number
            self.character.move_east()
            self.update_room(old_room_number=old_room, new_room_number=self.character.room.room_number)
            self.update_status(character.get_status())
            return
        else:
            events.game_event("You cannot find a way to move in that direction.")
            return

@DoActions.register_subclass('exit')
class Exit(DoActions):
    """\
    When ordering in a shop, EXIT leaves the order menu. In order to see the menu again, you will need to ORDER again.\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        if character.room.is_shop == False:
            game_window.print_status("You have nothing to exit.")
            return
        if character.room.shop_filled == False:
            game_window.print_status("You have nothing to exit.")
            return
        if character.room.shop.in_shop == False:
            game_window.print_status("You have nothing to exit.")
            return
        else:
            character.room.shop.exit_shop()
            character.print_status()
            return

@DoActions.register_subclass('experience')
@DoActions.register_subclass('exp')
class Experience(DoActions):
    """\
    Displays your experience information.\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        events.game_event('''\
Experience:  {}
        '''.format(character.experience))

@DoActions.register_subclass('flee')
class Flee(DoActions):
    """\
    FLEE sends you in a random direction in your environment. FLEE can only be used when not in round time.\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        if character.check_round_time():
            return
        if character.is_dead():
            return
        if not character.check_position_to_move():
            return
        if character.room.shop_filled == True:
            if character.room.shop.in_shop == True:
                character.room.shop.exit_shop()
        available_moves = character.room.adjacent_moves()
        r = random.randint(0, len(available_moves) - 1)
        actions.do_action(action_input=available_moves[r], character=character)
        character.print_status()

        return

@DoActions.register_subclass('get')
@DoActions.register_subclass('take')
class Get(DoActions):
    """\
    GET retrieves an item from your surroundings. Many objects cannot be moved from their current position.
    The item will be taken by your right hand, therefore you right hand will need to be empty. This
    verb functions the same as TAKE.

    Usage:
    GET <item>\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        if character.check_round_time():
            return
        if character.is_dead():
            return
        if not kwargs['direct_object']:
            events.game_event("I'm sorry, I could not understand what you wanted.")
            return
        for room_object in character.room.objects:
            if set(room_object.handle) & set(kwargs['direct_object']):
                events.game_event("Perhaps picking up {} is not a good idea.".format(room_object.name))
                return
        if character.get_dominant_hand_inv() is None:
            item_found = False
            for room_item in character.room.items:
                if set(room_item.handle) & set(kwargs['direct_object']):
                    character.set_dominant_hand_inv(room_item)
                    character.room.items.remove(room_item)
                    events.game_event("You pick up {}.".format(room_item.name))
                    character.print_status()
                    return
            if not item_found:
                for inv_item in character.inventory:
                    if inv_item.container:
                        for sub_item in inv_item.items:
                            if set(sub_item.handle) & set(kwargs['direct_object']):
                                character.set_dominant_hand_inv(sub_item)
                                inv_item.items.remove(sub_item)
                                events.game_event("You take {} from {}.".format(sub_item.name, inv_item.name))
                                character.print_status()
                                return
            if not item_found:
                events.game_event("A " + kwargs['direct_object'][0] + " is nowhere to be found")
        else:
            events.game_event('You already have something in your right hand')

@DoActions.register_subclass('give')
class Give(DoActions):
    """\
    GIVE allows you to exchange items between you and various npcs. In order to give an item to an npc, you
    must have the item in your right hand.

    Usage:
    GIVE <item> to <npc> : Gives the item to the npc if the npc has the ability to accept the item.\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        if character.check_round_time():
            return
        if character.is_dead():
            return
        elif not kwargs['direct_object']:
            events.game_event("What are you trying to give?")
            return
        elif character.get_dominant_hand_inv() is None:
            events.game_event("You don't seem to be holding that item in your hand.")
            return
        elif not set(character.get_dominant_hand_inv().handle) & set(kwargs['direct_object']):
            events.game_event("You don't seem to be holding that item in your hand.")
            return
        elif not kwargs['indirect_object']:
            events.game_event("To whom do you want to give?")
            return
        else:
            for npc in character.room.npcs:
                if {npc.first_name.lower()} & set(kwargs['indirect_object']):
                    if npc.give_item(character.get_dominant_hand_inv()):
                        character.set_dominant_hand_inv(item=None)
                        character.print_status()
                        return
                    else:
                        return
            events.game_event("That didn't seem to work.")
            return

@DoActions.register_subclass('go')
class Go(DoActions):
    """\
    GO allows you to move toward a certain object. If the object can be passed through, you will pass through it.

    Usage:

    GO <object> : move toward or through an object.\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        if character.check_round_time():
            return
        if character.is_dead():
            return
        if not character.check_position_to_move():
            return
        if not kwargs['direct_object']:
            events.game_event("Go where?")
            return
        for room_object in character.room.objects:
            if set(room_object.handle) & set(kwargs['direct_object']):
                events.game_event("You move toward {}.".format(room_object.name))
                room_object.go_object(character=character)
                return
        for room_item in character.room.items:
            if set(room_item.handle) & set(kwargs['direct_object']):
                events.game_event("You move toward {}.".format(room_item.name))
                return
        for room_npc in character.room.npcs:
            if set(room_npc.handle) & set(kwargs['direct_object']):
                events.game_event("You move toward {}.".format(room_npc.name))
                return

@DoActions.register_subclass('health')
class Health(DoActions):
    """\
    HEALTH shows your current health attributes.\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        events.game_event('''
Health:  {} of {} hit points
            '''.format(character.health,
                       character.health_max))

@DoActions.register_subclass('help')
class Help(DoActions):
    """\
    Provides help on all parts of the game

    Usage:

    HELP <subject> : Output help on a specific subject.\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        verb_list = ""

        if kwargs['subject_verb'] == None:

            for a, b, c in zip(verbs[::3], verbs[1::3], verbs[2::3]):
                verb_list = verb_list + '{:30s}{:30s}{:30s}\n'.format(a,b,c)

            events.game_event("""
Below are the list of actions for which you can ask for help.
Type HELP <verb> for more information about that specific verb.
{}\
            """.format(verb_list))

        elif kwargs['subject_verb'] in DoActions.do_actions:
            events.game_event(DoActions.do_actions[kwargs['subject_verb']].__doc__)
        else:
            events.game_event("I'm sorry, what did you need help with?")

@DoActions.register_subclass('info')
@DoActions.register_subclass('information')
class Information(DoActions):
    """\
    Provides general information on your character including level, experience, and other attributes.\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        events.game_event('''
Name:  {} {}
Gender:  {}
Race:  {}
Profession:  {}
Level:  {}
            '''.format(character.first_name, character.last_name,
                       character.gender,
                       character.race,
                       character.profession,
                       character.level))

@DoActions.register_subclass('inventory')
class Inventory(DoActions):
    """\
    INVENTORY allows you to view your inventory. It will list all items you have in your possession.  INVENTORY
    will not list the items within any containers you have.\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        if character.get_dominant_hand_inv():
            right_hand = "You have {} in your {} hand.".format(character.get_dominant_hand_inv().name, character.dominance)
        else:
            right_hand = "Your right hand is empty."
        if character.get_non_dominant_hand_inv():
            left_hand = "You have {} in your {} hand.".format(character.get_non_dominant_hand_inv().name, character.non_dominance)
        else:
            left_hand = "Your left hand is empty."
        inventory_clothing = [x.name for x in character.inventory if x.category == 'clothing']
        if len(inventory_clothing) > 1:
            inventory_clothing = "You are wearing {} and {}.".format(', '.join(inventory_clothing[:-1]), inventory_clothing[-1])
        elif len(inventory_clothing) == 1:
            inventory_clothing = "You are wearing {}.".format(inventory_clothing[0])
        else:
            inventory_clothing = "You are wearing nothing."

        inventory_armor = []
        for category in character.armor:
            inventory_armor.append(character.armor[category])
        if len(inventory_armor) > 1:
            inventory_armor ="You are also wearing {} and {}.".format(character.object_pronoun, ', '.join(inventory_armor[:-1]), inventory_armor[-1])
        elif len(inventory_armor) == 1:
            inventory_armor = "You are also wearing {}.".format(inventory_armor[0].name)
        else:
            inventory_armor = "You are also wearing no armor.".format(character.object_pronoun)
        wealth = "You have {} gulden.".format(character.money)
        events.game_event('''\
{}
{}
{}
{}
{}
                                    \
                                    '''.format(right_hand,
                                               left_hand,
                                               wrapper.fill(inventory_clothing),
                                               wrapper.fill(inventory_armor),
                                               wrapper.fill(wealth)))

@DoActions.register_subclass('kneel')
class Kneel(DoActions):
    """\
    Moves you to a kneeling position. While you may perform many actions from this position,
    movement is not possible.
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        if character.check_round_time():
            return
        if character.is_dead():
            return
        if character.position == 'kneeling':
            events.game_event('You seem to already be kneeling.')
            character.print_status()
            return
        else:
            character.position = 'kneeling'
            events.game_event('You move yourself to a kneeling position.')
            character.print_status()
            return

@DoActions.register_subclass('lie')
class Lie(DoActions):
    """\
    Moves you to a lying position on the ground. While many actions can be performed on the ground,
    movement is not possible.
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        if character.check_round_time():
            return
        if character.is_dead():
            return
        if character.position == 'lying':
            events.game_event('You seem to already be lying down.')
            character.print_status()
            return
        else:
            character.position = 'lying'
            events.game_event('You lower yourself to the ground and lie down.')
            character.print_status()
            return

@DoActions.register_subclass('look')
@DoActions.register_subclass('l')
class Look(DoActions):
    """\
    View the environment and objects or items within your environment.

    Usage:
    LOOK : shows the descriptions of the environment around you.
    LOOK <object/item> : shows the description of the object at which you want to look.
    LOOK <npc> : shows the description of the npc at which you want to look.\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        if character.check_round_time():
            return
        if character.is_dead():
            return
        if kwargs['preposition'] == None:
            character.room.intro_text()
            return
        if kwargs['preposition'][0] == 'in':
            item_found = False
            if kwargs['indirect_object'] is None:
                events.game_event("I am not sure what you are referring to.")
                return
            for item in character.room.items + character.room.objects + character.room.npcs + character.inventory + [character.get_dominant_hand_inv()] + [character.get_non_dominant_hand_inv()]:
                if isinstance(item, npcs.NPC):
                    events.game_event("It wouldn't be advisable to look in " + item.name)
                    return
                if set(item.handle) & set(kwargs['indirect_object']):
                    events.game_event(item.contents())
                    return
            if item_found is False:
                events.game_event("A {} is nowhere to be found.".format(kwargs['indirect_object'][0]))
                return
        if kwargs['preposition'][0] == 'at':
            item_found = False
            if kwargs['indirect_object'] is None:
                events.game_event("I am not sure what you are referring to.")
                return
            for item in character.room.items + character.room.objects + character.room.npcs + character.room.enemies + character.inventory + [character.get_dominant_hand_inv()] + [character.get_non_dominant_hand_inv()]:
                if not item:
                    pass
                elif set(item.handle) & set(kwargs['indirect_object']):
                    item.view_description()
                    return
            for item in character.inventory:
                if set(item.handle) & set(kwargs['indirect_object']):
                    item.view_description()
                    return
            for object in character.room.objects:
                if set(object.handle) & set(kwargs['indirect_object']):
                    object.view_description()
                    return
            for npc in character.room.npcs:
                if set(npc.handle) & set(kwargs['indirect_object']):
                    npc.view_description()
                    return
            for enemy in character.room.enemies:
                if set(npc.handle) & set(kwargs['indirect_object']):
                    enemy.view_description()
                    return
            if item_found is False:
                events.game_event("At what did you want to look?")
                return
        else:
            events.game_event("I'm sorry, I didn't understand you.")
            return

@DoActions.register_subclass('north')
@DoActions.register_subclass('n')
class North(DoActions):
    """\
    Moves you north, if you can move in that direction.\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        if character.check_round_time():
            return
        if character.is_dead():
            return
        if not character.check_position_to_move():
            return
        if world.tile_exists(x=self.character.location_x, y=self.character.location_y - 1, area=self.character.area):
            if character.room.shop_filled == True:
                if character.room.shop.in_shop == True:
                    character.room.shop.exit_shop()
            self.character.move_north()
            character.print_status()
            return
        else:
            events.game_event('You cannot find a way to move in that direction.')
            return

@DoActions.register_subclass('order')
class Order(DoActions):
    """\
    In certain rooms, you are able to order products through an ordering system. ORDER initiates the ordering system.\

    Usage:
    ORDER:  Enters the shop and displays the shop menu in the status window
    ORDER <#>:  Orders the relevant item. You cannot order a specific item until you have entered the shop using the ORDER command by itself.
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        if character.check_round_time():
            return
        if character.is_dead():
            return

        if character.room.is_shop == False:
            events.game_event("You can't seem to find a way to order anything here.")
            return
        elif character.room.is_shop == True:
            if character.room.shop_filled == False:
                character.room.fill_shop()
                character.room.shop.enter_shop()
                return
            if character.room.shop.in_shop == False:
                character.room.shop.enter_shop()
                return
            character.room.shop.order_item(kwargs['number_1'])
            return

@DoActions.register_subclass('position')
@DoActions.register_subclass('pos')
class Position(DoActions):
    """\
    Displays the position you are currently in.\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        self.character = character

        self.position()

    def position(self):
        events.game_event('''You are currently in the {} position.'''.format(self.character.position))

@DoActions.register_subclass('put')
class Put(DoActions):
    """\
    PUT sets an object within your environment.  This usage works the same as DROP <item>.

    Usage:
    PUT <item> : Places an item within an environment.
    PUT <item> in <object/item> : Will put an item within an object or within another item if that object or item
    is a container and if that object or item has enough room within it.
    PUT <item> on <object/item> : Will put an item on top of an object or on top of another item if that object
    or item is stackable.\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        if character.check_round_time():
            return
        if character.is_dead():
            return
        if not kwargs['direct_object']:
            events.game_event("What is it you're trying to put down?")
            return
        elif character.get_dominant_hand_inv() is None:
            events.game_event("You do not have that item in your hand.")
            return
        elif not set(character.get_dominant_hand_inv().handle) & set(kwargs['direct_object']):
            events.game_event("You do not have that item in your right hand.")
            return
        elif kwargs['preposition'][0] == "in":
            for inv_item in character.inventory:
                if set(inv_item.handle) & set(kwargs['indirect_object']):
                    if inv_item.container == False:
                        events.game_event("{} won't fit in there.".format(character.get_dominant_hand_inv().name))
                        return
                    if len(inv_item.items) == inv_item.capacity:
                        events.game_event("{} can't hold any more items".format(inv_item.name))
                        return
                    inv_item.items.append(character.get_dominant_hand_inv())
                    events.game_event("You put {} {} {}".format(character.get_dominant_hand_inv().name, kwargs['preposition'][0], inv_item.name))
                    character.set_dominant_hand_inv(item=None)
                    character.print_status()
                    return
            for room_item in character.room.items:
                if set(room_item.handle) & set(kwargs['indirect_object']):
                    if room_item.container == False:
                        events.game_event("{} won't fit {} there.".format(character.right_hand_inv[0].name, kwargs['preposition'][0]))
                        return
                    room_item.items.append(character.get_dominant_hand_inv())
                    character.set_dominant_hand_inv(item=None)
                    events.game_event("You put {} {} {}".format(character.get_dominant_hand_inv().name, kwargs['preposition'][0], room_item.name))
                    character.set_dominant_hand_inv(item=None)
                    character.print_status()
                    return
        elif kwargs['preposition'][0] == "on":
            events.game_event("You cannot stack items yet.")
            return
        else:
            events.game_event("That item is not around here, unfortunately.")
            return

@DoActions.register_subclass('quit')
class Quit(DoActions):
    """\
    Exits the game.\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        events.game_event("You will need to find a way to exit the game.")

@DoActions.register_subclass('save')
class Save(DoActions):
    """\
    \
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        self.character.save()

@DoActions.register_subclass('search')
class Search(DoActions):
    """\
    SEARCH allows you to explore your environment if the object, enemy, or area can be explored.

    Usage:
    SEARCH : Searches the environment around you and uncovers hidden items or objects.
    SEARCH <enemy> : Searches an enemy, uncovers any potential items that the enemy could be hiding, and places
    them in your environment.\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        if character.check_round_time():
            return
        if character.is_dead():
            return
        if not kwargs['direct_object']:
            items_found = 0
            for hidden_item in character.room.hidden:
                if 100 - character.level >= hidden_item.visibility:
                    character.room.add_item(hidden_item)
                    character.room.remove_hidden_item(hidden_item)
                    events.game_event('You found {}!'.format(hidden_item.name))
                    items_found += 1
            if items_found == 0:
                events.game_event("There doesn't seem to be anything around here.")
            return
        else:
            for object in character.room.objects:
                if set(object.handle) & set(kwargs['direct_object']):
                    object.search(character=character)
                    return
            for item in character.room.items:
                if set(item.handle) & set(kwargs['direct_object']):
                    events.game_event("Searching {} will not do you much good.".format(item.name))
                    return
            for char in character.room.enemies + character.room.npcs:
                if set(char.handle) & set(kwargs['direct_object']):
                    events.game_event("{} probably will not appreciate that.".format(char.first_name))
                    return
            else:
                events.game_event("That doesn't seem to be around here.")
                return

@DoActions.register_subclass('sell')
class Sell(DoActions):
    """\
    SELL allows you to exchange items for gulden. Certain merchants look for items you may find in the wilds.
    Different merchants look for different items. The item must be in your right hand.

    Usage:
    SELL <item> to <npc>  : Exchanges items for gulden with an npc if an item can be exchanged.
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        if character.check_round_time():
            return
        if character.is_dead():
            return
        elif not kwargs['direct_object']:
            events.game_event("What is it you are trying to sell?")
            return
        for npc in character.room.npcs:
            if set(npc.handle) & {kwargs['indirect_object']}:
                npc.sell_item(item=character.get_dominant_hand_inv())
                return
        else:
            events.game_event("Who are you trying to sell to?")

@DoActions.register_subclass('sit')
class Sit(DoActions):
    """\
    Moves you to a sitting position. While you can perform many actions while in a sitting position,
    movement is no possible.
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        if character.check_round_time():
            return
        if character.is_dead():
            return
        if character.position == 'sitting':
            events.game_event('You seem to already be sitting.')
            character.print_status()
            return
        else:
            character.position = 'sitting'
            events.game_event('You move yourself to a sitting position.')
            character.print_status()
            return

@DoActions.register_subclass('skills')
class Skills(DoActions):
    """\
    SKILLS displays the skills available to you as well as the skill rating for your character. Different skills
    allow you to accomplish different tasks.

    Usage:
    SKILLS:  Shows your available skills and their rating.
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        events.game_event('''
Edged Weapons Base:  {}

Edged Weapons:    {}  ({})          Armor:              {}  ({})
Blunt Weapons:    {}  ({})          Shield:             {}  ({})
Polearm Weapons:  {}  ({})          Dodging:            {}  ({})
Thrown Weapons:   {}  ({})          Physical Fitness:   {}  ({})
Ranged Weapons:   {}  ({})          Perception:         {}  ({})

            '''.format(character.skills_base['edged_weapons'],
                       character.skills['edged_weapons'], character.skills_bonus['edged_weapons'],
                       character.skills['armor'], character.skills_bonus['armor'],
                       character.skills['blunt_weapons'], character.skills_bonus['blunt_weapons'],
                       character.skills['shield'], character.skills_bonus['shield'],
                       character.skills['polearm_weapons'], character.skills_bonus['polearm_weapons'],
                       character.skills['dodging'], character.skills_bonus['dodging'],
                       character.skills['thrown_weapons'], character.skills_bonus['thrown_weapons'],
                       character.skills['physical_fitness'], character.skills_bonus['physical_fitness'],
                       character.skills['ranged_weapons'], character.skills_bonus['ranged_weapons'],
                       character.skills['perception'], character.skills_bonus['perception'])
              )

@DoActions.register_subclass('skin')
class Skin(DoActions):
    """\
    Many enemies are able to be skinned for various pelts, hides, etc. The SKIN verb allows you to skin enemies.
    if successful the resulting item will be places within the environment. Not all enemies are able to be skinned.

    Usage:
    SKIN <enemy> : Skins an enemy and, if successful, leaves a skin.\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        if character.check_round_time():
            return
        if character.is_dead():
            return
        elif not kwargs['direct_object']:
            events.game_event("What are you trying to skin?")
            return
        else:
            for object in character.room.objects:
                if set(object.handle) & set(kwargs['direct_object']):
                    object.skin_corpse()
                    return
            for item in character.room.items:
                if set(item.handle) & set(kwargs['direct_object']):
                    events.game_event("You can seem to find any way to skin {}.".format(item.name))
                    return
            for npc in character.room.npcs:
                if set(npc.handle) & set(kwargs['direct_object']):
                    events.game_event("You approach {}, but think better of it.".format(npc.name))
                    return

@DoActions.register_subclass('south')
@DoActions.register_subclass('s')
class South(DoActions):
    """\
    Moves you south, if you can move in that direction.\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        if character.check_round_time():
            return
        if character.is_dead():
            return
        if not character.check_position_to_move():
            return
        if world.tile_exists(x=self.character.location_x, y=self.character.location_y + 1, area=self.character.area):
            if character.room.shop_filled == True:
                if character.room.shop.in_shop == True:
                    character.room.shop.exit_shop()
            self.character.move_south()
            character.print_status()
        else:
            events.game_event("You cannot find a way to move in that direction.")

@DoActions.register_subclass('stance')
class Stance(DoActions):
    """\
    STANCE controls the position in which you carry yourself in combat. Your stance will affect the amount of
    attack and defensive strength you have during combat.

    Usage:
    STANCE:  Shows your current stance.
    STANCE <type>: Changes your stance to the desired stance.

    Types of Stances:
    offensive
    forward
    neutral
    guarded
    defense\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        self.character = character

        self.stance(character=character, desired_stance=kwargs['adjective_1'])

    def stance(self, character, desired_stance):
        if not desired_stance:
            events.game_event('''You are currently in the {} stance.'''.format(self.character.stance))
            return
        if set(desired_stance) & set(stances):
            self.character.stance = desired_stance[0]
            events.game_event('''You are now in {} stance.'''.format(desired_stance[0]))
            character.print_status()
            return
        else:
            events.game_event("You cannot form that stance.")
            return

@DoActions.register_subclass('stand')
class Stand(DoActions):
    """\
    Raises you to the standing position if you are not already in the standing position.
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        self.character = character

        self.stand(character=self.character)

    def stand(self, character):
        if self.character.check_round_time():
            return
        if self.character.is_dead():
            return
        if self.character.position == 'standing':
            self.update_character_output(character_output_text="You seem to already be standing.")
            self.update_status(status_text=character.get_status())
            return
        else:
            self.character.position = 'standing'
            self.update_character_output(character_output_text="You raise yourself to a standing position.")
            self.update_room_output(room_output_text={character.room.room_number: "{} raises {}self to a standing position".format(character.first_name, character.possessive_pronoun)})
            self.update_status(status_text=character.get_status())
            return

@DoActions.register_subclass('stats')
class Stats(DoActions):
    """\
    Displays your general statistics.\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        events.game_event('''
Name:  {} {}
Level: {}
Strength:       {}  ({})        Intellect:      {}  ({})
Constitution:   {}  ({})        Wisdom:         {}  ({})
Dexterity:      {}  ({})        Logic:          {}  ({})
Agility:        {}  ({})        Spirit:         {}  ({})
        '''.format(character.first_name,
                   character.last_name,
                   character.level,
                   character.stats['strength'], character.stats_bonus['strength'],
                   character.stats['intellect'], character.stats_bonus['intellect'],
                   character.stats['constitution'], character.stats_bonus['constitution'],
                   character.stats['wisdom'], character.stats_bonus['wisdom'],
                   character.stats['dexterity'], character.stats_bonus['dexterity'],
                   character.stats['logic'], character.stats_bonus['logic'],
                   character.stats['agility'], character.stats_bonus['agility'],
                   character.stats['spirit'], character.stats_bonus['spirit'])
              )

@DoActions.register_subclass('target')
class Target(DoActions):
    """\
    When in combat, you must TARGET an enemy before you can ATTACK them. Use the TARGET verb to set the enemy
    for which you want to ATTACK. TARGET only needs to be set once for the duration of the combat. The enemy
    does not have to be within sight in order for you to TARGET it.

    Usage:
    TARGET <enemy> : Targets an enemy.\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        if not kwargs['direct_object']:
            events.game_event("What do you want to target?")
            return
        else:
            character.target = kwargs['direct_object']
            events.game_event("You are now targeting {}".format(self.target[0]))
            return

@DoActions.register_subclass('west')
@DoActions.register_subclass('w')
class West(DoActions):
    """\
    Moves you west, if you can move in that direction.\
    """

    def __init__(self, character, **kwargs):
        DoActions.__init__(self, character, **kwargs)

        if character.check_round_time():
            return
        if character.is_dead():
            return
        if not character.check_position_to_move():
            return
        if world.tile_exists(x=self.character.location_x - 1, y=self.character.location_y, area=self.character.area):
            if character.room.shop_filled == True:
                if character.room.shop.in_shop == True:
                    character.room.shop.exit_shop()
            self.character.move_west()
            character.print_status()
        else:
            events.game_event("You cannot find a way to move in that direction.")

class Action:
    def __init__(self, method, name, action, **kwargs):
        self.method = method
        self.name = name
        self.action = action
        self.kwargs = kwargs

    def __str__(self):
        return "{}: {}".format(self.action, self.name)

class MoveNorthEnemy(Action):
    def __init__(self, **kwargs):
        super().__init__(method=enemies.Enemy.move_north,
                         name='Move North',
                         action=['north'],
                         kwargs=kwargs)

class MoveSouthEnemy(Action):
    def __init__(self, **kwargs):
        super().__init__(method=enemies.Enemy.move_south,
                         name='Move South',
                         action=['south'],
                         kwargs=kwargs)

class MoveEastEnemy(Action):
    def __init__(self, **kwargs):
        super().__init__(method=enemies.Enemy.move_east,
                         name='Move East',
                         action=['east'],
                         kwargs=kwargs)

class MoveWestEnemy(Action):
    def __init__(self, **kwargs):
        super().__init__(method=enemies.Enemy.move_west,
                         name='Move West',
                         action=['west'],
                         kwargs=kwargs)


import logging

logging.basicConfig(filename="human_resources.log", level=logging.DEBUG)

valid_employee_kvps = ['first_name', 'last_name', 'email', 'tasks', 'job_title', 'valid_tasks', 'is_active']

def get_departments(request):
    logging.debug('****GET DEPARTMENTS****')
    depts = Process.objects.filter(kind="department")
    logging.debug(depts)
    return [dept.as_dict() for dept in depts]

def get_dept_options(request):
    depts = Process.objects.filter(kind="department")
    return [{'value':dept.PROCESS_ID, 'label': dept.name} for dept in depts]

def all_employees(request):
    employees = Process.objects.filter(kind="employee", is_active=True)
    return [emp.as_dict() for emp in employees]

def get_pms(request):
    pms = Process.objects.filter(kind="employee", job_title="Project Manager", is_active=True)
    logging.debug(pms)
    return [pm.as_dict() for pm in pms]

def get_developers(request):
    emps = Process.objects.filter(kind="employee", is_active=True)
    devs = []
    for e in emps:
        if 'development' in e.valid_tasks:
            devs.append(e)
    return [dev.as_dict() for dev in devs]

def get_testers(request):
    emps = Process.objects.filter(kind="employee", is_active=True)
    testers = []
    for e in emps:
        if 'testing' in e.valid_tasks:
            emps.append(e)
    return [tester.as_dict() for tester in testers]

def find_employee(request):
    try:
        if not isinstance(request, Process) and not isinstance(request, NebriOS):
            if request.FORM is None:
                email = request.BODY.as_dict()['email']
            else:
                email = request.FORM.as_dict()['email']
        else:
            email = request.as_dict()['email']
        employee = Process.objects.get(kind="employee", is_active=True, email=email)
        return employee.as_dict(), employee.PARENT.PROCESS_ID
    except:
        return None, None

def update_employee(request):
    data = {}
    if request.FORM is not None:
        data = request.FORM.as_dict()
    else:
        data = request.BODY.as_dict()

    dept = data['department']
    logging.debug(data)
    # first, let's see if this is a new employee or update
    try:
        emp = Process.objects.get(kind="employee", email=email)
        for key, value in data:
            if key not in valid_employee_kvps:
                continue
            emp[key] = value
        emp.save()
    except:
        # need to create a new employee. let's find the right department.
        department = Process.objects.get(kind='department', PROCESS_ID=dept)
        emp = Process.objects.create(PARENT=department, kind="employee", is_active=True)
        for key, value in data.items():
            if key not in valid_employee_kvps:
                continue
            emp[key] = value
        emp.save()


from datetime import timedelta
from os import environ as os_environ

from celery.schedules import crontab

from .django import TIME_ZONE
from .redis import REDIS_URL

# Celery
CELERY_TIMEZONE = TIME_ZONE
CELERY_BROKER_URL = REDIS_URL
CELERY_RESULT_BACKEND = REDIS_URL
CELERY_WORKER_CONCURRENCY = os_environ.get("NEWARA_CELERY_CONCURRENCY")
CELERY_ACCEPT_CONTENT = ["json", "pickle"]  # datetime때문에 pickle 사용
CELERY_EVENT_SERIALIZER = "pickle"
CELERY_RESULT_SERIALIZER = "pickle"
CELERY_TASK_SERIALIZER = "pickle"
CELERY_TASK_RESULT_EXPIRES = int(os_environ.get("NEWARA_CELERY_EXPIRES", 600))

def create_scheduler_config(name, period=None, crontab=None):
    config = {"NAME": name, "PING_URL": os_environ.get(f"NEWARA_{name}_PING_URL", None)}
    if period is not None:
        config["PERIOD"] = timedelta(
            seconds=int(os_environ.get(f"NEWARA_{name}_PERIOD", period))
        )
    if crontab is not None:
        config["CRONTAB"] = crontab
    return config

SCHEDULERS = {
    "CRAWL_PORTAL": create_scheduler_config(
        "CRAWL_PORTAL", crontab=crontab(minute=0)
    ),  # 매 0분 (1시간마다)
    "SAVE_DAILY_BEST": create_scheduler_config(
        "SAVE_DAILY_BEST", crontab=crontab(minute=0)
    ),
    "SAVE_WEEKLY_BEST": create_scheduler_config(
        "SAVE_WEEKLY_BEST", crontab=crontab(minute=0)
    ),
    "SEND_EMAIL_FOR_REPLY_REMINDER": create_scheduler_config(
        "SEND_EMAIL_FOR_REPLY_REMINDER", crontab=crontab(hour=7, minute=0)
    ),  # 매일 오전 7시
}


# You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the ith customer has in the jth bank. Return the wealth that the richest customer has.

# A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth.

# Example 1:

# Input: accounts = [[1,2,3],[3,2,1]]
# Output: 6
# Explanation:
# 1st customer has wealth = 1 + 2 + 3 = 6
# 2nd customer has wealth = 3 + 2 + 1 = 6
# Both customers are considered the richest with a wealth of 6 each, so return 6.

class Solution:
    def maximumWealth(self,accounts):
        Max_wealth = 0
        for i in range(len(accounts)):
            money =0
            for j in range(len(accounts[i])):
                money+=accounts[i][j]
            if money>Max_wealth:
                Max_wealth= money
        return Max_wealth

accounts = [[1,2,3],[3,2,1]]

answer = Solution()
answer.maximumWealth(accounts)
# def example(accounts):
#     wealth=0
#     for i, j in range(len(accounts)):
#         wealth += accounts[i][j]
#     return wealth
# example(accounts)


import random
if_checker = True
customer_cards = []
computer_cards = []
computer_choice = True
user_choice = True
def deal_card():
    if (if_checker):
        i = 2
    else:
        i = 1
    if(user_choice):
        for x in range(0,i):
            cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
            random_cards = random.choice(cards)
            customer_cards.append(random_cards)
    if(computer_choice):
        for x in range(0,i):
            cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
            random_cards = random.choice(cards)
            computer_cards.append(random_cards)
    return customer_cards, computer_cards
def calculate_score():
    values = deal_card()
    customer_decks = values[0]
    computer_decks = values[1]
    customer_first_scores = customer_decks[0] + customer_decks[1]
    computer_first_scores = computer_decks[0] + computer_decks[1]

    if customer_first_scores == 21:
        print("you win")
        print(f"your cards {customer_decks}, current score: {customer_first_scores}")
        print(f"computer's first card {computer_decks}, current score {computer_first_scores}")
        return 0
    elif computer_first_scores == 21:
        print("you lose")
        print(f"your cards {customer_decks}, current score: {customer_first_scores}")
        print(f"computer's first card {computer_decks}, current score{computer_first_scores}")
        return 0
    elif customer_first_scores == 22:
         customer_decks[0] = 1
         print(f"yours cards {customer_decks}, current score: {customer_first_scores}")
         print(f"computer's first card {computer_decks[0]}")
         return customer_first_scores, computer_first_scores, customer_decks, computer_decks

    elif computer_first_scores == 22:
         computer_decks[0] = 1
         print(f"yours cards {customer_decks}, current score: {customer_first_scores}")
         print(f"computer's first card {computer_decks[0]}")
         return customer_first_scores, computer_first_scores, customer_decks, computer_decks

    else:
        print(f"your cards {customer_decks}, current score: {customer_first_scores}")
        print(f"computer's first card {computer_decks[0]}")
        return customer_first_scores,computer_first_scores,customer_decks,computer_decks

calculate_score()

game = input("Type \"y\" to get another card,type\"n\" to pass ").lower()
if game == "y":
    if_checker = False
    computer_choice = False
    cards = deal_card()
    customer_cards = cards[0]
    computer_cards = cards[1]
    customer_score = customer_cards[0] + customer_cards[1] + customer_cards[2]
    computer_score = computer_cards[0] + computer_cards[1]
    print(f"your cards: {customer_cards},current score: {customer_score}")
    print(f"computer's first card: {computer_cards[0]}")
    if customer_score > 21:
        print(f"Your final card: {customer_cards}, final score: {customer_score}")
        print(f"computer's final card {computer_cards}, final score: {computer_score}")
        print("you went over.  you lose.")

    if computer_score < 17:
        if_checker = False
        user_choice = False
        computer_choice = True
        final_cards = deal_card()
        computer_final_cards1 = final_cards[1]
        computer_final_score = computer_final_cards1[0]+computer_final_cards1[1]+computer_final_cards1[2]
        if computer_final_score > 21:
            print(f"Your final card: {customer_cards}, final score: {customer_score}")
            print(f"computer's final card {computer_final_cards1}, final score: {computer_final_score}")
            print("you win.")

    if customer_score > computer_final_score :
        print(f"Your final card: {customer_cards}, final score: {customer_score}")
        print(f"computer's final card {computer_final_cards1}, final score: {computer_final_score}")
        print("you win.")

    elif computer_final_score > customer_score :
        print(f"Your final card: {customer_cards}, final score: {customer_score}")
        print(f"computer's final card {computer_final_cards1}, final score: {computer_final_score}")
        print("you went over.  you lose.")

else:

    no_value = calculate_score()
    customer_score = no_value[0]
    computer_score = no_value[1]
    customer_decks = no_value[2]
    computer_decks = no_value[3]
    if (customer_score > computer_score):
        print(f"Your final card: {customer_decks[0:2]}, final score: {customer_score}")
        print(f"computer's final card {computer_decks[0:2]}, final score: {computer_score}")
        print("you win.")
    else:
        print(f"Your final card: {customer_decks[0:2]}, final score: {customer_score}")
        print(f"computer's final card {computer_decks[0:2]}, final score: {computer_score}")
        print("you lose")


import os

from aiohttp.web import middleware, HTTPUnauthorized

class Authentiction:
    @staticmethod
    @middleware
    async def handle(request, handler):
        _token = os.environ.get('AUTH_TOKEN', False)
        if _token:
            try:
                scheme, token = request.headers['Authorization'].strip().split(' ')
            except KeyError or ValueError:
                raise HTTPUnauthorized()

            if scheme.lower() != 'bearer' or token != _token:
                raise HTTPUnauthorized()

        return await handler(request)


import os
import sys
import argparse
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))

import torch
import torch.nn as nn
import torch.optim as optim

import numpy as np
from cnn_1d import CNN1D
from brain_dataset import BrainDataset
from model_trainer import ModelTrainer

DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'

def main():
	parser = argparse.ArgumentParser()
	parser.add_argument('--data', type=str, help='Data file path', required=True)
	parser.add_argument('--output', type=str, help='Output file path', required=True)
	parser.add_argument('--output_model', type=str, help='Model path', default=None)
	parser.add_argument('--level', type=int, default=0)
	parser.add_argument('--fold', type=int, default=2)
	parser.add_argument('--iter', type=int, default=1)
	parser.add_argument('--batch_size', type=int, default=16)
	parser.add_argument('--epoch', type=int, default=30)
	parser.add_argument('--random_state', type=int, default=None)
	args = parser.parse_args()

	dataset = BrainDataset(args.data, expand_dim=True, level=args.level)
	model = CNN1D(len(np.unique(dataset.label))).to(DEVICE)
	criterion = nn.CrossEntropyLoss()
	optimizer = optim.Adam(model.parameters(), lr=0.001)

	epochs = args.epoch
	batch_size = args.batch_size
	trainer = ModelTrainer(model, dataset, DEVICE)
	result = trainer.train(optimizer, criterion,
						   batch_size=batch_size,
						   epochs=epochs,
						   kfold=args.fold,
						   iteration=args.iter,
						   random_state=args.random_state)

	result = np.array(result)
	np.savetxt(args.output, result, delimiter=",")
	if args.output_model is not None:
		torch.save(model.state_dict(), args.output_model)

if __name__ == '__main__':
	main()


import time

from ..log_pintaformas import log, cat

NUM_DECIMALES = 2

def imprimir_ciclo_en_log(tiempo_inicial: float, num_ciclo: int) -> None:
    texto_ciclo = '\n'.join(
        [f'\n\nCiclo: {num_ciclo}', '.' * 8]
    )
    log.anotar(texto_ciclo)
    log.anotar(
        f'Tiempo actual: {round(time.time() - tiempo_inicial, NUM_DECIMALES)}',
        categoria=cat.mostrar_tiempo
    )

NOMBRES_AJUSTES_PERSISTENCIA = (
    'cargar_dibujo_guardado',
    'nombre_documento_proporcionado_por_el_usuario',
    'grabar_dibujo_al_salir'
)


import csv
from io import BytesIO

from flask import (
    Blueprint,
    Response,
    jsonify,
    current_app,
    request,
    abort
)

from werkzeug import exceptions

from munimap.print_requests import MapRequest
from munimap.query.feature_collection import query_feature_collection
from munimap.query.pq import LayerNotFoundError
from munimap.index import create_index_pdf, features_to_index_data
from munimap.helper import layer_allowed_for_user

vector = Blueprint('vector', __name__)

@vector.route('/geojson', methods=['GET'])
def geojson():
    req = MapRequest.from_req(request)

    for _layer in req.layers:
        layer = current_app.layers[_layer]
        if not layer_allowed_for_user(layer):
            raise exceptions.Forbidden()

    try:
        fc = query_feature_collection(req, current_app.pg_layers)
    except LayerNotFoundError as e:
        current_app.logger.error(str(e))
        abort(400)
    return jsonify(fc)

@vector.route('/index.json', methods=['GET'])
def index_json():
    req = MapRequest.from_req(request)
    fc = query_feature_collection(req, current_app.pg_layers)
    return jsonify(features_to_index_data(fc, current_app.pg_layers))

@vector.route('/index.pdf', methods=['GET'])
def index_pdf():
    req = MapRequest.from_req(request)
    fc = query_feature_collection(req, current_app.pg_layers)
    index = features_to_index_data(fc, current_app.pg_layers)
    return Response(
        create_index_pdf(index, 'Index', columns=3).getvalue(),
        mimetype='application/pdf',
    )

@vector.route('/index.csv', methods=['GET'])
def index_csv():
    encoding = request.args.get('encoding', 'latin-1')
    delimiter = request.args.get('delimiter', ';')[0]
    req = MapRequest.from_req(request)
    fc = query_feature_collection(req, current_app.pg_layers)
    buf = BytesIO()
    w = csv.writer(buf, delimiter=delimiter)
    for f in fc['features']:
        if f['properties'].get('__ref__'):
            w.writerow((f['properties']['name'].encode(encoding), f['properties']['__ref__']))

    buf.seek(0)
    resp = Response(buf.read())
    resp.content_type = 'text/csv'
    return resp

@vector.route('/export/grid.geojson', methods=['GET'])
def grid_geojson():
    labels = request.args.get('labels', 'true').lower() in ('1', 'yes', 'true', 'on')
    lines = request.args.get('lines', 'true').lower() in ('1', 'yes', 'true', 'on')
    req = MapRequest.from_req(request)
    grid = req.grid
    if grid is None:
        return exceptions.BadRequest()

    return jsonify(grid.features(lines=lines, points=labels, srs=req.srs))


sequence_len = 10
table_name_len = 15
attr_num = 20
instance_num = 20
char_num = 2000
char_embed_size = 64
batch_size = 100
lstm_units = 128
attention_size = 64

"""
    attr num 40
    char num 1000
    title len 30
"""


n =int(input("Enter Value"))
length=2*n-1
pattern=[["" for i in range(length)] for i in range(length)]
space=0
def create(l,s):
    if s==n:
        return None
    for i in range(l):
        if i in (0,l-1):
            for p in range(l):
                pattern[i+s][p+s]=n-s
        else:
            pattern [i+s][0+s]=n-s
            pattern [i+s][l-1+s]=n-s

    l=l-2
    s =s +1
    create(l,s)

create(length,space)
for i in pattern:
    print("".join(i))


from flask import Flask, request, jsonify
import data_connection as dc
import os

app = Flask(__name__)

APP_ROOT = os.path.dirname(os.path.abspath(__file__))

#@app.route('/sample')
def assess_percent(qtr,busunit,process,geo,market):

    sqlSOX = """
    WITH Q1 AS
    (
    SELECT DISTINCT
    RPTG_QTR,
    A.COUNTRY,
    B.MARKET,
    BUSINESS_UNIT,
    PROCESS,
    B.GEO,
    A.ASSESSED_ENTITY_TYPE,
    A.ASSESSED_ENTITY_ID,
    RATING,
    CASE WHEN RATING = 'Satisfactory' THEN 1 ELSE 0 END AS SATISFACTORY,
    CASE WHEN RATING = 'Unsatisfactory' THEN 1 ELSE 0 END AS UNSAT,
    CASE WHEN RATING = 'Marginal' THEN 1 ELSE 0 END AS MARGINAL,
    CASE WHEN RATING = 'Exempt' OR EXEMPT = 'E' THEN 1 ELSE 0 END AS EXEMPTS,
    CASE WHEN RATING = 'Pending' THEN 1 ELSE 0 END AS PENDING,
    CASE WHEN RATING = 'Pending' OR EXEMPT = 'E' THEN 0 ELSE 1 END AS TOTAL_RATING

    FROM SOX.CFOPORT_ASSESSMENT A
    LEFT JOIN SOX.MARKET B ON A.COUNTRY = B.COUNTRY

    )

    SELECT DISTINCT
    A.ASSESSED_ENTITY_TYPE,
    SUM(SATISFACTORY) AS SUM_SATISFACTORY,
    SUM(UNSAT) AS SUM_UNSATISFACTORY,
    SUM(MARGINAL) AS SUM_MARGINAL,
    SUM(EXEMPTS) AS SUM_EXEMPT,
    SUM(PENDING) AS SUM_PENDING,
    SUM(TOTAL_RATING) AS TOTAL_RATING,
    CAST((CAST(SUM(SATISFACTORY) AS DECIMAL(31,2)) / CAST(SUM(TOTAL_RATING) AS DECIMAL(31,2)) * 100) AS DECIMAL(31,2)) AS SAT_RATE

    FROM Q1 A

    WHERE A.RPTG_QTR IS NOT NULL
    AND A.TOTAL_RATING NOT IN (0)
    """

    sqlgroup = """

    GROUP BY A.ASSESSED_ENTITY_TYPE"""

    if busunit == "" and process == "" and market == "" and geo == "" and qtr == "":
        sqlSOX = sqlSOX + sqlgroup

    else:
        sqlSOX = concatFilter(sqlSOX, qtr, splitParam(qtr), 0, 'A.')
        sqlSOX = concatFilter(sqlSOX, busunit, splitParam(busunit), 1, 'A.')
        sqlSOX = concatFilter(sqlSOX, process, splitParam(process), 2, 'A.')
        sqlSOX = concatFilter(sqlSOX, geo, splitParam(geo), 3, 'A.')
        sqlSOX = concatFilter(sqlSOX, market, splitParam(market), 4, 'A.')

    sqlSOX = sqlSOX + sqlgroup

    # Execute the query
    assess_percent = list(dc.select_query(sqlSOX))

    print(assess_percent)

    return jsonify(assess_percent)

def concatFilter(sqlSOX, param, splitParam, cnt, alias): # Concatenate filters
    listParams = ['RPTG_QTR','BUSINESS_UNIT','PROCESS','GEO','MARKET']

    if param:
            sqlSOX +=" AND " + alias + listParams[cnt] + " IN (" + splitParam + ")"
    return sqlSOX

def splitParam(param): # Splitting multiple values for each parameters
    param = str(param)
    filters =param.split(',')
    itemfilter = ""
    for data in filters:
        if itemfilter == "":
            itemfilter = " '" + data +"' "
        else:
            itemfilter = itemfilter + " ,'" + data +"' "

    return itemfilter


from sklearn import naive_bayes, datasets
import numpy as np

def iris_naive_bayes_full_data(dataset):
    nb = naive_bayes.MultinomialNB(fit_prior=True)
    nb.fit(dataset.data[:-1], dataset.target[:-1])
    # taking the only one element which is the 31st instance to predict
    p31 = nb.predict(dataset.data[31:32])
    print(p31)
    # building a numpy 2d array containing only the last instance
    arr = np.reshape(dataset.data[-1], (1, 4))
    plast = nb.predict(arr)
    print(plast)
    prediction = nb.predict(dataset.data[:])
    print(prediction)

def iris_naive_bayes_partial_data(dataset):
    nb = naive_bayes.MultinomialNB(fit_prior=True)
    nb.fit(dataset.data[:99], dataset.target[:99])
    prediction = nb.predict(dataset.data[100: -1])
    print(prediction)
    pred_arr = np.array(prediction)
    actual_arr = np.array(dataset.target[100:-1])
    acc = 100*(len(pred_arr[pred_arr == actual_arr])/51)
    print("Accuracy = ", acc)
    # Terrible results since the dataset splitting here didn't include any instance classified as the second class

if __name__ == '__main__':
    iris_dataset = datasets.load_iris()
    iris_naive_bayes_full_data(iris_dataset)
    iris_naive_bayes_partial_data(iris_dataset)


import torch
import os
import wandb
import yaml

class Logger:
    def __init__(self, args, models):
        self.args = args
        # save args
        self.models = models
        # TODO: this is a hack to avoid logging outside train.py FIXME
        if hasattr(args, "basedir"):
            self.basedir = args.basedir
            with open(os.path.join(args.basedir, "args.yaml"), "w") as f:
                yaml.dump(vars(args), f, sort_keys=False)
            if args.WANDB:
                self.wandb = True
                n_params = sum(p.numel() for p in models[0].parameters())
                wandb.init(
                    project="nuclr_iclr24",
                    entity="iaifi",
                    name=args.name,
                    notes="new and great runs",
                    tags=["good_performance_run"],
                    group="ICLR24",
                    config=dict(vars(args)),
                )
                wandb.config.update({"n_params": n_params})
                artifact = wandb.Artifact(
                    "nuclr", type="code", description="nuclr code"
                )
                nuclr_dir = os.path.dirname(os.path.abspath(__file__))
                artifact.add_dir(nuclr_dir)
                wandb.log_artifact(artifact)
            else:
                self.wandb = False
        else:

            self.basedir = None
        self.best_loss = float("inf")
        self._defined_metrics = None

    def define_metrics_wandb(self, metrics):
        if not self.wandb or self._defined_metrics is not None:
            return
        self._defined_metrics = metrics
        for metric in metrics:
            wandb.define_metric(metric, summary="min")

    def log(self, metrics, epoch, save_model=False):
        if self.basedir is None:
            return -1
        self.define_metrics_wandb(metrics)
        val_loss = metrics["val_loss_all"]
        # keep track of the best model
        if val_loss < self.best_loss:
            self.best_loss = val_loss
            self.best_models = [m.state_dict().copy() for m in self.models]
            [
                torch.save(
                    self.best_models[fold],
                    os.path.join(self.basedir, f"model_best.pt.{fold}"),
                )
                for fold in self.args.WHICH_FOLDS
            ]
        if self.args.WANDB:
            wandb.log(metrics, step=epoch)
        else:
            train_items = [
                f"{' '.join(k.split('_')[1:]):<20} | {v:<8.2e}"
                for k, v in metrics.items()
                if "train" in k
            ]
            val_items = [
                f"{v:<8.2e}" for k, v in metrics.items() if "val" in k
            ]
            items = [
                " | ".join([x, y]) for x, y in zip(train_items, val_items)
            ]
            msg = f"Epoch {epoch:<14} | {'Train':^8} | {'Val':^8}\n"
            msg += "\n".join(sorted(items, key=lambda x: x.split(" ")[0]))
            print(msg)

        if save_model:
            epoch_str = (
                str(epoch) if epoch != self.args.EPOCHS - 1 else "final"
            )
            [
                torch.save(
                    self.models[fold].state_dict(),
                    os.path.join(self.basedir, f"model_{epoch_str}.pt.{fold}"),
                )
                for fold in self.args.WHICH_FOLDS
            ]

        # at the end, make a file "done.txt"
        if epoch == self.args.EPOCHS - 1:
            print("done", os.path.join(self.basedir), sep="\n")
            with open(os.path.join(self.basedir, "done.txt"), "w") as f:
                f.write("finalized successfully")


#!/usr/bin/env python3.7

string = 'abracadabra'

new_string = string[:5] +'k' + string[6:]
print(new_string)

#def mutate_string(string, position, character):
    #return
    #mutate_string = s[:i] +'c' + s[i:]
#s = input("Enter the string ")
#i = input("Enter the iteger index to replace ")
#c = input("Enter the character you want replaced ")

#s_new = s
#s_mod = s[:i] +'c' + s[i:]
#print(s_mod)

#if __name__ == '__main__':
    #  s = input()
    # i, c = input().split()
    # s_new = mutate_string(s, int(i), c)
   # print(s_new)


import torch
import torch.nn as nn
from mmcv.cnn.bricks.transformer import build_transformer_layer
import copy
import numpy as np
from einops import rearrange
from models.modules.dccm import DiffContextAwareCompressionModule

class ResolutionAlignTransformerLayerSequence(nn.Module):
    def __init__(self, transformerlayers=None, num_layers=None, compression_args=None, init_cfg=None):
        super().__init__()
        if isinstance(transformerlayers, dict):
            transformerlayers = [
                copy.deepcopy(transformerlayers) for _ in range(num_layers)
            ]
        else:
            assert isinstance(transformerlayers, list) and \
                   len(transformerlayers) == num_layers
        self.num_layers = num_layers
        self.layers = nn.ModuleList()
        for i in range(num_layers):
            self.layers.append(build_transformer_layer(transformerlayers[i]))
        self.embed_dims = self.layers[0].embed_dims
        self.pre_norm = self.layers[0].pre_norm

        compression_args = copy.deepcopy(compression_args)
        comp_module = compression_args['comp_module']
        comp_insert_layer = compression_args['comp_insert_layer']
        comp_k = compression_args['comp_k']
        comp_strategy = compression_args['comp_strategy']
        embed_dim = compression_args['embed_dim']
        embedding_temporal_size = compression_args['temporal_size']
        num_samples=compression_args['num_samples']
        sigma = compression_args['sigma']

        self.num_frames = embedding_temporal_size
        self.comp_insert_layer = comp_insert_layer
        self.sigma = sigma

        if comp_insert_layer > 0:
            self.dccm = DiffContextAwareCompressionModule(
                                                        in_channels=int(embed_dim),
                                                        T=embedding_temporal_size,
                                                        strategy=comp_strategy,
                                                        comp_module=comp_module,
                                                        k=comp_k,
                                                        sigma=sigma,
                                                        n_sample=num_samples)
        else:
            self.dccm = None

    def forward(self, query, key=None, value=None,):
        # query: (bs, 1+T*P, c)

        B, N, c = query.shape
        T = self.num_frames
        P = (N - 1) // T
        H = W = int( np.sqrt(P))

        multi_resolution = False
        sort_index =None
        for i, layer in enumerate(self.layers):

            if self.dccm is not None and i == self.comp_insert_layer:
                cls_token, ts_tokens = query[:, 0].unsqueeze(1), query[:, 1:]
                ts_tokens = rearrange(ts_tokens, "b (h w t) c -> b c t h w", b=B, t=T, c=c, h=H, w=W)
                # split token to different resolutions
                # ts_tokens_high: (B, H1, W1, T1, C), ts_tokens_low:(B, H2, W2, T2, C)
                ts_tokens_high, ts_tokens_low, sort_index = self.dccm(ts_tokens, cls_token.squeeze(1),return_index=True)
                multi_resolution = True
                query = (cls_token, ts_tokens_high, ts_tokens_low)

            query = layer(query)
            #print(f"layers[{i}]: {query[0].sum()}")

        if multi_resolution:
            x_cls, x_high, x_low = query
            x_high = rearrange(x_high, "b h w t c -> b (h w t) c")
            x_low = rearrange(x_low, "b h w t c -> b (h w t) c")
            x = torch.cat([x_cls, x_high, x_low], dim=1)
            query = x
        return query

    def get_rank_index(self, query):
        # query: (bs, 1+T*P, c)
        B, N, c = query.shape
        T = self.num_frames
        P = (N - 1) // T
        H = W = int( np.sqrt(P))
        if self.dccm is None:
            return torch.arange(T).unsqueeze(0).repeat(B, 1).to(query.device)

        for i, layer in enumerate(self.layers):
            if i == self.comp_insert_layer:
                cls_token, ts_tokens = query[:, 0].unsqueeze(1), query[:, 1:]
                ts_tokens = rearrange(ts_tokens, "b (h w t) c -> b c t h w", b=B, t=T, c=c, h=H, w=W)
                # split token to different resolutions
                # ts_tokens_high: (B, H1, W1, T1, C), ts_tokens_low:(B, H2, W2, T2, C)
                ts_tokens_high, ts_tokens_low, score_index = self.dccm(ts_tokens, cls_token.squeeze(1), return_index=True)
                query = (cls_token, ts_tokens_high, ts_tokens_low)
                break
            query = layer(query)

        return score_index


#线程_thread

import _thread
import time

def work01(tread_name,delay):
    print("{0} start...".format(tread_name))
    time.sleep(delay)
    print("{0} end...".format(tread_name))

def work02(tread_name,delay):
    print("{0} start...".format(tread_name))
    time.sleep(delay)
    print("{0} end...".format(tread_name))

if __name__ == "__main__":
    """生成主进程"""
    print("mainProcess start...")
    """创建线程，向函数传值，注意数据格式"""
    _thread.start_new_thread(work01,("tread_01",4))
    time.sleep(1)
    _thread.start_new_thread(work02,("tread_02",2))
    time.sleep(5)
    print("mainProcess end...")


import requests
import matplotlib.pyplot as plt
from tqdm import tqdm
import numpy as np
import time

url = "http://codingweb.eu-central-1.elasticbeanstalk.com/test234"
a = []

start = time.time()

while len(a) < 100000:
	print(len(a))
	r = requests.get(url=url)
	if("429" in str(r)):
		print("sleeping")
		time.sleep(.1)
	else:
		data = r.json()
		#print(data)
		for d in data:
			a.append(float(d))

	#time.sleep(1)

print(time.time() - start)

plt.hist(a, 20)
plt.show()

mean = sum(a)/len(a)

t = 0
for num in a:
	t += (num - mean)**2

std = np.sqrt((1/len(a))*t)

print(mean, std)


'''
Tom Ekshtein, Backend file of Lab3
'''
#Part A
# https://editorial.rottentomatoes.com/article/most-anticipated-movies-of-2021/
import requests
from bs4 import BeautifulSoup
import json
import re
from string import digits
import sqlite3

page=requests.get("https://editorial.rottentomatoes.com/article/most-anticipated-movies-of-2021/")
#page=requests.get("https://python.org/")

soup= BeautifulSoup(page.content,"lxml")
monthL=['January','February','March','April','May','June','July','August','September','October','November','December']

def webScraper():
   '''Main chunk of program. Handles all web-scraping and deals with each unique case/ prepares information from the web for the JSON file.
   Also uploads to the JSON'''
   found=(soup.body.find("div",class_="articleContentBody"))
   tagLists=[]
   directorKeyWords=["Directed by:","Director:"]
   counter=0
   removeNonAlpha=(re.compile('[^a-zA-Z]'))
   #Creates List of lists containing movie info
   for tag in found.find_all("p"):
      #Checks for movies after website update
      if (tag.find("p")):
         if "Directed by:" in tag.text:
            tagLists.append(list(str(tag.text).replace("\xa0"," ").split("\n")))
            del(tagLists[counter][0],tagLists[counter][0],tagLists[counter][1],tagLists[counter][1])
            tagLists[counter].append(tag.strong.a.get("href"))
            tagLists[counter].append(counter)
            counter+=1

      elif "Directed by:" in tag.text or "Director:" in tag.text:
         tagLists.append(list(str(tag.text).replace("\xa0"," ").split("\n")))
         try:
            tagLists[counter].append(tag.strong.a.get("href"))
         except AttributeError:
            tagLists[counter].append(None)
         counter+=1
   #Changes movie release date to contain only month
   for i in monthL:
      for j in range(0,len(tagLists)):
         if i in tagLists[j][3]:
            tagLists[j][3]=i
         elif "TBD" in tagLists[j][3]:
            tagLists[j][3]="TBD"
   maxActorCount=0
   #removes directed by or director from list and removes starring from actor list
   #Also converts actor list to tuple
   #Also removes non letters from movie title
   for i in range(0,len(tagLists)):
      for j in directorKeyWords:
         if j in tagLists[i][1]:
            tagLists[i][1]=tagLists[i][1].replace(j,"").strip()
      tagLists[i][2]=tagLists[i][2].replace("Starring:","")
      tagLists[i][2]=list(tagLists[i][2].split(","))
      tagLists[i][0]=str(tagLists[i][0]).translate({ord(k):None for k in digits}).replace("(","").replace(")","").rstrip("%")
      tagLists[i].append(i)
      actorLen=len(tagLists[i][2])
      if actorLen>maxActorCount:
         maxActorCount=actorLen
      #this adds None to the actor list if there aren't as many as the max
      if len(tagLists[i][2])<11:
         appendCount=11-len(tagLists[i][2])
         for j in range(appendCount):
            tagLists[i][2].append(None)
   #Special names
   tagLists[9][0]="Coming 2 America"
   tagLists[30][0]="F9"
   tagLists[34][0]="Escape Room 2"
   tagLists[61][0]="Jackass 4"
   tagLists[74][0]="The Matrix 4"
   tagLists[75][0]="Sing 2"
   tagLists[76][0]="Downtown Abbey 2"
   tagLists[78][0]="Sherlock Holmes 3"

   with open("lab3backJSON.json",'w') as file:
      jsonMovie=[]
      for i in range(len(tagLists)):
         jsonMovie.append([tagLists[i][5],tagLists[i][0],tagLists[i][1],tagLists[i][2],tagLists[i][3],tagLists[i][4]])
      json.dump(jsonMovie,file,indent=3)

#PART B
def dbCreator():
   '''
   Handles all SQL programming needed to create the DB and both tables.
   '''
   file=json.load(open("lab3backJSON.json"))
   conn=sqlite3.connect("MovieSQL.db")
   conn.execute("PRAGMA foreign_keys=1")
   cur=conn.cursor()
   cur.execute("DROP TABLE IF EXISTS MovieDB")
   cur.execute("DROP TABLE IF EXISTS MonthDB")
   monthDict={
      'January' :1,
       'February' :2,
       'March' :3,
       'April' :4,
       'May' :5,
       'June' :6,
       'July' :7,
       'August':8 ,
       'September':9 ,
       'October': 10,
       'November': 11,
       'December': 12,
       '(2021)': 13,
       'TBD':13,
       'Opening on: 2021':13
   }

   cur.execute('''CREATE TABLE MonthDB(
                   ID VARCHAR PRIMARY KEY,
                   Month INTEGER
               )''')
   #insert="INSERT INTO MonthDB (January,February,March,April,May,June,July,August,September,October,November,December) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)"

   cur.execute('''CREATE TABLE MovieDB(
                       name VARCHAR PRIMARY KEY,
                       director TEXT,
                       actor1 TEXT,
                       actor2 TEXT,
                       actor3 TEXT,
                       actor4 TEXT,
                       actor5 TEXT,
                       actor6 TEXT,
                       actor7 TEXT,
                       actor8 TEXT,
                       actor9 TEXT,
                       actor10 TEXT,
                       actor11 TEXT,
                       Month VARCHAR,
                       link TEXT,
                       id INTEGER
                       )
                  ''')
   insert="INSERT INTO MonthDB (ID,Month) VALUES(?,?)"
   for i in monthDict:
      #values=(i,monthDict[i])
      cur.execute(insert,(i,monthDict[i]))
      conn.commit()

   insert="INSERT INTO MovieDB (name,director,actor1,actor2,actor3,actor4,actor5,actor6,actor7,actor8,actor9,actor10,actor11,Month,link,id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
   for i in file:
      cur.execute('SELECT Month FROM MonthDB WHERE ID=?',(i[4],))
      MonthID=cur.fetchone()[0]
      values=(i[1],i[2],i[3][0],i[3][1],i[3][2],i[3][3],i[3][4],i[3][5],i[3][6],i[3][7],i[3][8],i[3][9],i[3][10],MonthID,i[5],i[0])
      cur.execute(insert,values)
   conn.commit()
   cur.close()

if __name__=="__main__":
   webScraper()
   dbCreator()


"""empty message

Revision ID: 6f73b5fffdf1
Revises: 611ba463d901
Create Date: 2017-01-31 12:28:57.626097

"""

# revision identifiers, used by Alembic.
revision = '6f73b5fffdf1'
down_revision = '611ba463d901'

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.add_column('amount', sa.Column('uniq_id', sa.String(length=240), nullable=True))
    op.create_unique_constraint(None, 'amount', ['uniq_id'])
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(None, 'amount', type_='unique')
    op.drop_column('amount', 'uniq_id')
    ### end Alembic commands ###


#!/usr/bin/python3
import socket

from ChatModule import ChatModule
from NetworkModule import NetworkModule
from WindowModule import WindowModule

class Client:
    """Chat client."""

    def __init__(self):
        self.__network_module = NetworkModule()
        self.__window_module = WindowModule()
        self.__chat_module = ChatModule(self.__network_module, self.__window_module)

    def run(self):
        self.__chat_module.connect_to_server(socket.gethostname(), 12345)

        self.__window_module.show_login_dialog()
        # self.__window_module.show_join_dialog()
        self.__chat_module.join_room('general', 'general')

        self.__window_module.show()


import requests
from bs4 import BeautifulSoup
import execjs

url = 'https://match.yuanrenxue.com/match/1'

session = requests.session()

# headers = {
#     "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36"
# }

headers = {
    "User-Agent": "yuanrenxue.project"
}

h = session.get(url,headers=headers,verify=False)
print(h)
print(session.cookies.get_dict())
session.cookies.set('sessionid','zt5jid1j4lkip4tz4cotm6fycn628je4')

with open('111.js', 'r+',errors='ignore')as f:
    result = f.read()

ctx = execjs.compile(result, cwd=r'C:\Users\Administrator\AppData\Roaming\npm\node_modules')

nums = 0
a = 0
for i in range(1,6):
    times = str(execjs.eval("Date['\x70\x61\x72\x73\x65'](new Date()) + (16798545 + -72936737 + 156138192)"))
    sion = ctx.call('oo0O0',str(times))
    print(sion)
    print(sion + '丨'+str(times)[:-3])
    url = 'https://match.yuanrenxue.com/api/match/1?page={}&m={}'.format(i,sion + '丨'+str(times)[:-3])
    h = session.get(url,headers=headers,verify=False)
    print(h.json())
    for resu in h.json()['data']:
        nums += list(resu.values())[0]
        a += 1
    print(nums)
print(nums/a)


import os
import sys
import json
import collections

from datetime import datetime

from alfred.utils import eval_util

def compute_metrics(subgoal_success, subgoal_idx, reward, task, t_agent):
    '''
    compute metrics for subgoal evaluation
    '''
    pl = float(t_agent) + 1 # +1 for last action
    expert_pl = len([ll for ll in task['plan']['low_actions']
                     if ll['high_idx'] == subgoal_idx])
    s_spl = (1 if subgoal_success else 0) * min(
        1., expert_pl / (pl + sys.float_info.epsilon))
    plw_s_spl = s_spl * expert_pl
    metrics = {'success_spl': float(s_spl),
               'subgoal_path_len_weighted_success_spl': float(plw_s_spl),
               'subgoal_path_len_weight': float(expert_pl),
               'reward': float(reward),
               'success': subgoal_success}
    return metrics

def evaluate_subgoals(
        env, model, dataset, extractor, trial_uid, dataset_idx, args, obj_predictor):
    # load trajectory data from the dataset
    traj_data, traj_key = dataset.jsons_and_keys[dataset_idx]
    r_idx, subgoal_idx = int(trial_uid.split(':')[1]), int(trial_uid.split(':')[2])
    assert traj_data['repeat_idx'] == r_idx
    # reset model and setup scene
    model.reset()
    eval_util.setup_scene(env, traj_data, reward_type='dense')
    vocab = {'word': dataset.vocab_in, 'action_low': model.vocab_out}
    # load language features, expert initialization and task info
    input_dict = eval_util.load_language(
        dataset, traj_data, traj_key, model.args, extractor, subgoal_idx)
    expert_dict = eval_util.load_expert_actions(
        dataset, traj_data, traj_key, subgoal_idx)
    task_info = eval_util.read_task_data(traj_data, subgoal_idx)
    if args.debug:
        print(task_info)

    prev_action, subgoal_success, init_failed = None, False, False

    # expert teacher-forcing upto subgoal, get expert action
    for a_expert in expert_dict['actions']:
        input_dict['frames'] = eval_util.get_observation(env.last_event, extractor)
        init_failed, prev_action = eval_util.expert_step(
            a_expert['action'], expert_dict['masks'], model,
            input_dict, vocab, prev_action, env, args)
        if init_failed:
            break

    t_agent, t_expert, num_fails, reward = 0, len(expert_dict['actions']), 0, 0
    if not init_failed:
        # this should be set during the teacher-forcing but sometimes it fails
        env.task.goal_idx = task_info['subgoal_idx']
        env.task.finished = task_info['subgoal_idx'] - 1
        while t_agent < args.max_steps:
            # get an observation and do an agent step
            input_dict['frames'] = eval_util.get_observation(env.last_event, extractor)
            episode_end, prev_action, num_fails, _, _ = eval_util.agent_step(
                model, input_dict, vocab, prev_action, env, args,
                num_fails, obj_predictor)
            # get rewards and subgoal success
            reward += env.get_transition_reward()[0]
            subgoal_success = (env.get_subgoal_idx() == subgoal_idx)
            t_agent += 1
            # break if stop is predicted, args.max_fails is reached or success
            if episode_end or subgoal_success:
                break

    # compute metrics and dump a video
    metrics = compute_metrics(subgoal_success, subgoal_idx, reward, traj_data, t_agent)
    return dict(**metrics, **task_info)

def process_eval_subgoals(results_path, model_paths, args):
    print('Processing evaluation results')
    with open(results_path, 'r') as results_file:
        trial_results = json.load(results_file)

    for model_path in model_paths:
        successes, failures, results = collections.defaultdict(list), collections.defaultdict(list), {}

        # collect all entries from the trial_results
        log_entries = trial_results[os.path.basename(model_path)]['subgoal'].values()
        for log_entry in log_entries:
            subgoal_action = log_entry['subgoal_action']
            if log_entry['success']:
                successes[subgoal_action].append(log_entry)
            else:
                failures[subgoal_action].append(log_entry)

        # save results
        print('Model = {}'.format(os.path.basename(model_path)))
        print("-------------")
        subgoals_to_evaluate = list(successes.keys())
        subgoals_to_evaluate.sort()
        for sg in subgoals_to_evaluate:
            num_successes, num_failures = len(successes[sg]), len(failures[sg])
            num_evals = len(successes[sg]) + len(failures[sg])
            if num_evals > 0:
                sr = float(num_successes) / num_evals
                total_path_len_weight = sum(
                    [entry['subgoal_path_len_weight'] for entry in successes[sg]]) + \
                    sum([entry['subgoal_path_len_weight'] for entry in failures[sg]])
                sr_plw = float(
                    sum([entry['subgoal_path_len_weighted_success_spl'] for entry in successes[sg]]) +
                    sum([entry['subgoal_path_len_weighted_success_spl'] for entry in failures[sg]]))
                sr_plw /= total_path_len_weight
                results[sg] = {
                    'sr': sr,
                    'successes': num_successes,
                    'evals': num_evals,
                    'sr_plw': sr_plw
                }
                print("%s ==========" % sg)
                print("SR: %d/%d = %.3f" % (num_successes, num_evals, sr))
                print("PLW SR: %.3f" % (sr_plw))
        print("------------")

        # record everything
        results = {'successes': {k: v for k, v in successes.items() if len(v) > 0},
                   'failures': {k: v for k, v in failures.items() if len(v) > 0},
                   'results': results,
                   'model': model_path,
                   'timestamp': datetime.now().strftime("%d.%m.%Y_%H:%M:%S_%f")}
        dataset_id = os.path.basename(results_path).split('.')[0]
        eval_util.overwrite_eval_json(results, model_path, 'subgoal', args, dataset_id)


class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def __init__(self):
        self.max_depth = -float("inf")
        self.expecting_partial = False

    def isCompleteTree(self, root: TreeNode) -> bool:

        return self.dfs(root, 0)

    def dfs(self, node, d):
        if not node:

            if self.max_depth == -float("inf"):
                self.max_depth = d - 1
                return True
            elif self.expecting_partial:
                return d == self.max_depth
            else:
                if d == self.max_depth + 1:
                    return True
                if d == self.max_depth:
                    self.expecting_partial = True
                    return True
                return False

        return self.dfs(node.left, d + 1) and self.dfs(node.right, d + 1)

data_files/958 Check Completeness of a Binary Tree.py