import random

rock = '''
    _______
---'   ____)
      (_____)
      (_____)
      (____)
---.__(___)
'''

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

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

print("Welcome to rock-paper-scissors online game!!!\n")

name = input("what is your name? ")
name = name.upper()
rock_paper_scissors = [rock,paper,scissors]
player = input(f"So {name}, \nWhat do you choose? \nRock, Paper or Scissors? \n")
player = player.lower()
your_result = "You don't select rock, paper or scissors!\n"
print(f"\n{name} :\n")
if player == "rock":
  your_result = rock
elif player == "paper":
  your_result = paper
elif player == "scissors":
  your_result = scissors
else:
  print("What did you jest choose? ")
print(your_result)
cpu = random.randint(0,2)
print("\nComputer :\n")
cpu_result = rock_paper_scissors[cpu]
print(cpu_result)
if your_result == cpu_result:
  print("No one Won!\nThe game is a Draw!!!")
elif (your_result == rock and cpu_result == scissors) or (your_result == scissors and cpu_result == paper) or (your_result == paper and cpu_result == rock):
  print("Cpu Lost!\nYou Won!!!")
elif (cpu_result == rock and your_result == scissors ) or (cpu_result == scissors and your_result == paper) or (cpu_result == paper and your_result == rock):
  print("Cpu Won!\nYou Lost!!!")
else:
  print("The result can't be determined...")

# OR

#import random

# rock = '''
#     _______
# ---'   ____)
#       (_____)
#       (_____)
#       (____)
# ---.__(___)
# '''

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

# scissors = '''
#     _______
# ---'   ____)____
#           ______)
#        __________)
#       (____)
# ---.__(___)
# '''
# game_images = [rock, paper, scissors]
# choice = [0,1,2]
# user_choice = int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\n"))
# if user_choice in choice:
#  print(game_images[user_choice])

# computer_choice = random.randint(0, 2)
# print("Computer chose:")
# print(game_images[computer_choice])

# if user_choice >= 3 or user_choice < 0:
#   print("You typed an invalid number, you lose!")
# elif user_choice == 0 and computer_choice == 2:
#   print("You win!")
# elif computer_choice == 0 and user_choice == 2:
#   print("You lose")
# elif computer_choice > user_choice:
#   print("You lose")
# elif user_choice > computer_choice:
#   print("You win!")
# elif computer_choice == user_choice:
#   print("It's a draw")

Day 4/Program Day 4/Day 4 - project - rock - paper - scissor.py


from collections import Counter
import json, re

def make_vocab(batch_seq, char_level=False):
    cnt = Counter()
    for seq in batch_seq:
        cnt.update(seq)
    if not char_level:
        return cnt
    char_cnt = Counter()
    for x, y in cnt.most_common():
        for ch in list(x):
            char_cnt[ch] += y
    return cnt, char_cnt

def write_vocab(vocab, path):
    with open(path, 'w') as fo:
        for x, y in vocab.most_common():
            fo.write('%s\t%d\n'%(x,y))

import argparse
def parse_config():
    parser = argparse.ArgumentParser()
    parser.add_argument('--train_eq_src', type=str)
    parser.add_argument('--train_wd_src', type=str)
    parser.add_argument('--train_wd_orig', type=str)

    parser.add_argument('--train_data_tgt', type=str)
    parser.add_argument('--train_processed_data_tgt', type=str)

    parser.add_argument('--output_file', type=str)

    parser.add_argument('--ratio', type=float, default=1.5)
    parser.add_argument('--min_len', type=int, default=1)
    parser.add_argument('--max_len', type=str, default=250)
    return parser.parse_args()

if __name__ == "__main__":
    args = parse_config()

    fo = open(args.output_file, 'w')
    eq_src_lines = []
    wd_src_lines = []
    tgt_processed_lines = []
    tgt_lines = []
    tot_lines = 0
    for eq_src_line, wd_src_line, tgt_line, wd_orig_line, tgt_processed_line in zip(open(args.train_eq_src).readlines(),
                                                                                open(args.train_wd_src).readlines(),
                                                                                open(args.train_data_tgt).readlines(),
                                                                                open(args.train_wd_orig).readlines(),
                                                                                open(args.train_processed_data_tgt).readlines()):
        eq_src_line = eq_src_line.strip().split()
        wd_src_line = wd_src_line.strip().split()
        wd_orig_line = wd_orig_line.strip().split()
        tgt_line = tgt_line.strip().split()
        tgt_processed_line = tgt_processed_line.strip().split()
        tot_lines += 1
        fo.write(' '.join(eq_src_line) + '\t' + ' '.join(wd_src_line) + '\t' + ' '.join(tgt_line) + '\t' + ' '.join(tgt_processed_line) + '\t' + ' '.join(wd_orig_line) + '\n')
        eq_src_lines.append(eq_src_line)
        wd_src_lines.append(wd_src_line)
        tgt_lines.append(tgt_line)
        tgt_processed_lines.append(tgt_processed_line)
    fo.close()


from typing import List
from project.horse_race import HorseRace
from project.horse_specification.appaloosa import Appaloosa
from project.horse_specification.horse import Horse
from project.horse_specification.thoroughbred import Thoroughbred
from project.jockey import Jockey

class HorseRaceApp:
	VALID_HORSE_TYPES = {"Appaloosa": Appaloosa, "Thoroughbred": Thoroughbred}

	def __init__(self):
		self.horses: List[Horse] = []
		self.jockeys: List[Jockey] = []
		self.horse_races: List[HorseRace] = []

	@staticmethod
	def __find_entity_from_name(entities, name: str):
		for entity in entities:
			if entity.name == name:
				return entity

	def __find_horse_race_from_type(self, race_type: str):
		for horse_race in self.horse_races:
			if horse_race.race_type == race_type:
				return horse_race

	def __find_horse_from_type(self, horse_type):
		for horse in self.horses[::-1]:
			if horse.__class__.__name__ == horse_type and not horse.is_taken:
				return horse

	def add_horse(self, horse_type: str, horse_name: str, horse_speed: int):
		if self.__find_entity_from_name(self.horses, horse_name):
			raise Exception(f"Horse {horse_name} has been already added!")

		if horse_type in HorseRaceApp.VALID_HORSE_TYPES:

			horse = HorseRaceApp.VALID_HORSE_TYPES[horse_type](horse_name, horse_speed)
			self.horses.append(horse)

			return f"{horse_type} horse {horse_name} is added."

	def add_jockey(self, jockey_name: str, age: int):
		if self.__find_entity_from_name(self.jockeys, jockey_name):
			raise Exception(f"Jockey {jockey_name} has been already added!")

		jockey = Jockey(jockey_name, age)
		self.jockeys.append(jockey)

		return f"Jockey {jockey_name} is added."

	def create_horse_race(self, race_type: str):
		if self.__find_horse_race_from_type(race_type):
			raise Exception(f"Race {race_type} has been already created!")

		race = HorseRace(race_type)
		self.horse_races.append(race)

		return f"Race {race_type} is created."

	def add_horse_to_jockey(self, jockey_name: str, horse_type: str):
		jockey = self.__find_entity_from_name(self.jockeys, jockey_name)
		horse = self.__find_horse_from_type(horse_type)

		if jockey is None:
			raise Exception(f"Jockey {jockey_name} could not be found!")

		elif horse is None:
			raise Exception(f"Horse breed {horse_type} could not be found!")

		elif jockey.horse is not None:
			return f"Jockey {jockey_name} already has a horse."

		jockey.horse = horse
		horse.is_taken = True

		return f"Jockey {jockey_name} will ride the horse {horse.name}."

	def add_jockey_to_horse_race(self, race_type: str, jockey_name: str):
		horse_race = self.__find_horse_race_from_type(race_type)
		jockey = self.__find_entity_from_name(self.jockeys, jockey_name)

		if horse_race is None:
			raise Exception(f"Race {race_type} could not be found!")

		elif jockey is None:
			raise Exception(f"Jockey {jockey_name} could not be found!")

		elif jockey.horse is None:
			raise Exception(f"Jockey {jockey_name} cannot race without a horse!")

		elif jockey in horse_race.jockeys:
			return f"Jockey {jockey_name} has been already added to the {race_type} race."

		horse_race.jockeys.append(jockey)
		return f"Jockey {jockey_name} added to the {race_type} race."

	def start_horse_race(self, race_type: str):
		horse_race = self.__find_horse_race_from_type(race_type)

		if horse_race is None:
			raise Exception(f"Race {race_type} could not be found!")

		elif not len(horse_race.jockeys) > 1:
			raise Exception(f"Horse race {race_type} needs at least two participants!")

		winner = sorted(horse_race.jockeys, key=lambda jokey: -jokey.horse.speed)[0]

		return f"The winner of the {race_type} race, " \
			f"with a speed of {winner.horse.speed}km/h is {winner.name}!" \
			f" Winner's horse: {winner.horse.name}."


import sys
input = sys.stdin.readline
def seg(s, e, su, idx = 1):
    if nl[idx] < su:
        return 1111111
    if s == e:
        return s + 1
    m = (s + e) // 2
    idx <<= 1
    if nl[idx] >= su:
        return seg(s, m, su, idx)
    else:
        return min(seg(s, m, su, idx), seg(m+1, e, su-nl[idx], idx + 1))

nl = [0] * 2097152
tmp = 1048575
r = []
n = int(input())
while n:
    n -= 1
    tmp2 = input()
    if tmp2[0] == '1':
        #꺼내기
        a, b = map(int, tmp2.split())
        #누적합이 b보다 작거나 같은 최대의 구간
        tmp3 = seg(0, tmp, b)
        idx = tmp + tmp3
        while idx:
            nl[idx] -= 1
            idx >>= 1
        r.append(str(tmp3))

    else:
        a, b, c = map(int, tmp2.split())
        # b맛 c개 넣기(b인덱스에 c 더하기)
        idx = tmp + b
        while idx:
            nl[idx] += c
            idx >>= 1

print('\n'.join(r))


#!/usr/bin python3
""" The command frame for Faceswap GUI """

import logging
import tkinter as tk
from tkinter import ttk

from .control_helper import set_slider_rounding, ControlPanel
from .tooltip import Tooltip
from .utils import get_images, get_config

logger = logging.getLogger(__name__)  # pylint:disable=invalid-name

class CommandNotebook(ttk.Notebook):  # pylint:disable=too-many-ancestors
    """ Frame to hold each individual tab of the command notebook """

    def __init__(self, parent):
        logger.debug("Initializing %s: (parent: %s)", self.__class__.__name__, parent)
        self.actionbtns = dict()
        super().__init__(parent)
        parent.add(self)

        self.tools_notebook = ToolsNotebook(self)
        self.set_running_task_trace()
        self.build_tabs()
        get_config().command_notebook = self
        logger.debug("Initialized %s", self.__class__.__name__)

    def set_running_task_trace(self):
        """ Set trigger action for the running task
            to change the action buttons text and command """
        logger.debug("Set running trace")
        tk_vars = get_config().tk_vars
        tk_vars["runningtask"].trace("w", self.change_action_button)

    def build_tabs(self):
        """ Build the tabs for the relevant command """
        logger.debug("Build Tabs")
        cli_opts = get_config().cli_opts
        for category in cli_opts.categories:
            book = self.tools_notebook if category == "tools" else self
            cmdlist = cli_opts.commands[category]
            for command in cmdlist:
                title = command.title()
                commandtab = CommandTab(book, category, command)
                book.add(commandtab, text=title)
        self.add(self.tools_notebook, text="Tools")
        logger.debug("Built Tabs")

    def change_action_button(self, *args):
        """ Change the action button to relevant control """
        logger.debug("Update Action Buttons: (args: %s", args)
        tk_vars = get_config().tk_vars

        for cmd, action in self.actionbtns.items():
            btnact = action
            if tk_vars["runningtask"].get():
                ttl = "Terminate"
                hlp = "Exit the running process"
            else:
                ttl = cmd.title()
                hlp = "Run the {} script".format(cmd.title())
            logger.debug("Updated Action Button: '%s'", ttl)
            btnact.config(text=ttl)
            Tooltip(btnact, text=hlp, wraplength=200)

