def solve(program):
    accumulator = 0
    pointer = 0
    executed = set()

    while pointer not in executed and pointer < len(program):
        instruction, argument = program[pointer]

        executed.add(pointer)
        pointer += 1

        if instruction == 'acc':
            accumulator += argument

        if instruction == 'jmp':
            pointer += argument - 1

    return accumulator, pointer

def solve_part1(program):
    accumulator, _ = solve(program)
    return accumulator

def solve_part2(program):
    for i in range(len(program)):
        instruction, argument = program[i]
        if instruction != 'acc':
            program[i] = ('jmp' if instruction == 'nop' else 'nop', argument)

        accumulator, pointer = solve(program)
        program[i] = (instruction, argument)

        if pointer == len(program):
            return accumulator

    return None

with open('input', 'r') as f:
    program = [line.strip().split( ) for line in f.readlines()]
    program = [(line[0], int(line[1])) for line in program]

    result = solve_part1(program)
    print(f"The accumulator contains the value {result} (part1).")

    result = solve_part2(program)
    print(f"The accumulator contains the value {result} (part2).")


#!/usr/bin/python3

import numpy as np
from matplotlib import pyplot as plt

lx = []
ly = []

with open("HailStoneNum.txt", "r") as f:
    for line in f:
        ls = line.split(",")
        lx.append(int(ls[0]))
        ly.append(int(ls[1]))

x = np.array(lx)
y = np.array(ly)

plt.plot(x,y)
plt.savefig("HailStone.jpg")


# Climate App
# Now that you have completed your initial analysis, design a Flask api based on the queries that you have just developed.
#  - Use FLASK to create your routes.
#################################################
# Import Flask & jsonify & the kitchen sink...
#################################################
import datetime as dt
import numpy as np
import pandas as pd

import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func

from flask import Flask, jsonify
#################################################
# Database Setup
#################################################
engine = create_engine("sqlite:///hawaii.sqlite")
# reflect an existing database into a new model
Base = automap_base()
# reflect the tables
Base.prepare(engine, reflect=True)
# Save reference to the tables
Station = Base.classes.station
Measurement = Base.classes.measurement
# Create our session (link) from Python to the DB
session = Session(engine)

#################################################
# Flask Setup
#################################################
app = Flask(__name__)
#################################################
# Flask Routes
#################################################
@app.route("/")
def welcome():
    """List all available api routes."""
    return (
        "
HW 11 Surf Is Up!
"
        "
"
        "
Available APIs
"
        "
Precipitation
"
        "
Stations
"
        "
Temps observed
"
        "
Calculated Temps
"
    )

#################################################
# /api/v1.0/precipitation
#################################################
@app.route("/api/v1.0/precipitation")
def precipitation():
    yearago_date = dt.date(2016, 8 , 22)
    # select(station, date, prcp) frome measurement
    # where date >= yearago_date
    prcp_in_last_year = session.query(Measurement.date, func.sum(Measurement.prcp)).\
        filter(Measurement.date > yearago_date).group_by(Measurement.date).all()

    prcp_list = [prcp_in_last_year]

    return jsonify(prcp_list)

#################################################
# /api/v1.0/stations
#################################################
@app.route("/api/v1.0/stations")
def stations():
    all_stations = session.query(Station.name, Station.station, Station.elevation).all()

    station_list = []
    for a_station in all_stations:
        row = {}
        row['elevation'] = a_station[2]
        row['station'] = a_station[1]
        row['name'] = a_station[0]
        station_list.append(row)
    return jsonify(station_list)

#################################################
# /api/v1.0/tobs
#   - Return a json list of Temperature Observations (tobs) for the previous year
#################################################
@app.route("/api/v1.0/tobs")
def temp_obs():
    yearago_date = dt.date(2016, 8 , 22)
    temps = session.query(Station.name, Measurement.date, Measurement.tobs).\
    filter(Measurement.date > yearago_date).all()

    tobs_list = []
    for temp in temps:
        t = {}
        t["Station"] = temp[0]
        t["Date"] = temp[1]
        t["Temperature"] = int(temp[2])
        tobs_list.append(t)
    return jsonify(tobs_list)

#################################################
#
# - /api/v1.0/<start> and /api/v1.0/<start>/<end>
#   - Return a json list of the minimum temperature, the average temperature, and the max temperature
#      for a given start or start-end range.
#   - When given the start only, calculate TMIN, TAVG, and TMAX for all dates greater than and equal
#      to the start date.
#   - When given the start and the end date, calculate the TMIN, TAVG, and TMAX for dates between the
#      start and end date inclusive.
#
# Hints
# - You will need to join the station and measurement tables for some of the analysis queries.
# - Use Flask jsonify to convert your api data into a valid json response object.
#################################################
@app.route("/api/v1.0/start_end")
def calc_temps():
    sy = 2017 # start year
    sm = 7    # start month
    sd = 1    # start day
    ey = 2017 # end year
    em = 7    # end month
    ed = 11   # end day
    # Convert dates to "year - 1" dates
    start_date = dt.date(sy, sm, sd)
    end_date = dt.date(ey, em, ed)

    temp_info = session.query(Measurement.tobs).filter(Measurement.date >= start_date, Measurement.date <= end_date).all()
    temperatures = [temperature[0] for temperature in temp_info]
    # Get the minimum temp
    temp_min = min(temperatures)
    # Get the maximum temp
    temp_max = max(temperatures)
    # Get the average temp
    temp_avg = np.mean(temperatures)
    date_results = 'Start date:  ' + str(start_date) + '
' + 'End date:  ' + str(end_date) + '
'
    minmax_results = 'Min temp: ' + str(temp_min) + '
' + 'Avg temp: ' + str(temp_avg) +'
' + 'Max temp: ' + str(temp_max)
    temp_results = date_results + minmax_results
    return(temp_results)

#################################################
# Define Main behavior
#################################################
if __name__ == '__main__':
    app.run(debug=True)


# -*- coding: utf-8 -*-
"""
Created on Sat Jan  2 00:48:47 2021

@author: baris
"""

import pandas as pd
import math
import numpy as np
import xlsxwriter

xlxs_file = pd.read_excel("example.xlsx")

# All columns have separeted into a list on their own.
parsed_store = xlxs_file["store"].tolist()
parsed_x = xlxs_file["x"].tolist()
parsed_y = xlxs_file["y"].tolist()
parsed_demand = xlxs_file["demand"].tolist()

result = np.zeros((len(parsed_x) + 5, len(parsed_y)))

for i in range(len(parsed_store)):
    for j in range(len(parsed_store)):
        distance = math.sqrt((parsed_x[i] - parsed_x[j])**2 + (parsed_y[i] - parsed_y[j])**2)
        result[i][j] = distance*parsed_demand[i]

for i in range(len(parsed_store)):
    sum = .0
    for j in range(len(parsed_store)):
        sum += result[j][i]
    result[-5][i] = sum

result[-4] = sorted(result[-5])
result[-3] = np.argsort(result[-5]) + 1

min1, min2 = int(result[-3][0] - 1), int(result[-3][1] - 1)

sum1 = 0
sum2 = 0
sum1_m = .0
sum2_m = .0
for i in range(len(parsed_store)):
    tmp1 = result[i][min1]
    tmp2 = result[i][min2]
    if tmp1 < tmp2:
        result[-2][i] = min1 + 1
        sum1 += 1
        sum1_m += tmp1
    else:
        result[-2][i] = min2 + 1
        sum2 += 1
        sum2_m += tmp2

result[-1][0] = sum1
result[-1][1] = sum2
result[-1][2] = sum1_m
result[-1][3] = sum2_m

workbook = xlsxwriter.Workbook('result.xlsx')
worksheet = workbook.add_worksheet()
row = 0

column = 0

for module in result :

    worksheet.write_row(row, column, module)
    row += 1

workbook.close()


from typing import List
from instructor import patch
from pydantic import BaseModel, Field

import openai

patch()

class Property(BaseModel):
    key: str
    value: str
    resolved_absolute_value: str

class Entity(BaseModel):
    id: int = Field(
        ...,
        description="Unique identifier for the entity, used for deduplication, design a scheme allows multiple entities",
    )
    subquote_string: List[str] = Field(
        ...,
        description="Correctly resolved value of the entity, if the entity is a reference to another entity, this should be the id of the referenced entity, include a few more words before and after the value to allow for some context to be used in the resolution",
    )
    entity_title: str
    properties: List[Property] = Field(
        ..., description="List of properties of the entity"
    )
    dependencies: List[int] = Field(
        ...,
        description="List of entity ids that this entity depends  or relies on to resolve it",
    )

