"""
Purpose: Advent of Code challenge
Day: 14
Date created: 2020-12-13
URL: https://adventofcode.com

Contributor(s):
    Mark M.
"""

import re
import itertools as ittr
from utils import current_file, day_number, get_lines, read_data

# If testing, set DEBUG to True for a smaller data set.
DEBUG: bool = True

# Import data
if DEBUG:
    raw_data = """mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
mem[8] = 11
mem[7] = 101
mem[8] = 0"""

else:
    # Current file filepath
    thisfile = current_file(__file__)

    # AOC day number
    DAY_NO: int = day_number(thisfile.stem)

    raw_data = read_data(f"day-{DAY_NO}-input.txt")

# raw_data = read_data(f"day-14-input.txt")

# Split data into lines for further processing.  Skip any missing or blank lines.
def process_data(string):
    try:
        return list(map(int, get_lines(string)))
    except ValueError:
        pass
    finally:
        return get_lines(string)

data = process_data(raw_data)
enum_data = {i:v for i, v in enumerate(data)}
mask_idxs = [i for i, v in enum_data.items() if v.startswith("mask")]
mask_dict = {i:str(v).split("=")[1].strip() for i, v in enum_data.items() if v.startswith("mask")}
mem_dict = [i for i in data if not i.startswith("mask")]

for line in data:
    if line.startswith("mask"):
        mask = line.split("=")[1].strip()

mask = data[0].split("=")[1].strip()
commandz = {i:re.search(r"(\d+).+?(\d+)", v).groups() for i, v in enum_data.items() \
            if not v.startswith("mask")}

commands = {i:(int(v[0]), int(v[1])) for i, v in commandz.items()}

# def getcmd(string):

def getbits(n):
    b = bin(n).split("b")[1]
    return f"{b:0>36}"

def writemask(number, mask_val):
    b = getbits(number)
    res = []
    length = 36
    for i in range(length):
        if mask_val[i] == "X":
            res.append(b[i])
        else:
            res.append(mask_val[i])
    return "".join(res)

def memsum(mem_list):
    return sum([int(i, 2) for i in mem_list])

####################################
######### --- Part 1 --- ###########
####################################

total = 0
memory = ["0"] * 36
for idx, line in enum_data.items():
    if idx in mask_dict:
        mask = mask_dict[idx]
        total = memsum(memory)
    else:
        memcmd, numcmd= commands[idx]
        if memcmd > len(memory):
            tmp = ["0"] * (memcmd - len(memory) + 1)
            memory.extend(tmp)
        memory[memcmd] = writemask(numcmd, mask)

result = memsum(memory)

print(f"Part 1: The total memory used was:\n\t\t{result}\t({result:,})")

####################################
######### --- Part 2 --- ###########
####################################

def writemask2(number, mask_val):
    b = getbits(number)
    res = []
    length = 36
    for i in range(length):
        if mask_val[i] == "1":
            res.append("1")
        elif mask_val[i] == "0":
            res.append(b[i])
        else:
            res.append("X")
    return "".join(res)

# tmask = "00000000000000000000000000000000X0XX"

def part2(N, mask_string):
    x_count = mask_string.count("X")
    Tmask = writemask2(N, mask_string)

    out = []
    for el in ittr.product([0, 1], repeat=x_count):
        tmp_mask = list(Tmask)
        prev_idx = 0
        for n in el:
            tmp_idx = Tmask.index("X", prev_idx)
            tmp_mask[tmp_idx] = f"{n}"
            prev_idx = tmp_idx + 1
        out.append("".join(tmp_mask))

    return memsum(out) + 36

pmem = re.compile(r"mem\[(?P<memory>[\d]+)\].+")

if DEBUG:
    raw_data = """mask = 1X000X0101XX101101X01X101X1000111X00
    mem[10004] = 3787163
    mem[18866] = 665403
    mem[13466] = 175657346
    mem[21836] = 99681152"""

    # raw_data = """mask = 00000000000000000000000000000000X0XX
    # mem[26] = 1"""
else:
    raw_data = read_data(f"day-14-input.txt")

data = process_data(raw_data)
enum_data = {i:v for i, v in enumerate(data)}
mask = data[0].split("=")[1].strip()
mask_idxs = [i for i, v in enum_data.items() if v.startswith("mask")]
mask_dict = {i:str(v).split("=")[1].strip() for i, v in enum_data.items() if v.startswith("mask")}
mem_dict = [i for i in data if not i.startswith("mask")]
commandz = {i:re.search(r"(\d+).+?(\d+)", v).groups() for i, v in enum_data.items() \
            if not v.startswith("mask")}

commands = {i:(int(v[0]), int(v[1])) for i, v in commandz.items()}

# mems = data[1:]
# memdict = {}
# for mem in mems:
#     addr = pmem.search(mem)
#     if addr:
#         n = int(addr.group("memory"))
#         print(n)
#         tot = part2(n, mask)
#         memdict[n] = tot

total = 0
memory = ["0"] * 36
for idx, line in enum_data.items():
    if idx in mask_dict:
        mask = mask_dict[idx]
        # total = memsum(memory)
    else:
        memcmd, numcmd= commands[idx]
        if memcmd > len(memory):
            tmp = ["0"] * (memcmd - len(memory) + 1)
            memory.extend(tmp)
        memory[memcmd] = part2(memcmd, mask)

result = sum(map(int, memory))

print(f"Part 2: The total memory used was:\n\t\t{result}\t({result:,})")

# 2479965152859844
# 2478724542131444


from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from markdown import Markdown

# Create your models here.

class Category(models.Model):
    """文章分類"""
    title = models.CharField(max_length=100)
    created = models.DateTimeField(default=timezone.now)

    class Meta:
        ordering = ['-created']

    def __str__(self):
        return self.title

class Tag(models.Model):
    """文章標籤"""
    text = models.CharField(max_length=30)

    class Meta:
        ordering = ['-id']

    def __str__(self):
        return self.text

class Avatar(models.Model):
    # 圖片
    content = models.ImageField(upload_to='avatar/%Y%m%d')

class Article(models.Model):
    # 分類
    category = models.ForeignKey(
        Category,
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='articles'
    )

    author = models.ForeignKey(
        User,
        null=True,
        on_delete=models.CASCADE,
        related_name='articles'
    )
    # 標題
    title = models.CharField(max_length=100)
    # 內文
    body = models.TextField()
    # 創建時間
    created = models.DateTimeField(default=timezone.now)
    # 更新時間
    updated = models.DateTimeField(auto_now=True)
    # 標籤
    tags = models.ManyToManyField(
        Tag,
        blank=True,
        related_name='articles'
    )
    # 標題圖
    avatar = models.ForeignKey(
        Avatar,
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='article'
    )

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['-created']

    # 新增方法，將body 轉為帶 html 標籤的正文
    def get_md(self):
        md = Markdown(
            extensions=[
                'markdown.extensions.extra',
                'markdown.extensions.codehilite',
                'markdown.extensions.toc',
            ]
        )
        md_body = md.convert(self.body)
        # toc 是轉換後的目錄
        return md_body, md.toc


class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        if len(s) <= 1 or len(s) % 2 != 0:
            return False
        for i in range(len(s)):
            if (len(stack)) > 0 :
                if stack[-1] == "(" and s[i] == ")" or stack[-1] == "{" and s[i] == "}" or stack[-1] == "[" and s[i] == "]":
                    stack.pop()
                    continue
            stack.append(s[i])

        return True if len(stack) == 0 else False

Daily Questions 2023/April Leetcoding Challenge/20. Valid Parentheses.py


import argparse

from pyexp import __version__ as version
import pyexp.cmd_handler as cmd_handler

def main() -> None:

    parser = argparse.ArgumentParser(description="Python experiment manager.")

    # Experiment creation/deletion/suprression
    subparsers = parser.add_subparsers(help="sub-command help")

    parser_new = subparsers.add_parser("list", help="list all experiments")
    parser_new.set_defaults(func=cmd_handler.list_experiments)

    parser_new = subparsers.add_parser("show", help="show selected experiment")
    parser_new.add_argument("-n", "--name", type=str, help="name of the new experiment")
    parser_new.set_defaults(func=cmd_handler.show_experiment)

    parser_new = subparsers.add_parser("new", help="create a new experiment")
    parser_new.add_argument("name", type=str, help="name of the new experiment")
    parser_new.set_defaults(func=cmd_handler.new_experiment)

    parser_new = subparsers.add_parser("mv", help="rename selected experiment")
    parser_new.add_argument("name", type=str, help="new name of the experiment")
    parser_new.set_defaults(func=cmd_handler.rename_experiment)

    parser_sel = subparsers.add_parser("sel", help="select specified experiment")
    parser_sel.add_argument("name", type=str, help="name of the experiment")
    parser_sel.set_defaults(func=cmd_handler.sel_experiment)

    parser_sel = subparsers.add_parser("del", help="delete specified experiment")
    parser_sel.add_argument("-n", "--name", type=str, help="name of the experiment")
    parser_sel.set_defaults(func=cmd_handler.del_experiment)

    parser_sel = subparsers.add_parser("add", help="add artifacts to the experiment")
    parser_sel.add_argument("paths", type=str, nargs="+", help="name of the experiment")
    parser_sel.set_defaults(func=cmd_handler.add_artifacts)

    parser_sel = subparsers.add_parser(
        "rm", help="remove artifacts from the experiment"
    )
    parser_sel.add_argument("paths", type=str, nargs="+", help="name of the experiment")
    parser_sel.set_defaults(func=cmd_handler.del_artifacts)

    parser_new = subparsers.add_parser(
        "artifacts", help="show artifacts of the selected experiment"
    )
    parser_new.add_argument("-n", "--name", type=str, help="name of the new experiment")
    parser_new.set_defaults(func=cmd_handler.show_artifacts)

    parser_new = subparsers.add_parser(
        "diff", help="show diff for artifacts of the selected experiment"
    )
    parser_new.add_argument("-n", "--name", type=str, help="name of the new experiment")
    parser_new.set_defaults(func=cmd_handler.show_diff)

    parser_sel = subparsers.add_parser(
        "save", help="save a compressed version of the experiment"
    )
    parser_sel.add_argument("-n", "--name", type=str, help="name of the experiment")
    parser_sel.add_argument(
        "dst",
        type=str,
        help="destination file (extensions: zip, tar, tar.bz2, tar.gz, tar.xz)",
    )
    parser_sel.set_defaults(func=cmd_handler.save_experiment)

    # parser_sel = subparsers.add_parser("load", help="load a compressed version of the experiment")
    # parser_sel.add_argument("-n", "--name", type=str, help="name of the experiment")
    # parser_sel.add_argument("src", type=str, help="source file")
    # parser_sel.set_defaults(func=cmd_handler.load_experiment)

    parser_sel = subparsers.add_parser("cmd", help="add a command to the experiment")
    parser_sel.add_argument(
        "cmd",
        type=str,
        default="-",
        nargs="+",
        help="the command to add. - represents the last command. default: -",
    )
    parser_sel.set_defaults(func=cmd_handler.add_command)

    parser.add_argument("--version", action="version", version=f"%(prog)s {version}")

    args = parser.parse_args()
    if hasattr(args, "func"):
        args.func(args)

if __name__ == "__main__":
    main()


"""
read 3 numbers from the user and print their total sum

"""

print ("pls enter 3 number")
x = input() #user needs to insert a valu by keyboard
y = input()
z = input()
isintiger = input()

#total = float(x) + float(y) + float(z)
#print ("the total is:",total)

if isintiger == 'y':
    total = int(x)+int(y)+int(z)
    print ("the total is:",total)
else:
    total = float(x)+ float(y)+float(z)
    print ("the total is:",total)


get_pet = {'id': 450198289, 'category': {'id': 1, 'name': 'Tests'}, 'name': 'Gold',
           'photoUrls': ['https://vk.com/cute.jpg'], 'tags': [{'id': 450198289, 'name': 'Cute'}], 'status': 'available'}

put_e = {"id": 2, "category": {"id": 2, "name": "Cats"}, "name": "Whiskers", "photoUrls": ["https://vk.com/cute.jpg"],
         "tags": [{"id": 2, "name": "Playful"}], "status": "pending"}