class ToolsNotebook(ttk.Notebook):  # pylint:disable=too-many-ancestors
    """ Tools sit in their own tab, but need to inherit objects from the main command notebook """
    def __init__(self, parent):
        super().__init__(parent)
        self.actionbtns = parent.actionbtns

class CommandTab(ttk.Frame):  # pylint:disable=too-many-ancestors
    """ Frame to hold each individual tab of the command notebook """

    def __init__(self, parent, category, command):
        logger.debug("Initializing %s: (category: '%s', command: '%s')",
                     self.__class__.__name__, category, command)
        super().__init__(parent, name="tab_{}".format(command.lower()))

        self.category = category
        self.actionbtns = parent.actionbtns
        self.command = command

        self.build_tab()
        logger.debug("Initialized %s", self.__class__.__name__)

    def build_tab(self):
        """ Build the tab """
        logger.debug("Build Tab: '%s'", self.command)
        options = get_config().cli_opts.opts[self.command]
        cp_opts = [val["cpanel_option"] for key, val in options.items() if key != "helptext"]
        ControlPanel(self,
                     cp_opts,
                     label_width=16,
                     option_columns=3,
                     columns=1,
                     header_text=options.get("helptext", None))
        self.add_frame_separator()
        ActionFrame(self)
        logger.debug("Built Tab: '%s'", self.command)

    def add_frame_separator(self):
        """ Add a separator between top and bottom frames """
        logger.debug("Add frame seperator")
        sep = ttk.Frame(self, height=2, relief=tk.RIDGE)
        sep.pack(fill=tk.X, pady=(5, 0), side=tk.TOP)
        logger.debug("Added frame seperator")

class ActionFrame(ttk.Frame):  # pylint:disable=too-many-ancestors
    """Action Frame - Displays action controls for the command tab """

    def __init__(self, parent):
        logger.debug("Initializing %s: (command: '%s')", self.__class__.__name__, parent.command)
        super().__init__(parent)
        self.pack(fill=tk.BOTH, padx=5, pady=5, side=tk.BOTTOM, anchor=tk.N)

        self.command = parent.command
        self.title = self.command.title()

        self.add_action_button(parent.category,
                               parent.actionbtns)
        self.add_util_buttons()
        logger.debug("Initialized %s", self.__class__.__name__)

    def add_action_button(self, category, actionbtns):
        """ Add the action buttons for page """
        logger.debug("Add action buttons: '%s'", self.title)
        actframe = ttk.Frame(self)
        actframe.pack(fill=tk.X, side=tk.LEFT)
        tk_vars = get_config().tk_vars

        var_value = "{},{}".format(category, self.command)

        btnact = ttk.Button(actframe,
                            text=self.title,
                            width=10,
                            command=lambda: tk_vars["action"].set(var_value))
        btnact.pack(side=tk.LEFT)
        Tooltip(btnact,
                text="Run the {} script".format(self.title),
                wraplength=200)
        actionbtns[self.command] = btnact

        btngen = ttk.Button(actframe,
                            text="Generate",
                            width=10,
                            command=lambda: tk_vars["generate"].set(var_value))
        btngen.pack(side=tk.LEFT, padx=5)
        if self.command == "train":
            self.add_timeout(actframe)
        Tooltip(btngen,
                text="Output command line options to the console",
                wraplength=200)
        logger.debug("Added action buttons: '%s'", self.title)

    def add_timeout(self, actframe):
        """ Add a timeout option for training """
        logger.debug("Adding timeout box for %s", self.command)
        tk_var = get_config().tk_vars["traintimeout"]
        min_max = (10, 600)

        frameto = ttk.Frame(actframe)
        frameto.pack(padx=5, pady=5, side=tk.RIGHT, fill=tk.X, expand=True)
        lblto = ttk.Label(frameto, text="Timeout:", anchor=tk.W)
        lblto.pack(side=tk.LEFT)
        sldto = ttk.Scale(frameto,
                          variable=tk_var,
                          from_=min_max[0],
                          to=min_max[1],
                          command=lambda val, var=tk_var, dt=int, rn=10, mm=min_max:
                          set_slider_rounding(val, var, dt, rn, mm))
        sldto.pack(padx=5, side=tk.LEFT, fill=tk.X, expand=True)
        tboxto = ttk.Entry(frameto, width=3, textvariable=tk_var, justify=tk.RIGHT)
        tboxto.pack(side=tk.RIGHT)
        helptxt = ("Training can take some time to save and shutdown. "
                   "Set the timeout in seconds before giving up and force quitting.")
        Tooltip(sldto,
                text=helptxt,
                wraplength=200)
        Tooltip(tboxto,
                text=helptxt,
                wraplength=200)
        logger.debug("Added timeout box for %s", self.command)

    def add_util_buttons(self):
        """ Add the section utility buttons """
        logger.debug("Add util buttons")
        utlframe = ttk.Frame(self)
        utlframe.pack(side=tk.RIGHT)

        config = get_config()
        for utl in ("load", "save", "clear", "reset"):
            logger.debug("Adding button: '%s'", utl)
            img = get_images().icons[utl]
            action_cls = config if utl in (("save", "load")) else config.cli_opts
            action = getattr(action_cls, utl)
            btnutl = ttk.Button(utlframe,
                                image=img,
                                command=lambda cmd=action: cmd(self.command))
            btnutl.pack(padx=2, side=tk.LEFT)
            Tooltip(btnutl,
                    text=utl.capitalize() + " " + self.title + " config",
                    wraplength=200)
        logger.debug("Added util buttons")


import pandas as pd
import numpy as np
from training.com import OpenDSSCOM
from training.tenv import FisrEnvironment
from production.penv import PFisrEnvironment
from production.tcp import OpenDSSG

ts_df = pd.read_feather('E:/pg_fisr/data/123_06022020_nsimulation/ieee123bus_terminal_states_2020-06-02.ftr')
term_states = ts_df.values.tolist()
com = OpenDSSCOM('E:/pg_fisr/data/models/IEEE_123_FLISR_Case/Master.DSS')
env = FisrEnvironment(com,[],[],[])

ss = []
for i,term in enumerate(term_states):
    env.failure = i
    aux = env.get_ss_from_state(term[0]).tolist()
    ss.append(aux)

ss = np.asarray(ss)

ss_df = pd.DataFrame(data=ss, columns=com.switches)
ss_df.to_feather('E:/term_states.ftr')

# -------------------------------------------
tcp = OpenDSSG()
aux = []
for i, sw in enumerate(tcp.switches):
    aux.append(ss_df[sw].tolist())
aux = np.asarray(aux).transpose()

penv = PFisrEnvironment([])
aux2 = aux.tolist()
terminal_states = []
for i, cs in enumerate(aux2):
    current_state = str(cs).strip('[]').replace(',', '').replace(' ', '')
    sspos = penv.switch_states_dict[current_state]
    terminal_states.append(i*penv.num_switch_states + sspos)

term_df = pd.DataFrame(data=terminal_states,columns= ['ts'])
term_df.to_feather('E:/term_states_dss2g.ftr')


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

# Solution 1, recursion
# The trick is to return two values, (depth, subtree node with deepest leaf nodes)
# Similar to LC 0687 Longest Univalue Path
class Solution:
    def dfs(self, node):
        if node is None:
            return 0, None
        L, R = self.dfs(node.left), self.dfs(node.right)

        if L[0] > R[0]:
            return L[0] + 1, L[1]
        if L[0] < R[0]:
            return R[0] + 1, R[1]

        return L[0] + 1, node

    def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
        _, res = self.dfs(root)

        return res

Algorithms/0865 Smallest Subtree with all the Deepest Nodes.py


from Sprites import Sprites
import pygame
from pygame.locals import *
import Maths
from traits import go,jump
from traits.go import goTrait
from traits.jump import jumpTrait
from Animation import Animation
from Collission_Detection import Collided,Collision
from Camera import Camera
from entities.EntityBase import EntityBase

class Mario(EntityBase):
    def __init__(self,x,y,level,screen,gravity=0.04):
        super(Mario,self).__init__(x,y,gravity)
        self.spriteCollection = Sprites().spriteCollection
        self.camera = Camera(self.pos)
        self.animation = Animation([
            self.spriteCollection["mario_run1"].image,
            self.spriteCollection["mario_run2"].image,
            self.spriteCollection["mario_run3"].image
        ],self.spriteCollection["mario_idle"].image)
        self.traits = {
            "jumpTrait":jumpTrait(self),
            "goTrait":goTrait(self.animation,screen,self.camera,self)
        }
        self.level = level.level
        self.levelObj = level
        self.collision = Collision(self,self.level,True)

    def drawMario(self):
        self.updateTraits()
        self.moveMario()

    def debug(self):
        print(self.pos.x, self.pos.y, self.vel.x, self.vel.y)

    def moveMario(self):
        self.pos.y += self.vel.y
        self.pos.x += self.vel.x
        #Camera Offset + Camera Move
        if self.pos.x > 10 and self.pos.x < 50:
            self.camera.pos.x = -self.pos.x+10
        self.collision.checkCollision()


# -*- coding: utf-8 -*-
"""
Created on Fri Apr  8 19:25:19 2022

@author: jhd9252

LeetCode Problem: 15. 3Sum
Test Cases: 318/318 tests cases passed
Runtime:  681 ms ( faster than 94.71% of Python3 submissions)
Memory Usage: 19.4 MB (less than 5.51% of Python3 online submissions for 3Sum)

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

Constraints:
   0 <= nums.length <= 3000
   -105 <= nums[i] <= 105
"""

# given an array of integers
# return all the triples [i,j,k] such that the sum [i,j,k] = 0
# i != j != k # indexes cannot be the same
# solution set must not contain duplicates
class Solution:
    def threeSum(self, nums):
        """

        # 315/318 test cases passed
        # time limit exceeded on test case 316
        # edge case that len(nums) < 3
        res = []
        if len(nums) < 3:
            return res
        # edge case that only zeroes. Where len(nums) >=3
        z = True
        for num in nums:
            if num != 0:
                z = False
                break
        if z:
            return [[0,0,0]]
        nums = sorted(nums)
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                target = 0 - nums[i] - nums[j]
                if target in nums:
                    k = nums.index(target)
                    if (i!=j) and (i!=k) and (k!=j):
                        if sorted([nums[i],nums[j],nums[k]]) not in res:
                            res.append(sorted([nums[i],nums[j],nums[k]]))
        return res
        """
        # create var = set() to cross ref solutions when we add them
        res = set()
        # edge case 1: where len(nums) <3 -> return res = []
        if len(nums) < 3:
            return res
        # set up rest of cases
        # partition set into negative integers, zeroes, positive integers for faster look up times
        n, z, p = [], [], []
        for num in nums:
            if num > 0: p.append(num)
            elif num < 0: n.append(num)
            else: z.append(num)
        N, P = set(n), set(p)
        # edge case 2: add (0,0,0) if len(z) >= 3
        if len(z) >= 3:
            res.add((0,0,0))
        # edge case 3: if there is at least 1 zero, check if there is a corresponding integer in negatives and positives
        # such that sum == 0
        if len(z) >= 1:
            for i in N:
                if -1*i in P:
                    res.add(tuple(sorted([i, 0, -1*i])))
        # edge case 4: check all pairs of negative integers, corresponding positive integer
        for i in range(len(n)):
            for j in range(i+1, len(n)):
                target = -1*(n[i]+n[j])
                if target in P:
                    res.add(tuple(sorted([n[i],n[j],target])))
        # edge case 5: check all pairs of positive integers, corresponding negative integer
        for i in range(len(p)):
            for j in range(i+1, len(p)):
                target = -1*(p[i]+p[j])
                if target in N:
                    res.add(tuple(sorted([p[i],p[j],target])))
        # at this point, our res set() contains all possible (0,0,0), (n, p, p) and (n,n,p) solutions
        # convert all tuples into lists, convert res to list, return
        return list(map(list, res))