class DocumentExtraction(BaseModel):
    entities: List[Entity] = Field(
        ...,
        description="Body of the answer, each fact should be its seperate object with a body and a list of sources",
    )

def ask_ai(content) -> DocumentExtraction:
    resp: DocumentExtraction = openai.ChatCompletion.create(
        model="gpt-4",
        response_model=DocumentExtraction,
        messages=[
            {
                "role": "system",
                "content": "You are a perfect entity resolution system that extracts facts from the document. Extract and resolve a list of entities from the following document:",
            },
            {
                "role": "user",
                "content": content,
            },
        ],
    )  # type: ignore
    return resp

content = """
Sample Legal Contract
Agreement Contract

This Agreement is made and entered into on 2020-01-01 by and between Company A ("the Client") and Company B ("the Service Provider").

Article 1: Scope of Work

The Service Provider will deliver the software product to the Client 30 days after the agreement date.

Article 2: Payment Terms

The total payment for the service is $50,000.
An initial payment of $10,000 will be made within 7 days of the the signed date.
The final payment will be due 45 days after [SignDate].

Article 3: Confidentiality

The parties agree not to disclose any confidential information received from the other party for 3 months after the final payment date.

Article 4: Termination

The contract can be terminated with a 30-day notice, unless there are outstanding obligations that must be fulfilled after the [DeliveryDate].
"""

model = ask_ai(content)
print(model.model_dump_json(indent=2))

"""
{
  "entities": [
    {
      "id": 1,
      "subquote_string": [
        "This Agreement is made and entered into on 2020-01-01 by and between Company A (\"the Client\") and Company B (\"the Service Provider\")."
      ],
      "entity_title": "Agreement between Company A and Company B",
      "properties": [
        {
          "key": "Date",
          "value": "2020-01-01",
          "resolved_absolute_value": "2020-01-01"
        },
        {
          "key": "Party 1",
          "value": "Company A",
          "resolved_absolute_value": "Company A"
        },
        {
          "key": "Party 2",
          "value": "Company B",
          "resolved_absolute_value": "Company B"
        }
      ],
      "dependencies": []
    },
    {
      "id": 2,
      "subquote_string": [
        "The Service Provider will deliver the software product to the Client 30 days after the agreement date."
      ],
      "entity_title": "Scope of Work",
      "properties": [
        {
          "key": "Delivery Date",
          "value": "30 days after the agreement date",
          "resolved_absolute_value": "2020-01-31"
        }
      ],
      "dependencies": [
        1
      ]
    },
    {
      "id": 3,
      "subquote_string": [
        "The total payment for the service is $50,000.",
        "An initial payment of $10,000 will be made within 7 days of the the signed date.",
        "The final payment will be due 45 days after [SignDate]."
      ],
      "entity_title": "Payment Terms",
      "properties": [
        {
          "key": "Total Payment",
          "value": "$50,000",
          "resolved_absolute_value": "50000"
        },
        {
          "key": "Initial Payment",
          "value": "$10,000",
          "resolved_absolute_value": "10000"
        },
        {
          "key": "Final Payment Due Date",
          "value": "45 days after [SignDate]",
          "resolved_absolute_value": "2020-02-15"
        }
      ],
      "dependencies": [
        1
      ]
    },
    {
      "id": 4,
      "subquote_string": [
        "The parties agree not to disclose any confidential information received from the other party for 3 months after the final payment date."
      ],
      "entity_title": "Confidentiality Terms",
      "properties": [
        {
          "key": "Confidentiality Duration",
          "value": "3 months after the final payment date",
          "resolved_absolute_value": "2020-05-15"
        }
      ],
      "dependencies": [
        3
      ]
    },
    {
      "id": 5,
      "subquote_string": [
        "The contract can be terminated with a 30-day notice, unless there are outstanding obligations that must be fulfilled after the [DeliveryDate]."
      ],
      "entity_title": "Termination",
      "properties": [
        {
          "key": "Termination Notice",
          "value": "30-day",
          "resolved_absolute_value": "30 days"
        }
      ],
      "dependencies": [
        2
      ]
    }
  ]
}
"""


class Dice():
    def __init__(self, x, y):
        self.side = int(random(1, 7))
        self.x = x
        self.y = y
        self.status = 'stopped' # rolling
        self.last_rolled = millis()
        self.keep = False

    def roll(self):
        if self.status != 'rolling' and not self.keep:
            self.status = 'rolling'
            self.last_rolled = millis()

    def translate(self, dst_x, dst_y):
        dx = int((dst_x - self.x) / 4)
        dy = int((dst_y - self.y) / 4)

        if dx == 0:
            self.x = dst_x
        else:
            self.x += dx
        if dy == 0:
            self.y = dst_y
        else:
           self.y += dy

    def display(self):
        if self.status == 'rolling':
            if millis() - self.last_rolled > random(1000, 3000):
                self.status = 'stopped'

            self.side = int(random(1, 7))

            self.x += int(random(-10, 10))
            self.y += int(random(-10, 10))

            self.x = max(50, self.x)
            self.y = max(50, self.y)

        if self.keep:
            strokeWeight(5)
            stroke(204, 102, 0)
        else:
            noStroke()

        for i in range(1, 10, 2):
            fill(0, 100 - 5 * (i + 1))
            rectMode(CENTER)
            rect(self.x + i, self.y + i, 100, 100)

        fill('#ffffff')
        rectMode(CENTER)
        rect(self.x, self.y, 100, 100)

        noStroke()
        fill('#333333')
        if self.side == 1 or self.side == 3 or self.side == 5:
            ellipse(self.x, self.y, 20, 20)
        if self.side == 4 or self.side == 5 or self.side == 6:
            ellipse(self.x - 30, self.y - 30, 20, 20)
        if self.side == 6:
            ellipse(self.x - 30, self.y, 20, 20)
        if self.side == 2 or self.side == 3 or self.side == 4 or self.side == 5 or self.side == 6:
            ellipse(self.x - 30, self.y + 30, 20, 20)
        if self.side == 2 or self.side == 3 or self.side == 4 or self.side == 5 or self.side == 6:
            ellipse(self.x + 30, self.y - 30, 20, 20)
        if self.side == 6:
            ellipse(self.x + 30, self.y, 20, 20)
        if self.side == 4 or self.side == 5 or self.side == 6:
            ellipse(self.x + 30, self.y + 30, 20, 20)

class Strategy():
    def __init__(self, strategies):
        self.strategies = strategies

    def set_dices(self, dices):
        self.dices = dices

    def calculate(self):
        self.sides = [dice.side for dice in self.dices]
        self.unique = set(self.sides)

        upper_score = 0
        for i in range(1, 7):
            if self.strategies['%ds' % i]['done']:
                continue

            score = self.sum_of_single(i)
            self.strategies['%ds' % i]['score'] = score
            upper_score += score

        if upper_score >= 63:
            self.strategies['Bonus']['score'] = 35

        if not self.strategies['Choice']['done']:
            self.strategies['Choice']['score'] = sum(self.sides)
        if not self.strategies['3-of-a-kind']['done']:
            self.strategies['3-of-a-kind']['score'] = self.of_a_kind(3)
        if not self.strategies['4-of-a-kind']['done']:
            self.strategies['4-of-a-kind']['score'] = self.of_a_kind(4)
        if not self.strategies['Full House']['done']:
            self.strategies['Full House']['score'] = self.full_house()
        if not self.strategies['S. Straight']['done']:
            self.strategies['S. Straight']['score'] = self.small_straight()
        if not self.strategies['L. Straight']['done']:
            self.strategies['L. Straight']['score'] = self.large_straight()
        if not self.strategies['Yacht']['done']:
            self.strategies['Yacht']['score'] = self.of_a_kind(5)

        self.strategies['Total']['score'] = 0
        for k, v in self.strategies.items():
            if v['done']:
                self.strategies['Total']['score'] += v['score']

        return self.strategies

    def count(self, number):
        return len([side for side in self.sides if side == number])

    def highest_repeated(self, min_repeats):
        repeats = [x for x in self.unique if self.count(x) >= min_repeats]
        return max(repeats) if repeats else 0

    def of_a_kind(self, n):
        hr = self.highest_repeated(n)

        if hr == 0:
            return 0

        if n == 5:
            return 50

        rests = [side for side in self.sides if side != hr]

        return hr * n + sum(rests)

    def sum_of_single(self, number):
        return sum([x for x in self.sides if x == number])

    def full_house(self):
        hr = self.highest_repeated(3)
        if hr > 0:
            rests = [side for side in self.sides if side != hr]
            if len(set(rests)) == 1 and len(rests) == 2:
                return 25

        hr = self.highest_repeated(2)
        if hr > 0:
            rests = [side for side in self.sides if side != hr]
            if len(set(rests)) == 1 and len(rests) == 3:
                return 25

        return 0

    def small_straight(self):
        if set([1, 2, 3, 4]).issubset(self.unique) or set([2, 3, 4, 5]).issubset(self.unique) or set([3, 4, 5, 6]).issubset(self.unique):
            return 30
        return 0

    def large_straight(self):
        if set([1, 2, 3, 4, 5]).issubset(self.unique) or set([2, 3, 4, 5, 6]).issubset(self.unique):
            return 40
        return 0