put_i = {"id": 1, "category": {"id": 1, "name": "Dogs"}, "name": "Fluffy", "photoUrls": ["https://vk.com/cute.jpg"],
         "tags": [{"id": 1, "name": "Cute"}], "status": "available"}

e_schema = {"type": "object", "properties": {"id": {"type": "integer", "format": "int64"},
                                             "category": {"type": "object",
                                                          "properties": {"id": {"type": "integer", "format": "int64"},
                                                                         "name": {"type": "string"}}},
                                             "name": {"type": "string"},
                                             "photoUrls": {"type": "array", "items": {"type": "string"}},
                                             "tags": {"type": "array", "items": {"type": "object", "properties": {
                                                 "id": {"type": "integer", "format": "int64"},
                                                 "name": {"type": "string"}}}},
                                             "status": {"type": "string", "enum": ["available", "pending", "sold"]}}}

p_data = {"id": 450198289, "category": {"id": 1, "name": "Tests"}, "name": "Gold",
          "photoUrls": ["https://vk.com/cute.jpg"], "tags": [{"id": 450198289, "name": "Cute"}], "status": "available"}


import sys
from tkinter import *
def ramo():
        ment1=ment.get()
        nlabel=Label(abc,text=ment1).pack()

abc = Tk()
ment = StringVar()
abc.geometry('400x500+200+100')
mlabel = Label(abc,text="My Label",fg='red',bg='yellow').pack()
mbutton = Button(abc,text="OK",command=ramo,fg='black',bg='purple').pack()
mentry = Entry(abc,textvariable=ment).pack()


import dataclasses
import pprint
import re
import typing

class Stack:
    """A stack of crates, top crate is 1st."""

    def __init__(self, *raw_crates: str) -> None:
        crates = tuple(crate for crate in raw_crates if crate != " ")
        self.crates = crates

    def __repr__(self) -> str:
        return f"Stack: {self.crates}"

    def __eq__(self, other: "Stack") -> bool:
        return isinstance(other, self.__class__) and self.crates == other.crates

Stacks = list[Stack]

@dataclasses.dataclass
class Instruction:
    """An instruction to perform."""

    num_to_move: int
    source_stack: int
    target_stack: int

def main(grid_and_instructions: list[str]) -> str:
    stacks, instructions = parse_input(grid_and_instructions)
    for instruction in instructions:
        pprint.pprint(stacks)
        print(instruction)
        stacks = perform_instruction(stacks, instruction)
    return "".join(stack.crates[0] for stack in stacks)

def parse_input(grid_and_instructions: list[str]) -> tuple[Stacks, list[Instruction]]:
    stacks_hoz: list[list[str]] = []
    instructions = []

    is_stacks = True
    for line in grid_and_instructions:
        if not line:
            transposed = zip(*stacks_hoz)
            stacks = [Stack(*crates) for crates in transposed]
            continue
        if is_stacks:
            if re.match(r"(\s\d\s\s)+", line):
                is_stacks = False
                continue
            stacks_hoz.append(parse_stacks_line(line))
        else:
            maybe_instruction = parse_instruction_line(line)
            if maybe_instruction:
                instructions.append(maybe_instruction)
    return stacks, instructions

def parse_stacks_line(stacks_str: str) -> list[str]:
    return [stacks_str[idx + 1] for idx in range(0, len(stacks_str), 4)]

def parse_instruction_line(instruction_str: str) -> typing.Optional[Instruction]:
    match = re.match(r"move (\d+) from (\d) to (\d)", instruction_str)
    if match:
        return Instruction(
            int(match.group(1)),
            int(match.group(2)) - 1,
            int(match.group(3)) - 1,
        )
    return None

def perform_instruction(stacks: Stacks, instruction: Instruction) -> Stacks:
    source_crates = stacks[instruction.source_stack].crates
    mover, new_source_crates = (
        source_crates[0 : instruction.num_to_move],
        source_crates[instruction.num_to_move :],
    )
    new_target_crates = [*mover, *stacks[instruction.target_stack].crates]
    stacks[instruction.source_stack] = Stack(*new_source_crates)
    stacks[instruction.target_stack] = Stack(*new_target_crates)
    return stacks

def input_lines() -> list[str]:
    with open("input") as input_file:
        return list(input_file.readlines())

if __name__ == "__main__":
    inputs = input_lines()
    inputs = [line[:-1] for line in inputs if line[0]]
    answer = main(inputs)
    print(f"Answer: {answer}")


word="hackerrank"
k=0|0

def longstring(word,k):
    res=""
    maxstring=""
    res+=word[0]
    for i in range(len(word)-1):
        if (abs(ord(word[i])-ord(word[i+1]))<=k):
            res+=word[i+1]
        else:
            if (len(res)>len(maxstring)):
                maxstring=res
            res=""
            res+=word[i+1]

    if maxstring=="":
        return res
    else:
        return maxstring

print(longstring(word,k))


import logging
from functools import partial

class Levels:
    FATAL = logging.FATAL
    ERROR = logging.ERROR
    WARNING = logging.WARNING
    LOG_LINKS = logging.INFO + 5
    LOG_CD_OR_PLAN = logging.INFO
    LOG_EACH_STOW = logging.DEBUG + 5
    LOG_STOW_PROCESS = logging.DEBUG + 3
    LOG_IGNORE_DETAILS = logging.DEBUG

FATAL = logging.fatal
ERROR = logging.error
EXCEPTION = logging.exception
WARNING = logging.warning
LOG_LINKS = partial(logging.log, Levels.LOG_LINKS)
LOG_CD_OR_PLAN = partial(logging.log, Levels.LOG_CD_OR_PLAN)
LOG_EACH_STOW = partial(logging.log, Levels.LOG_EACH_STOW)
LOG_STOW_PROCESS = partial(logging.log, Levels.LOG_STOW_PROCESS)
LOG_IGNORE_DETAILS = partial(logging.log, Levels.LOG_IGNORE_DETAILS)
DEBUG = LOG_IGNORE_DETAILS

def setup_logging(verbosity: int):
    """
    Setup logging depending on the same
    verbosity level that is propagated to Stow
    """
    levels = [Levels.WARNING, Levels.LOG_LINKS,
              Levels.LOG_CD_OR_PLAN, Levels.LOG_EACH_STOW,
              Levels.LOG_STOW_PROCESS, Levels.LOG_IGNORE_DETAILS]
    try:
        log_level = levels[verbosity]
    except IndexError:
        log_level = levels[-1]
    logging.basicConfig(format='*StowY*: %(message)s', level=log_level)


import numpy as np
import cupy as cp

def basis_product(flux, basis_arr, axis, permutation):
    return cp.transpose(cp.tensordot(flux, basis_arr, axes=([axis], [1])),
                        axes=permutation)

class DGFlux:
    def __init__(self, resolutions, orders, viscosity=False, nu=1.0e-2):
        # flags
        self.viscosity = viscosity

        # parameters
        self.resolutions = resolutions
        self.orders = orders
        self.nu = nu  # viscosity

        # book-keeping: permutations
        self.permutations = [(0, 1, 4, 2, 3),
                             (0, 1, 2, 3, 4)]

        # more book-keeping: axis-wise boundary slices
        self.boundary_slices = [
            # x-directed face slices [(comps), (left), (right)]
            [(slice(2), slice(resolutions[0]), 0,
              slice(resolutions[1]), slice(orders[1])),
             (slice(2), slice(resolutions[0]), -1,
              slice(resolutions[1]), slice(orders[1]))],
            # y-directed face slices [(left), (right)]
            [(slice(2), slice(resolutions[0]), slice(orders[0]),
              slice(resolutions[1]), 0),
             (slice(2), slice(resolutions[0]), slice(orders[0]),
              slice(resolutions[1]), -1)]]
        # Flux speed slices [(comps), (left), (right)]
        self.speed_slices = [
            # x-directed face slices [(left), (right)]
            [(slice(resolutions[0]), 0,
              slice(resolutions[1]), slice(orders[1])),
             (slice(resolutions[0]), -1,
              slice(resolutions[1]), slice(orders[1]))],
            # y-directed face slices [(left), (right)]
            [(slice(resolutions[0]), slice(orders[0]),
              slice(resolutions[1]), 0),
             (slice(resolutions[0]), slice(orders[0]),
              slice(resolutions[1]), -1)]]

        # Grid and sub-element axes
        self.grid_axis = np.array([1, 3])
        self.sub_element_axis = np.array([2, 4])
        # Numerical flux allocation size arrays
        self.num_flux_sizes = [(2, resolutions[0], 2, resolutions[1], orders[1]),
                               (2, resolutions[0], orders[0], resolutions[1], 2)]

    def semi_discrete_rhs(self, elsasser, elliptic, basis, grids):
        """
        Calculate the right-hand side of semi-discrete equation
        """
        return [((self.x_flux(vector=elsasser.plus, advector=elsasser.minus,
                              basis=basis.basis_x) * grids.x.J) +
                (self.y_flux(vector=elsasser.plus, advector=elsasser.minus,
                             basis=basis.basis_y) * grids.y.J) +
                self.source_term(elliptic=elliptic, vector=elsasser.plus, grids=grids)),
                ((self.x_flux(vector=elsasser.minus, advector=elsasser.plus,
                              basis=basis.basis_x) * grids.x.J) +
                 (self.y_flux(vector=elsasser.minus, advector=elsasser.plus,
                              basis=basis.basis_y) * grids.y.J) +
                 self.source_term(elliptic=elliptic, vector=elsasser.minus, grids=grids))]

    def x_flux(self, vector, advector, basis):  # , elliptic, grid_x):
        dim = 0
        # Advection: flux is the tensor v_i * v_j
        flux = advector.arr[0, :, :, :, :] * vector.arr[:, :, :, :, :]
        # Compute internal and numerical fluxes
        return (basis_product(flux=flux, basis_arr=basis.up,
                              axis=self.sub_element_axis[dim],
                              permutation=self.permutations[dim])
                - self.spatial_flux(flux=flux, speed=advector.arr, basis=basis, dim=dim))

    def y_flux(self, vector, advector, basis):  # , elliptic, grid_y):
        dim = 1
        # Advection: flux is the tensor v_i * v_j
        flux = advector.arr[1, :, :, :, :] * vector.arr[:, :, :, :, :]
        # Compute internal and numerical fluxes
        return (basis_product(flux=flux, basis_arr=basis.up,
                              axis=self.sub_element_axis[dim],
                              permutation=self.permutations[dim])
                - self.spatial_flux(flux=flux, speed=advector.arr, basis=basis, dim=dim))

    def spatial_flux(self, flux, speed, basis, dim):
        # Allocate
        num_flux = cp.zeros(self.num_flux_sizes[dim])

        # Measure upwind directions
        speed_neg = cp.where(condition=speed[dim, :, :, :, :] < 0, x=1, y=0)
        speed_pos = cp.where(condition=speed[dim, :, :, :, :] >= 0, x=1, y=0)

        # Upwind flux, left and right faces
        num_flux[self.boundary_slices[dim][0]] = -1.0 * (cp.multiply(cp.roll(flux[self.boundary_slices[dim][1]],
                                                                             shift=1, axis=self.grid_axis[dim]),
                                                                     speed_pos[self.speed_slices[dim][0]]) +
                                                         cp.multiply(flux[self.boundary_slices[dim][0]],
                                                                     speed_neg[self.speed_slices[dim][0]]))
        num_flux[self.boundary_slices[dim][1]] = (cp.multiply(flux[self.boundary_slices[dim][1]],
                                                              speed_pos[self.speed_slices[dim][1]]) +
                                                  cp.multiply(cp.roll(flux[self.boundary_slices[dim][0]], shift=-1,
                                                                      axis=self.grid_axis[dim]),
                                                              speed_neg[self.speed_slices[dim][1]]))

        return basis_product(flux=num_flux, basis_arr=basis.xi,
                             axis=self.sub_element_axis[dim],
                             permutation=self.permutations[dim])

    def source_term(self, elliptic, vector, grids):
        """
        Add source term in ideal MHD momentum equation point-wise: the pressure gradient
        future work: experimental_viscosity
        """
        if self.viscosity:
            return self.nu * vector.laplacian(grids=grids) - elliptic.pressure_gradient.arr
        else:
            return -1.0 * elliptic.pressure_gradient.arr