#Input: nums = [-1,0,1,2,-1,-4]
#Output: [[-1,-1,2],[-1,0,1]]
alpha = Solution()
print(alpha.threeSum([-1,0,1,2,-1,-4]))
print(alpha.threeSum([]))
print(alpha.threeSum([0,0,0]))


from transformers import BertConfig, BertModel, BertTokenizer, AutoTokenizer, AutoModel

# Building the config,
# The configuration contains many attributes that are used to build the model
config = BertConfig()
print(config)
# Building the model from the config
# Model is randomly initialized!
model_0 = BertModel(config)

# Model is pretrained
model_1 = BertModel.from_pretrained("bert-base-cased")
# or model_1 = AutoModel.from_pretrained("bert-base-cased")

tokenizer = BertTokenizer.from_pretrained("bert-base-cased")
# Or tokenizer = AutoTokenizer("bert-base-cased")

sequence = "Using a Transformer network is simple"
tokens = tokenizer.tokenize(sequence)
print(tokens)

# Encoding tokens -> #s
ids = tokenizer.convert_tokens_to_ids(tokens)

print(ids)

# Decoding #s -> tokens
decoded_string = tokenizer.decode([7993, 170, 11303, 1200, 2443, 1110, 3014])
print(decoded_string)


def fillWithAT(grid, theRow, theCol, display, fileData):
    y = int(theRow)
    x = int(theCol)
    if(grid[y][x] == '-'):
        grid[y][x] = '@'
        if (display):
            for i in range (len(grid)):
                for j in range (len(grid[0])):
                    print (grid[i][j], end = ' ')
                print()
    try:
        fillWithAT( grid , y-1 , x , display)
        fillWithAT( grid , y+1 , x , display)
        fillWithAT( grid , x-1 , y , display)
        fillWithAT( grid , x+1 , y , display)
    except:
        print('ding')

def printMatrix(fileName):
    with open(fileName) as textFile:
        grid = [line.split() for line in textFile]
        for i in range (len(grid)):
            for j in range (len(grid[0])):
                print (grid[i][j], end = ' ')
            print()
        return grid
def printGreeting():
    print('This program will replace instances of "-" in a given file with the "@" symbol')
    print('along with the instaces of "-" surrounding the chosen instance')
    print('The file must contain only the characters "-" and "I" and must be rectangular')

def testCharacter(fileData):
    charlist = list()
    charList = set('-I')
    for i in (fileData):
        for char in i:
            if not (char in charList):
                print('false')
                return False
    return True

def testRectangle(fileData):
    n = fileData
    for i in n:
        if len(i) != len(n[0]):
            return False
    return True

def countRows (fileData):
    sum1 = len(fileData)
    print(sum1)
    return sum1

def countColumns (fileData):
    sum2 = len(fileData[0])
    print(sum2)
    return sum2

def getRow(fileName , fileData):
    flagrow = True
    rowcount = countRows(fileData)
    while (flagrow == True):
        theRow = int(input('Enter the row number: '))
        rowtest = testRow(theRow , rowcount)
        if (rowtest):
            flagrow = False
            return theRow
        else:
            flagrow = True

def testRow(theRow , rowcount):
    if ((theRow <= rowcount) and (theRow >= 0)):
        return True
    else:
        return False

def getCol(fileData):
    flagcolumn = True
    columncount = countColumns(fileData)
    while (flagcolumn == True):
        theCol = int(input('Enter the column number: '))
        coltest = testRow(theCol , columncount)
        if (coltest):
            flagcolumn = False
            return theCol
        else:
            flagcolumn = True

def testCol(theCol , columncount):
    if ((theCol <= columncount) and (theCol >= 0)):
        return True
    else:
        return False
def requestStep():
    displaychoice = input('Print out step by step? Enter yes: ')
    displaychoice = displaychoice.lower()
    if (displaychoice == 'yes'):
        return True
    else:
        return False

def main():
    flagmain = True
    printGreeting()
    fileData = list()
    while (flagmain == True):
        try:
            fileName = input('Enter the name of your file: ')
            infile = open(fileName , 'r')
            for line in infile:
                fileData.extend(line.strip().split('\n'))
            bool1 = testCharacter(fileData)
            bool2 = testRectangle(fileData)
            if ((bool1 == True) and (bool2 == True)):
                grid = printMatrix(fileName)
                flagmain = False
            elif (bool1 == False):
                print('Your input has a character other than "-" and "I"')
                fileData = list()
            elif (bool2 == False):
                print('Your input was not rectangular')
                fileData = list()
            else:
                flagmain = True
                fileData = list()
        except:
            flagmain = True
            fileData = list()
    theRow = getRow(fileName , fileData)
    theCol = getCol(fileData)
    display = requestStep()
    fillWithAT(grid, theRow, theCol, display, fileData)
    continueChoice = input('Go again? Enter yes: ')
main()


"""
780. Reaching Points
https://leetcode.com/problems/reaching-points/description/
"""

class Solution:
    def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:
        while sx < tx and sy < ty:
            if tx < ty:
                ty %= tx
            else:
                tx %= ty

        if sx == tx and sy <= ty and (ty - sy) % sx == 0:
            return True

        return sy == ty and sx <= tx and (tx - sx) % sy == 0


from . import addon_updater_ops
from . import mdr_prefs

bl_info = {
    "name": "MD Retopology",
    "author": "Elias Schwarze",
    "description": "A suite of tools for retopologizing Marvelous Designer garments in Blender",
    "blender": (3, 6, 0),
    "version": (0, 1, 0),
    "location": "3D Viewport > Properties panel (N) > MD Retopo Tab",
    "category": "Object"
}

classes = (mdr_prefs,
           )

def register():

    addon_updater_ops.register(bl_info)

    for c in classes:
        c.register()

def unregister():

    for c in reversed(classes):
        c.unregister()

    addon_updater_ops.unregister()


import sys
import logging
from typing import List
import boto3
import json
import os
from aws_orbit import sh
from aws_orbit.services import s3
from aws_orbit import ORBIT_CLI_ROOT

_logger: logging.Logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
# Helper function to download the demo data from public sites.
# Usage - python download_demo_data.py dev_env

def _download_demo_data(bucket_name: str, bucket_key_prefix: str, download_files: List[str]) -> None:
    # Verify existence of demo data, conditionally download the demo data and upload to toolkit bucket.
    # Prepare file names list
    download_file_names = [fname.split("/")[-1] for fname in download_files]
    # Find list of objects in S3 path
    response = s3.list_s3_objects(bucket_name, bucket_key_prefix)
    s3_data_files = []
    if "Contents" in response.keys():
        for obj in response["Contents"]:
            file_name = obj["Key"].split("/")[-1]
            if file_name:
                s3_data_files.append(file_name)
    _logger.info(f"data_files={s3_data_files}")
    # Check if required files are matching
    files_to_download = set(download_file_names) - set(s3_data_files)
    if files_to_download:
        downloaded_files = []
        remote_dir = os.path.join(os.getcwd(), "data")
        # Download specific files and upload to S3 bucket path
        for fp in download_files:
            file_name = fp.split("/")[-1]
            if file_name in files_to_download:
                sh.run(f"wget {fp} -P {remote_dir} -q")
                downloaded_files.append(fp)
                # Uploading to S3 data files path
                remote_src_file = os.path.join(remote_dir, file_name)
                s3_key_prefix = f"{bucket_key_prefix}{file_name}"
                _logger.info(f"uploading {remote_src_file} to s3 {bucket_name}/{s3_key_prefix}")
                s3.upload_file(remote_src_file, bucket_name, s3_key_prefix)
        _logger.info(f"Downloaded CSM data from {downloaded_files}")
    else:
        # Verify the S3 path
        _logger.info("Data files are up to date. No need to download")
        response = s3.list_s3_objects(bucket_name, bucket_key_prefix)
        if "Contents" in response.keys():
            for obj in response["Contents"]:
                _logger.debug(obj["Key"])

def _prepare_demo_data(bucket_name) -> None:
    _logger.debug("Adding CMS data sets")
    cms_files: List[str] = [
        "https://www.cms.gov/Research-Statistics-Data-and-Systems/Downloadable-Public-Use-Files/SynPUFs/Downloads/DE1_0_2008_Beneficiary_Summary_File_Sample_1.zip",  # noqa
        "http://downloads.cms.gov/files/DE1_0_2008_to_2010_Carrier_Claims_Sample_1A.zip",
        "http://downloads.cms.gov/files/DE1_0_2008_to_2010_Carrier_Claims_Sample_1B.zip",
        "https://www.cms.gov/Research-Statistics-Data-and-Systems/Downloadable-Public-Use-Files/SynPUFs/Downloads/DE1_0_2008_to_2010_Inpatient_Claims_Sample_1.zip",  # noqa
        "https://www.cms.gov/Research-Statistics-Data-and-Systems/Downloadable-Public-Use-Files/SynPUFs/Downloads/DE1_0_2008_to_2010_Outpatient_Claims_Sample_1.zip",  # noqa
        "http://downloads.cms.gov/files/DE1_0_2008_to_2010_Prescription_Drug_Events_Sample_1.zip",
        "https://www.cms.gov/Research-Statistics-Data-and-Systems/Downloadable-Public-Use-Files/SynPUFs/Downloads/DE1_0_2009_Beneficiary_Summary_File_Sample_1.zip",  # noqa
        "https://www.cms.gov/Research-Statistics-Data-and-Systems/Statistics-Trends-and-Reports/SynPUFs/Downloads/DE1_0_2010_Beneficiary_Summary_File_Sample_20.zip",  # noqa
    ]
    _download_demo_data(bucket_name=bucket_name, bucket_key_prefix="landing/data/cms/", download_files=cms_files)
    _logger.debug("Adding SageMaker regression notebooks data sets")
    sagemaker_files: List[str] = [
        "https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data",
        "https://github.com/mnielsen/neural-networks-and-deep-learning/raw/master/data/mnist.pkl.gz",
    ]
    _download_demo_data(bucket_name=bucket_name, bucket_key_prefix="landing/data/sagemaker/", download_files=sagemaker_files)
    _logger.debug("Adding CSM schema files")
    cms_schema_files = os.path.join(ORBIT_CLI_ROOT, "data", "cms", "schema")
    schema_key_prefix = "landing/cms/schema/"
    sh.run(f"aws s3 cp --recursive {cms_schema_files} s3://{bucket_name}/{schema_key_prefix}")

def main() -> None:
    _logger.debug("sys.argv: %s", sys.argv)
    if len(sys.argv) == 2:
        env_name = sys.argv[1]
    else:
        raise ValueError("Orbit environment name required")
        sys.exit(1)
    try:
        ssm = boto3.client('ssm')
        demo_config = json.loads(ssm.get_parameter(Name=f"/orbit/{env_name}/demo")['Parameter']['Value'])
        lake_bucket = demo_config.get("LakeBucket").split(':::')[1]
        _logger.info(f"Using Lake Bucket {lake_bucket}")
        _prepare_demo_data(lake_bucket)
    except Exception as ex:
        error = ex.response["Error"]
        _logger.error("Invalid environment %s. Cause: %s", env_name, error)
        sys.exit(1)

if __name__ == "__main__":
    main()


import socket
from time import ctime

HOST = "0.0.0.0" #"localhost"
PORT = 12345
BUFSIZE = 1024
ADDR = (HOST,PORT)