class GameManager():
    def __init__(self):
        self.set_status('normal')
        self.n_rolling_dices = 0
        self.n_rolls = 0
        self.n_keeps = 0
        self.score = 0
        self.n_rounds = 1
        self.highest_score = 0

    def reset(self):
        self.set_status('normal')
        self.n_rolling_dices = 0
        self.n_rolls = 0
        self.n_keeps = 0
        self.score = 0

        for dice in dices:
            dice.keep = False

        if self.n_rounds == 13:
            self.reset2()
        else:
            self.n_rounds += 1

    def reset2(self):
        self.n_rounds = 1
        self.highest_score = strategies['Total']['score']

        for k, v in strategies.items():
            strategies[k]['done'] = False

    def set_status(self, status):
        self.status = status # (normal, rolling, sorting, keeping, calculating)
        self.last_status_changed = millis()

    def roll_dices(self):
        if self.n_keeps < 5:
            self.set_status('rolling')
            self.n_rolls += 1

            for dice in dices:
                dice.roll()
        else:
            self.set_status('calculating')

    def print_board(self, strategies):
        textSize(32)
        textAlign(LEFT)

        for k, strategy in strategies.items():
            if strategy['selected']:
                fill(0, 255, 255)
            elif strategy['done']:
                fill(150)
            else:
                fill(240)
            text('%s' % (k,), strategy['position'][0], strategy['position'][1])
            text('%2d' % (strategy['score'],), strategy['position'][0] + 300, strategy['position'][1])

    def print_status(self):
        status_map = {
            'normal': 'Roll dices',
            'rolling': '',
            'sorting': '',
            'keeping': 'Select dices',
            'calculating': 'Choose category'
        }

        fill(240)
        textSize(32)
        textAlign(CENTER)
        text(status_map[self.status], 500, 100)

        textAlign(RIGHT)
        text('Round %d/13' % (self.n_rounds), 980, 40)
        text('%d/3' % (self.n_rolls), 980, 80)

        textAlign(LEFT)
        text('Highest %d' % (self.highest_score), 10, 40)

# main
strategies_order = ['1s', '2s', '3s', '4s', '5s', '6s', 'Bonus', 'Choice', '3-of-a-kind', '4-of-a-kind', 'Full House', 'S. Straight', 'L. Straight', 'Yacht', 'Total']
strategies = {
    '1s': 0,
    '2s': 0,
    '3s': 0,
    '4s': 0,
    '5s': 0,
    '6s': 0,
    'Bonus': 0,
    'Choice': 0,
    '3-of-a-kind': 0,
    '4-of-a-kind': 0,
    'Full House': 0,
    'S. Straight': 0,
    'L. Straight': 0,
    'Yacht': 0,
    'Total': 0
}

for i, strategy_name in enumerate(strategies_order):
    strategies[strategy_name] = {
           'position': [300, 400 + i * 40],
           'score': 0,
           'selected': False,
           'done': False
    }

gm = GameManager()
strategy = Strategy(strategies)

dices = []
init_pos = [
    (200, 200),
    (350, 200),
    (500, 200),
    (650, 200),
    (800, 200)
]

for pos in init_pos:
    dice = Dice(pos[0], pos[1])
    dices.append(dice)

def setup():
    frameRate(30)
    size(1000, 1000)

def draw():
    global init_pos, strategy

    background('#777777')

    gm.n_rolling_dices = 0
    gm.n_keeps = 0

    for i, dice in enumerate(dices):
        dice.display()

        if dice.status == 'rolling':
            gm.n_rolling_dices += 1

        if dice.keep:
            gm.n_keeps += 1

    if gm.status == 'rolling' and gm.n_rolling_dices == 0:
        gm.set_status('sorting')
    elif gm.status == 'sorting':
        dices.sort(key=lambda x: x.side, reverse=False)

        for dice, pos in zip(dices, init_pos):
            dice.translate(pos[0], pos[1])

        if millis() - gm.last_status_changed > 1000:
            if gm.n_rolls >= 3 or gm.n_keeps >= 5:
                gm.set_status('calculating')
            else:
                gm.set_status('keeping')

    strategy.set_dices(dices)
    strategy.calculate()

    gm.print_board(strategies)
    gm.print_status()

def mouseReleased():
    # dices area
    for i, pos in enumerate(init_pos):
        if pos[0] - 50 < mouseX < pos[0] + 50 and pos[1] - 50 < mouseY < pos[1] + 50:
            if gm.status == 'keeping':
                dices[i].keep = not dices[i].keep
                break

    # score board area
    if 300 < mouseX < 640 and strategies[strategies_order[0]]['position'][1] - 30 < mouseY < strategies[strategies_order[-1]]['position'][1]:
        if gm.status == 'keeping' or gm.status == 'calculating':
            for k, v in strategies.items():
                if k == 'Bonus' or k == 'Total':
                    continue

                pos = v['position']
                if 300 < mouseX < 640 and pos[1] - 30 < mouseY < pos[1] + 10 and strategies[k]['done'] == False:
                    strategies[k]['selected'] = not strategies[k]['selected']
                else:
                    strategies[k]['selected'] = False

    # background area
    elif not (init_pos[0][0] - 50 < mouseX < init_pos[-1][0] + 50 and init_pos[0][1] - 50 < mouseY < init_pos[-1][1] + 50):
        selected = None

        for k, v in strategies.items():
            if v['selected']:
                selected = k

        if selected is not None:
            if gm.status == 'keeping' or gm.status == 'calculating':
                strategies[selected]['done'] = True
                strategies[selected]['selected'] = False
                selected = None
                gm.reset()
        else:
            if gm.status == 'keeping' or gm.status == 'normal':
                gm.roll_dices()
            elif gm.status == 'calculating':
                if selected is not None:
                    strategies[selected]['done'] = True
                    strategies[selected]['selected'] = False
                    selected = None
                    gm.reset()


from __future__ import annotations

from typing import Iterable, Iterator, List, Literal, Optional, Type

import frictionless as fl
import marshmallow as mm
from dimcat import DimcatConfig, get_class
from dimcat.data.base import Data
from dimcat.data.packages.base import Package, PackageSpecs
from dimcat.data.resources.base import Resource
from dimcat.data.resources.dc import FeatureSpecs
from dimcat.dc_exceptions import (
    DuplicatePackageNameError,
    EmptyCatalogError,
    EmptyPackageError,
    NoMatchingResourceFoundError,
    PackageNotFoundError,
    ResourceNotFoundError,
)
from dimcat.utils import treat_basepath_argument
from frictionless import FrictionlessException
from typing_extensions import Self