def f(n):
    divisorsList = []

    for i in range(1, int(n ** (1 / 2)) + 1):
        if (n % i == 0):
            divisorsList.append(i)
            if ((i ** 2) != n):
                divisorsList.append(n // i)
    return sorted(divisorsList)

def solution(a,b):
    li = f(a+b)
    if len(li)%2 == 0:
        idx_l = int(len(li)/2)-1
        idx_r = int(len(li)/2)
    else:
        idx_l = int(len(li)/2)
        idx_r = int(len(li)/2)
    while 1:
        if (li[idx_l]-2) * (li[idx_r]-2) == b:
            return [li[idx_r],li[idx_l]]
        else:
            idx_l -= 1
            idx_r += 1


from dotenv import load_dotenv
from flask import Flask
from models import initialize_database
from os import environ
from resources import initialize_resources
from schema.schema_file import Schema

# Starting Flask application
application = Flask(__name__)

# Loading environment variables from .env file only in development
if not environ.get('EBS_ENVIRONMENT', None):
    print('Loading environment variables from .env file')
    load_dotenv('./environments/local.env')

# Loading environment variables into Flask application
for item in environ.items():
    application.config[item[0]] = item[1]

# Starting database configuration
initialize_database(application)

# Starting RESTful endpoints
initialize_resources(application)

# Run application
if __name__ == '__main__':
    print('Initilizing application')
    application.run()

@application.before_first_request
def startup():
    print("Initializing migration DB")
    Schema.migration()
    Schema.prepare_db()

# Run application
if __name__ == '__main__':
    application.run()


"""This file produces the main results of the LESST model"""
from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor
from sklearn.linear_model import (
    LinearRegression,
    HuberRegressor,
)
from xgboost import XGBRegressor
from lightgbm import LGBMRegressor
from main import results_LESST
import numpy as np

np.seed = 1

# models to consider
models = {
    "xgb": XGBRegressor(tree_method="gpu_hist"),
    "lgbm": LGBMRegressor(),
    "rf": RandomForestRegressor(
        bootstrap=True, max_depth=80, max_features=6, n_estimators=100
    ),
    "ols": LinearRegression(),
    "huber": HuberRegressor(),
    "gradient": GradientBoostingRegressor(),
}

# Initiate parameters
datasets = ["Yearly", "Quarterly", "Monthly", "Weekly", "Daily", "Hourly"]
frequencies = [1, 4, 12, 52, 7, 24]
n_clusters = clusters = [3, 10, 30, 50, 100]

localmodels = [
    "ols",
    "huber",
    "xgb",
    "lgbm",
    "huber",
    "lgbm",
]
globalmodels = ["ols", "huber", "xgb", "lgbm", "rf", "huber"]

# Run and evaluate LESST and Benchmark deseasonalized
benchds, lessds = results_LESST(
    datasets,
    n_clusters,
    frequencies,
    localmodels,
    globalmodels,
    models,
    deseason=True,
)

# Run and evaluate LESST and Benchmark non-deseasonalized
bench, less = results_LESST(
    datasets,
    n_clusters,
    frequencies,
    localmodels,
    globalmodels,
    models,
    deseason=False,
)


# Definition for an interval.
# class Interval(object):
#     def __init__(self, s=0, e=0):
#         self.start = s
#         self.end = e

class Solution(object):
    def findRightInterval(self, intervals):
        sorted_start = sorted((interval.start, i) for i, interval in enumerate(intervals))
        sorted_end = sorted((interval.end, i) for i, interval in enumerate(intervals))

        result = [-1] * len(intervals)
        i = 0

        for start in sorted_start:
            while start[0] >= sorted_end[i][0]:
                result[sorted_end[i][1]] = start[1]
                i += 1

        return result

        """
        result = []
        comp = sorted(zip(range(len(intervals)), intervals), key=lambda x: x[1].start)
        print(comp)

        for i in range(len(intervals)):
            curr_min = -1
            for j in range(len(intervals)):
                if j != i and intervals[j].start >= intervals[i].end:
                    if curr_min == -1 or intervals[j].start < intervals[curr_min].start:
                        curr_min = j
            result.append(curr_min)

        return result
        """


#! /usr/env python

from constants import *
from struct import pack, unpack, calcsize
from collections import Mapping, Set, Sequence
from bitstring import BitStream, Bits

string_types = (str, bytes)
primitive_types = (int, str, float, bool, type(None))

def pack_message(bytelist):
    bytelist.insert(0, BitStream(uint=PROTOCOL_VERSION, length=2))

    return Bits().join(bytelist).tobytes()

def encode_key(data):
    utf = data.encode('utf-8')
    utflen = len(utf)
    return pack_len(utflen) + utf

def encode_variable(data):
    """Infers the type of data, then packs it into a network-order
    bytestring in accordance with the wire protocol. Data must be of type:
    int, str, float, boolean, None.
    @param data - the data to pack"""
    if data is None:
        #         print('packing null')
        return pack_type(TYPE_NULL)
    elif isinstance(data, bool):
        #         print('packing bool')
        return pack_type(TYPE_BOOL) + pack_bool(data)
    elif isinstance(data, str):
        #         print('packing string')
        utf = data.encode('utf-8')
        utflen = len(utf)
        return pack_type(TYPE_STRING) + pack_len(utflen) + utf
    elif isinstance(data, int):
        #         print('packing int')
        if abs(data) <= (2**7 - 1):
            return pack_type(TYPE_INT) + BitStream(uint=0, length=2) + BitStream(int=data, length=8)
        elif abs(data) <= (2**15 - 1):
            return pack_type(TYPE_INT) + BitStream(uint=1, length=2) + BitStream(int=data, length=16)
        elif abs(data) <= (2**31 - 1):
            return pack_type(TYPE_INT) + BitStream(uint=2, length=2) + BitStream(int=data, length=32)
        elif abs(data) <= (2**63 - 1):
            return pack_type(TYPE_INT) + BitStream(uint=3, length=2) + BitStream(int=data, length=64)
        else:
            raise ValueError("int values outside +/- 2**63 are not supported.")
    elif isinstance(data, float):
        if len(str(data)) < 8:
            utf = str(data).encode('utf-8')
            utflen = len(utf)
            assert(utflen < 8)
            return pack_type(TYPE_FLOAT) + pack_bool(False) + pack_len(utflen, short=True) + utf
        else:
            return pack_type(TYPE_FLOAT) + pack_bool(True) + BitStream(float=data, length=64)

    else:
        raise TypeError("Wire protocol does not support this data type. \
        Expected: int, str, float, None. Got:", type(data))

def encode_object(obj, bytelist, memo=None):
    if memo is None:
        memo = set()

    if isinstance(obj, primitive_types):
        encoding = encode_variable(obj)
        bytelist.append(encoding)
    elif isinstance(obj, Mapping):
        if id(obj) not in memo:
            memo.add(id(obj))
        else:
            raise ValueError(
                "ProtoN does not support circular references within objects")
        bytelist.extend([pack_type(TYPE_OBJECT), pack_len(len(obj.items()))])
        for key, value in obj.items():
            assert(isinstance(key, str))
            bytelist.append(pack_type(TYPE_PAIR))
            bytelist.append(encode_key(key))
            encode_object(value, bytelist, memo)
        memo.remove(id(obj))
    elif isinstance(obj, (Sequence, Set)) and not isinstance(obj, string_types):
        if id(obj) not in memo:
            memo.add(id(obj))
        else:
            raise ValueError(
                "ProtoN does not support circular references within objects")
        bytelist.extend([pack_type(TYPE_LIST), pack_len(len(obj))])
        for elt in obj:
            encode_object(elt, bytelist, memo)
        memo.remove(id(obj))

    elif hasattr(obj, '__dict__'):
        encode_object(vars(obj), bytelist)

def pack_type(dtype):
    return BitStream(uint=dtype, length=3)

def pack_len(length, short=False):
    assert(length >= 0)
    if short:
        sz = 3
        return BitStream(uint=length, length=sz)
    elif length < 2**8-1:
        return BitStream(uint=0, length=2) + BitStream(uint=length, length=8)
    elif length < 2**16-1:
        return BitStream(uint=1, length=2) + BitStream(uint=length, length=16)
    elif length < 2**32-1:
        return BitStream(uint=2, length=2) + BitStream(uint=length, length=32)
    elif length < 2**64-1:
        return BitStream(uint=3, length=2) + BitStream(uint=length, length=64)

def pack_bool(boolean):
    return BitStream(uint=1, length=1) if boolean else BitStream(uint=0, length=1)

def encode(data):
    bytelist = []
    encode_object(data, bytelist)
    msg = pack_message(bytelist)
    return msg


# Örnek Soru 8.1 Polindrom Uygulama Sorusu: Girilen bir  metnin Palindrom olup olmadığını bulan programı yazınız.
def is_palindrome(text):
    # Metni temizle: Rakam, boşluk ve noktalama işaretlerini kaldır
    cleaned_text = ''.join(char.lower() for char in text if char.isalpha())
    # Temizlenmiş metni tersten al
    reversed_text = cleaned_text[::-1]
    # Temizlenmiş metin ile tersten alınmış metni karşılaştır
    if cleaned_text == reversed_text:
        return True
    else:
        return False

# Kullanıcıdan metni al
text = input("Metni Giriniz: ")
# Palindrom kontrolü yap
if is_palindrome(text):
    print("Girilen metin palindromiktir.")
else:
    print("Girilen metin palindromik değildir.")

# Ekran Çıktısı
# Metni Giriniz: anna
# Girilen metin palindromiktir.

# Ekran Çıktısı
# Metni Giriniz: adanada
# Girilen metin palindromiktir.


#!/usr/bin/python3

import collections

import re
import sys
import math
import pprint
import copy
sys.path.insert(1, '/home/eric_weigle_gmail_com/advent-of-code/library/')
import aoc

def consume_packet(data, ver_no_sum, off, indent):
  #The three bits labeled V (110) are the packet version, 6.
  if off >= len(data):
    print(" "*indent + "Out of bits")
    sys.exit(1)
  version = int(data[off:off+3],2)
  ver_no_sum[0] += version
  off += 3
  #The three bits labeled T (100) are the packet type ID, 4, which means the packet is a literal value.
  type_id = int(data[off:off+3],2)
  off += 3
  print(" "*indent + f"{version} {type_id}")

  if type_id == 4:
    # literal value
    bits = []
    while True:
      bits.append(data[off+1:off+5])
      print(" "*indent + f"{data[off:off+5]} {bits}")
      if data[off] != '1':
        # last group
        off += 5
        break
      off += 5
    value = int(''.join(bits),2)
  else: # if type_id == 6:
    # operator
    length_type = int(data[off])
    off+=1
    if length_type == 0:
      #If the length type ID is 0, then the next 15 bits are a number that represents the total length in bits of the sub-packets contained by this packet.
      sub_packet_bits = int(data[off:off+15], 2)
      print(" "*indent + f"op15 binary {data[off:off+15]}")
      print(" "*indent + f"op15 {sub_packet_bits}")
      off += 15
      target = off + sub_packet_bits
      while True:
        off = consume_packet(data, ver_no_sum, off, indent+2)
        if off>=target:
          break
    else:
      print(" "*indent + f"op11")
      #If the length type ID is 1, then the next 11 bits are a number that represents the number of sub-packets immediately contained by this packet.
      sub_packet_count = int(data[off:off+11],2)
      off += 11
      for i in range(sub_packet_count):
        off = consume_packet(data, ver_no_sum, off, indent+2)

  return off

def part1(data):
  #print(data[0])
  in_bin = ''.join([format(int(x,16), "04b") for x in data])
  print(in_bin)
  #  6   1 B
  #[ 110 001 0 000000001000000 ] [ 000 000 0000001011000010001010101100010110010001000000000100001000 11000111000110100 ]
  ver_no_sum = [0]
  consume_packet(in_bin, ver_no_sum, off=0, indent=0)

  print("version no sum", ver_no_sum)

def part2(data):
  pass

def mymain(filename):
  data = aoc.lines(filename)

  print("Part 1")
  part1(data)

  print("Part 2")
  part2(data)

aoc.run(mymain)


import numpy as np
from population import Population
from individual import Individual
from tqdm.auto import trange, tqdm
from PIL import Image
from utilities import save_segmented_img
# from evaluator.run import main
import optuna

def genetic_algorithm(img_data, segment_constraints, population_size: int, num_generations: int = 40, weights=(0.33, 0.33, 0.33), debug=False, save: bool = False, nsga: bool = False) -> Population:

    # Initialize population
    pop = Population(img_data, population_size,
                     segment_constraints, weights=weights)
    pop.initialize_population()

    if save:
        b = pop.get_best_individual()
        save_segmented_img("training_images/"+image_no+"/solutions/gif/"+str(0),
                           img_data, b.get_segments(), 2)

    # Run evolution for num_generations
    for i in trange(num_generations, leave=True):
        if debug:
            tqdm.write(str(pop.get_avg_fitness()))
        if nsga:
            pop.nsga2_evolve(i == num_generations - 1)
        else:
            pop.generate_new_population(i == num_generations - 1)

        if save:
            b = pop.get_best_individual()
            save_segmented_img("training_images/"+image_no+"/solutions/gif/"+str(i+1),
                               img_data, b.get_segments(), 2)

    # Save all the solutions
    if save and nsga:
        for i in range(len(pop.individuals)):
            save_segmented_img("training_images/"+image_no+"/solutions/nsga2/type1/"+str(i),
                               img_data, pop.individuals[i].get_segments(), 1)
            save_segmented_img("training_images/"+image_no+"/solutions/nsga2/type2/"+str(i),
                               img_data, pop.individuals[i].get_segments(), 2)

    # Get best individual solution
    return pop

def check_PRI_value(img_data, segment_ids):
    save_segmented_img("evaluator/evaluator/test_student/check_pri",
                       img_data, segment_ids, 2)
    PRI = main()
    print(f"PRI value: {PRI}")
    return PRI

# Optuna optimziing

def objective(trial):
    edge_weight = trial.suggest_float('edge_weight', 1e-8, 1, log=True)
    connectivity_weight = trial.suggest_float(
        'connectivity_weight', 1e-8, 1, log=True)
    deviation_weight = trial.suggest_float(
        'deviation_weight', 1e-8, 1, log=True)
    weights = (edge_weight, connectivity_weight, deviation_weight)

    img_data = np.asarray(Image.open(
        "training_images/"+image_no+"/Test image.jpg"), dtype='int64')

    s = genetic_algorithm(img_data, segment_constraints=segment_constraints,
                          population_size=40, num_generations=15, weights=weights)

    result = check_PRI_value(img_data, s.get_segments())

    return result

if __name__ == "__main__":
    # Variables
    segment_constraints = {
        "min": 1,
        "max": 30
    }
    image_no = "image4"
    # image_no = "118035"
    # image_no = "147091"
    # image_no = "176035"

    # Load img data
    img_data = np.asarray(Image.open(
        "training_images/"+image_no+"/Test image.jpg"), dtype='int64')

    weights = {'edge_weight': 0.0011748120300752,
               'connectivity_weight': 0.9985902255639098, 'deviation_weight': 2.349624060150376e-4}
    # weights = {'edge_weight': 0.001,
    #            'connectivity_weight': 0.998, 'deviation_weight': 0.001}
    # weights = {'edge_weight': 8.471792933811565e-06,
    #            'connectivity_weight': 0.2084033056268151, 'deviation_weight': 0.00048472170184982}
    weights_tuple = (
        weights['edge_weight'], weights['connectivity_weight'], weights['deviation_weight'])
    # study = optuna.create_study(direction='maximize')
    # study.optimize(objective, n_trials=100)

    nsga = False

    # Run GA
    solutions = genetic_algorithm(
        img_data, segment_constraints=segment_constraints, population_size=100, num_generations=30, weights=weights_tuple, save=True, nsga=nsga)

    b = solutions.get_best_individual()

    save_segmented_img("training_images/"+image_no+"/solutions/",
                       img_data, b.get_segments(), 1)
    save_segmented_img("training_images/"+image_no+"/solutions/",
                       img_data, b.get_segments(), 2)

    if nsga:
        solutions.population_summary()


import sys

input = sys.stdin.readline

n = int(input())
arr = []

for _ in range(n):
    arr.append(int(input()))

dp = [1 for i in range(n)]

for i in range(n):
    for j in range(i):
        if arr[i] > arr[j]:
            dp[i] = max(dp[i], dp[j]+1)

print(n-max(dp))


from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from .views import ReviewCreateView, ReviewUpdateView, ReviewDeleteView, \
    APIReviewList, APIReviewDetail

urlpatterns = [
    path('api/v1/products/<int:pk>/reviews/', APIReviewList.as_view(), name='api-review-list'),
    path('api/v1/products/<int:prod>/reviews/<int:pk>/', APIReviewDetail.as_view(), name='api-review-detail'),
]

#urlpatterns = format_suffix_patterns(urlpatterns)

urlpatterns += [
    path('legacy/product/<int:pk>/rev-create/', ReviewCreateView.as_view(), name='review-create'),
    path('legacy/product/<int:prod>/<int:pk>/rev-update/', ReviewUpdateView.as_view(), name='review-update'),
    path('legacy/product/<int:prod>/<int:pk>/rev-delete/', ReviewDeleteView.as_view(), name='review-delete'),
]


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

# Sample Python code for youtube.playlists.list
# See instructions for running these code samples locally:
# https://developers.google.com/explorer-help/guides/code_samples#python

import os, json, re, pickle, requests
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient import errors, discovery
from google.auth.transport.requests import Request
import secrets as spotify_secrets

class Youtube :
    def __init__(self):
        self.scopes = ["https://www.googleapis.com/auth/youtube.readonly"]

        os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

        api_service_name = "youtube"
        api_version = "v3"
        client_secrets_file = "secret.json"

        # Get credentials and create an API client
        flow = InstalledAppFlow.from_client_secrets_file(
            client_secrets_file, self.scopes)
        # credentials = flow.run_console()
        credentials = self.get_credentials(flow)

        self.youtube_client = discovery.build(
            api_service_name, api_version, credentials=credentials)

    def get_credentials(self, flow) :
        creds = None

        # The file token.pickle stores the user's access and refresh tokens, and is
        # created automatically when the authorization flow completes for the first
        # time.
        if os.path.exists('token.pickle'):
            with open('token.pickle', 'rb') as token:
                creds = pickle.load(token)

        # If there are no (valid) credentials available, let the user log in.
        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request())
            else:
                creds = flow.run_local_server(port=0)
            # Save the credentials for the next run
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)

        return creds

    def get_playlist_items(self) :

        request = self.youtube_client.playlistItems().list(
            part="contentDetails,snippet",
            maxResults=13,
            playlistId="PLEp1lyvf6DrKr5FBKQESMIdXTzsEvZT2Z"
        )
        response = request.execute()

        self.song_titles = []

        for res in response['items'] :
            title = res['snippet']['title']
            title = title.split('|')[0].strip()
            title = title.split('-')[0].strip() + ' ' + title.split('-')[1].strip() if len(title.split('-')) > 1 else title.split('-')[0].strip()

            # Removing brackets
            bracket_start = title.find('(')
            bracket_end = title.find(')')
            title = title.replace('(', ' ')
            title = title.replace(')', '')

            title = re.sub(title[bracket_start - 1:bracket_end + 1], '', title)

            # Corner Cases
            if title.startswith('Dil Beparvah') : title = 'Dil Beparvah'
            elif title.startswith('Lucifer') : title = 'Creep Lucifer'
            elif title.startswith('Kadam') : title = 'Kadam'
            elif title.startswith('Kho gaye hum kahan') : title = 'Kho gaye hum kahan'
            elif title.startswith('Grant Gustin Running Home to You') : title = 'Grant Gustin Runnin Home to You'

            self.song_titles.append(title)

        return self.song_titles