server_sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
server_sock.bind(ADDR)

server_sock.listen(5)

server_sock.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )

try:

    while True:
        print("Server waiting for connection ...")

        client_sock, addr = server_sock.accept()
        print("Client connected from: ", addr)

        while True:
            data = client_sock.recv(BUFSIZE)
            if not data or data.decode("utf-8") == "END":
                print("No data or receiving \"END\"")
                print("I will not do nothing")
                break

            print("Received from client: %s" % data.decode("utf-8"))

            timenow = ctime()
            print("Sending server time to client")
            client_sock.send( bytes(timenow,"utf-8") )

        client_sock.close()
        #
except KeyboardInterrupt:
    print()
    print("----------------------------------")
    print("Server is shutdown by user request")
    print("----------------------------------")

server_sock.close()


# -*- coding: utf-8 -*-
import scrapy
from urllib import parse
from lagou.items import LagouItem
import json
import time

class CodeSpider(scrapy.Spider):
    name = 'code'
    allowed_domains = ['www.lagou.com']

    def parse(self, response):
        result = json.loads(response.text)
        if result.get("content"):
        # print(result)
            results = result["content"]["positionResult"]["result"]
            for id in results:
                item = LagouItem()
                item['city'] = id.get("city")
                item['companyFullName'] = id.get("companyFullName")
                item['companyLabelList'] = id.get("companyLabelList")
                item['companySize'] = id.get("companySize")
                item['createTime'] = id.get("createTime")
                item['district'] = id.get("district")
                item['education'] = id.get("education")
                item['financeStage'] = id.get("financeStage")
                item['firstType'] = id.get("firstType")
                item['formatCreateTime'] = id.get("formatCreateTime")
                item['industryLables'] = id.get("industryLables")
                item['jobNature'] = id.get("jobNature")
                item['lastLogin'] = id.get("lastLogin")
                item['linestaion'] = id.get("linestaion")
                item['positionAdvantage'] = id.get("positionAdvantage")
                item['positionName'] = id.get("positionName")
                item['salary'] = id.get("salary")
                item['workYear'] = id.get("workYear")
                item['url'] = "https://www.lagou.com/jobs/%s.html" % id.get("positionId")
                yield item
        else:
            pass

    def parse_html(self):
        pass

    def start_requests(self):

        base_url = 'https://www.lagou.com/jobs/positionAjax.json?'

        data = {
            "city": "北京",
            "needAddtionalResult":"false"
        }
        url = base_url + parse.urlencode(data)

        for page in range(1,31):
            body = {
                "first": "false",
                "pn": str(page),
                "kd": "python爬虫"
            }

            yield scrapy.FormRequest(url,method="POST",formdata=body,callback=self.parse)


import os
import glob

def traverse_dir(
        root_dir,
        extension=('mid', 'MID', 'midi', 'pkl', 'npy'),
        amount=None,
        str_=None,
        is_pure=False,
        verbose=False,
        is_sort=False,
        is_ext=True):
    if verbose:
        print('[*] Scanning...')
    file_list = []
    cnt = 0
    for root, _, files in os.walk(root_dir):
        for file in files:
            if file.endswith(extension):
                if (amount is not None) and (cnt == amount):
                    break
                if str_ is not None:
                    if str_ not in file:
                        continue
                mix_path = os.path.join(root, file)
                pure_path = mix_path[len(root_dir)+1:] if is_pure else mix_path
                if not is_ext:
                    ext = pure_path.split('.')[-1]
                    pure_path = pure_path[:-(len(ext)+1)]
                if verbose:
                    print(pure_path)
                file_list.append(pure_path)
                cnt += 1
    if verbose:
        print('Total: %d files' % len(file_list))
        print('Done!!!')
    if is_sort:
        file_list.sort()
    return file_list

if __name__ == '__main__':
    root_dir = "/Users/wayne391/Documents/Projects/mt-new/flickinger/dataset/representations/uncond/cp/ailab17k_from-scratch_cp/events"
    filelist = traverse_dir(root_dir)
    filelist.sort()

    for idx, f in enumerate(filelist):
        print(f'{idx}-------------')
        print(f)

        bn = os.path.basename(f)
        path_dir = f[:-len(bn)]
        ext = bn.split('.')[-1]

        outname = os.path.join(path_dir, f'{idx}.{ext}')
        print(outname)
        os.rename(f, outname)


from collections import defaultdict, Counter

EXAMPLES1 = (
    ('12-exemple1.txt', 10),
    ('12-exemple2.txt', 19),
    ('12-exemple3.txt', 226),
)

EXAMPLES2 = (
    ('12-exemple1.txt', 36),
    ('12-exemple2.txt', 103),
    ('12-exemple3.txt', 3509),
)

INPUT =  '12.txt'

def read_data(fn):
    data = defaultdict(list)
    with open(fn) as f:
        for line in f:
            x, y = line.strip().split('-')
            data[x].append(y)
            data[y].append(x)
    return data

def possible1(node, path):
    if node == node.upper():
        return True
    else:
        return node not in path

def possible2(node, path):
    if node == node.upper():
        return True
    elif node in ('start', 'end') and node in path:
        return False
    elif node not in path:
        return True
    else:
        counter = Counter([x for x in path if x.lower() == x])
        return 2 not in counter.values()

def search(data, possible):
    paths = list()
    paths.append(['start'])
    finished = list()
    while paths:
        path0 = paths.pop()
        for node in data[path0[-1]]:
            path = path0[:]
            if not possible(node, path):
                pass
            else:
                path.append(node)
                if node == 'end':
                    finished.append(path)
                else:
                    paths.append(path)
    return len(finished)

def code1(data):
    return search(data, possible1)

def code2(data):
    return search(data, possible2)

def test(n, code, examples, myinput):
    for fn, expected in examples:
        data = read_data(fn)
        result = code(data)
        assert expected is None or result == expected, (data, expected, result)

    print(f'{n}>', code(read_data(myinput)))

test(1, code1, EXAMPLES1, INPUT)
test(2, code2, EXAMPLES2, INPUT)


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

from collections import deque
from typing import List

class Solution:
    def canReach(self, arr: List[int], start: int) -> bool:
        frontier = deque([start])
        while frontier:
            current = frontier.pop()
            if 0 <= current < len(arr) and arr[current] >= 0:
                arr[current] = -arr[current]
                if arr[current] == 0:
                    return True
                frontier.append(current + arr[current])
                frontier.append(current - arr[current])
        return False

if __name__ == "__main__":
    solution = Solution()

    assert solution.canReach([4, 2, 3, 0, 3, 1, 2], 5)
    assert solution.canReach([4, 2, 3, 0, 3, 1, 2], 0)
    assert not solution.canReach([3, 0, 2, 1, 2], 2)


import RPi.GPIO as GPIO
import time

def main():
    dac = [26, 19, 13, 6, 5,11, 9, 10]

    GPIO.cleanup()
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(dac, GPIO.OUT)

    while True:
        try:
            GPIO.setmode(GPIO.BCM)
            GPIO.setup(dac, GPIO.OUT)
            value = input("Put number: ")

            if value == "q":
                print("finish")
                break

            value = float(value)
            if 0 != (float(value) - int(value)):
                print("Число не целое")
                exit(0)

            value = int(value)

            if value < 0:
                print("Отрицательное")
                exit(0)

            if value > 255:
                print("Превышает")
                exit(0)

            print("Напряжение будет", (value / 255* 3.3))
            binary = to_binary(value)
            for el in binary:
                print(el)
            GPIO.output(dac, binary)
            time.sleep(4)
        except ValueError:
            print("Это не число")
        finally:
            GPIO.output(dac, 0)
            GPIO.cleanup()

def to_binary(value):
    return [int(element) for element in bin(value)[2:].zfill(8)]

main()


from algorithms.common.runner import run
from run_ddpg import agent_params

env_name = 'scenario_3'
exp_name = 's3_preplan'
perfect_channel = False

action_dir = 'experiments/' + exp_name + '/model/planned_actions.mat'
agent_params['action_dir'] = action_dir

# Optimize
try:
    import matlab.engine
except ImportError:
    print('MATLAB engine not installed. Make sure to run optimization in MATLAB first')
else:
    eng = matlab.engine.start_matlab()
    eng.cd('matlab/optimize')
    if perfect_channel:
        eng.opt_perfect(env_name, exp_name, nargout=0)
    else:
        eng.opt_predicted(env_name, exp_name, nargout=0)

# Run experiment
if perfect_channel:
    algorithm_name = 'perfect'
else:
    algorithm_name = 'preplan'
run(algorithm_name, exp_name, env_name, agent_params, train_params=None, use_ray=False, use_gpu=False,
    is_train=False, num_runs=0, test_run_id=[0], test_model_id=[0])


import random
print("This is a Number Guessing Game")
num=random.randint(1,9)
chances=0
print("Guess a number between 1-9")
while chances<5:
    guess=int(input("enter your guess :"))
    if guess==num:
        print ("You guessed correctly!")
        break
    elif guess<num:
        print ("Your guess is too low")
    else:
        print ("your guess it too high")
    chances+=1
if chances>=5:
    print("You lose")


import numpy
import matplotlib.pylab as plt

matrix = numpy.loadtxt("matrix")
matrix_magnify=numpy.zeros((matrix.shape[0]*10,matrix.shape[1]))
for i in range(matrix.shape[0]):
    for j in range(10):
        matrix_magnify[i*10+j,:]=matrix[i,:]
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
plt.imshow(matrix_magnify, interpolation='nearest', cmap=plt.cm.Blues)
plt.colorbar()
plt.show()


from tensorflow import keras
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import numpy as np
import ywcho.models as yw

""" load mnist datasets """
# load datasets #####################################
(train_input, train_target), (test_input, test_target) = keras.datasets.mnist.load_data()

# check shape #####################################
# print(train_input.shape, train_target.shape)    # (60000, 28, 28) (60000,)

# show 10 input #####################################
# fig, axs = plt.subplots(1,10, figsize = (10,1))
# for i in range(10):
#     axs[i].imshow(train_input[i],cmap='gray_r')
#     axs[i].axis('off')
# plt.show()

# print 10 target   #####################################
# print([train_target[i] for i in range(10)])     # [5, 0, 4, 1, 9, 2, 1, 3, 1, 4]

# 레이블 당 샘플 개수 확인    #####################################
# print(np.unique(train_target, return_counts=True))

""" datasets preprocessing """
# scale #####################################
train_scaled = train_input.reshape(-1,28,28,1) / 255.0

# train_test_split
train_scaled, val_scaled, train_target, val_target = train_test_split(train_scaled, train_target, test_size=0.2)
print(train_scaled.shape, train_target.shape)
""" Convolution Neural Network """
# make model    #####################################
model = yw.cnn_sequential(output=10)
# model = keras.Sequential()
# model.add(keras.layers.Conv2D(32, kernel_size=3, padding='same', activation='relu',input_shape=(28,28,1)))
# model.add(keras.layers.MaxPooling2D(2))
# model.add(keras.layers.Conv2D(64,kernel_size=(3,3),padding='same', activation='relu'))
# model.add(keras.layers.MaxPooling2D(2))
# model.add(keras.layers.Flatten())
# model.add(keras.layers.Dense(100,activation='relu'))
# model.add(keras.layers.Dropout(0.4))
# model.add(keras.layers.Dense(10, activation='softmax'))

# summary   #####################################
model.summary()

# plot_model    #####################################
# keras.utils.plot_model(model)
keras.utils.plot_model(model,show_shapes=True,to_file='cnn-architecture.png',dpi=100)

""" 모델 컴파일과 훈련 """
# compile   #####################################
model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics='accuracy')