class DimcatCatalog(Data):
    """Has the purpose of collecting and managing a set of :obj:`Package` objects.

    Analogous to a :obj:`frictionless.Catalog`, but without intermediate :obj:`frictionless.Dataset` objects.
    Nevertheless, a DimcatCatalog can be stored as and created from a Catalog descriptor (ToDo).
    """

    class PickleSchema(Data.PickleSchema):
        packages = mm.fields.List(
            mm.fields.Nested(Package.Schema),
            required=False,
            allow_none=True,
            metadata=dict(description="The packages in the catalog."),
        )

    class Schema(PickleSchema, Data.Schema):
        pass

    def __init__(
        self,
        basepath: Optional[str] = None,
        packages: Optional[PackageSpecs | List[PackageSpecs]] = None,
    ) -> None:
        """Creates a DimcatCatalog which is essentially a list of :obj:`Package` objects.

        Args:
            basepath: The basepath for all packages in the catalog.
        """
        self._packages: List[Package] = []
        super().__init__(basepath=basepath)
        if packages is not None:
            self.packages = packages

    def __getitem__(self, item: str) -> Package:
        try:
            return self.get_package(item)
        except Exception as e:
            raise KeyError(str(e)) from e

    def __iter__(self) -> Iterator[Package]:
        yield from self._packages

    def __len__(self) -> int:
        return len(self._packages)

    @property
    def basepath(self) -> Optional[str]:
        """If specified, the basepath for all packages added to the catalog."""
        return self._basepath

    @basepath.setter
    def basepath(self, basepath: str) -> None:
        new_catalog = self._basepath is None
        self._set_basepath(basepath, set_packages=new_catalog)

    @property
    def package_names(self) -> List[str]:
        return [package.package_name for package in self._packages]

    @property
    def packages(self) -> List[Package]:
        return self._packages

    @packages.setter
    def packages(self, packages: PackageSpecs | List[PackageSpecs]) -> None:
        if len(self._packages) > 0:
            raise ValueError("Cannot set packages if packages are already present.")
        if isinstance(packages, (Package, fl.Package, str)):
            packages = [packages]
        for package in packages:
            try:
                self.add_package(package)
            except FrictionlessException as e:
                self.logger.error(f"Adding the package {package!r} failed with\n{e!r}")

    def add_package(
        self,
        package: PackageSpecs,
        basepath: Optional[str] = None,
        copy: bool = False,
    ):
        """Adds a :obj:`Package` to the catalog."""
        if isinstance(package, fl.Package):
            dc_package = Package.from_descriptor(package)
        elif isinstance(package, str):
            dc_package = Package.from_descriptor_path(package)
        elif isinstance(package, Package):
            if copy:
                dc_package = package.copy()
            else:
                dc_package = package
        else:
            msg = f"{self.name}.add_package() takes a package, not {type(package)!r}."
            raise TypeError(msg)
        if dc_package.package_name in self.package_names:
            raise DuplicatePackageNameError(dc_package.package_name)
        if basepath is not None:
            dc_package.basepath = basepath
        self._packages.append(dc_package)

    def add_resource(
        self,
        resource: Resource,
        package_name: Optional[str] = None,
    ):
        """Adds a resource to the catalog. If package_name is given, adds the resource to the package with that name."""
        package = self.get_package_by_name(package_name, create=True)
        package.add_resource(resource=resource)

    def check_feature_availability(self, feature: FeatureSpecs) -> bool:
        """Checks whether the given feature is potentially available."""
        return True

    def copy(self) -> Self:
        new_object = self.__class__(basepath=self.basepath)
        new_object.packages = self.packages
        return new_object

    def extend(self, catalog: Iterable[Package]) -> None:
        """Adds all packages from another catalog to this one."""
        for package in catalog:
            if package.package_name not in self.package_names:
                self.add_package(package.copy())
                continue
            self_package = self.get_package_by_name(package.package_name)
            self_package.extend(package)

    def extend_package(self, package: Package) -> None:
        """Adds all resources from the given package to the existing one with the same name."""
        catalog_package = self.get_package_by_name(package.package_name, create=True)
        catalog_package.extend(package)

    def get_package(self, name: Optional[str] = None) -> Package:
        """If a name is given, calls :meth:`get_package_by_name`, otherwise returns the last loaded package.

        Raises:
            RuntimeError if no package has been loaded.
        """
        if name is not None:
            return self.get_package_by_name(name=name)
        if len(self._packages) == 0:
            raise EmptyCatalogError
        return self._packages[-1]

    def get_package_by_name(self, name: str, create: bool = False) -> Package:
        """

        Raises:
            fl.FrictionlessException if none of the loaded packages has the given name.
        """
        for package in self._packages:
            if package.package_name == name:
                return package
        if create:
            self.make_new_package(
                package_name=name,
                basepath=self.basepath,
            )
            self.logger.info(f"Automatically added new empty package {name!r}")
            return self.get_package()
        raise PackageNotFoundError(name)

    def get_resource_by_config(self, config: DimcatConfig) -> Resource:
        """Returns the first resource that matches the given config.

        Raises:
            EmptyCatalogError: If the package is empty.
            NoMatchingResourceFoundError: If no resource matching the specs is found in the "features" package.
        """
        if len(self._packages) == 0:
            raise EmptyCatalogError
        for package in self._packages:
            try:
                return package.get_resource_by_config(config)
            except (EmptyPackageError, ResourceNotFoundError):
                pass
        raise NoMatchingResourceFoundError(config)

    def get_resource_by_name(self, name: str) -> Resource:
        """Returns the Resource with the given name.

        Raises:
            EmptyCatalogError: If the package is empty.
            ResourceNotFoundError: If the resource with the given name is not found.
        """
        if len(self._packages) == 0:
            raise EmptyCatalogError
        for package in self._packages:
            try:
                return package.get_resource_by_name(name=name)
            except (EmptyPackageError, ResourceNotFoundError):
                pass
        raise ResourceNotFoundError(name, self.catalog_name)

    def get_resources_by_regex(self, regex: str) -> List[Resource]:
        """Returns the Resource objects whose names contain the given regex."""
        result = []
        for package in self._packages:
            result.extend(package.get_resources_by_regex(regex=regex))
        return result

    def get_resources_by_type(
        self,
        resource_type: Type[Resource] | str,
    ) -> List[Resource]:
        """Returns the Resource objects of the given type."""
        if isinstance(resource_type, str):
            resource_type = get_class(resource_type)
        results = []
        for package in self._packages:
            results.extend(package.get_resources_by_type(resource_type=resource_type))
        return results

    def has_package(self, name: str) -> bool:
        """Returns True if a package with the given name is loaded, False otherwise."""
        for package in self._packages:
            if package.package_name == name:
                return True
        return False

    def iter_resources(self):
        """Iterates over all resources in all packages."""
        for package in self:
            for resource in package:
                yield resource

    def make_new_package(
        self,
        package: Optional[PackageSpecs] = None,
        package_name: Optional[str] = None,
        basepath: Optional[str] = None,
        auto_validate: bool = False,
    ):
        """Adds a package to the catalog. Parameters are the same as for :class:`Package`."""
        if package is None or isinstance(package, (fl.Package, str)):
            package = Package(
                package_name=package_name,
                basepath=basepath,
                auto_validate=auto_validate,
            )
        elif not isinstance(package, Package):
            msg = f"{self.name} takes a Package, not {type(package)!r}."
            raise ValueError(msg)
        self.add_package(package, basepath=basepath)

    def replace_package(self, package: Package) -> None:
        """Replaces the package with the same name as the given package with the given package."""
        if not isinstance(package, Package):
            msg = (
                f"{self.name}.replace_package() takes a Package, not {type(package)!r}."
            )
            raise TypeError(msg)
        for i, p in enumerate(self._packages):
            if p.package_name == package.package_name:
                self.logger.info(
                    f"Replacing package {p.package_name!r} ({p.n_resources} resources) with "
                    f"package {package.package_name!r} ({package.n_resources} resources)"
                )
                self._packages[i] = package
                return
        self.add_package(package)

    def _set_basepath(
        self,
        basepath: str | Literal[None],
        set_packages: bool = True,
    ) -> None:
        """Sets the basepath for all packages in the catalog (if set_packages=True)."""
        self._basepath = treat_basepath_argument(basepath, self.logger)
        if not set_packages:
            return
        for package in self._packages:
            package.basepath = self.basepath

    def summary_dict(self, include_type: bool = True) -> dict:
        """Returns a summary of the dataset."""
        if include_type:
            summary = {
                p.package_name: [f"{r.resource_name!r} ({r.dtype})" for r in p]
                for p in self._packages
            }
        else:
            summary = {p.package_name: p.resource_names for p in self._packages}
        return dict(basepath=self.basepath, packages=summary)