class Spotify :
    def __init__(self, songs):
        self.token = spotify_secrets.SPOTIFY_TOKEN
        self.user_id = spotify_secrets.SPOTIFY_USER_ID
        self.songs = songs

    def find_songs(self) :
        found_songs = []

        url = 'https://api.spotify.com/v1/search?type=track'

        for song in self.songs :
            query = url + f"&q={re.sub(' ', '%20', song)}"

            response = requests.get(
                query,
                headers = {
                    'Content-Type': 'application/json',
                    'Authorization': f'Bearer {self.token}'
                }
            )
            try :
                uri = response.json()['tracks']['items'][0]['uri']
            except Exception as e :
                print(e)
                print("Song:", re.sub(' ', '%20', song))

            found_songs.append(
                response.json()['tracks']['items'][0]['uri']
            )

        self.songs_searched = found_songs
        # print(found_songs)

    def create_or_find_playlist(self) :
        url = f'https://api.spotify.com/v1/users/{self.user_id}/playlists'

        response = requests.get(
            url,
            headers = {
                'Authorization': f'Bearer {self.token}',
                'Content-Type': 'application/json'
            }
        )

        for playlist in json.loads(response.content)['items'] :
            if playlist['name'] == 'From Youtube' :
                self.playlist_id = playlist['id']

        if not self.playlist_id :
            response = requests.post(
                url,
                headers = {
                    'Content-Type': 'application/json',
                    'Authorization': f'Bearer {self.token}'
                },
                data = json.dumps({
                    'name': 'From Youtube',
                    'public': True,
                    'description': "Tracks automatically being added from Youtube from a python program."
                })
            )

            self.playlist_id = json.loads(response.content)['id']

    def add_songs_to_playlist(self) :
        url = f'https://api.spotify.com/v1/playlists/{self.playlist_id}/tracks'

        response = requests.post(
            url,
            headers = {
                'Authorization': f'Bearer {self.token}',
                'Content-Type': 'application/json'
            },
            data = json.dumps([
                    track for track in self.songs_searched
                ])
        )

        if response.status_code == 201 :
            print(f"{len(self.songs_searched)} Songs Added to Playlist Successfully")

        else :
            print(response.status_code, json.loads(response.content))

def main():

    youtube = Youtube()
    spotify = Spotify(youtube.get_playlist_items())
    spotify.find_songs()
    spotify.create_or_find_playlist()
    spotify.add_songs_to_playlist()

    # youtube.get_song_details()

if __name__ == "__main__":
    main()


#!/usr/bin/env python

import sys
import string

currentkey = None
count = 0
prev_val = None

for line in sys.stdin:
    line = line.strip()
    key, value = line.split('\t',1)
    if key == currentkey:
        count = count + 1
    else:
        if currentkey:
            if count == 1:
                print(str(currentkey) + '\t' + str(prev_val))

        currentkey = key
        count = 1
        prev_val = value

if count == 1:
    print(str(key) + '\t' + str(value))


class bstNode:
    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right

class BST:
    def __init__(self):
        self.root = None

    def insert(self, data):
        if not self.root:
            self.root = bstNode(data)
        else:
            cur = self.root
            while cur.left or cur.right:
                if data == cur.data:
                    return
                elif data < cur.data and cur.left:
                    cur = cur.left
                elif data < cur.data and not cur.left:
                    break
                elif data > cur.data and cur.right:
                    cur = cur.right
                elif data > cur.data and not cur.right:
                    break
            if data < cur.data:
                cur.left = bstNode(data)
            else:
                cur.right = bstNode(data)

    def print_helper(self, node):
        if not node:
            return
        self.print_helper(node.left)
        print(node.data)
        self.print_helper(node.right)

    def print_all(self):
        self.print_helper(self.root)

    def findTilt(self):
        val = [0]
        def dfsForTilt(node, val):
            if not node:
                return 0
            left = dfsForTilt(node.left, val)
            right = dfsForTilt(node.right, val)
            val[0] += abs(left-right)
            return node.data + left + right
        dfsForTilt(self.root, val)
        return val[0]

    def minDepth(self):
        def hlperMin(node):
            if not node:
                return 0
            return(1+max(hlperMin(node.left), hlperMin(node.right)))
        return hlperMin(self.root)