# train & save model, history   #####################################
checkpoint_cb = keras.callbacks.ModelCheckpoint('best-cnn-model.h5', save_best_only=True)
early_stopping_cb = keras.callbacks.EarlyStopping(patience=2, restore_best_weights=True)
history = model.fit(train_scaled, train_target, epochs=20, validation_data=(val_scaled, val_target), callbacks=[checkpoint_cb,early_stopping_cb])
np.save('my_history.npy',history.history)

# load model and history    #####################################
# model = keras.models.load_model('best-cnn-model.h5')
# history=np.load('my_history.npy',allow_pickle='TRUE').item()

# loss graph    #####################################
# plt.plot(history['loss'])           # model.fit 메서드에서 반환된 history는 history.history로 접근해야한다.
# plt.plot(history['val_loss'])       # also
# plt.xlabel('eopchs')
# plt.ylabel('loss')
# plt.legend(['train', 'validation'])
# plt.show()

# evaluate  #####################################
model.evaluate(val_scaled, val_target)
plt.imshow(val_scaled[0].reshape(28,28),cmap='gray_r')
plt.show()

preds = model.predict(val_scaled[0:1])
print(preds)

plt.bar(range(0,10),preds[0])
plt.xlabel('class')
plt.ylabel('prob.')
plt.show()

classes = range(0,10)
print(classes[np.argmax(preds)])

""" final test """
test_scaled = test_input.reshape(-1,28,28,1) / 255.0
model.evaluate(test_scaled, test_target)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 29 17:26:43 2020

@author: ljia