import cv2
import numpy as np
import os
import random
import torch
from tqdm import tqdm
def draw(prediction,dependency):
    img=np.full((256,256,3),220,dtype=np.uint8)
    for i,c in enumerate(prediction):
        if c==0 or c>9:
            if i not in dependency:
                cv2.rectangle(img,(10+i%9*26, 10+i//9*26),(36+i%9*26, 36+i//9*26),(255,255,255),-1)
            else:
                cv2.rectangle(img, (10 + i % 9 * 26, 10 + i // 9 * 26), (36 + i % 9 * 26, 36 + i // 9 * 26),
                              (255, 180, 180), -1)
        if c>0:
            txt=str((c-1)%9+1)
            color=[(0,0,0),(0,0,255),(0,120,0)][(c-1)//9]
            cv2.putText(img, txt, (18+i%9*26, 30+i//9*26), cv2.FONT_HERSHEY_SIMPLEX, 0.7, color, 2, cv2.LINE_AA)
    for i in range(10):
        cv2.line(img,(10+26*i,10),(10+26*i,245),(0,0,0),2 if i%3==0 else 1)
    for i in range(10):
        cv2.line(img,(10,10+26*i),(245,10+26*i),(0,0,0),2 if i%3==0 else 1)
    return img

if __name__=='__main__':
    import datasets
    path='output/bart_base_sudoku_bs64'
    os.makedirs(os.path.join(path,'pic4'),exist_ok=True)
    gt=datasets.load_dataset(path='csv',
                          data_files={
                              k: os.path.join('data/sudoku',f'sudoku_{k}.csv') for k in ['test']})["test"][96339]
    src = np.int64(list(gt['quizzes']))
    tgt = np.int64(list(gt['solutions']))
    tgt[src == 0] += 18
    preds=[]
    atts=[]
    for casstep in range(5):
        pred=torch.load(os.path.join(path,f'cas_{casstep}/cas_test_generation.pk'))[96339]
        pd = pred - 3
        pd[(src == 0) & (pd + 9 == tgt)] += 9
        preds.append(pd)
        if casstep==0:
            atts.append(None)
        else:
            atts.append(torch.load(os.path.join(path,f'cas_{casstep}/cas_test_generation.pk.96339.att')))

    for i in range(1,5):
        os.makedirs(os.path.join(path, 'pic4',str(i)), exist_ok=True)
        mask=np.where((preds[i-1]!=preds[i])&(preds[i]==tgt))[0]
        for x in mask:
            row_att=atts[i][x]
            row_att[src != 0]=0
            row_att[x]=0
            dependency=np.argsort(row_att)[-5:]
            img_pd = draw(preds[i-1],dependency)
            cv2.imwrite(os.path.join(path, 'pic4', str(i), '%d-%d.png'%(x//9,x%9)), img_pd)


#!/usr/bin/env python3
# coding=utf-8

import xml.dom.minidom as xmldom
import os

class Appconfig(object):
    AppCode=""
    #AppType=""
    Icon=""
    Version=""
    PathType=""
    Path=""
    Arguments=""
    AppStartupType=""

    def __init__(self,appCode,icon,version,pathType,path,arguments,appStartupType):
        self.AppCode=appCode
        self.Icon=icon
        self.Version=version
        self.PathType=pathType
        self.Path=path
        self.Arguments=arguments
        self.AppStartupType=appStartupType

class AppConfigure(object):
    Appconfigs = []
    def __init__(self):
        super().__init__()
        self.Appconfigs.clear()

    def loadConf(self,filepath):
        self.Appconfigs.clear()
        if not os.path.isfile(filepath):
            return
        domTree = xmldom.parse(filepath)
        rootNode = domTree.documentElement
        apps=rootNode.getElementsByTagName("AppConfig")
        for app in apps:
            if app.hasAttribute("AppCode"):
                appCode = app.getAttribute("AppCode")
                icon = app.getAttribute("Icon")
                version = app.getAttribute("Version")
                pathType = app.getAttribute("PathType")
                path = app.getAttribute("Path")
                arguments = app.getAttribute("Arguments")
                appStartupType = app.getAttribute("AppStartupType")
                self.Appconfigs.append(Appconfig(appCode,icon,version,pathType,path,arguments,appStartupType))


# Packages
import numpy as np
import os

# Path to txt files
path_to_d1 = ""

########
# Data #
########
# Preallocation
data = {}

# Loading .txt files
for i in range(1,1001):
  with open(path_to_d1 + 'Domain01/{0}.txt'.format(i)) as f:
    lines = f.readlines()
    # Retrieve domain, class and user ids
    dom = lines[0].split(" ")[-1][:1]
    cla = lines[1].split(" ")[-1].split("\n")[0]
    use = lines[2].split(" ")[-1].split("\n")[0]

    # Check for right domain
    if dom != "1":
      print("Found data for domain {0} in file {1}".format(dom,i))
    # Check if the order of data insertion is the same for all files
    if lines[4].split('\n')[0].split(',') != ["<x>","<y>","<z>","<t>"]:
      print("Different order found in data insertion at index {0}".format(i))

    # Retrieve x, y, z and t data
    lines = lines[5:]
    x = []
    y = []
    z = []
    t = []
    for line in lines:
      line = line.split('\n')[0].split(',')
      x.append(float(line[0]))
      y.append(float(line[1]))
      z.append(float(line[2]))
      t.append(float(line[3]))
    # Insert data in the main dico
    if use not in data.keys():
      data[use] = {}
      data[use][cla] = {'x':[x], 'y':[y], 'z':[z], 't':[t]}
    else:
      if cla not in data[use].keys():
        data[use][cla] = {'x':[x], 'y':[y], 'z':[z], 't':[t]}
      else:
        data[use][cla]['x'].append(x)
        data[use][cla]['y'].append(y)
        data[use][cla]['z'].append(z)
        data[use][cla]['t'].append(t)

#######
# DTW #
#######

# Dynamic time warping

def dtw(user='1',k=1,dist='dtwi',data=data):
  """
  INPUTS: user, k, dist, data
    user --> str corresponding to the user left out for cross-validation
    k --> int corresponding to the number of K nearest neighbours asked to provide
    for each sequence
    dist --> str = 'euclidian' OR 'dtwi' OR 'dtwd' according to the type of distance to use
    data --> a dict corresponding to the data to use in the model (involving the
    user to leave out). Order of the keys: user > class > coordinates
  OUTPUTS: list_out
  """
  ###########################
  # Complementary functions #
  ###########################

  def comp_dtwi(c_test,c_train):
    """
    INPUTS: c_test, c_train
    c_test --> list of int/float
    c_train --> list of int/float
    OUTPUTS: dtw distance between the two 1D time series
    """
    # Preallocation
    matrix = np.zeros((len(c_test)+1,len(c_train)+1))
    # Filling the fist line and the first column with infinity values
    matrix[0,0] = 0
    for i in range(1,len(c_test)+1):
      matrix[i,0] = np.inf
    for j in range(1,len(c_train)+1):
      matrix[0,j] = np.inf
    # Filling the rest of the matrix
    for i in range(1,len(c_test)+1):
      for j in range(1,len(c_train)+1):
        matrix[i,j] = (c_test[i-1]-c_train[j-1])**2 + np.min([matrix[i-1,j-1],matrix[i-1,j],matrix[i,j-1]])
    # Computing the value with the best backward path
    i = len(c_test)
    j = len(c_train)
    path = []
    while i > 1 or j > 1:
      path.append(matrix[i,j])
      next = np.min([matrix[i-1,j-1],matrix[i-1,j],matrix[i,j-1]])
      if next == matrix[i-1,j-1]:
        i -= 1
        j -= 1
      elif next == matrix[i,j-1]:
        j -= 1
      elif next == matrix[i-1,j]:
        i -= 1
    # Add last value
    path.append(matrix[1,1])
    # Return sum of the path
    return np.sqrt(sum(path))

  def comp_dtwd(c_test,c_train):
    """
    INPUTS: c_test, c_train
    c_test --> list of lists of int/float
    c_train --> list of lists of int/float
    OUTPUTS: dtwd distance between the two multi-dimensional time series
    """
    # Preallocation
    matrix = np.zeros((len(c_test[0])+1,len(c_train[0])+1))
    # Filling the fist line and the first column with infinity values
    matrix[0,0] = 0
    for i in range(1,len(c_test[0])+1):
      matrix[i,0] = np.inf
    for j in range(1,len(c_train[0])+1):
      matrix[0,j] = np.inf
    # Filling the rest of the matrix
    for i in range(1,len(c_test[0])+1):
      for j in range(1,len(c_train[0])+1):
        # d(i,j) is computed as the sum of the squared euclidian distance for all dimensions
        distij = []
        for m in range(len(c_test)):
          distij.append((c_test[m][i-1]-c_train[m][j-1])**2)
        matrix[i,j] = sum(distij) + np.min([matrix[i-1,j-1],matrix[i-1,j],matrix[i,j-1]])
    # Computing the value with the best backward path
    i = len(c_test)
    j = len(c_train)
    path = []
    while i > 1 or j > 1:
      path.append(matrix[i,j])
      next = np.min([matrix[i-1,j-1],matrix[i-1,j],matrix[i,j-1]])
      if next == matrix[i-1,j-1]:
        i -= 1
        j -= 1
      elif next == matrix[i,j-1]:
        j -= 1
      elif next == matrix[i-1,j]:
        i -= 1
    # Add last value
    path.append(matrix[i,i])
    # Return sum of the path
    return np.sqrt(sum(path))

  def samples_dist(type,c_test,c_train):
    """
    INPUTS: type, c_test, c_train
    type --> str = 'euclidian' OR 'dtwi' OR 'dtwd' according to the type of distance to compute
    c_test --> list of float [x,y,z] of testing sample
    c_train --> list of float [x,y,z] of training sample
    OUTPUT: overall distance between the two samples
    """
    if type == 'euclidian':
      # By definition, euclidian distance cannot take into account the differences
      # in lengths or in timesteps of the two time series. The test sample is set
      # as the refence sequence.
      dist = 0
      if len(c_test[0]) <= len(c_train[0]):
        for i in range(len(c_test[0])):
          dist += np.sqrt((c_test[0][i]-c_train[0][i])**2 +
                          (c_test[1][i]-c_train[1][i])**2 +
                          (c_test[2][i]-c_train[2][i])**2)
      else:
        for i in range(len(c_train[0])):
          dist += np.sqrt((c_test[0][i]-c_train[0][i])**2 +
                          (c_test[1][i]-c_train[1][i])**2 +
                          (c_test[2][i]-c_train[2][i])**2)
      return dist
    elif type == 'dtwi':
      # dtwi is the sum of the distances computed independently for all dimensions
      dtwi = []
      for coord in range(len(c_test)):
        dtwi.append(comp_dtwi(c_test[coord],c_train[coord]))
      return sum(dtwi)
    elif type == 'dtwd':
      return comp_dtwd(c_test,c_train)

  #############
  # Main part #
  #############

  # Preallocation
  dico = {}
  coord = ['x','y','z']
  users_train = []
  for u in data.keys():
    if u != user:
      users_train.append(u)
  # Number of iterations
  it_tot = 100
  it = 1
  # Preallocation of the output
  list_out = []

  # Iterate through the testing classes
  for key in data[user].keys():
    dico[key] = []
    # Iterate through the testing samples
    for samp in range(len(data[user][key]['x'])):
      x_test = data[user][key]['x'][samp]
      y_test = data[user][key]['y'][samp]
      z_test = data[user][key]['z'][samp]

      # Preallocation with fake values
      knn_d = []
      indices = {}
      for v in range(k):
        knn_d.append(1e10)
        indices[str(v)] = [-1,-1,-1]     # [user, class, samp]
      knn_dist = np.array(knn_d)

      # Iterate through the users of the training set
      for user_tr in users_train:
        # Iterate through the training classes
        for key_tr in data[user].keys():
          # Iterate through the training samples
          for iter in range(len(data[user_tr][key_tr]['x'])):

            # Compare training and testing samples forward and backward in time
            # At the end, only the best of the two will be compared to the current knn
            dtime = []
            compo = []
            for tim in range(2):
              # Training sample
              if tim == 0:
                x_train = data[user_tr][key_tr]['x'][iter]
                y_train = data[user_tr][key_tr]['y'][iter]
                z_train = data[user_tr][key_tr]['z'][iter]
              else:
                x_train = data[user_tr][key_tr]['x'][iter]
                x_train.reverse()
                y_train = data[user_tr][key_tr]['y'][iter]
                y_train.reverse()
                z_train = data[user_tr][key_tr]['z'][iter]
                z_train.reverse()
              # Compute the distance between the testing and the training samples
              dtime.append(samples_dist(dist,[x_test,y_test,z_test],[x_train,y_train,z_train]))
              if tim == 0:
                compo.append([user_tr,key_tr,str(iter),"forward"])
              else:
                compo.append([user_tr,key_tr,str(iter),"backward"])
            # Determine best output between forward and backward in time
            ind = np.where(np.array(dtime) == min(np.array(dtime)))[0][0]
            d = dtime[ind]
            comp = compo[ind]
            # Compare to the current knn
            if d < max(knn_dist):
              # If smaller distance, replace max value in knn
              ind2 = np.where(knn_dist == max(knn_dist))[0][0]
              knn_dist[ind2] = d
              indices[str(ind2)] = comp

      # Print the current progress
      print("Iteration {0}/{1} done.".format(it,it_tot))
      it += 1
      # Store the sample's outputs in the output list
      list_out.append([indices, knn_dist.tolist()])

  return list_out

#############
# Computing #
#############

# Output path
path_out = "path/out/"

for dist_type in ["euclidian", "dtwd", "dtwi"]:
    for u in range(1,11):
        user = str(u)
        result = dtw(user=user, k=3, dist=dist_type, data=data)

        # Writing the output
        with open(path_out + "res_user={0}_type={1}.txt".format(user,dist_type), "w") as output:
            output.write("[")
            for i in range(len(result)):
                if i != len(result)-1:
                    output.write(str(result[i])+",\n")
                else:
                    output.write(str(result[i]))
            output.write("]")


# Given two binary search trees root1 and root2.

# Return a list containing all the integers from both trees sorted in ascending order.

# Example 1:

# Input: root1 = [2,1,4], root2 = [1,0,3]
# Output: [0,1,1,2,3,4]
# Example 2:

# Input: root1 = [0,-10,10], root2 = [5,1,7,0,2]
# Output: [-10,0,0,1,2,5,7,10]
# Example 3:

# Input: root1 = [], root2 = [5,1,7,0,2]
# Output: [0,1,2,5,7]
# Example 4:

# Input: root1 = [0,-10,10], root2 = []
# Output: [-10,0,10]
# Example 5:

# Input: root1 = [1,null,8], root2 = [8,1]
# Output: [1,1,8,8]

# Constraints:

# Each tree has at most 5000 nodes.
# Each node's value is between [-10^5, 10^5].
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
        def inorder(root,ans):
            if root is None:
                return
            inorder(root.left,ans)
            ans.append(root.val)
            inorder(root.right,ans)
        res1 = []
        inorder(root1,res1)
        res2 = []
        inorder(root2,res2)
        i=j=0
        res = []
        while i<len(res1) and j<len(res2):
            if res1[i]<res2[j]:
                res.append(res1[i])
                i+=1
            else:
                res.append(res2[j])
                j+=1
        while i<len(res1):
            res.append(res1[i])
            i+=1
        while j<len(res2):
            res.append(res2[j])
            j+=1
        return res

1305 All Elements in Two Binary Search Trees.py


# 예산
case = int(input())
lands = list(map(int, input().split()))
lands.sort()
max_t = int(input())

left = 0
right = lands[-1]
ret = 0
while left <= right:
    mid = (left+right)//2

    tmp = sum([min(i, mid) for i in lands])
    if tmp <= max_t:
        left = mid+1
    else:
        right = mid-1
print(right)


"""Module for I/O related data parsing"""
__author__    = "Copyright (c) 2016, Mac Xu <shinyxxn@hotmail.com>"
__copyright__ = "Licensed under GPLv2 or later."

import datetime
import pprint
import re

from app.modules.lepd.LepDClient import LepDClient

class IOProfiler:

    def __init__(self, server, config='release'):
        self.server = server
        self.client = LepDClient(self.server)
        self.config = config

    def get_status(self):

        start_time = datetime.datetime.now()

        result = self.client.getIostatResult()

        if not result:
            return {}

        end_time = datetime.datetime.now()

        raw_results = result[:]

        headerline = result.pop(0)

        duration = "%.1f" % ((end_time - start_time).total_seconds())
        io_status = {
            'lepdDuration': duration,
            'disks': {},
            'diskCount': 0,
            'ratio': 0
        }

        for line in result:
            if (line.strip() == ""):
                continue

            line_values = line.split()

            device_name = line_values[0]
            io_status['diskCount'] += 1
            io_status['disks'][device_name] = {}

            io_status['disks'][device_name]['rkbs'] = line_values[5]
            io_status['disks'][device_name]['wkbs'] = line_values[6]
            io_status['disks'][device_name]['ratio'] = line_values[-1]

            this_disk_ratio = self.client.toDecimal(line_values[-1])
            if this_disk_ratio > io_status['ratio']:
                io_status['ratio'] = this_disk_ratio

        end_time_2 = datetime.datetime.now()
        duration = "%.1f" % ((end_time_2 - end_time).total_seconds())
        io_status['lepvParsingDuration'] = duration

        response_data = {
            'data': io_status,
            'rawResult': raw_results
        }
        return response_data

    def get_capacity(self):
        responseLines = self.client.getResponse("GetCmdDf")
        if (len(responseLines) == 0):
            return {}

        responseData = {}
        if (self.config == 'debug'):
          responseData['rawResult'] = responseLines[:]

        diskData = {}
        for resultLine in responseLines:
            if (not resultLine.startswith('/dev/')):
                continue

            lineValues = resultLine.split()
            diskName = lineValues[0][5:]
            diskData[diskName] = {}
            diskData[diskName]['size'] = lineValues[1]
            diskData[diskName]['used'] = lineValues[2]
            diskData[diskName]['free'] = lineValues[3]

            diskData['size'] = lineValues[1]
            diskData['used'] = lineValues[2]
            diskData['free'] = lineValues[3]

        capacity = {}
        capacity['diskTotal'] = diskData['size']
        capacity['diskUsed'] = diskData['used']

        responseData['data'] = capacity
        return responseData

    def get_io_top(self, ioTopLines = None):

        if (ioTopLines == None):
            ioTopLines = self.client.getResponse('GetCmdIotop')

        ioTopResults = {}
        ioTopResults['data'] = {}
        ioTopResults['rawResult'] = ioTopLines[:]
        # print(len(ioTopLines))
        if (len(ioTopLines) < 2):
            return ioTopResults

        dataLineStartingIndex = 0
        for line in ioTopLines:
            if (re.match(r'\W*TID\W+PRIO\W+USER\W+DISK READ\W+DISK WRITE\W+SWAPIN\W+IO\W+COMMAND\W*', line.strip(), re.M|re.I)):
                break
            else:
                dataLineStartingIndex += 1

        while(dataLineStartingIndex >= 0):
            ioTopLines.pop(0)
            dataLineStartingIndex -= 1

        # for line in ioTopLines:
        #     print(line)
        # print('--------------------')

        orderIndex = 0
        for line in ioTopLines:
            # print(line)
            if (line.strip() == ''):
                continue

            try:
                # find the 'M/s" or 'B/s', they are for disk read and write
                matches = re.findall('\s*\d+\.\d{2}\s*[G|M|K|B]\/s\s+', line)
                diskRead = matches[0].strip()
                diskWrite = matches[1].strip()

                # find the "0.00 %" occurrences, they are for swapin and io
                matches = re.findall('\s*\d+\.\d{2}\s*\%\s+', line)
                swapin = matches[0].strip()
                io = matches[1].strip()

                lineValues = line.split()
                pid = lineValues[0].strip()
                prio = lineValues[1].strip()
                user = lineValues[2].strip()

                lastPercentIndex = line.rfind('%')
                command = line[lastPercentIndex+1:]

                ioTopItem = {}
                ioTopItem['TID'] = pid
                ioTopItem['PRIO'] = prio
                ioTopItem['USER'] = user
                ioTopItem['READ'] = diskRead
                ioTopItem['WRITE'] = diskWrite
                ioTopItem['SWAPIN'] = swapin
                ioTopItem['IO'] = io
                ioTopItem['COMMAND'] = command
            except Exception as err:
                print(err, "-------  GetCmdIotop")
                continue

            # use an incremental int as key, so we keey the order of the items.
            ioTopResults['data'][orderIndex] = ioTopItem
            orderIndex += 1

        return ioTopResults

if( __name__ =='__main__' ):
    profiler = IOProfiler('www.rmlink.cn')
    profiler.config = 'debug'

    pp = pprint.PrettyPrinter(indent=2)

    # monitor = IOMonitor('www.rmlink.cn')
    # pp.pprint(profiler.get_io_top())
    profiler.get_io_top()
    # pp.pprint(profiler.getIoPPData())

    # to make a io change on server:  sudo dd if=/dev/sda of=/dev/null &


#hyperparameters
feature_dim = 300
regularizer = 0.01
activation='relu'
optimizer = 'adam'
padding = 'valid'
dropout_rate = 0.01
nb_epochs = 10
batch_size = 256
stop_epochs = 5
nb_neurons_dense = 100

#we use this only for lstm
nb_neurons_lstm = 150

# only used for cnn
nb_filter = 100
filter1_length = 3
filter2_length = 2
pool1_length = 5
pool2_length = 3


# assignment 1
# Name-Peyush Jindal
# SID=21103092

# Question 1

number_1=input("Enter first number:")
number_2=input("Enter first number:")
number_3=input("Enter first number:")

number_1=int(number_1)
number_2=int(number_2)
number_3=int(number_3)

# average
average=(number_1 + number_2 + number_3)/3
print(average)

# Question 2

# all values are in US dollars $

Gross_Income=input("Please enter gross income:")
Gross_Income=float(Gross_Income)

Standard_Deduction=10000

Dependents=input("Enter the number of dependents:")
Dependents=int(Dependents)

#  For each dependent, a taxpayer is allowed an additional $3,000 deduction.
Dependent_Deduction=3000

Taxable_Income=Gross_Income-Standard_Deduction-(Dependent_Deduction*Dependents)
# tax rate=20%
Tax=(Taxable_Income*20)/100
print("Tax:",Tax)

# Question 3

name= input("Please enter name:")
sid= input("Enter Student ID:")
sid=int(sid)
#  Enter Gender values:
#   ‘F’ for female
#   ‘M’ for male
#   ‘U’ for unknown
gender= input("Enter gender:")
course_name= input("Enter your course name:")
cgpa= input("Enter CGPA:")
cgpa=float(cgpa)
Student=[sid,name,gender,course_name,cgpa]
print(Student)

# Question 4

student_1_marks= int(input("Enter student 1 marks:"))
student_2_marks= int(input("Enter student 2 marks:"))
student_3_marks= int(input("Enter student 3 marks:"))
student_4_marks= int(input("Enter student 4 marks:"))
student_5_marks= int(input("Enter student 5 marks:"))

my_list=[student_1_marks,student_2_marks,student_3_marks,student_4_marks,student_5_marks]
my_list.sort()
print(my_list)

# Question 5

# part a
color=['Red','Green','White','Black','Pink','Yellow']
color.remove(color[3])
print("Part a Answer:",color)

# part b
color=['Red','Green','White','Black','Pink','Yellow']
color[3:5]=['Purple']
print("Part b Answer:",color)


from regression_tests import *

class Test(Test):
    settings = TestSettings(
        input='hello.exe'
    )

    def test_main_addresses(self):
        assert self.out_c.contains('Address range: 0x407740 - 0x40775e')
        assert self.out_dsm.contains('function: main at 0x407740 -- 0x40775e')


#  Pobierz od użytkownika 10 liczb, wyświetl tylko te, które są nieparzyste.

# Wprowadzanie n numerów na listę
lista = []
print("Wprowadż 10 numerów")
for number in range(0, 10):
    new_number = int(input(f'{number+1} ->'))
    lista.append(new_number)

print("podane liczby to: ", lista)

# Sprawdzenie czy numery są parzyste i dodawanie do nowej listy
lista_parzysta = []
for i in lista:
    if i % 2 == 0:
        lista_parzysta.append(i)

print("Liczby parzyste na podanej liście to: ", lista_parzysta)

04 Kolekcje/Homework/12 Listy - zad 2.py


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

from PyQt5.QtWidgets import QWidget, QTreeWidgetItem, QMenu
from PyQt5.QtCore import pyqtSlot, QPoint

from selfcheck.controllers.selfcheckcontroller import SelfCheckController
from selfcheck.modules.editselfcheckitemmodule import EditSelfCheckItemModule
from selfcheck.views.selfcheckitemlist import Ui_Form

import user

class SelfCheckItemListModule(QWidget, Ui_Form):

    def __init__(self, parent=None):
        super(SelfCheckItemListModule, self).__init__(parent)
        self.setupUi(self)
        self.SC = SelfCheckController()
        self.current_kind = ''
        self.treeWidget_items.hideColumn(0)
        self.get_item_kind()

    def get_item_kind(self):
        temp_kind = self.current_kind
        self.comboBox_kind.clear()
        res = self.SC.get_data(0, True, *VALUES_TUPLE_KIND).distinct()
        if len(res):
            self.comboBox_kind.addItems(res)
        if temp_kind != '':
            self.comboBox_kind.setCurrentText(temp_kind)

    def get_detail(self):
        self.treeWidget_items.clear()
        condition = {'kind': self.current_kind}
        res = self.SC.get_data(0, False, *VALUES_TUPLE_ITEM, **condition)
        if not len(res):
            return
        for item in res.order_by('seqid'):
            qtreeitem = QTreeWidgetItem(self.treeWidget_items)
            qtreeitem.setText(0, str(item['autoid']))
            qtreeitem.setText(1, str(item['seqid']))
            qtreeitem.setText(2, item['itemname'])
            qtreeitem.setText(3, item['basic'])
        for i in range(1, 4):
            self.treeWidget_items.resizeColumnToContents(i)

    @pyqtSlot(str)
    def on_comboBox_kind_currentTextChanged(self, p_str):
        self.current_kind = p_str
        self.get_detail()

    @pyqtSlot(QPoint)
    def on_treeWidget_items_customContextMenuRequested(self, pos):
        global_pos =  self.treeWidget_items.mapToGlobal(pos)
        current_item = self.treeWidget_items.currentItem()
        menu = QMenu()
        action_1 = menu.addAction("增加")
        action_2 = menu.addAction("修改")
        action_3 = menu.addAction("删除")
        action = menu.exec(global_pos)
        if action == action_1:
            detail = EditSelfCheckItemModule(parent=self)
            detail.accepted.connect(self.get_item_kind)
            detail.accepted.connect(self.get_detail)
            detail.show()
        elif action == action_2:
            if current_item is None:
                return
            id = int(current_item.text(0))
            detail = EditSelfCheckItemModule(id, self)
            detail.accepted.connect(self.get_item_kind)
            detail.accepted.connect(self.get_detail)
            detail.show()
        elif action == action_3:
            if current_item is None:
                return
            id = int(current_item.text(0))
            condition = {'autoid': id}
            self.SC.delete_data(0, **condition)
            self.get_item_kind()
            self.get_detail()

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_items_itemDoubleClicked(self, qtreeitem, p_int):
        id = int(qtreeitem.text(0))
        detail = EditSelfCheckItemModule(id, self)
        detail.accepted.connect(self.get_item_kind)
        detail.accepted.connect(self.get_detail)
        detail.show()

VALUES_TUPLE_KIND = ('kind', )
VALUES_TUPLE_ITEM = ('autoid', 'seqid', 'itemname', 'basic')


#!/usr/bin/python3
# 涉及对象的定义过程，不能交互式执行，需要放入.py代码文件中执行。

# 导入LCD数字，滑块，部件，Box布局，Q程序，网格布局
from PySide2.QtWidgets import QLCDNumber, QSlider, QWidget, QVBoxLayout, QApplication, QGridLayout
# 导入Qt库
from PySide2.QtCore import Qt

class MyLCDNumber(QWidget):                 # 创建LCD数字显示器类
    def __init__(self, parent=None):        # 初始化，无父类
        super().__init__(parent)

        self.lcd_number = QLCDNumber()      # 创建一个lcd数字显示器对象
        self.slider = QSlider(Qt.Horizontal)# 创建滑动条，水平显示

        self.layout = QVBoxLayout()         # 两元素使用垂直布局（上下排列）
        self.layout.addWidget(self.lcd_number)  # 将lcd_num对象加入
        self.layout.addWidget(self.slider)  # 将slider对象加入

        self.setLayout(self.layout)
        self.setFixedSize(120, 100)         # 设置整个控件大小

        self.lcd_number.setDigitCount(2)    # 设置lcd显示器最多显示两位数字
        self.slider.setRange(0, 99)         # 设置可调节的范围
        self.slider.valueChanged.connect(self.lcd_number.display)   # 滑动条的值修改，连接到lcd的显示值

app = QApplication()                        # 初始化Q程序实例，app

window = QWidget()                          # 创建window实例，继承自Q部件

layout = QGridLayout()                      # 布局使用网格布局

mylcdnumber01 = MyLCDNumber()               # 创建lcd显示器的4个实例
mylcdnumber02 = MyLCDNumber()
mylcdnumber03 = MyLCDNumber()
mylcdnumber04 = MyLCDNumber()

layout.addWidget(mylcdnumber01, 1, 1)       # 将4个lcd显示器实例，逐个加入到全局控件中（按照坐标）
layout.addWidget(mylcdnumber02, 1, 2)
layout.addWidget(mylcdnumber03, 2, 1)
layout.addWidget(mylcdnumber04, 2, 2)

window.setLayout(layout)                    # window对象使用上述layout布局

window.show()                               # 显示window对象

app.exec_()                                 # 执行程序


from pathlib import Path

N, S = int(Path("day17.txt").read_text()), 50000000
l, pos, after2017, afterzero = [0], 0, 0, 0
for v in range(1, S+1):
  pos = (pos + N) % v + 1
  if v == 2017: after2017 = l[pos]
  elif v > 2017:
    if pos == 1:
      afterzero = v
    continue
  l.insert(pos, v)

print(after2017, afterzero)


def DeBruijnKmer(kmers):
    graph=dict()
    for item in kmers:
        temp=item[:-1]
        if temp in graph:
            graph[temp].append(item[1:])
        else:
            graph[temp]=[item[1:]]
    return graph

def GenerateCycle(graph,start):
    unexplored_edges=graph
    route=[]
    lastnode=start
    nownode=unexplored_edges[lastnode][0]
    if len(unexplored_edges[lastnode])!=1:
        del unexplored_edges[lastnode][0]
    else:
        del unexplored_edges[lastnode]
    route.append(lastnode)
    route.append(nownode)
    while nownode in unexplored_edges:
        lastnode=nownode
        nownode=unexplored_edges[lastnode][0]
        route.append(nownode)
        if len(unexplored_edges[lastnode])==1:
            del unexplored_edges[lastnode]
        else:
            del unexplored_edges[lastnode][0]
    return[route,unexplored_edges]

def EulerianCycle(graph):
    edges_remained=graph
    startnode=list(edges_remained)[0]
    [route,edges_remained]=GenerateCycle(edges_remained,startnode)
    while edges_remained:
        del route[-1]
        length=len(route)
        temp=[]
        for i in range(length):
            if route[i] in edges_remained:
                for j in range(length):
                    temp.append(route[(i+j)%length])
                route=temp
                break
        [newroute,edges_remained]=GenerateCycle(edges_remained,route[0])
        route.extend(newroute)
    return route

def GenomePath(reads):
    k=len(reads[0])
    genome=reads[0]
    for i in range(1,len(reads)):
        temp=reads[i]
        genome=genome+temp[-1]
    return(genome)

reads=[]
with open('dataset_203_7.txt','r') as f:
    content=f.read().split()
    k=content[0]
    for i in range(1,len(content)):
        reads.append(content[i])
graphstring=DeBruijnKmer(reads)
graphnumber=dict()
nodelist=list(graphstring)
nodenumber=len(nodelist)+1
indegree=[0]*nodenumber
outdegree=[0]*nodenumber
for key in graphstring:
    startnode=nodelist.index(key)
    for value in graphstring[key]:
        if value not in nodelist:
            nodelist.append(value)
        endnode=nodelist.index(value)
        if startnode in graphnumber:
            graphnumber[startnode].append(endnode)
        else:
            graphnumber[startnode]=[endnode]
        outdegree[startnode]+=1
        indegree[endnode]+=1
for i in range(nodenumber):
    if outdegree[i]>indegree[i]:
        fakeend=i
    if outdegree[i]<indegree[i]:
        fakestart=i
if fakestart in graphnumber:
    graphnumber[fakestart].append(fakeend)
else:
    graphnumber[fakestart]=[fakeend]
temp=EulerianCycle(graphnumber)
del temp[-1]
answer=[]
length=len(temp)
if temp[0]!=fakeend or temp[-1]!=fakestart:
    for i in range(1,length):
        if temp[i]==fakeend and temp[i-1]==fakestart:
            for j in range(length):
                answer.append(temp[(i+j)%length])
kmersinorder=[]
for item in answer:
    kmersinorder.append(nodelist[item])
text=GenomePath(kmersinorder)
print(text)
with open('answer.txt','w') as f:
    f.write(text)