# tree = Bst()
#
# tree.insert(7)
# tree.insert(14)
# tree.insert(2)
# tree.insert(3)
#
# tree.insert(1)
# tree.insert(17)
# tree.insert(4)
# tree.insert(3)
# tree.insert(-1)
# tree.insert(5)
# tree.insert(9)
# tree.insert(13)
# tree.insert(2)
# tree.insert(0)
# tree.print_all()
# print(tree.minDepth())


import pandas as pd
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE

import re
import time

from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

def remove_html_tags(data):
    p = re.compile(r'<.*?>')
    text = p.sub(' ', str(data))
    text = text.replace('[', '')
    text = text.replace(']', '')
    text = text.replace('125610', '')
    text = ILLEGAL_CHARACTERS_RE.sub(r'', text)
    return text.strip()

def get_crawl(URL):
    response = driver.get(URL)
    html = driver.page_source
    soup7 = BeautifulSoup(html, 'html.parser')
    ex_id_divs_title = soup7.select('body > div > div:nth-child(7) > div > table.pic_bg > tbody > tr > td > span')
    ex_id_divs = soup7.select('#bonmoon > tbody > tr:nth-child(1) > td > div')
    ex_date = soup7.select('body > div > div:nth-child(7) > div > table:nth-child(13) > tbody > tr > td:nth-child(2) > span:nth-child(4)')

    ex_see = soup7.select('body > div > div:nth-child(7) > div > table:nth-child(13) > tbody > tr > td:nth-child(2) > span:nth-child(7) > span')
    ex_like = soup7.select_one('#div_chu_bbs > div').text
    ex_comment = soup7.select('body > div > div:nth-child(7) > div > table:nth-child(25) > tbody > tr > td.sm > div > b')

    crawl_data_title = remove_html_tags(ex_id_divs_title)

    crawl_data = remove_html_tags(ex_id_divs)
    crawl_data = crawl_data[:-40]

    crawl_date = remove_html_tags(ex_date)
    crawl_date = crawl_date[6:25]

    crawl_see = remove_html_tags(ex_see)
    crawl_like = remove_html_tags(ex_like)
    crawl_like = crawl_like[2:]

    crawl_comment = remove_html_tags(ex_comment)

    result = pd.DataFrame({'title': [crawl_data_title], 'text': [crawl_data], 'date': [crawl_date], 'see': [crawl_see], 'like': [crawl_like], 'comment': [crawl_comment]})
    return result

if __name__ == "__main__":
    driver.implicitly_wait(3)
    driver.get("https://www.koreapas.com/")
    print(driver.page_source)

    time.sleep(1)

    # 로그인 버튼 XPath
    login_x_path = '/html/body/div/div[5]/div[2]/div/table[2]/tbody/tr/td[2]/form/div/div/input'
    # ID 칸 css selector
    driver.find_element(By.CSS_SELECTOR, 'body > div > div:nth-child(7) > div:nth-child(2) > div > table:nth-child(2) > tbody > tr > td:nth-child(2) > form > table > tbody > tr:nth-child(1) > td:nth-child(1) > input').send_keys("id")
    time.sleep(1)
    # PW 칸 css selector
    driver.find_element(By.CSS_SELECTOR, 'body > div > div:nth-child(7) > div:nth-child(2) > div > table:nth-child(2) > tbody > tr > td:nth-child(2) > form > table > tbody > tr:nth-child(2) > td > input').send_keys("pass")
    time.sleep(1)
    driver.find_element(By.XPATH, login_x_path).click()
    time.sleep(3)

    # row 생략 없이 출력
    pd.set_option('display.max_rows', None)
    # col 생략 없이 출력
    pd.set_option('display.max_columns', None)

    print('\n' + '-' * 40 + '\n')
    df = pd.DataFrame({'title': [], 'text': [], 'date': [], 'see': [], 'like': [], 'comment': []})
    for i in range(1684000, 1683000, -1):

        try:
            main_url = "https://www.koreapas.com/bbs/view.php?id=mento&page=1&sn1=&divpage=322&sn=off&ss=on&sc=on&no=" + str(i)
            data = get_crawl(main_url)
            df = pd.concat([df, data])
            time.sleep(2)

        except:
            time.sleep(1)
            continue

    print(df)
    print(df.describe())
    df.describe()
    print(df.info())

    df.to_excel('이천개.xlsx', index=False)


from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'mysite.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
    url(r'^hello/', 'addr_book.views.hello'),
    url(r'^time/', 'addr_book.views.current_time'),
    url(r'^insert', 'addr_book.views.insert'),
    url(r'^list', 'addr_book.views.list'),
)


wt = dict()
for d_n in range(10):
	for d_1 in range(1, 10):
		#print(d_n, d_1)
		if d_n - d_1 in wt.keys():
			wt[d_n - d_1] += 1
		else:
			wt[d_n - d_1] = 1
#print(sum(wt))
MOD = 10**9 + 7