This script groups results together into a single file for the sake of faster
searching and loading.
"""
import os
import pickle
import numpy as np
from shutil import copyfile
from tqdm import tqdm
import sys

def check_group_existence(file_name):
	path, name = os.path.split(file_name)
	marker_fn = os.path.join(path, 'group_names_finished.pkl')
	if os.path.isfile(marker_fn):
		with open(marker_fn, 'rb') as f:
			fns = pickle.load(f)
			if name in fns:
				return True

	if os.path.isfile(file_name):
		return True

	return False

def update_group_marker(file_name):
	# @todo: possible error when seveal tasks are using this file at the same time.
	path, name = os.path.split(file_name)
	marker_fn = os.path.join(path, 'group_names_finished.pkl')
	if os.path.isfile(marker_fn):
		with open(marker_fn, 'rb') as f:
			fns = pickle.load(f)
			if name in fns:
				return
			else:
				fns.add(name)
	else:
		fns = set({name})
	with open(marker_fn, 'wb') as f:
		pickle.dump(fns, f)

def create_group_marker_file(dir_folder, overwrite=True):
	if not overwrite:
		return

	fns = set()
	for file in sorted(os.listdir(dir_folder)):
		if os.path.isfile(os.path.join(dir_folder, file)):
			if file.endswith('.npy'):
				fns.add(file)

	marker_fn = os.path.join(dir_folder, 'group_names_finished.pkl')
	with open(marker_fn, 'wb') as f:
		pickle.dump(fns, f)

# This function is used by other scripts. Modify it carefully.
def group_trials(dir_folder, name_prefix, overwrite, clear, backup, num_trials=100):

	# Get group name.
	label_name = name_prefix.split('.')[0]
	if label_name == 'ged_matrix':
		group_label = 'ged_mats'
	elif label_name == 'runtime':
		group_label = 'runtimes'
	else:
		group_label = label_name
	name_suffix = name_prefix[len(label_name):]
	if label_name == 'ged_matrix':
		name_group = dir_folder + 'groups/' + group_label + name_suffix + 'npy'
	else:
		name_group = dir_folder + 'groups/' + group_label + name_suffix + 'pkl'

	if not overwrite and os.path.isfile(name_group):
		# Check if all trial files exist.
		trials_complete = True
		for trial in range(1, num_trials + 1):
			file_name = dir_folder + name_prefix + 'trial_' + str(trial) + '.pkl'
			if not os.path.isfile(file_name):
				trials_complete = False
				break
	else:
		# Get data.
		data_group = []
		for trial in range(1, num_trials + 1):
			file_name = dir_folder + name_prefix + 'trial_' + str(trial) + '.pkl'
			if os.path.isfile(file_name):
				with open(file_name, 'rb') as f:
					try:
						data = pickle.load(f)
					except EOFError:
						print('EOF Error occurred.')
						return
					data_group.append(data)

# 					unpickler = pickle.Unpickler(f)
# 					data = unpickler.load()
# 					if not isinstance(data, np.array):
# 						return
# 					else:
# 						data_group.append(data)

			else: # Not all trials are completed.
				return

		# Write groups.
		if label_name == 'ged_matrix':
			data_group = np.array(data_group)
			with open(name_group, 'wb') as f:
				np.save(f, data_group)
		else:
			with open(name_group, 'wb') as f:
				pickle.dump(data_group, f)

		trials_complete = True

	if trials_complete:
		# Backup.
		if backup:
			for trial in range(1, num_trials + 1):
				src = dir_folder + name_prefix + 'trial_' + str(trial) + '.pkl'
				dst = dir_folder + 'backups/' + name_prefix + 'trial_' + str(trial) + '.pkl'
				copyfile(src, dst)

		# Clear.
		if clear:
			for trial in range(1, num_trials + 1):
				src = dir_folder + name_prefix + 'trial_' + str(trial) + '.pkl'
				os.remove(src)

def group_all_in_folder(dir_folder, overwrite=False, clear=True, backup=True):

	# Create folders.
	os.makedirs(dir_folder + 'groups/', exist_ok=True)
	if backup:
		os.makedirs(dir_folder + 'backups', exist_ok=True)

	# Iterate all files.
	cur_file_prefix = ''
	for file in tqdm(sorted(os.listdir(dir_folder)), desc='Grouping', file=sys.stdout):
		if os.path.isfile(os.path.join(dir_folder, file)):
			name_prefix = file.split('trial_')[0]
# 			print(name)
# 			print(name_prefix)
			if name_prefix != cur_file_prefix:
				group_trials(dir_folder, name_prefix, overwrite, clear, backup)
				cur_file_prefix = name_prefix

if __name__ == '__main__':
 	# dir_folder = 'outputs/CRIANN/edit_costs.num_sols.ratios.IPFP/'
 	# group_all_in_folder(dir_folder)

 	# dir_folder = 'outputs/CRIANN/edit_costs.repeats.ratios.IPFP/'
 	# group_all_in_folder(dir_folder)

 	# dir_folder = 'outputs/CRIANN/edit_costs.max_num_sols.ratios.bipartite/'
 	# group_all_in_folder(dir_folder)

 	# dir_folder = 'outputs/CRIANN/edit_costs.repeats.ratios.bipartite/'
 	# group_all_in_folder(dir_folder)

	dir_folder = 'outputs/CRIANN/edit_costs.real_data.num_sols.ratios.IPFP/groups/'
	create_group_marker_file(dir_folder)


import pygame
import sys

pygame.init()

#Tela
tamanho = comprimento, altura = 600, 600
janela = pygame.display.set_mode(tamanho)

#imagens
xis = pygame.image.load("xis.png")
bola = pygame.image.load("bola2.png")

xis = pygame.transform.scale(xis, (100,100))
bola = pygame.transform.scale(bola,(100,100))

# Cores De Fundo
preto = 0, 0, 0
branco = 255, 255, 255
vermelho = 255, 0, 0
verde = 0, 255, 0
azul = 0, 0, 255
ciano = 27, 242, 213
rosa = 203, 7, 118
roxo = 158, 151, 255

cores = [preto, branco, vermelho, verde, azul, ciano, rosa, roxo]

vencedorUM = ""
vez = 'X'
rodada = 0

jogo = [
    ['_', '_', '_'],
    ['_', '_', '_'],
    ['_', '_', '_'], ]

# quadrantes
quadrante_linha = [50 , 250, 450]
quadrante_coluna = [50, 250, 450]

#Preenche a janela (0.Preto - 1.branco - 2.vermelho - 3.verde - 4.azul - 5.ciano - 6.rosa - 7.roxo)
janela.fill(cores[5])

#Desenha o jogo da velha
def desenha_quadro():
    pygame.draw.line(janela, preto, (200,0),(200,600),10)
    pygame.draw.line(janela, preto, (400,0),(400,600),10)
    pygame.draw.line(janela, preto, (0,200),(600,200),10)
    pygame.draw.line(janela, preto, (0,400),(600,400),10)

# Inserir imagem X ou O
def faz_jogada_bola(pos):
    index_linha = int(pos[0]/200)
    index_coluna = int(pos[1]/200)

    if (jogo[index_coluna][index_linha] == '_'):
        janela.blit(bola,(quadrante_linha[index_linha], quadrante_coluna[index_coluna]))
        jogo[index_coluna][index_linha] = 'O'
        return True
    else:
        print('Essa Posição ja esta ocupada!!!!')
        return False

def faz_jogada_xis(pos):
    index_linha = int(pos[0]/200)
    index_coluna = int(pos[1]/200)

    if (jogo[index_coluna][index_linha] == '_'):
        janela.blit(xis,(quadrante_linha[index_linha], quadrante_coluna[index_coluna]))
        jogo[index_coluna][index_linha] = 'X'
        return True

    else:
        print('Essa Posição já esta ocupada!!!!')
        return False

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #

def ganhou1():
    vencedor = ''

    # Verifica Linhas
    if (jogo[0][0]== "X") and (jogo[0][1]== "X") and (jogo[0][2]== "X"):
        print ("JOGADOR X GANHOU!!!")
        pygame.draw.line(janela, preto,(0,100), [600,100], 10)
        vencedor = 'X'
    if (jogo[1][0] == "X") and (jogo[1][1]== "X") and (jogo[1][2] == "X"):
        print ("JOGADOR X GANHOU!!!")
        pygame.draw.line(janela, preto, (0, 300), (600, 300), 5)
        vencedor = 'X'
    if (jogo[2][0] == "X") and (jogo[2][1] == "X") and(jogo[2][2] == "X"):
        print ("JOGADOR X GANHOU!!!")

        pygame.draw.line(janela, preto, (0, 500), (600, 500), 5)
        vencedor = 'X'

    # Verifica Coluna
    if (jogo[0][0] == "X") and (jogo[1][0] == "X") and(jogo[2][0] == "X"):
        print ("JOGADOR X GANHOU!!!")
        pygame.draw.line(janela, preto, (100, 0), (100, 600), 5)
        vencedor = 'X'
    if (jogo[0][1] == "X") and (jogo[1][1] == "X") and(jogo[2][1] == "X"):
        print ("JOGADOR X GANHOU!!!")
        pygame.draw.line(janela, preto, (300, 0), (300, 600), 5)
        vencedor = 'X'
    if (jogo[0][2] == "X") and (jogo[1][2] == "X") and(jogo[2][2] == "X"):
        print ("JOGADOR X GANHOU!!!")
        pygame.draw.line(janela, preto, (500, 0), (500, 600), 5)
        vencedor = 'X'

    # Verifica Diagonal
    if (jogo[0][0] == "X") and (jogo[1][1] == "X") and (jogo[2][2] == "X"):
        print ("JOGADOR X GANHOU!!!")
        pygame.draw.line(janela, preto, (0, 0), (600, 600), 5)
        vencedor = 'X'
    if (jogo[0][2] == "X") and (jogo[1][1] == "X") and (jogo[2][0] == "X"):
        print ("JOGADOR X GANHOU!!!")
        pygame.draw.line(janela, preto, (0, 600), (600, 0), 5)
        vencedor = 'X'
    return vencedor

def ganhou2():
    vencedor = ''
    if (jogo[0][0]== "O") and (jogo[0][1]== "O") and (jogo[0][2]== "O"):
        print ("JOGADOR O GANHOU!!!")
        pygame.draw.line(janela, preto,(0,100), [600,100], 10)
        vencedor = 'O'
    if (jogo[1][0] == "O") and (jogo[1][1]== "O") and (jogo[1][2] == "O"):
        print ("JOGADOR O GANHOU!!!")
        pygame.draw.line(janela, preto, (0, 300), (600, 300), 5)
        vencedor = 'O'
    if (jogo[2][0] == "O") and (jogo[2][1] == "O") and(jogo[2][2] == "O"):
        print ("JOGADOR O GANHOU!!!")
        pygame.draw.line(janela, preto, (0, 500), (600, 500), 5)
        vencedor = 'O'

    # Verifica Coluna
    if (jogo[0][0] == "O") and (jogo[1][0] == "O") and(jogo[2][0] == "O"):
        print ("JOGADOR O GANHOU!!!")
        pygame.draw.line(janela, preto, (100, 0), (100, 600), 5)
        vencedor = 'O'
    if (jogo[0][1] == "O") and (jogo[1][1] == "O") and(jogo[2][1] == "O"):
        print ("JOGADOR O GANHOU!!!")
        pygame.draw.line(janela, preto, (300, 0), (300, 600), 5)
        vencedor = 'O'
    if (jogo[0][2] == "O") and (jogo[1][2] == "O") and(jogo[2][2] == "O"):
        print ("JOGADOR O GANHOU!!!")
        pygame.draw.line(janela, preto, (500, 0), (500, 600), 5)
        vencedor = 'O'

    # Verifica Diagonal
    if (jogo[0][0] == "O") and (jogo[1][1] == "O") and (jogo[2][2] == "O"):
        print ("JOGADOR O GANHOU!!!")
        pygame.draw.line(janela, preto, (0, 0), (600, 600), 5)
        vencedor = 'O'
    if (jogo[0][2] == "O") and (jogo[1][1] == "O") and (jogo[2][0] == "O"):
        print ("JOGADOR O GANHOU!!!")
        pygame.draw.line(janela, preto, (0, 600), (600, 0), 5)
        vencedor = 'O'
    return vencedor

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #
while True:
    desenha_quadro()
    #Verifica eventos na janela do jogo
    for event in pygame.event.get():
        # fechar a janela e o jogo é encerrado
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            click_pos = pygame.mouse.get_pos()

            if (vez=='X'):
                print("Vez de X")
                fez_jogada = faz_jogada_xis(click_pos)
                vencedorUM = ganhou1()
                if (fez_jogada == True):
                        vez='O'
                        rodada = rodada + 1
                elif (fez_jogada == False):
                    vez = 'X'

            elif (vez=='O'):
                print("Vez de O")
                fez_jogada = faz_jogada_bola(click_pos)
                vencedorUM = ganhou2()
                if (fez_jogada == True):
                    vez = 'X'
                    rodada = rodada + 1
                elif (fez_jogada == False):
                    vez = 'O'

    pygame.display.flip() #Atualiza a janela

    if (rodada>=9) or (vencedorUM !=''):
        print ('Jogo Finalizado!')
        print(jogo)
        break


import sys, re

read_regex = re.compile(r'^#\d+] .*?\+(.*): R \[\+(.*?) - .*?\) - (.*) bytes$')
write_regex = re.compile(r'^#\d+] .*?\+(.*): W \[\+(.*?)\] = (.*)  \(\d+ values\)')

class Gadget(object):

    def __init__(self, ip):
      self.ip=ip

    def __hash__(self):
        return self.ip

class ReadGadget(Gadget):

    def __init__(self, ip):
        super().__init__(ip)
        self.reads = {}

    def update(self, offset, size):
        assert offset not in self.reads
        self.reads[offset] = size

    def __repr__(self):
        return f'{self.ip:X} READ:'+'\n'.join(f'\t{offset:X} - {offset+size:X}' for offset, size in self.reads.items())

class WriteGadget(Gadget):

    def __init__(self, ip):
        super().__init__(ip)
        self.writes = {}

    def update(self, offset, values):
        self.writes.setdefault(offset, []).extend(values)

    def __repr__(self):
        ret = f'{self.ip:X} WRITE: {len(self.writes)} ' + ('values\n' if len(self.writes)>1 else 'value\n')
        ret += '\n'.join(f'\t{offset:X}: [' + ', '.join(f'{val:X}' for val in values) + ']' \
                    for offset, values in self.writes.items())
        return ret

class Importer(object):

  def __init__(self, filename):
    self.filename = filename

  def loadDB(self):
    gadgets = {}
    with open(self.filename, 'r') as f:
        for line in f.readlines():
            m = read_regex.match(line)
            if m:
                ip = int(m.group(1), 16)
                gadgets.setdefault(ip, ReadGadget(ip)).update(int(m.group(2), 16), int(m.group(3), 16))
            else:
                m = write_regex.match(line)
                if m:
                    ip = int(m.group(1), 16)
                    values = [int(v, 16) for v in m.group(3).split()]
                    gadgets.setdefault(ip, WriteGadget(ip)).update(int(m.group(2), 16), values)
    return gadgets

if __name__ == '__main__':
    imp = Importer(sys.argv[1])
    gadgets = imp.loadDB()
    for g in gadgets.values():
        print(g)


import matplotlib.pyplot as plt
import cmath
from math import sqrt

fig = plt.figure()

def f(x):
    y = x  # можно подставить любую функцию
    return y.real, y.imag

i = -10
a = 0
ax = fig.add_subplot(projection='3d')
ax.set_xlabel('$X$', fontsize=20)
ax.set_ylabel('$Y$')
ax.set_zlabel('$Z$')
while (i < 10):
    x = []
    y = []
    z = []
    x1 = -10
    x2 = []
    y2 = []
    z2 = []
    while x1 < 10:
        if x1 == 0 and i == 0:
            x1 += 0.05
            continue
        y1, z1 = f(complex(x1, i))
        x.append(x1)
        y.append(y1)
        z.append(z1)
        x2.append(0)
        y2.append(0)
        z2.append(0)
        x1 += 0.05
    a += 20
    ax.plot(x, y, z)
    plt.draw()
    plt.pause(0.00000000001)
    i += 0.05
plt.pause(100000)


from socket import *
from urllib.parse import urlparse

class HttpCliente:

    def __init__(self):
        self._hostServidor = "localhost"
        self._portaServidor = 8080
        self._conexao = (self._hostServidor, self._portaServidor)
        try:
            self._socket_cliente = socket(AF_INET, SOCK_STREAM)
            self._socket_cliente.connect(self._conexao)

        except Exception as msg_erro:
            print(msg_erro)

    def receber_pagina(self, url):
        url_info = urlparse(url)
        mensagem_http = str.format("GET {0} HTTP/1.1\r\nHost: {1}\r\n\r\n", url_info.path, url_info.netloc)

        self._socket_cliente.send(bytes(mensagem_http, "UTF-8"))
        retorno_servidor = self._socket_cliente.recv(1024)
        self._socket_cliente.close()
        return retorno_servidor.decode("UTF-8")


import string

palavra = input("insira: ")

chars2Count = [" "]
charsCounter = []
for index, char in enumerate(chars2Count):
    charsCounter.append(palavra.count(chars2Count[index]))

print("total de chars e espaços: ", len(palavra),
        "\nespaços em branco: ", charsCounter[0], "\ncaracteres: ", len(palavra) - charsCounter[0])


class Solution:
  def reversedNum(self,n):
    rnum = 0
    while n:
      digit = n%10
      rnum = (rnum*10)+digit
      n=n//10
    return rnum

  def sumOfNumberAndReverse(self,num):

    for i in range(int(10e5)+1):
      r = self.reversedNum(i)
      if i+r == num:
        return True
    return False

n = 443
print(Solution().sumOfNumberAndReverse(n))


from urllib import request,parse

def youdao(key):

    url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'

    data = {
        "i":"girl",
        "from":"AUTO",
        "to":"AUTO",
        "smartresult":"dict",
        "client":"fanyideskweb",
        "salt":"15759889253989",
        "sign":"e87ec35d90276484cec74bd0dc806ea8",
        "ts":"1575988925398",
        "bv":"ab57a166e6a56368c9f95952de6192b5",
        "doctype":"json",
        "version":"2.1",
        "keyfrom":"fanyi.web",
        "action":"FY_BY_REALTlME"
    }

    headers = {
        "Accept":"application/json, text/javascript, */*; q=0.01",
        #"Accept-Encoding":"gzip, deflate",
        "Accept-Language":"zh-CN,zh;q=0.9",
        "Connection":"keep-alive",
        "Content-Length":"237",
        "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",
        "Cookie":"OUTFOX_SEARCH_USER_ID=1664548967@10.169.0.84; JSESSIONID=aaaM3XFL5LElm9kCvqW7w; OUTFOX_SEARCH_USER_ID_NCOO=901115725.592805; ___rl__test__cookies=1575989409848",
        "DNT":"1",
        "Host":"fanyi.youdao.com",
        "Origin":"http://fanyi.youdao.com",
        "Referer":"http://fanyi.youdao.com/",
        "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
        "X-Requested-With":"XMLHttpRequest"
    }

    data = parse.urlencode(data).encode()

    req = request.Request(url=url, data=data, headers=headers)

    rsp = request.urlopen(req)

    html = rsp.read().decode()

    print(html)
if __name__ == '__main__':
    youdao('girl')


class Node():
    def __init__(self):
        self.next = None

def cycle_check(node:Node):
    check = {}
    currentNode = node
    while currentNode.next:
        currentNode = currentNode.next
        if currentNode in check:
            return True
        else:
            check[currentNode] = True
    return False
a = Node()
b = Node()
c = Node()
d = Node()

a.next = b
b.next = c
c.next = d

print(cycle_check(a))

d.next = a
print(cycle_check(a))


import csv

def print_file_content(file):
    with open(file) as f:
        reader = csv.reader(f)
        for row in reader:
            print(row)

def write_list_to_file(output_file, lst):
    with open(output_file, 'w') as f:
        writer = csv.writer(f)
        for element in lst:
            writer.writerow(element + "\n")
            print(element)

def write_strings_to_file(file, *strings):
    with open(file, 'w') as f:
        for string in strings:
            f.write(string + "\n")
            print(string)

def read_csv(input_file):
    with open(input_file) as f:
        new_list = []
        reader = csv.reader(f)
        for row in reader:
            new_list.append(row)
        return new_list


from flask import request
from flask_restx import Resource

from ..util.dto import UserDto
from ..service.user_service import save_new_user, get_all_users, get_a_user

api = UserDto.api
_user = UserDto.user

@api.route('/')
class UserList(Resource):
    @api.doc('list_of_registered_users')
    @api.marshal_list_with(_user, envelope='data')
    def get(self):
        """List all registered users"""
        all_users = get_all_users()
        print("All users=",all_users)
        return all_users

    @api.response(201, 'User successfully created.')
    @api.doc('create a new user')
    @api.expect(_user, validate=True)
    def post(self):
        """Creates a new User """
        data = request.json
        return save_new_user(data=data)

@api.route('/<public_id>')
@api.param('public_id', 'The User identifier')
@api.response(404, 'User not found.')
class User(Resource):
    @api.doc('get a user')
    @api.marshal_with(_user)
    def get(self, public_id):
        """get a user given its identifier"""
        user = get_a_user(public_id)
        if not user:
            api.abort(404)
        else:
            return user

# line 1 through 8 imports all the required resources for the user controller.
# We defined two concrete classes in our user controller which are
# userList and user. These two classes extends the abstract flask-restplus resource.
# The api namespace in line 7 above provides the controller with several decorators which includes but is not limited to the following:
# api.route: A decorator to route resources
# api.marshal_with: A decorator specifying the fields to use for serialization (This is where we use the userDto we created earlier)
# api.marshal_list_with: A shortcut decorator for marshal_with above withas_list = True
# api.doc: A decorator to add some api documentation to the decorated object
# api.response: A decorator to specify one of the expected responses
# api.expect: A decorator to Specify the expected input model ( we still use the userDto for the expected input)
# api.param: A decorator to specify one of the expected parameters


from django import forms
from .models import Reclamation

lieux = (
    ("pav1", "Pavillon 1"),
    ("pav2", "Pavillon 2"),
    ("pav3", "Pavillon 3"),
    ("Ascensseur", "Ascensseur"),
    ("autre", "Autre"),)

class Reclamationform(forms.Form):
    Nom_complet=forms.CharField(max_length=20,label='Nom_complet',widget=forms.TextInput(attrs={
        'id':'title',
        'placeholder':"Entrer votre nom..."
        }))
    Numéro_de_Téléphone=forms.IntegerField(widget=forms.NumberInput(attrs={
        'id':'title',
        'placeholder':"Entrer votre Numéro de téléphone..."
        }))
    Lieu_concerné=forms.ChoiceField(choices=lieux,required=True)
    Numéro_de_chambre=forms.IntegerField(required=False,widget=forms.NumberInput(attrs={
        'id':'title',
        'placeholder':"Entrer le numéro de chambre..."

        }))
    Description=forms.CharField(max_length=500,widget=forms.Textarea(attrs={
        'id':'title',
        'placeholder':"Entrer la description précise de votre réclamation..."

        }))
    Pièce_jointe=forms.FileField(required=False)


# dictionary sort
## 1. 둘다 values값에 따른 key sort

genres_score=sorted(genres_score.items(),reverse=True,key=lambda item: item[1])
g = sorted(g.keys(), key=lambda x: g[x], reverse=True)

from functools import reduce
## 2. reduce 함수 : reduce( function ,list, 가장 초기값)
## 언제쓰이냐?-> 누적일때

answer=reduce(lambda x,y: x*(y+1), clothes_number.values(),1)-1
##ex2>
a=[5,4,3,2,1]
answer = reduce(lambda x,y : x*y , a,1 )

### 접두사(?)가 같은 문제
### 1. string.startswith(기준이되는 string)
### 2. sort()를 통해 가장 짧은것부터 비교해야한다

### counter함수
## n차원list의 원소를 counter쓰고 싶을때
from collections import Counter

clothes=[["yellow_hat", "headgear"], ["blue_sunglasses", "eyewear"], ["green_turban", "headgear"]]
clothes_number=Counter(element[1] for element in clothes)


'''
    Gaussian Process Regressor as environment surrogate.

    @author:    Xian Yuehui <xianyeuhui@stu.xjtu.edu.cn>
    @date:      20220415
    @license:   BSD3 clause
'''
# print(__doc__)

import math
from state import State
from typing import List
from arguments import *
from gpr_typedef import *
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import \
    ConstantKernel, RBF, WhiteKernel
import numpy as np
import pickle

class Surrogate:
    def __init__(self):
        # prepare buffers
        with open(ALL_FEATURE_ENTHALPY_PATH, 'rb') as f:
            self.__feature_enthalpy_buffer = pickle.load(f)
        self.__proposed_exp_points_buffer = []

        # instantiate GPR model
        gpr_kernel = ConstantKernel() * RBF() + WhiteKernel()
        self.__gp_model = GaussianProcessRegressor(kernel = gpr_kernel, n_restarts_optimizer = 10)
        # train a gpr model with initial exp_points
        self.update_gp_model()

    # save Surrogate.__gp_model -> gp_model_path
    def save_gp_model(self, gp_model_path = GP_MODEL_PATH):
        with open(gp_model_path, 'wb') as f:
            pickle.dump(self.__gp_model, f)

    '''
        Update gpr model with one input experiment point.
        Push one experiment point into buffers.

        @input:     one ExperimentPoint
        @output:    none
    '''
    def update_gp_model(self, exp_point: ExperimentPoint = None):
        if exp_point:
            # use one experiment point to update gpr model
            # [Ti, Ni, Cu, Hf, Zr]
            feature = self.cal_feature(exp_point[0][0 : 5])
            # enthalpy
            enthalpy = exp_point[1][0]
            # push feature_enthalpy and exp_point -> buffers
            self.__feature_enthalpy_buffer.append([feature, enthalpy])
            self.__proposed_exp_points_buffer.append(exp_point)
        # self.__feature_enthalpy_buffer: [[*atomic_features, enthalpy]...]
        x = [item[0] for item in self.__feature_enthalpy_buffer]
        y = [[item[1]] for item in self.__feature_enthalpy_buffer]
        self.__gp_model.fit(x, y)

    '''
        @input:     mole percentage of [Ti, Ni, Cu, Hf, Zr]
        @output:    expected abs enthalpy of the alloy
    '''
    def predict(self, compositins: List[float]) -> float:
        norm_atomic_features = self.cal_feature(compositins)
        l2_features = np.atleast_2d(norm_atomic_features)
        pred_val, sigma = self.__gp_model.predict(l2_features, return_std = True)       # reture [[predicted_value]]
        return pred_val[0][0], sigma[0]

    '''
        @input:     mole percentage of [Ti, Ni, Cu, Hf, Zr]
        @output:    normalized feature of ['config_entropy', 'diff_atom_radii', 'ea', 'cs']
    '''
    def cal_feature(self, compositions) -> List[float]:
        # calculate abs features
        config_entropy = sum([0. if not c else -c * math.log(c) for c in compositions])
        r_mean = np.array(R_S).dot(np.array(compositions).T)
        diff_r = math.sqrt(sum([compositions[i] * (1 - R_S[i] / r_mean) ** 2 for i in range(len(compositions))]))
        ea = np.array(EA_S).dot(np.array(compositions).T)
        cs = np.array(CS_S).dot(np.array(compositions).T)
        # normalize features
        normalized_features = (np.array([config_entropy, diff_r, ea, cs]) - np.array(EFF_FEATURE_MINS)) \
                                / np.array(EFF_FEATURE_INTERVALS)
        return normalized_features

    '''
        Pack (s, a, r, s') tuple

        @input:     s, a, s'
        @output:    Transition(s, a, r, s')

        @Note:      r: (mean + k * std)
    '''
    def pack_transition(self, current_state: State, action: ActionType, next_state: State) -> Transition:
        # delayed_reward = - (self.predict(next_state.get_composition()) - \
        #     self.predict(current_state.get_composition()))
        # if next_state.is_end_state():
        #     delayed_reward *= 2.
        next_state_pred_mean, next_state_pred_std = self.predict(next_state.get_composition())
        current_state_pred_mead, current_state_pred_std = self.predict(current_state.get_composition())
        k = UCB_K if UCB_ENABLE else 0.
        delayed_reward = - (
            (next_state_pred_mean - k * next_state_pred_std) - \
            (current_state_pred_mead - k * current_state_pred_std)
            )
        return Transition(current_state, action, delayed_reward, next_state)

    '''
        Save experimental and predicted enthalpy into path.
        For data visualization.

        @input:     saving path
    '''
    def save_exp_pred(self, exp_pred_enthalpy_save_path: str = 'exp_pred_enthalpy.txt'):
        with open(exp_pred_enthalpy_save_path, 'wt') as f:
            f.write('# exp_en pred_en std_dev\n')
            for item in self.__feature_enthalpy_buffer:
                feature = item[0]   # []
                exp_enthalpy = item[1]
                # [[...]] -> [[...]], []
                pred_enthalpy, std_dev = self.__gp_model.predict([feature], return_std= True)
                f.write('{}\t{}\t{}\n'.format(exp_enthalpy, pred_enthalpy[0][0], std_dev[0]))


import unittest
import sys
import re
import sys
import os

sys.path.append('../AIMSDataManager/')

from AddressFactory import AddressFactory,AddressChangeFactory,AddressResolutionFactory,TemplateReader
from Address import Address,AddressChange,AddressResolution
from AimsUtility import ActionType,ApprovalType
from AimsUtility import FeedType
from AimsLogging import  Logger

testlog = Logger.setup('test')

#user to init an address, simple text string read from a stored config file
user_text = 'aims_user'

class Test_0_TemplateReaderSelfTest(unittest.TestCase):
    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test10_selfTest(self):
        #assertIsNotNone added in 3.1
        self.assertNotEqual(testlog,None,'Testlog not instantiated')
        testlog.debug('TemplateReader_Test Log')

    def test20_templatereaderInitTest(self):
        #assertIsNotNone added in 3.1
        testlog.debug('Test_0.20 TemplateReader instantiation test')
        tr = TemplateReader()
        self.assertNotEqual(tr,None,'TemplateReader not instantiated')

    def test30_templatereaderGetTest(self):
        #assertIsNotNone added in 3.1
        testlog.debug('Test_0.20 TemplateReader instantiation test')
        t = TemplateReader().get()
        self.assertNotEqual(t,None,'Template values not retrieved')

class Test_1_AddressFactorySelfTest(unittest.TestCase):

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test10_selfTest(self):
        #assertIsNotNone added in 3.1
        self.assertNotEqual(testlog,None,'Testlog not instantiated')
        testlog.debug('Address_Test Log')

    def test20_addressfactoryTest(self):
        #assertIsNotNone added in 3.1
        testlog.debug('Test_1.20 Address instantiation test')
        afact = AddressFactory(user_text)
        self.assertNotEqual(afact,None,'AddressFactory not instantiated')
        acfact = AddressChangeFactory(user_text)
        self.assertNotEqual(acfact,None,'AddressChangeFactory not instantiated')
        arfact = AddressResolutionFactory(user_text)
        self.assertNotEqual(arfact,None,'AddressResolutionFactory not instantiated')

    def test30_addressfactoryGetInstanceTest(self):
        #assertIsNotNone added in 3.1
        testlog.debug('Test_1.30 Address instantiation test')
        afact = AddressFactory.getInstance(FeedType.FEATURES)
        self.assertNotEqual(afact,None,'Unable to getInstance of AddressFactory')
        acfact = AddressFactory.getInstance(FeedType.CHANGEFEED)
        self.assertNotEqual(acfact,None,'Unable to getInstance of AddressChangeFactory')
        arfact = AddressFactory.getInstance(FeedType.RESOLUTIONFEED)
        self.assertNotEqual(arfact,None,'Unable to getInstance of AddressResolutionFactory')

class Test_2_AddressTestSetters(unittest.TestCase):

    def setUp(self):
        testlog.debug('Instantiate addressfactories')
        self.factories = {FeedType.reverse[ft]:AddressFactory.getInstance(ft) for ft in FeedType.reverse}

    def tearDown(self):
        testlog.debug('Destroy null address')
        self.factories = None

    def test10_instAddresses(self):
        '''Tests that all the setters set a matching attribute i.e. setAttribute("X") -> self._Attribute = "X"'''
        faddr = self.factories['FEATURES'].getAddress()
        self.assertTrue(isinstance(faddr,Address), 'Features address not instantiated correctly')
        caddr = self.factories['CHANGEFEED'].getAddress()
        self.assertTrue(isinstance(caddr,AddressChange), 'Change address not instantiated correctly')
        raddr = self.factories['RESOLUTIONFEED'].getAddress()
        self.assertTrue(isinstance(raddr,AddressResolution), 'Resolution address not instantiated correctly')
        self.assertTrue(isinstance(raddr.getWarnings(),list), 'Resolution address doesnt have warnings atrbute')

    def test20_convertAddresses(self):
        caddr = self.factories['CHANGEFEED'].getAddress()
        caddr.setVersion(1)
        caddr.setAddressId(1)
        caddr.setAddressNumber(100)
        caddr.setRoadName('One Road')
        chg_add = self.factories['CHANGEFEED'].convertAddress(caddr,ActionType.ADD)
        self.assertTrue(isinstance(chg_add,dict), 'Change Add request incorrect')
        chg_ret = self.factories['CHANGEFEED'].convertAddress(caddr,ActionType.RETIRE)
        self.assertTrue(isinstance(chg_ret,dict), 'Change Retire request incorrect')
        chg_cup = self.factories['CHANGEFEED'].convertAddress(caddr,ActionType.UPDATE)
        self.assertTrue(isinstance(chg_cup,dict), 'Change Update request incorrect')

    def test30_convertAddresses(self):
        raddr = self.factories['RESOLUTIONFEED'].getAddress()
        raddr.setVersion(1)
        raddr.setAddressNumber(100)
        raddr.setChangeId(100)
        raddr.setRoadName('One Road')
        chg_acc = self.factories['RESOLUTIONFEED'].convertAddress(raddr,ApprovalType.ACCEPT)
        self.assertTrue(isinstance(chg_acc,dict), 'Resolution Accept request incorrect')
        chg_dec = self.factories['RESOLUTIONFEED'].convertAddress(raddr,ApprovalType.DECLINE)
        self.assertTrue(isinstance(chg_dec,dict), 'Resolution Decline request incorrect')
        chg_rup = self.factories['RESOLUTIONFEED'].convertAddress(raddr,ApprovalType.UPDATE)
        self.assertTrue(isinstance(chg_rup,dict), 'Resolution Update request incorrect')

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


"""This file categorizes instructions into their various types."""

ALUR_INSTRUCTIONS = ["ADD", "SUB", "AND", "OR", "XOR", "NAND", "NOR", "XNOR"]

ALUI_INSTRUCTIONS = ["ADDI", "SUBI", "ANDI", "ORI", "XORI", "NANDI", "NORI", "XNORI", "MVHI"]

LOAD_STORE_INSTRUCTIONS = ["LW", "SW"]

CMPR_INSTRUCTIONS = ["F", "EQ", "LT", "LTE", "T", "NE", "GTE", "GT"]

CMPI_INSTRUCTIONS = ["FI", "EQI", "LTI", "LTEI", "TI", "NEI", "GTEI", "GTI"]

BRANCH_INSTRUCTIONS = ["BF", "BEQ", "BLT", "BLTE", "BEQZ", "BLTZ", "BLTEZ", "BT", "BNE", "BGTE", \
"BGT", "BNEZ", "BGTEZ", "BGTZ", "JAL"]

IRR_BRANCHES = ["BF", "BEQ", "BLT", "BLTE", "BT", "BNE", "BGTE", "BGT", "JAL"]

IR_BRANCHES = ["BEQZ", "BLTZ", "BLTEZ", "BNEZ", "BGTEZ", "BGTZ"]


from __future__ import unicode_literals
import frappe
from frappe.utils import getdate
import pandas

def execute(filters=None):
    return get_data(filters)

def get_data(filters):
    data = frappe.db.sql(
        """
    with fn as
    (
        select
        ld.name, u.full_name owner,
        DATE_FORMAT(LAST_DAY(COALESCE(v.creation, ld.creation)),'%%Y-%%m-%%d') last_changed,
        ROW_NUMBER() over (PARTITION by ld.name order by v.creation DESC) rn,
        v.data
        from tabLead ld
        left outer join tabUser u on u.name = ld.lead_owner
        left outer join tabVersion v on v.docname = ld.name
        and v.ref_doctype = 'Lead'
        and v.data REGEXP '.*"changed":.*().*'
        and v.data  REGEXP concat(',\n(   )("',ld.status,'")\n(  ]).*')
        {where_conditions}
    )
    select fn.owner, fn.last_changed, fn.rn
    from fn
    where rn = 1
    """.format(
            where_conditions=get_conditions(filters)
        ),
        filters,
        as_dict=True,
        # debug=True,
    )

    if not data:
        return [], []

    # add default 0 for all months
    for d in pandas.date_range(
        filters.get("from_date"), filters.get("to_date"), freq="m"
    ):
        data.append(
            {"owner": data[0].owner, "last_changed": d.strftime("%Y-%m-%d"), "rn": 0,}
        )
    print(data)

    df = pandas.DataFrame.from_records(data)
    import numpy as np

    df1 = pandas.pivot_table(
        df,
        index=["owner"],
        values=["rn"],
        columns=["last_changed"],
        aggfunc=sum,
        fill_value=0,
        margins=True,
        dropna=True,
    )

    df1.drop(index="All", axis=0, inplace=True)
    df1.columns = [d for d in df1.columns.to_series().str[1]]
    df2 = df1.reset_index()

    columns = [dict(label="Salesman", fieldname="owner", fieldtype="Data", width=165)]

    columns += [
        dict(
            label=frappe.utils.format_date(col, "MMM YYYY")
            if not col == "All"
            else "Total",
            fieldname=col,
            fieldtype="Int",
            width=95,
        )
        for col in df1.columns
    ]
    return columns, df2.to_dict("r")

def get_conditions(filters):
    conditions = ["ld.status in ('Converted','Do Not Contact')"]
    if filters.get("from_date"):
        conditions += ["ld.creation >= %(from_date)s"]
    if filters.get("to_date"):
        conditions += ["ld.creation <= %(to_date)s"]

    return conditions and " where " + " and ".join(conditions) or ""


#!/bin/env python3
"""
Advent Of Code 2021 Day 24
"""

import sys
import time

from typing import Optional

x_adds = [12, 12, 15, -8, -4, 15, 14, 14, -13, -3, -7, 10, -6, -8]
y_adds = [ 1,  1, 16,  5,  9,  3,  2, 15,   5, 11,  7,  1, 10,  3]

def process_input(digit: int, z_val: int, input_num: int) -> Optional[int]:
    x = (z_val % 26) + x_adds[input_num]
    if x_adds[input_num] < 0:
        z_val = int(z_val / 26)
        if x != digit:
            # If x_adds is negative then it is possible to get a digit
            # that equals x, further to get z back to zero by the end we need
            # to take every opportuity to skip z being multiplied by 26 i.e
            # when possible digit must equal x. Since it doesn't signal that
            # this digit is a bad choice
            return None
    if x != digit:
        z_val = 26 * z_val + digit + y_adds[input_num]

    return z_val

def find_valid_model(num_digits: int, smallest: bool = False,
                     digit_idx: int = 0, z_val: int = 0) -> Optional[str]:
    res = None
    if digit_idx == num_digits:
        if z_val == 0:
            res = ""
    else:
        val_range = range(1, 10) if smallest else range(9, 0, -1)
        for digit_val in val_range:
            new_z = process_input(digit_val, z_val, digit_idx)
            if new_z is not None:
                res = find_valid_model(num_digits, smallest, digit_idx + 1, new_z)
                if res is not None:
                    res = str(digit_val) + res
                    break
    return res

def p1p2(input_file: str) -> tuple[int, int]:
    return (int(find_valid_model(14)), int(find_valid_model(14, True)))  # type: ignore

def main(cli_args: list[str]) -> int:
    start = time.perf_counter()
    print(p1p2(cli_args[0]))
    print(f"Elapsed: {time.perf_counter() - start:.6f}s")
    return 0

if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))


from networktables import NetworkTables
import wpilib
import math

class Aligner(wpilib.command.Subsystem):
    def __init__(self, robot):
        super().__init__(self.__class__.__name__)

        self.robot = robot

        self.lime_light_table = NetworkTables.getTable('limelight')

        self.tx = self.lime_light_table.getEntry('tx')
        self.ty = self.lime_light_table.getEntry('ty')

    def periodic():
        ox = self.tx.getDouble(0)
        oy = self.ty.getDouble(0)

        nx = (1 / 160) * (ox - 159.5)
        ny = (1 / 120) * (119.5 - oy)

        vpw = 2 * math.tan(49.7 / 2)
        vph = 2 * math.tan(59.6 / 2)

        x = (vpw / 2) * nx
        y = (vph / 2) * ny

        height_of_camera = 8
        height_of_target = 24.5

        distance = ((height_of_target - height_of_camera) / math.tan(math.atan2(36, y)))

        print(f'Distance: {distance:7.2f} inches')


import torch
import torch.nn as nn
import models.ResidualBlocks as rb
from utils.utils import count_parameters

class BasicExtractor(nn.Module):

    def __init__(self):
        super(BasicExtractor, self).__init__()
        self.layer1 = rb.BasicPreActResBlock(1, 16, 2)
        self.layer2 = rb.BasicPreActResBlock(16, 32, 2)
        self.layer3 = rb.BasicPreActResBlock(32, 16, 2)
        self.layer4 = rb.BasicPreActResBlock(16, 16, 1)

    def forward(self, x):
        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)
        x = x.view(x.shape[0], -1)
        return x

class Deep1Extractor(nn.Module):

    def __init__(self):
        super(Deep1Extractor, self).__init__()
        self.layer1 = rb.BasicPreActResBlock(1, 16, 1)
        self.layer2 = rb.BasicPreActResBlock(16, 16, 2)
        self.layer3 = rb.BasicPreActResBlock(16, 32, 2)
        self.layer4 = rb.BasicPreActResBlock(32, 32, 2)
        self.layer5 = rb.BasicPreActResBlock(32, 64, 2)

    def forward(self, x):
        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)
        x = self.layer5(x)
        x = x.view(x.shape[0], -1)
        return x

class Deep3Extractor(nn.Module):

    def __init__(self, opt):
        super(Deep3Extractor, self).__init__()
        self.layer1 = rb.BasicPreActResBlock(opt.DATA.CHANNELS, 16, 1)
        self.layer2 = rb.BasicPreActResBlock(16, 16, 2)
        self.layer3 = rb.BasicPreActResBlock(16, 32, 2)
        self.layer4 = rb.BasicPreActResBlock(32, 32, 2)
        self.layer5 = rb.BasicPreActResBlock(32, 64, 2)

    def forward(self, x):
        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)
        x = self.layer5(x)
        x = x.view(x.shape[0], -1)
        return x

def get_feature_extractor(name, opt):
    return {
        "basic": lambda: BasicExtractor(),
        "deep1": lambda: Deep1Extractor(),
        "deep3": lambda: Deep3Extractor(opt)
        }[name]()

if __name__ == '__main__':
    b = get_feature_extractor("deep3")
    print(count_parameters(b))
    x = torch.rand([1, 3, 32, 32])
    print(b(x).shape)


from typing import Callable

from ...core import Observable

def _pairwise() -> Callable[[Observable], Observable]:
    def pairwise(source: Observable) -> Observable:
        """Partially applied pairwise operator.

        Returns a new observable that triggers on the second and
        subsequent triggerings of the input observable. The Nth
        triggering of the input observable passes the arguments from
        the N-1th and Nth triggering as a pair. The argument passed to
        the N-1th triggering is held in hidden internal state until the
        Nth triggering occurs.

        Returns:
            An observable that triggers on successive pairs of
            observations from the input observable as an array.
        """

        def subscribe(observer, scheduler=None):
            has_previous = [False]
            previous = [None]

            def on_next(x):
                pair = None

                with source.lock:
                    if has_previous[0]:
                        pair = (previous[0], x)
                    else:
                        has_previous[0] = True

                    previous[0] = x

                if pair:
                    observer.on_next(pair)

            return source.subscribe_(on_next, observer.on_error, observer.on_completed)
        return Observable(subscribe)
    return pairwise


# -*- coding: utf-8 -*-
"""
Created on Fri Dec 18 18:56:21 2020

@author: Sam
"""

months = {'Jan':31, 'Feb':28, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':31, 'Sep':30,
          'Oct':31, 'Nov':30, 'Dec':31}

count = 0
currentDay = 2                  #01/01/1901 was Tuesday
for year in range(1901, 2001):
    for month in months:
        days = months.get(month) + 1
        if month == 'Feb':
            if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
                days = 29 + 1
        for day in range(1,days):
            if day == 1 and currentDay % 7 == 0:
                count += 1
            currentDay += 1

print(count)