def fast_pow(base, exponent, modulo):
	if exponent == 0:
		return 1
	elif exponent % 2 == 0:
		tmp = fast_pow(base, exponent // 2, modulo) % modulo
		tmp = (tmp * tmp) % modulo
		return tmp
	elif exponent % 2 == 1:
		tmp = fast_pow(base, exponent // 2, modulo) % modulo
		tmp = (tmp * tmp) % modulo
		tmp = (tmp * base) % modulo
		return tmp

t = int(input())
for test in range(t):
	n, w = map(int, input().split())
	if w in wt.keys():
		w = wt[w]
	else:
		w = 0
	ans = (w * fast_pow(10, n - 2, MOD)) % MOD
	print(ans)


from random import SystemRandom
from time import time
rand = SystemRandom()

class PostPart:
    def __init__(self, name, email, newsgroups, subject, lines, linelength, filename, filesize, part, parts, data, encfunc):
        self.name       = name
        self.email      = email
        self.newsgroups = newsgroups

        self.subject    =  subject

        self.lines      = lines
        self.linelength = linelength

        self.filename   = filename
        self.filesize   = filesize
        self.part       = part
        self.parts      = parts

        self.data       = data

        self.encfunc    = encfunc

    def __str__(self):
        t = []
        headers = 'From: %s (%s)\r\nNewsgroups: %s\r\nSubject: %s\r\nMessage-ID: <%s>\r\n\r\n' %\
            (self.email, self.name, ','.join(self.newsgroups), self.subject, self.gen_mid())
        t.append(headers)
        t.append(self.encfunc(data=self.data, name=self.filename, fsize=self.filesize, part=self.part, parts=self.parts, linelength=self.linelength, lines=self.lines))
        t.append('\r\n.\r\n')
        return ''.join(t)

    def gen_mid(self):
        return 'Part%dof%d.%08X%08X%08X%d@4894782.local' % (self.part, self.parts, rand.randint(0, 0xffffffff), rand.randint(0, 0xffffffff), rand.randint(0, 0xffffffff), int(time()))


#!/usr/bin/python3
import os
import csv
import json
import subprocess

def save_as_json(obj):
    return json.dumps(obj, sort_keys=True, indent=2)

subprocess.call("ansible -m setup winad --tree Internal_Workstations", shell=True)

with open("/home/ansible/InternalDevice_report.csv", "w", newline="") as internal_device:
    csv_header_column = ["computer_name", "os_version", "windows_build_number", "logged_user", "bios_vendor", "bios_version", "mac_address"]
    csv_writer = csv.writer(internal_device)
    csv_writer.writerow(csv_header_column)  # write header
    for files in os.listdir("/home/ansible/facts"):
        with open("/home/ansible/facts/"+files, "r") as info_from_ansible:
            for row in info_from_ansible:
                d = json.loads(row)
                computer_name = d['ansible_facts']['ansible_env']['COMPUTERNAME']
                os_version = d['ansible_facts']['ansible_distribution'].split(" ")[1] + " " + d['ansible_facts']['ansible_distribution'].split(" ")[2]
                windows_build_number = d['ansible_facts']['ansible_distribution_version']
                logged_user = d['ansible_facts']['ansible_env']['USERNAME']
                bios_vendor = d['ansible_facts']['ansible_system_vendor']
                bios_version = d['ansible_facts']['ansible_bios_version']
                mac_address = d['ansible_facts']['ansible_interfaces'][0]['macaddress']
                internal_device_information = [computer_name, os_version, windows_build_number, logged_user, bios_vendor,
                                               bios_version, mac_address]
                csv_writer.writerow(internal_device_information)
        info_from_ansible.close()
internal_device.close()

subprocess.call("rm -rf Internal_Workstations", shell=True)


from flask_restplus import Api

from .auth_controller import api as auth_ns
from .user_controller import api as user_ns
from .admin_controller import api as admin_ns
from .event_controller import api as event_ns

authorizations = {
    'Bearer Auth': {
        'type': 'apiKey',
        'in': 'header',
        'name': 'Authorization'
    },
    'Basic Auth': {
        'type': 'basic',
        'in': 'header',
        'name': 'Authorization'
    },
    'Admin Auth': {
        'type': 'apiKey',
        'in': 'header',
        'name': 'X-Admin-Token'
    }
}

api = Api(
    title='Event API',
    version='1.0.0',
    description='Sveučilište u Zadru - Studij informacijske tehnologije - Razvoj web aplikacija \nProjekt 1',
    contact='sarosaravanja11@gmail.com',
    authorizations=authorizations,
    serve_challenge_on_401=False
)

api.add_namespace(auth_ns)
api.add_namespace(user_ns)
api.add_namespace(admin_ns)
api.add_namespace(event_ns)


from nose.tools import *
from CompuSalt.stat_tracker import get_stats, winner_loser

def test_get_stats():
    make_stats = get_stats('yamcha', 'B', {'A': {}, 'B': {}, 'C': {}, 'P': {}, 'X': {}})
    got_stats = get_stats('yamcha', 'B', {'A': {}, 'B': {'yamcha': {'wins': 1, 'loses': 0}}, 'C': {}, 'P': {}, 'X': {}})

    assert_equal(make_stats, {'wins': 0, 'loses': 0})
    assert_equal(got_stats, {'wins': 1, 'loses': 0})

def test_winner_loser():
    goku_wins = winner_loser('yamcha', 'goku', {'wins': 0, 'loses': 0}, {'wins': 0, 'loses': 0}, 'goku')

    assert_equal(goku_wins, ({'wins': 0, 'loses': 1}, {'wins': 1, 'loses': 0}))


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

import psutil

def net_connections():
    return psutil.net_connections()

def get_in_use_ports():
    sconns = net_connections()
    port_list = []
    for s in sconns:
        p = s.laddr.port
        if p in port_list:
            continue
        port_list.append(p)

    return port_list

def get_in_use_port_infos():
    sconns = net_connections()
    port_map = {}
    for s in sconns:
        p = s.laddr.port
        if p in port_map:
            continue
        port_map[p] = s

    return port_map


import statistics
students = [
    {
        "name": "Matt",
        "homework": [90.0, 97.0, 75.0, 92.0],
        "quizzes": [88.0, 40.0, 94.0],
        "tests": [75.0, 90.0],
    },
    {
        "name": "Mich",
        "homework": [100.0, 92.0, 98.0, 100.0],
        "quizzes": [82.0, 83.0, 91.0],
        "tests": [89.0, 97.0],
    },
{
        "name": "Mark",
        "homework": [0.0, 87.0, 75.0, 22.0],
        "quizzes": [0.0, 75.0, 78.0],
        "tests": [100.0, 100.0],
    }
]

if __name__ == '__main__':
    total_hw = 0
    total_quiz= 0
    total_tests = 0
    for x in students:
        ave_hw = statistics.mean(x['homework'])
        ave_quiz = statistics.mean(x['quizzes'])
        ave_tests = statistics.mean(x['tests'])
        total_hw += ave_hw
        total_quiz += ave_quiz
        total_tests += ave_tests
    average_hw = total_hw / len(students)
    average_quiz = total_quiz / len(students)
    average_tests = total_tests/ len(students)
        #print(f"average is {average}. total is {total}")

    print(f"Average homework mark: {average_hw}")
    print(f"Average quiz mark: {average_quiz}")
    print(f"Average test mark: {average_tests}")


import os
from flask import (
  Blueprint
  , current_app as app
  , send_from_directory
)

bp = Blueprint(__name__, __name__, url_prefix="/downloads")

@bp.route('/', methods=["GET"])
@bp.route('/<path:path>', methods=["GET"])
@bp.route('/<path:path>/<string:filename>', methods=["GET"])
def index(path="", filename=None):
  target_path = os.path.join(app.static_folder, path)

  if filename is not None:
    return send_from_directory(directory=target_path, filename=filename)

  return "Not Found Files", 203


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: victor
@site: http://victor.info/
@email: victor@bai.info
@time: 2022/5/2 10:39
"""
from fastapi import APIRouter, Request
from textMG.APIs.api_loggers.api_logger import logger
from fastapi.templating import Jinja2Templates

template = Jinja2Templates("/home/projects/TFpackageText/textMG/APIs/htmls")

router = APIRouter(
    tags=["health_check"],
)

@router.get("/")
async def health(req: Request):
    """get the tf API health status"""
    logger.info("health check api is called")
    return template.TemplateResponse("health_check.html", context={"request":req})


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

from utils.misc import format_params
from api.return_tools import return_error
from log.logger import logger
from api.error import Error

import connexion as connexion
from constants import ACTION_V2V_HEALTH_HEALTH_CHECK
from handlers.controllers.common import (
    process_query_list_param,
    validate_user_request,
    handle_send_fg_request,
)
from handlers.impl.health_impl import (
    handle_health_check_local
)

def health_check(**kwargs):
    """Health Check健康检查"""
    if "Channel" in connexion.request.headers:
        kwargs["channel"] = connexion.request.headers["Channel"]
    process_query_list_param(kwargs, connexion.request.args)
    logger.debug("health_check with req params: [%s]"
                 % format_params(kwargs))

    action = ACTION_V2V_HEALTH_HEALTH_CHECK
    kwargs.update({'action': action})
    valid_user, error = validate_user_request(kwargs,
                                              connexion.request)
    if not valid_user:
        return return_error(kwargs, error, dump=False)

    need_send_fg, ret_msg, ret_code = handle_health_check_local(kwargs)
    if isinstance(ret_msg, Error):
        return return_error(kwargs, ret_msg, dump=False)

    if need_send_fg:
        logger.debug("health_check send req to fg with "
                     "user:[%s] params:[%s] req:[%s]"
                     % (valid_user, format_params(kwargs),
                        format_params(connexion.request)))
        rsp = handle_send_fg_request(valid_user, kwargs, connexion.request)
        logger.debug("health_check get fg rsp: rsp=[%s]"
                     % (format_params(rsp)))
        return rsp
    else:
        logger.debug("health_check get local handle rsp: msg=[%s] code=[%s]"
                     % (format_params(ret_msg), ret_code))
        return ret_msg, ret_code


import random
import string
import sys
import os

f_chars = list(string.ascii_uppercase)
start = 'E'
non_term = {'E', 'D', 'C', 'N', 'V'}
rules = {
    'E': ['D'] * 85 + ['D -> E'] * 15,
    'D': ['C'] * 85 + ['D | C'] * 15,
    'C': ['N'] * 85 + ['C & N'] * 15,
    'N': ['!N'] * 10 + ['V'] * 80 + ['(E)'] * 10,
    'V': f_chars
}

def generate_expr():
    result = start
    while True:
        cur = 0
        flag = False
        for sym in result:
            if sym in non_term:
                replacement = random.choice(rules[sym])
                result = result[:cur] + replacement + result[cur + 1:]
                flag = True
                cur += len(replacement) - 1
            cur += 1
        if not flag:
            break
    return result

if __name__ == '__main__':
    while True:
        expr = generate_expr()
        with open('test.txt', 'w') as test_file:
            test_file.write(expr)
        os.system('cat test.txt | stack run > result.txt')
        result_str = None
        with open('result.txt', 'r') as res_file:
            result_str = res_file.read().strip()
        if result_str == ':(':
            print(':( occured')
            continue
        with open('result.txt', 'w') as res_file:
            res_file.write(result_str)
        os.system('cat result.txt | 3stress/main > final.txt')
        with open('final.txt', 'r') as final_file:
            if final_file.read().strip() == 'Proof is incorrect':
                print('Fucked up')
                break


# P51

# Napisz program, który zamieni wprowadzony przez użytkownika ciąg cyfr na formę tekstową:
# znaki nie będące cyframi mają być ignorowane
# konwertujemy cyfry, nie liczby, a zatem:
# 911 to "dziewięć jeden jeden"
# 1100 to "jeden jeden zero zero.

# slownik = {"zero": 0, "jeden": 1, "dwa": 2, "trzy": 3, "cztery": 4, "pięć": 5, "sześć": 6, "siedem": 7, "osiem": 8, "dziewięć": 9, "dziesieńc": 10}
slownik = {"0": "zero", "1": "jeden", "2": "dwa", "3": "trzy", "4": "cztery", "5": "pięć", "6": "sześć", "7": "siedem", "8": "osiem", "9": "dziewięć", "10": "dziesieńc"}

try:
    number = 4566 #int(input("Podaj liczbę: "))

except:
    print("Podaj liczbę w postacie INT")

lista = list(str(number))
# lista = str(number).split()
# lista = str(number)
for i in lista:
    # print(i)
    print(slownik[i] if i in slownik.keys() else "", end=" ")


# _*_ coding:utf-8 _*_
# File Name: read_json
# Author： Emily
# Date:  2021/3/15  16:04
# Description :

import json

def read_json(filename):
    filepath = "../data/" + filename
    # 调用 load 方法
    with open(filepath, "r", encoding="utf-8")as f:
        return json.load(f)

if __name__ == '__main__':
    datas = read_json("calc.json")
    arrs = []
    for data in datas.values():
        arrs.append((data['a'], data['b'], data['expect']))
    print(arrs)


import datetime
from sqlalchemy import desc
from flask_babel import gettext
from sqlalchemy.orm import joinedload
from sqlalchemy.sql.expression import nullslast

from flask import render_template
from flask import flash
from flask import redirect
from flask import url_for
from flask import g
from flask import request

from app.context_processors import staleness_factor
from app.models import Watches
from app.models import Series
from app.models import Releases
from app import app
from app import db

from app.utilities import get_latest_release
from app.utilities import get_latest_releases

def load_watches(active_filter_override=None):

	watches = Watches                                    \
				.query                                   \
				.options(joinedload(Watches.series_row)) \
				.filter(Watches.user_id == g.user.id)    \
				.all()

	active_filter = 'all'
	if 'active-filter' in request.args:
		active_filter = request.args['active-filter'] if request.args['active-filter'] in ['active', 'maybe-stalled', 'stalled', 'all'] else 'all'

	if active_filter_override:
		active_filter = active_filter_override if active_filter_override in ['active', 'maybe-stalled', 'stalled', 'all'] else 'all'

	data = {}

	ids = []
	for watch in [tmp for tmp in watches]:

		series = watch.series_row
		if not series:
			watches.remove(watch)
			db.session.delete(watch)
			db.session.commit()
		else:
			ids.append(series.id)

	latest = get_latest_releases(ids)

	for watch in watches:
		series = watch.series_row
		# latest = get_latest_release(series)

		# build easier-to-use dicts we can pass the template,
		# and calculate a aggregate progress number that works for
		# direct comparisons across chapter/volume releases
		avail = {}
		prog  = {}
		prog['vol']  = watch.volume   if watch and watch.volume    != None else -1
		prog['chp']  = watch.chapter  if watch and watch.chapter   != None else -1
		prog['frag'] = watch.fragment if watch and watch.fragment  != None else -1

		# avail['vol'] = latest.volume  if latest and latest.volume  != None else -1
		# avail['chp'] = latest.chapter if latest and latest.chapter != None else -1

		avail['date'] = latest[series.id][1]
		avail['vol']  = latest[series.id][0][0]
		avail['chp']  = latest[series.id][0][1]
		avail['frag'] = latest[series.id][0][2]

		prog['agg']  = 0
		if prog['vol'] > 0:
			prog['agg'] += prog['vol'] * 1e4
		if prog['chp'] > 0:
			prog['agg'] += prog['chp']
		if prog['frag'] > 0:
			prog['agg'] += prog['frag'] * 1e-4

		avail['agg'] = 0
		if avail['vol'] > 0:
			avail['agg'] += avail['vol'] * 1e4
		if avail['chp'] > 0:
			avail['agg'] += avail['chp']
		if avail['frag'] > 0:
			avail['agg'] += avail['frag'] * 1e-4

		data.setdefault(watch.listname, [])

		sf = staleness_factor(avail['date'])
		if active_filter == 'active' and sf in ["updating-current"]:
			data[watch.listname].append((series, prog, avail, watch.watch_as_name))
		elif active_filter == 'maybe-stalled' and sf in ["updating-current", "updating-stale"]:
			data[watch.listname].append((series, prog, avail, watch.watch_as_name))
		elif active_filter == 'stalled' and sf in ["updating-current", "updating-stale", "updating-stalled"]:
			data[watch.listname].append((series, prog, avail, watch.watch_as_name))
		elif active_filter == 'all':
			data[watch.listname].append((series, prog, avail, watch.watch_as_name))

		# else:  # This /shouldn't/ ever happen, but wth.
		# 	data[watch.listname].append((series, prog, avail, watch.watch_as_name))

	for key in data.keys():
		data[key].sort(key=lambda x: (x[0].title.lower()))

	lists = list(data.keys())
	lists.sort(key=lambda x: (x.lower()))

	return data, lists, active_filter

def recursively_convert_dt(in_val):
	if isinstance(in_val, dict):
		return {key : recursively_convert_dt(val) for key, val in in_val.items()}
	elif isinstance(in_val, datetime.datetime):
		return in_val.timestamp()
	elif isinstance(in_val, (list, tuple)):
		return [recursively_convert_dt(item) for item in in_val]

	return in_val

def serialize_series_object(series):
	return {
		"name"           : series.title,
		"id"             : series.id,
		"tl_type"        : series.tl_type,
		"rating"         : series.rating,
		"rating_count"   : series.rating_count,
		"extra_metadata" : series.extra_metadata,
	}

def serialize_watches(watches):

	data, lists, active_filter = watches
	clean_data = {}

	for listname, listitems in data.items():
		clean_data[listname] = [(serialize_series_object(series), prog, recursively_convert_dt(avail), watch_as_name) for series, prog, avail, watch_as_name in listitems]

	return clean_data, lists, active_filter

@app.route('/watches', methods=['GET'])
def renderUserWatches():
	if not g.user.is_authenticated():
		flash(gettext('You need to log in to create or view series watches.'))
		return redirect(url_for('index'))

	# data.sort(key=lambda x: (x[0].lower(), x[1].title.lower()))

	watches, lists, active_filter = load_watches()

	return render_template(
			'watched.html',
			watches = watches,
			lists   = lists,
			active_filter = active_filter,
		)

@app.route('/user-cp')
def renderUserCp():
	if not g.user.is_authenticated():
		flash(gettext('You need to log in to acces your user control-panel.'))
		return redirect(url_for('index'))

	return render_template('user_cp.html')


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

from django.db import models, migrations
import django.core.validators

class Migration(migrations.Migration):

    dependencies = [
        ('website', '0038_auto_20150722_0847'),
    ]

    operations = [
        migrations.AlterField(
            model_name='application',
            name='num_years_rank',
            field=models.FloatField(default=None, validators=[django.core.validators.MinValueValidator(0)]),
        ),
    ]


import os
import os.path as osp
import glob

import numpy as np
import matplotlib.pyplot as plt

from bayes_cbf.unicycle_move_to_pose import unicycle_learning_helps_avoid_getting_stuck_exp
from bayes_cbf.trigger_interval import unicycle_trigger_interval_compute

def unicycle_trigger_interval_vis(data_files):
    Lfh_traj = np.loadtxt(data_files['Lfh.np.txt'])
    Lfh_num_traj = np.loadtxt(data_files['Lfh_num.np.txt'])
    tau_traj = np.loadtxt(data_files['tau.np.txt'])
    tau_num_traj = np.loadtxt(data_files['tau_num.np.txt'])
    xvel_traj = np.loadtxt(data_files['xvel.np.txt'])
    fig, ax = plt.subplots(2,2, figsize=(4.5, 3), sharex=True,
                           gridspec_kw=dict(hspace=0.05, wspace=0.4, left=0.15,
                                            right=0.95,
                                            bottom=0.15))
    ax[0, 0].semilogy(range(Lfh_traj.shape[0]), Lfh_traj)
    ax[0, 0].set_ylabel(r'$L_{\mathbf{f}_k}$')
    ax[1, 0].semilogy(range(tau_traj.shape[0]), tau_traj)
    ax[1, 0].set_ylabel(r'$\tau_k$')
    # ax[2].semilogy(range(xvel_traj.shape[0]), xvel_traj)
    # ax[2].set_ylabel(r'$\|\dot{\mathbf{x}}\|_2$')
    ax[1, 0].set_xlabel('time (k)')
    ax[1, 1].set_xlabel('time (k)')
    ax[0, 1].semilogy(range(Lfh_num_traj.shape[0]), Lfh_num_traj)
    ax[0, 1].set_ylabel(r'Numerical $L_{\mathbf{f}_k}$')
    ax[1, 1].semilogy(range(tau_num_traj.shape[0]), tau_num_traj)
    ax[1, 1].set_ylabel(r'Numerical $\tau_{k}$')
    fig.savefig(osp.join(events_dir, 'triggering_time.pdf'))
    plt.show()

if '__main__' == __name__:
    # events_dir = unicycle_learning_helps_avoid_getting_stuck_exp()
    # events_file = max(glob.glob(osp.join(events_dir, '*tfevents*')),
    #                   key=lambda f: os.stat(f).st_mtime)
    # events_file = 'docs/saved-runs/unicycle_move_to_pose_fixed_learning_helps_avoid_getting_stuck_v1.6.2-29-gffc84c6/events.out.tfevents.1629403712.dwarf.9630.0'
    events_file = 'docs/saved-runs/unicycle_move_to_pose_fixed_learning_helps_avoid_getting_stuck_v1.6.3-1-g5fa08e8/events.out.tfevents.1629498656.dwarf.4257.0'
    events_dir = osp.dirname(events_file)
    data_file_basenames = [
        "Lfh.np.txt",
        "Lfh_num.np.txt",
        "tau.np.txt",
        "tau_num.np.txt",
        "xvel.np.txt"
        ]
    data_files = {bn : osp.join(events_dir, bn) for bn in data_file_basenames}
    if not all(osp.exists(d) for d in data_files.values()):
        unicycle_trigger_interval_compute(events_file, data_files)
    unicycle_trigger_interval_vis(data_files)


answer = []
for test_case in range(10):
    dump = int(input())
    box = list(map(int,input().split()))
    for i in range(dump):
        box.sort()
        box[-1] -= 1
        box[0] += 1
    box.sort()
    answer.append(box[-1]-box[0])
for i in range(len(answer)):
    print('#' +str(i+1) + ' ' + str(answer[i]))

SWExpert/1208. [SW 문제해결 기본] 1일차 - Flatten.py


import ctypes
import pyparsenames as pn
import sys
import numpy as np
import os

dir_path = os.path.dirname(os.path.realpath(__file__))
so_file = os.path.join(dir_path, 'parsenames.so')
names_path = os.path.join(dir_path, 'names/yob2018.txt')

class genderName(ctypes.Structure):
    _fields_ = [('name', ctypes.POINTER(ctypes.c_char)),
                ('gender', ctypes.c_char),
                ('popularity', ctypes.c_int),
                ]

genderName._fields_.append(('next', ctypes.POINTER(genderName)))

parsenames = ctypes.CDLL(so_file)

parsenames.readdata.argtypes = [ctypes.POINTER(ctypes.c_char), ]
parsenames.readdata.restype = ctypes.POINTER(genderName)

parsenames.release.argtypes = [ctypes.POINTER(genderName)]

parsenames.gender.restype = ctypes.c_char
parsenames.gender.argtypes = [
    ctypes.POINTER(genderName),
    ctypes.POINTER(ctypes.c_char),
    ctypes.POINTER(ctypes.c_double),
]

class closeMatches:
    def __init__(self):
        self.sp = parsenames.readdata(names_path.encode('utf-8'))

    def find(self, name, translit=True):
        """find gender by name.

        name: string
        translit: bool, include or not python translit, default True
        returns tuple gender (char) and score
        """
        if not isinstance(name, str):
            return [None]

        if translit:
            name = pn.translitt(name)
        score = ctypes.c_double(0.)
        a = parsenames.gender(self.sp, name.encode(
            'utf-8'), ctypes.byref(score))
        a = a.decode('utf-8')
        if a != 'E':
            return [a, float(score.value)]
        elif score.value == 0.5:
            return [None]
        else:
            a = pn.closeMatches(name)
            return a

    def __del__(self):
        parsenames.release(self.sp)

if __name__ == '__main__':
    from datetime import datetime
    if len(sys.argv) != 2:
        print('Usage : python parsenames_optimized.py <name>')
        sys.exit()
    startt = datetime.now()
    p = closeMatches()
    print('Loading time is ', datetime.now() - startt)
    startt = datetime.now()
    a = p.find(sys.argv[1])
    print(a)
    print(datetime.now() - startt)


'''Collection of methods that work on (list of) strings'''
from future.utils import string_types
import re
import numpy
import os

timestamp_re = re.compile('.*((?<!\d)\d{15,15}|(?<!\d)\d{10,10}).*')

def is_decodable_to_str(bytearray_in, codec = 'Latin1'):
    ''' Strings stored by pytables are read back as byte array. This one liner detects if the byte array can be converted back to string or not'''
    if is_pickle_bytestream(bytearray_in):
        return False # pickle stream should not be decoded
    return hasattr(bytearray_in, 'decode') and isinstance(bytearray_in.decode(codec), str)

def coerce_if_string23(str_or_byte):
    ''' Handles all cases when str_or_byte is a string or can be converted to a string.
    Leaves data untouched when it is not a string. '''
    if is_pickle_bytestream(str_or_byte): return  # pickle stream should not be decoded
    if isinstance(str_or_byte, string_types): return str_or_byte
    if is_decodable_to_str(str_or_byte):
        try:
            return str_or_byte.decode()
        except:
            t=1
    if hasattr(str_or_byte, 'astype') and str_or_byte.dtype.kind == 'S': return str_or_byte.astype('U13')
    return str_or_byte

def is_pickle_bytestream(bytearray_in):
    ''' Guesses whether data (byte array) is a string or pickled stream'''
    is_pickle_stream = (isinstance(bytearray_in, (bytes, bytearray)) or hasattr(bytearray, 'dtype') and bytearray.dtype.kind == 'S')\
                       and bytearray_in[0:1] == b'\x80' and bytearray_in[1:2][-1] <=4 and bytearray_in[-1:]==b'.'
    return is_pickle_stream

def latex_float(f, only_exponent=False):
    '''Converts a python float into latex string, e.g. 0.001 -> 10^-3'''
    float_str = "{0:.2g}".format(f)
    if "e" in float_str:
        base, exponent = float_str.split("e")
        if only_exponent:
            return r"10^{{{0}}}".format(int(exponent))
        return r"{0} \times 10^{{{1}}}".format(base, int(exponent))
    else:
        return float_str

def extract_common_string(flist, to_remove=['\)-r\d-']):
    ''' Locates '-rx-' part in filenames (where -rx- mean repetition x) and tries to find filenames that differ
    only in x but otherwise are identical,i.e. these files represent repeated trials of the stimulus. Returns the
    strings without the varying parts
    '''
    flist2 = flist[:]
    for k in to_remove: # remove varying parts from the strings
        ss = re.compile(k)
        flist2= [ss.sub('', i) for i in flist2]
    flistu,  indices = numpy.unique(flist2, return_inverse=True)
    commons   =[]
    for i in numpy.unique(indices):
        commons.append([flist2[i1] for i1 in numpy.where(indices==i)[0]][0])
    return  commons

def join(*args):
    '''Same functionality as os.path.join but for paths using dot as separator'''
    items = [text.replace('.', '/') for text in args]
    joined = os.path.join(*items)
    return joined.replace('/', '.')

def split(dotted_path):
    slashed = dotted_path.replace('.', '/')
    path, name = os.path.split(slashed)
    return path.replace('/', '.'),  name

def array2string(inarray, formatstring = ''):
    if hasattr(inarray,'ndim') and inarray.ndim == 2:
        a = ["%.3g "*inarray.shape[1] % tuple(x) for x in inarray]
    elif isinstance(inarray, (list,tuple)) or (hasattr(inarray,'ndim') and inarray.ndim == 1):
        fstr = '{0:'+formatstring +'}'
        a = [fstr.format(x) for x in inarray]
    return numpy.array(a)


class Solution(object):
    def findStrobogrammatic(self, n):
        assert n >= 0
        if n == 0:
            return []
        if n == 1:
            return ['0', '1', '8']
        letters = [None] * n
        rv = []

        def fill(left_index):
            if left_index == n // 2 and n & 1:
                # n is odd, there is one more value to fill.
                for x in ('0', '1', '8'):
                    letters[left_index] = x
                    fill(left_index + 1)
            elif left_index >= n // 2:
                rv.append(''.join(letters))
            else:
                if left_index == 0:
                    self_alike = ('1', '8')
                else:
                    self_alike = ('0', '1', '8')
                for x in self_alike:
                    letters[left_index] = letters[n - 1 - left_index] = x
                    fill(left_index + 1)
                for x, y in [('6', '9'), ('9', '6')]:
                    letters[left_index] = x
                    letters[n - 1 - left_index] = y
                    fill(left_index + 1)

        fill(0)
        return rv

class Solution2(object):
    def findStrobogrammatic(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        assert n >= 0

        self_the_same = ['0', '1', '8']
        pairs = [('6', '9'), ('9', '6')] + [(x,x) for x in self_the_same]

        if n == 0:
            return []
        if n == 1:
            return self_the_same[:]

        rv = []
        number = [None] * n
        ODD = n & 1
        MIDDLE = (n - 1) // 2
        RIGHT = n - 1

        # Note that this function assume that n >= 2
        def fill(left_index=0):
            if left_index > MIDDLE:
                rv.append(''.join(number))
            elif left_index == MIDDLE and ODD:
                for x in self_the_same:
                    if left_index == 0 and x == '0':
                        continue
                    number[left_index] = x
                    rv.append(''.join(number))
            else:
                for x, y in pairs:
                    if left_index == 0 and x == '0':
                        continue
                    number[left_index] = x
                    number[RIGHT - left_index] = y
                    fill(left_index + 1)

        fill()
        return rv

def test():
    def check(n, expected):
        assert sorted(Solution().findStrobogrammatic(n)) == sorted(expected)
    check(1, ['0', '1', '8'])
    check(2, ["11","69","88","96"])
    check(3, ['101','111','181','609','619','689','808','818','888','906','916','986'])


import random

"""
    Variables of the environment:
"""
# Simulation Frequency Hz
SIMULATION_FREQUENCY = 15

# inter arrival time of ego vehicles
time_difference = 40

# number of other cars in roundabout north
num_other_cars_north = 10

# number of cars in roundabout south
num_other_cars_south = 10

# number of ego vehicles
#num_ego_vehicles = 20
num_ego_vehicles = 10

# roundabout radius
raradius = 30

# roundabout centers
center_south = [0, 0]
center_north = [0, -210]

"""
    Variables of the agents:
"""

# Starting position
START_POS = ("start", "east", 0)
X = random.randint(0, 50)
Y = random.randint(-35, 35)

# Actions of the vehicles
ACTIONS = {0: 'IDLE',
           1: 'FASTER',
           2: 'SLOWER',
           3: 'STOP'}

# communication radius
com_radius = 70

# Vehicles Max Velocity
#MAX_VELOCITY = 11
MAX_VELOCITY = 11
""" Maximum reachable velocity [m/s] """

# Max Waiting Time of the Agent to enter the roundabout
MAX_WAITING_TIME = 30 # [s]

# Mutation probability and relevant distribution variance
mutation_probability = 0.5

# risk mutation bounds
upper_risk_bound = 1.
lower_risk_bound = 0.01

# CAF variable
CAF_FACTOR = 100

# Crash penalty
CRASH_PENALTY = 100

# Termination criterion: Number of entries in the roundabout
test_terminal = 200
training_terminal = 1000

# Path for storing results
path = '/home/swarmlab/Test code/cdm_project-1/highwayEnv/Tests'


#Addition of 2 Binary Numbers...

def binarySum(x, y):
    if len(x) > len(y):
        return binarySum(y, x)

    diff = len(y) - len(x)
    padding = '0' * diff
    x = padding + x
    res = []
    carry = '0'

    for i in range(len(x) - 1, -1, -1):
        if x[i] == '1' and y[i] == '1':
            if carry == '1':
                res.append('1')
                carry = '1'
            else:
                res.append('0')
                carry = '1'
        elif x[i] == '0' and y[i] == '0':
            if carry == '1':
                res.append('1')
                carry = '0'
            else:
                res.append('0')
                carry = '0'
        else:
            if carry == '1':
                res.append('0')
                carry = '1'
            else:
                res.append('1')
                carry = '0'

    if carry == '1':
        res.append(carry)

    return ''.join(res[::-1]).lstrip('0')

a = "101"
b = "1001"
print("Sum of ",a," & ",b," is ",binarySum(a, b))


with open('day8.txt') as f:
    lines = f.readlines()   #whole file stored as list
lines = [x.strip() for x in lines]

regValue = {}

for line in lines:
	splitted = line.split(' ');
	if splitted[0] not in regValue:
		regValue[splitted[0]] = 0

print(regValue)

biggest = 0

for line in lines:
	splitted = line.split(' ');
	register = splitted[0]
	command = splitted[1]
	value = int(splitted[2])
	condReg = splitted[4]
	condition = splitted[5]
	condValue = splitted[6]

	if eval("regValue[condReg] " + condition + condValue): #check if cond is true
		if command == 'inc':
			regValue[register] += value
			if regValue[register] >= biggest:
				biggest = regValue[register]
		else:
			regValue[register] -= value
			if regValue[register] >= biggest:
				biggest = regValue[register]

print(max(zip(regValue.values(), regValue.keys())))
print('Maximum value ever held was: ' + str(biggest))


"""
Autoencoder help us dealing with noisy data. Since the latent space only keeps the important information,
the noise will not be preserved in the space and we can reconstruct the cleaned data.
"""

# imports
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

# ___Step 1___: Load MNIST data
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

# helper function for the MNIST data loading
# modes:    train (which loads the training and validation images and their corresponding labels)
#           test (which loads the test images and their corresponding labels)
def load_data(mode='train'):
    """
    Function to (download and) load the MNIST data
    :param mode: train or test
    :return: images and the corresponding labels
    """

    if mode == 'train':
        x_train, y_train, x_valid, y_valid = mnist.train.images, mnist.train.labels, \
                                             mnist.validation.images, mnist.validation.labels
        return x_train, y_train, x_valid, y_valid
    elif mode == 'test':
        x_test, y_test = mnist.test.images, mnist.test.labels
    return x_test, y_test

def get_next_batch(batch_size):
    return mnist.train.next_batch(batch_size)

# load data
x_train, y_train, x_valid, y_valid = load_data(mode='train')
x_test, y_test = load_data(mode='test')

print("Size of MNIST:")
print("- Train labels:\t\t{}".format(len(y_train)))
print("- Test labels:\t\t{}".format(len(y_test)))
print("- validation labels:\t{}".format(len(y_valid)))

# ___Step 2___: Hyper-parameters

learning_rate = 0.001   # The optimization learning rate
epochs = 10             # Total number of training epochs
batch_size = 100        # Training batch size
display_freq = 100      # Frequency of displaying the training results
h1 = 100                # number of units in the hidden layer
noise_level = 0.6       # level of the noise in noisy data

# data dimenstion
img_h = img_w = 28             # MNIST images are 28x28
img_size_flat = img_h * img_w  # 28x28=784, the total number of pixels

# path to the folder that we want to save the logs for Tensorboard
logs_path = "./graphs"

# ___Step 3___: Variables

def weight_variable(name, shape):
    """
    Create a weight variable with appropriate initialization
    :param name: weight name
    :param shape: weight shape
    :return: initialized weight variable
    """
    initer = tf.truncated_normal_initializer(stddev=0.01)
    return tf.get_variable('W_' + name, dtype=tf.float32, shape=shape, initializer=initer)

def bias_variable(name, shape):
    """
    Create a bias variable with appropriate initialization
    :param name: bias variable name
    :param shape: bias variable shape
    :return: initialized bias variable
    """
    initial = tf.constant(0., shape=shape, dtype=tf.float32)
    return tf.get_variable('b_' + name, dtype=tf.float32, initializer=initial)

def fc_layer(x, num_units, name, use_relu=True):
    """
    Create a fully-connected layer
    :param x: input from previous layer
    :param num_units: number of hidden units in the fully-connected layer
    :param name: layer name
    :param use_relu: boolean to add ReLU non-linearity (or not)
    :return: The output array
    """

    # define a variable scope with the name fc1 representing all the nodes in the first fully connected layer.
    with tf.variable_scope(name):
        in_dim = x.get_shape()[1]

        W = weight_variable(name, shape=[in_dim, num_units])
        b = bias_variable(name, [num_units])

        # To visualize the parameters, we will use tf.summary class to write the summaries of parameters.
        tf.summary.histogram('W', W)
        tf.summary.histogram('b', b)

        layer = tf.matmul(x, W)
        layer += b

        if use_relu:
            layer = tf.nn.relu(layer)
        return layer, W

# ___Step 4___: Create the newwork graph

# Placeholders for inputs (x), outputs(y)
with tf.variable_scope('Input'):
    x_original = tf.placeholder(tf.float32, shape=[None, img_size_flat], name='X_original')
    x_noisy = tf.placeholder(tf.float32, shape=[None, img_size_flat], name='X_noisy')

# ___Step 5___: Create the model structure

fc1, W1 = fc_layer(x_noisy, h1, 'Hidden_layer', use_relu=True)
out, W2 = fc_layer(fc1, img_size_flat, 'Output_layer', use_relu=False)

# calculate the activation
h_active = W1 / tf.sqrt(tf.reduce_sum(tf.square(W1), axis=0)) # [784, 100]

# ___Step 6___: Define the loss function, optimizer, accuracy, and predicted class
with tf.variable_scope('Train'):
    with tf.variable_scope('Loss'):
        loss = tf.reduce_mean(tf.losses.mean_squared_error(x_original, out), name='loss')
        tf.summary.scalar('loss', loss)
    with tf.variable_scope('Optimizer'):
        optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate, name='Adam-op').minimize(loss)

# ___Step 7___: Initialize all variables

# Creating the op for initializing all variables
init = tf.global_variables_initializer()

# Add 5 images from original, noisy and reconstructed samples to summaries
tf.summary.image('original', tf.reshape(x_original, (-1, img_w, img_h, 1)), max_outputs=5)
tf.summary.image('noisy', tf.reshape(x_noisy, (-1, img_w, img_h, 1)), max_outputs=5)
tf.summary.image('reconstructed', tf.reshape(out, (-1, img_w, img_h, 1)), max_outputs=5)

# Finally, to merge all the summeries
merged = tf.summary.merge_all()

# ___Step 8___: Training

# Create an interactive session (to keep the session in the other cells)
sess = tf.InteractiveSession()

# Initialize all variables
sess.run(init)

# To write all the summaries on the disk
train_writer = tf.summary.FileWriter(logs_path, sess.graph)

# Number of training iterations in each epoch
num_tr_iter = int(len(y_train) / batch_size)

global_step = 0 # for visualize

# Loop for epoch
import datetime as time

for epoch in range(epochs):
    print('Training epoch: {}'.format(epoch + 1))

    time_start = time.datetime.now()

    for iteration in range(num_tr_iter):
        # get batch data
        batch_x, _ = get_next_batch(batch_size)
        batch_x_noisy = batch_x + noise_level * np.random.normal(loc=0.0, scale=1.0, size=batch_x.shape)

        global_step += 1    # for visualize

        # Run optimization op (backprop)
        feed_dict_batch = {x_original: batch_x, x_noisy: batch_x_noisy}

        _, summary_tr = sess.run([optimizer, merged], feed_dict=feed_dict_batch)
        train_writer.add_summary(summary_tr, global_step)

        if iteration % display_freq == 0:
            # Calculate and display the batch loss and accuracy
            loss_batch = sess.run(loss, feed_dict=feed_dict_batch)

            print("iter {0:3d}:\t Reconstruction loss={1:.3f}".
                  format(iteration, loss_batch))

    # Run validation after every epoch
    x_valid_original  = x_valid
    x_valid_noisy = x_valid_original + noise_level * np.random.normal(loc=0.0, scale=1.0, size=x_valid_original.shape)

    feed_dict_valid = {x_original: x_valid_original, x_noisy: x_valid_noisy}
    loss_valid = sess.run(loss, feed_dict=feed_dict_valid)

    # report result
    time_end = time.datetime.now()

    print('---------------------------------------------------------')
    print("Epoch: {0}, validation loss: {1:.3f}, time cost: {2:.2f} ms".
          format(epoch + 1, loss_valid, (time_end - time_start).total_seconds() * 1000))
    print('---------------------------------------------------------')

# ___Step 9___:Test the network after training

#  visualize the activation of the hidden units
def plot_max_active(x):
    """
    Plots the images that are maximally activating the hidden units
    :param x: numpy array of size [input_dim, num_hidden_units]
    """
    fig, axes = plt.subplots(nrows=10, ncols=10, figsize=(17, 17))
    fig.subplots_adjust(hspace=.1, wspace=0)
    img_h = img_w = np.sqrt(x.shape[0]).astype(int)
    for i, ax in enumerate(axes.flat):
        # Plot image.
        ax.imshow(x[:, i].reshape((img_h, img_w)), cmap='gray')
        ax.set_xticks([])
        ax.set_yticks([])
        ax.set_yticklabels([])
        ax.set_xticklabels([])
    plt.show()

plot_max_active(sess.run(h_active))

# Make a noisy image
x_test_5 = x_test[:5]   # 5 samples
x_test_noisy = x_test_5 + noise_level * np.random.normal(loc=0.0, scale=1.0, size=x_test_5.shape)

time_start = time.datetime.now()

# Reconstruct a clean image from noisy image
x_reconstruct = sess.run(out, feed_dict={x_noisy: x_test_noisy})

# Calculate the loss between reconstructed image and original image
loss_test = sess.run(loss, feed_dict={x_original: x_test_5, x_noisy: x_test_noisy})

time_end = time.datetime.now()

print('---------------------------------------------------------')
print("Test loss of original image compared to reconstructed image : {0:.3f}, , time cost: {1:.2f} ms".
        format(loss_test, (time_end - time_start).total_seconds() * 1000))
print('---------------------------------------------------------')

# ___Step 10___: plot result

def plot_images(original_images, noisy_images, reconstructed_images):
    """
    Create figure of original and reconstructed image.
    :param original_image: original images to be plotted, (?, img_h*img_w)
    :param noisy_image: original images to be plotted, (?, img_h*img_w)
    :param reconstructed_image: reconstructed images to be plotted, (?, img_h*img_w)
    """
    num_images = original_images.shape[0]
    fig, axes = plt.subplots(num_images, 3, figsize=(9, 9))
    fig.subplots_adjust(hspace=.1, wspace=0)

    img_h = img_w = np.sqrt(original_images.shape[-1]).astype(int)

    for i, ax in enumerate(axes):
        # Plot image.
        ax[0].imshow(original_images[i].reshape((img_h, img_w)), cmap='gray')
        ax[1].imshow(noisy_images[i].reshape((img_h, img_w)), cmap='gray')
        ax[2].imshow(reconstructed_images[i].reshape((img_h, img_w)), cmap='gray')

        # Remove ticks from the plot.
        for sub_ax in ax:
            sub_ax.set_xticks([])
            sub_ax.set_yticks([])

    for ax, col in zip(axes[0], ["Original Image", "Noisy Image", "Reconstructed Image"]):
        ax.set_title(col)

    fig.tight_layout()
    plt.show()

# Plot original image, noisy image and reconstructed image
plot_images(x_test_5, x_test_noisy, x_reconstruct)

# ___Step 11___: finish all
sess.close()