import numpy as np

def quicksort(a):
    qsort(a,0,len(a)-1)

def particion(a,i,j): # particiona a[i],...,a[j], retorna posición del pivote
    k=np.random.randint(i,j) # genera un número al azar k en rango i..j
    (a[i],a[k])=(a[k],a[i]) # mueve a[k] al extremo izquierdo
    # a[i] es el pivote
    s=i # invariante: a[i+1..s]<=a[i], a[s+1..t]>a[i]
    for t in range(s,j):
        if a[t+1]<=a[i]:
            (a[s+1],a[t+1])=(a[t+1],a[s+1])
            s=s+1
    # mover pivote al centro
    (a[i],a[s])=(a[s],a[i])
    return s

def qsort(a,i,j): # ordena a[i],...,a[j]
    if i<j: # quedan 2 o más elementos por ordenar
        k=particion(a,i,j)
        qsort(a,i,k-1)
        qsort(a,k+1,j)

def check_order(a):
    print("Ordenado" if np.all(a[:-1]<=a[1:]) else "Desordenado")

a = np.random.random(12)
print(a)
check_order(a)
quicksort(a)
print(a)
check_order(a)


import scrapy

class KusonimeSpider(scrapy.Spider):
    name = 'kusonime'
    allowed_domains = ['kusonime.com']
    start_urls = ['http://kusonime.com/']

    def parse(self, response):
        for i in response.css(".episodeye a::attr(href)"):
            yield scrapy.Request(url=i.get(), callback=self.parse_content)

        next_page = response.css("link[rel='next']::attr(href)")
        if next_page:
            yield scrapy.Request(url=next_page.get())

    def parse_content(self, response):
        item = {
            "title": (
                response.css(".clear ~ p strong::text").get() or
                response.css(".wp-post-image::attr(title)").get()
            ).strip(),
            "url": response.url,
            "genre": response.css("a[rel='tag']::text").extract(),
            "thumbnail": response.css(".wp-post-image::attr(src)").get()
        }

        for info in response.css(".info p"):
            data = info.css("::text").getall()
            if data[0].strip() == "Genre":
                continue

            if len(data) > 2:
                k, v = data[0], data[-1]
            else:
                k, v = data
            item[k.strip()] = v.strip(": ")
        item["sinopsis"] = response.css(".clear ~ p ::text").get().strip()

        downloads = []
        for ddl in response.css(".smokeddl"):
            name = ddl.css(".smokettl::text").get()
            if not name:
                continue

            data = []
            for smokeurl in ddl.css(".smokeurl"):
                data.append({
                    "desc": smokeurl.css("strong::text").get(),
                    "url": smokeurl.css("a::attr(href)").extract()
                })
            downloads.append({
                "name": name,
                "link": data})
        item["download_data"] = downloads
        yield item


import io
import csv
import logging
import requests
import glob, os
import numpy as np
import pandas as pd
from pathlib import Path
from astropy.table import Table
from astropy import units as u
from astropy.coordinates import SkyCoord

def generate_csv(s: str, lists: list) -> str:
    """ Make a string (CSV formatted) given lists of data and header.
    Parameters
    ----------
    s: str
        String which will contain the data.
        Should initially contain the CSV header.
    lists: list of lists
        List containing data.
        Length of `lists` must correspond to the header.
    Returns
    ----------
    s: str
        Updated string with one row per line.
    Examples
    ----------
    >>> header = "toto,tata\\n"
    >>> lists = [[1, 2], ["cat", "dog"]]
    >>> table = generate_csv(header, lists)
    >>> print(table)
    toto,tata
    1,"cat"
    2,"dog"
    <BLANKLINE>
    """
    output = io.StringIO()
    writer = csv.writer(output, quoting=csv.QUOTE_NONNUMERIC)
    _ = [writer.writerow(row) for row in zip(*lists)]
    return s + output.getvalue().replace("\r", "")

def refine_search(
    ra: list,
    dec: list,
    oid: list,
    id_out: list,
    names: list,
    types: list,
    sptypes: list,
    redshift: list,
) -> list:
    """ Create a final table by merging coordinates of objects found on the
    bibliographical database, with those objects which were not found.
    Parameters
    ----------
    ra: list of float
        List of RA
    dec: list of float
        List of Dec of the same size as ra.
    oid: list of str
        List of object ID (custom)
    id_out: list of str
        List of object ID returned by the xmatch with CDS
    names: list of str
        For matches, names of the celestial objects found
    types: list of str
        For matches, astronomical types of the celestial objects found
    sptypes: list of str
        For matches, spectral types of the celestial objects found
    redshift: list of str
        For matches, astronomical redshifts of the celestial objects found
    Returns
    ----------
    out: List of Tuple
        Each tuple contains (objectId, ra, dec, name, type,sptype,redshift).
        If the object is not found in Simbad, name & type
        are marked as Unknown. In the case several objects match
        the centroid of the alert, only the closest is returned.
    """
    out = []
    for ra_in, dec_in, id_in in zip(ra, dec, oid):
        # cast for picky Spark
        ra_in, dec_in = float(ra_in), float(dec_in)
        id_in = str(id_in)

        # Discriminate with the objectID
        if id_in in id_out:
            # Return the closest object in case of many
            # (smallest angular distance)
            index = id_out.index(id_in)
            sp_type_tmp = sptypes[index] if sptypes[index] != "" else "Unknown"
            redshift_tmp = redshift[index] if redshift[index] != "" else "Unknown"
            out.append(
                (
                    id_in,
                    ra_in,
                    dec_in,
                    str(names[index]),
                    str(types[index]),
                    str(sp_type_tmp),
                    str(redshift_tmp),
                )
            )

        else:
            # Mark as unknown if no match
            out.append(
                (id_in, ra_in, dec_in, "Unknown", "Unknown", "Unknown", "Unknown")
            )

    return out

def xmatch(
    ra: list, dec: list, id: list, extcatalog: str = "simbad", distmaxarcsec: int = 1
) -> (list, list):
    """

    Build a catalog of (ra, dec, id) in a CSV-like string,
    cross-match with `extcatalog`, and decode the output.
    See http://cdsxmatch.u-strasbg.fr/ for more information.
    Parameters
    ----------
    ra: list of float
        List of RA
    dec: list of float
        List of Dec of the same size as ra.
    id: list of str
        List of object ID (custom)
    extcatalog: str
        Name of the catalog to use for the xMatch.
        See http://cdsxmatch.u-strasbg.fr/ for more information.
    distmaxarcsec: int
        Radius used for searching match. extcatalog sources lying within
        radius of the center (ra, dec) will be considered as matches.
    Returns
    ----------
    data: list of string
        Unformatted decoded data returned by the xMatch
    header: list of string
        Unformatted decoded header returned by the xmatch
    """
    # Build a catalog of alert in a CSV-like string
    table_header = """ra_in,dec_in,objectId\n"""
    table = generate_csv(table_header, [ra, dec, id])

    # Send the request!
    r = requests.post(
        "http://cdsxmatch.u-strasbg.fr/xmatch/api/v1/sync",
        data={
            "request": "xmatch",
            "distMaxArcsec": distmaxarcsec,
            "selection": "all",
            "RESPONSEFORMAT": "csv",
            "cat2": extcatalog,
            "colRA1": "ra_in",
            "colDec1": "dec_in",
        },
        files={"cat1": table},
    )

    # Decode the message, and split line by line
    # First line is header - last is empty
    data = r.content.decode().split("\n")[1:-1]
    header = r.content.decode().split("\n")[0].split(",")

    return data, header

def cross_match_alerts_raw_simbad(oid: list, ra: list, dec: list) -> list:
    """ Query the CDSXmatch service to find identified objects
    in alerts. The catalog queried is the SIMBAD bibliographical database.
    We can also use the 10,000+ VizieR tables if needed :-)
    Parameters
    ----------
    oid: list of str
        List containing object ids (custom)
    ra: list of float
        List containing object ra coordinates
    dec: list of float
        List containing object dec coordinates
    Returns
    ----------
    out: List of Tuple
        Each tuple contains (objectId, ra, dec, name, type).
        If the object is not found in Simbad, name & type
        are marked as Unknown. In the case several objects match
        the centroid of the alert, only the closest is returned.
    Examples
    ----------
    >>> ra = [26.8566983, 26.24497]
    >>> dec = [-26.9677112, -26.7569436]
    >>> id = ["1", "2"]
    >>> objects = cross_match_alerts_raw(id, ra, dec)
    >>> print(objects) # doctest: +NORMALIZE_WHITESPACE
    [('1', 26.8566983, -26.9677112, 'TYC 6431-115-1', 'Star'),
     ('2', 26.24497, -26.7569436, 'Unknown', 'Unknown')]
    """
    if len(ra) == 0:
        return []

    # Catch TimeoutError and ConnectionError
    try:
        data, header = xmatch(ra, dec, oid, extcatalog="simbad", distmaxarcsec=5)
    except (ConnectionError, TimeoutError, ValueError) as ce:
        logging.warning("XMATCH failed " + repr(ce))
        return []

    # Sometimes the service is down, but without TimeoutError or ConnectionError
    # In that case, we grab the error message from the data.
    if len(data) > 0 and "504 Gateway Time-out" in data[0]:
        msg_head = "CDS xmatch service probably down"
        msg_foot = "Check at http://cdsxmatch.u-strasbg.fr/xmatch/api/v1/sync"
        logging.warning(msg_head)
        logging.warning(data[0])
        logging.warning(msg_foot)
        return []

    # Fields of interest (their indices in the output)
    if "main_id" not in header:
        return []

    # Fields of interest (their indices in the output)
    main_id = header.index("main_id")
    main_type = header.index("main_type")
    oid_ind = header.index("objectId")
    redshift_ind = header.index("redshift")
    sp_type_ind = header.index("sp_type")

    # Get the objectId of matches
    id_out = [np.array(i.split(","))[oid_ind] for i in data]

    # Get the names of matches
    names = [np.array(i.split(","))[main_id] for i in data]

    # Get the types of matches
    types = [np.array(i.split(","))[main_type] for i in data]

    # Get the types of matches
    sp_types = [np.array(i.split(","))[sp_type_ind] for i in data]

    # Get the z of matches
    redshifts = [np.array(i.split(","))[redshift_ind] for i in data]

    # Assign names and types to inputs
    out = refine_search(ra, dec, oid, id_out, names, types, sp_types, redshifts)

    return out

if __name__ == "__main__":
    inpath = "./S82sub8_59.12"
    list_files = glob.glob(f"{inpath}/*.forced.difflc.txt")

    list_idx = []
    list_ra = []
    list_dec = []
    for fname in list_files:
        # read file and convert to pandas
        df_tmp = Table.read(fname, format="ascii").to_pandas()

        # get ra,dec, idx for xmatch
        ra_tmp, dec_tmp = df_tmp["ra"][0], df_tmp["dec"][0]
        # convert to degrees
        coo = SkyCoord(ra_tmp, dec_tmp, unit=(u.hourangle, u.deg))
        list_ra.append(coo.ra.degree)
        list_dec.append(coo.dec.degree)

        # get id
        list_idx.append(Path(fname).stem.replace(".forced.difflc", ""))

        # clean
        # del df_tmp

    # xmatch better done in list (da,dec in deg)
    matches = cross_match_alerts_raw_simbad(list_idx, list_ra, list_dec)

    xmatch_simbad_redshift = np.transpose(matches)[-1]
    xmatch_simbad_sptype = np.transpose(matches)[-2]
    xmatch_simbad_type = np.transpose(matches)[-3]
    xmatch_simbad_ctlg = np.transpose(matches)[-4]

    # save in df
    df = pd.DataFrame()
    df["id"] = list_idx
    df["simbad_type"] = xmatch_simbad_type
    df["simbad_ctlg"] = xmatch_simbad_ctlg
    df["simbad_sptype"] = xmatch_simbad_sptype
    df["simbad_redshift"] = xmatch_simbad_redshift

    df.to_csv(f"{Path(list_files[0]).parent}.csv")


#Data Processor module and methods
import json
import codecs
import math
import random
import os
import bz2

# =============================================================================
# Make sure to store raw json files under raw folder and processed csv in processed folder
# =============================================================================
csv_filename = 'processed/hash.txt'
COORDINATES = 'coordinates'
ENTITIES = 'entities'
HASHTAGS = 'hashtags'

# =============================================================================
# Captures the contents of the file
# =============================================================================
def loadFile(filename):
     with open(filename) as file:
            content = file.read()
            return content

def get_clean_files(raw_tweets):
    files = os.listdir(raw_tweets)
    if '.DS_Store' in files:
        files.remove('.DS_Store')
    return files
# =============================================================================
# Reads the json file and split record wise. If record does not have required values
# then do not write to csv file
# =============================================================================
def readFile(content):
    tweets = content.split('\n')
    fout = codecs.open(csv_filename, 'a', 'utf-8')
    #print("Number of tweets collected in this stream: ",len(tweets))
    data = []
    read=True
    for tweet in tweets:
        if read:
            [id,hashtags,long,lat] = parseTweets(tweet)
            hashes = ""
            #print("Tweets with all required features")
            for hash in hashtags:
                hashes = hashes + '#' +hash
            if id and long and hashes:
                print(id)
                record =  str(id) + ',' + hashes + ',' + str(long) + ',' + str(lat)
                fout.write(record + "\n")
    fout.close()
    return data

# =============================================================================
# Loads the json and also fill up default values
# =============================================================================
def parseTweets(content):
    try:
        obj = json.loads(content)
        lat = False
        long = False
        if 'limit' in obj:
            return ['','',0,0]
        if 'delete' in obj:
            return ['','',0,0]
        if obj['lang'] != 'en':
            return ['','',0,0]
        id = obj['id']
        if obj[COORDINATES]:
            long = obj[COORDINATES][COORDINATES][0]
            lat = obj[COORDINATES][COORDINATES][1]
        else:
            return ['','',0,0]

        hashtags = []
        for hashtag in obj[ENTITIES][HASHTAGS]:
            hashtags.append(hashtag['text'])
        if len(hashtags) == 0:
            return ['','',0,0]          # Some Default Hashtags
        return [id,hashtags,long,lat]
    except:
        return ['','',0,0]

if __name__ == '__main__':
    raw_tweets = 'raw_tweets/'
    files = get_clean_files(raw_tweets)
    for file in files:
        print("---------------------------------------------------------------")
        print(file)
        content = loadFile(raw_tweets+file)
        data = readFile(content)


import numpy as np
from matplotlib import pyplot as plt
import pywt

img = pywt.data.camera().astype(float)

# Fully separable transform
fswavedecn_result = pywt.fswavedecn(img, 'db2', 'periodization', levels=4)

# Standard DWT
coefs = pywt.wavedec2(img, 'db2', 'periodization', level=4)
# convert DWT coefficients to a 2D array
mallat_array, mallat_slices = pywt.coeffs_to_array(coefs)

fig, (ax1, ax2) = plt.subplots(1, 2)

ax1.imshow(np.abs(mallat_array)**0.25,
           cmap=plt.cm.gray,
           interpolation='nearest')
ax1.set_axis_off()
ax1.set_title('Mallat decomposition\n(wavedec2)')

ax2.imshow(np.abs(fswavedecn_result.coeffs)**0.25,
           cmap=plt.cm.gray,
           interpolation='nearest')
ax2.set_axis_off()
ax2.set_title('Fully separable decomposition\n(fswt)')

plt.show()


"""şiir.txt" şeklinde bir dosya oluşturun.
Bu dosyanın herbir satırını okuyun.
Satırların baş harflerini birbirine ekleyerek bir string oluşturun ve bu string'i ekrana yazdırın."""

from curses.ascii import isupper
from ntpath import join

with open("siir.txt", "r", encoding="utf-8")as file:

    siir = file.read()
    kelime = siir.split()

    str = ""

    for i in kelime:

        if (i.islower() == False):
            str += i[0]

print(str)


import pygame
from utils import SCREEN_WIDTH, SCREEN_HEIGHT, BG, FPS, TEXT_COL
from wall_class import Wall
from paddle_class import Paddle
from ball_class import Ball

# function outputting text onto the screen
def draw_text(text, current_font, text_col, x, y):
    img = current_font.render(text, True, text_col)
    screen.blit(img, (x, y))

pygame.init()

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Breakout 1.0")

# define font
font = pygame.font.SysFont('Constantia', 30)

# define game variables
clock = pygame.time.Clock()
live_ball = False
game_over = 0

# create the wall
wall = Wall(screen)
wall.create_wall()

# create the paddle
player_paddle = Paddle(screen)

# create the ball
ball = Ball(player_paddle.x + player_paddle.width / 2, player_paddle.y - player_paddle.height, screen)

running = True
while running:

    clock.tick(FPS)

    screen.fill(BG)

    # draw objects
    wall.draw_wall()
    player_paddle.draw()
    ball.draw()

    if live_ball:
        # move objects
        player_paddle.move()
        game_over = ball.move(player_paddle, wall)
        if game_over != 0:
            live_ball = False

    # print player instructions
    if not live_ball:
        if game_over == 0:
            draw_text("CLICK ANYWHERE TO START", font, TEXT_COL, 100, SCREEN_HEIGHT // 2+100)
        elif game_over == 1:
            draw_text("YOU WON!", font, TEXT_COL, 230, SCREEN_HEIGHT // 2 + 50)
            draw_text("CLICK ANYWHERE TO START", font, TEXT_COL, 100, SCREEN_HEIGHT // 2 + 100)
        elif game_over == -1:
            draw_text("YOU LOST!", font, TEXT_COL, 230, SCREEN_HEIGHT // 2 + 50)
            draw_text("CLICK ANYWHERE TO START", font, TEXT_COL, 100, SCREEN_HEIGHT // 2 + 100)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN and live_ball == False:
            live_ball = True
            ball.reset(player_paddle.x + player_paddle.width / 2, player_paddle.y - player_paddle.height, screen)
            player_paddle.reset(screen)
            wall.create_wall()

    pygame.display.update()


'''
英文字分析、取代、插入、删除

输入一篇英文文章 ，文章中单字与单字之间以一个空白间隔。另外输入两个单字(word) P、Q。
P为文章中所出现的单字，Q为取代或加入的单字
(1) 在文章中把 P 字串以 Q 字串取代，并输出。
(2) 在文章中把P 字串前插入 Q 字串，并输出。
(3) 在文章中把P 字串删除，并输出。

输入范例说明:
第一行，文章
第二行，英文字 P
第三行，英文字 Q

输出范例说明:
第一行，将文章中的 P 替换成 Q。
第二行，将Q 插入文章中的P 前面。
第三行，将文章中P单字删除后印出

Sample Input

This is a book That is a cook
is
was

Sample Output

This was a book That was a cook
This was is a book That was is a cook
This a book That a cook
'''

pp = input()
P = input()
Q = input()

PP = pp.split(" ")
while (P in PP):
    PP[PP.index(P)] = Q
L1 = " ".join(PP)
print(L1)

PP = pp.split(" ")
while (P in PP):
    PP[PP.index(P)] = (Q + " " + P)
L2 = " ".join(PP)
print(L2)

PP = pp.split(" ")
while (P in PP):
    PP.remove(P)
L3 = " ".join(PP)
print(L3)


import cv2
import os

# check if a folder named images exists
if not os.path.exists("images"):
    os.makedirs("images")

# capture the video from the webcam
cap = cv2.VideoCapture(0)

num_frames=0

while 1:
    ret,frame = cap.read()
    if ret==False:
        break
    # show the video
    cv2.imshow("video",frame)
    k=cv2.waitKey(1)
    if k==ord('q'):
        print("Exiting...")
        break
    # if space bar is pressed, save the frame
    if k==ord(' '):
        cv2.imwrite("images/frame%d.jpg"%num_frames,frame)
        num_frames+=1

cap.release()
cv2.destroyAllWindows()


import openerp.pooler
from openerp import models, fields, api, _

class create_tax_certificate(models.TransientModel):
    _name = 'create.tax.certificate'
    _description = 'Tax certificate creation'

    fiscalyear_id = fields.Many2one('account.fiscalyear',
                                    'Fiscal Year', required=True)
    filter = fields.Selection([
                               ('no_one', 'No Filters'),
                               ('date', 'By dates'),
                               ('period', 'By period'),
                               ('both', 'By date and by period'),
                               ], 'Date/period chosen', required=True,
                              default='no_one')
    date_begin = fields.Date('Begin Date')
    date_end = fields.Date('End Date')
    period_ids = fields.Many2many('account.period', 'certificate_wizard_rel',
                                  'period_id', 'memory_id', 'Periods')
    partner_ids = fields.Many2many('res.partner',
                                   'certificate_wizard_partner_rel',
                                   'partner_id', 'memory_id', 'Partners')

    @api.onchange('fiscalyear_id', 'filter')
    def onchange_fiscal_filter(self):
        if not self.fiscalyear_id:
            self.date_begin = False
            self.date_end = False
            self.period_ids = []
        else:
            if self.filter and self.filter != 'no_one':
                if self.filter in ['date', 'both']:
                    self.date_begin = self.fiscalyear_id.date_start
                    self.date_end = self.fiscalyear_id.date_stop
                if self.filter in ['period', 'both']:
                    self.period_ids = self.fiscalyear_id.period_ids

    _defaults = {
        'partner_ids': lambda self, cr, uid, ctx: ctx.get('active_ids', []),
    }

    @api.multi
    def create_certificate(self):
        for rec in self:
            invoice_obj = self.env['account.invoice']
            domain = [('state', 'not in', ['draft', 'cancel'])]
            period_ids = []
            filter = rec.filter
            if filter in ['period', 'both']:
                period_ids = rec.period_ids.ids
            else:
                period_ids = rec.fiscalyear_id.period_ids.ids
            domain.append(
                ('period_id', 'in', period_ids),
            )
            if rec.partner_ids:
                partner_ids = rec.partner_ids.ids
                domain += [
                    '|', ('partner_id', 'in', partner_ids),
                    ('partner_id.parent_id', 'in', partner_ids)
                ]
            if filter in ['date','both']:
                domain.append(
                    ('date_invoice', '>=', rec.date_begin)
                )
                domain.append(
                    ('date_invoice', '<=', rec.date_end)
                )
            invoices = invoice_obj.search(domain)
            fiscalyear = rec.fiscalyear_id
            certificates = invoices.create_certificate(fiscalyear,
                                                       product_ids=[])
            act = self.env.ref('tax_certificate.action_tax_certificate_list')
            action = act.read()
            if isinstance(action, list):
                action = action and action[0] or {}
            action['domain'] = [('id', 'in', certificates.ids)]
            return action

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:


class Translator:
    def __init__(self, files, language, split=None):
        self.files = files
        self.language = language
        self.split = '|' if split is None else split

    def get(self, path, values={}):
        keys = path.split(self.split)

        string = self.files.strings[self.language]

        for key in keys:
            string = string[key]

        if values:
            return string.format(**values)

        return string


"""

"""
#import the libraries
import queue

#Node Class
class Node:
    def __init__(self, data):
        self.data = data
        self.children = []

#Build a tree using BFS
def buildTree():
    #Tree is built using BFS
    q = queue.Queue()
    q.put(root)
    while(q.qsize() > 0):
        curr = q.get()
        childnum = int(input("Number of children for parent " + str(curr.data) + ": "))
        for i in range(childnum):
            child = int(input("Enter the child " + str(i+1) + " of parent " + str(curr.data) + ": "))
            n = Node(child)
            curr.children.append(n)
            q.put(n)

#Function to calculate the cost
def calculateCost(root):
    q = queue.Queue()
    q.put(root)
    cost = 0
    while(q.qsize() > 0):
        curr = q.get()
        for child in curr.children:
            if(len(child.children) >= x):
                cost += (child.data * child.parent.data) + y
            else:
                cost += child.data * child.parent.data
            q.put(child)
    return cost

#Function to calculate the cost of the new Nodes
def calculateCostNewNodes(root, newNodes):
    q = queue.Queue()
    q.put(root)
    cost = 0
    while(q.qsize() > 0):
        curr = q.get()
        for child in curr.children:
            if(len(child.children) >= x):
                cost += (child.data * child.parent.data) + y
            else:
                cost += child.data * child.parent.data
            q.put(child)
    for node in newNodes:
        if(len(node.children) >= x):
            cost += (node.data * node.parent.data) + y
        else:
            cost += node.data * node.parent.data
    return cost

#Function to print the tree
def printTree(root):
    q = queue.Queue()
    q.put(root)
    while(q.qsize() > 0):
        curr = q.get()
        print("Parent " + str(curr.data))
        for child in curr.children:
            print("Child " + str(child.data))
            q.put(child)

#Main Function
def main():
    global root, x, y
    N = int(input("Enter the number of nodes in the tree: "))
    nodeValues = input("Enter the values of the nodes in the tree: ").split()
    root = Node(int(nodeValues[0]))
    for i in range(1, N):
        node = Node(int(nodeValues[i]))
        node.parent = root
        root.children.append(node)
    #buildTree()
    print("Tree built.")
    #printTree(root)
    Q = int(input("Enter the number of queries you want to perform: "))
    for i in range(Q):
        M, x, y = input("Enter the M, x, y values: ").split()
        M, x, y = int(M), int(x), int(y)
        newNodes = []
        newNodeValues = input("Enter the values of the new nodes: ").split()
        for j in range(M):
            node = Node(int(newNodeValues[j]))
            node.parent = root
            root.children.append(node)
            newNodes.append(node)
        print("The cost of adding the new nodes (from newNodes) to the tree is: " + str(calculateCostNewNodes(root, newNodes)))

main()


from djitellopy import Tello
from time import sleep
import math
# Фигуры
import pawn, elephant, tower, queen, horse, king

drone = Tello()
drone.connect()
print(drone.get_battery())

drone.takeoff()
sleep(1)

drone_type = input()

while True:
    cmd = input()

    # Проверка и получение кол-ва шагов
    if len(cmd.split()) > 1:
        steps = int(list(cmd.split())[1])
        cmd = list(cmd.split())[0]

    if drone_type == "pawn":
        if cmd == "first_move":
            pawn.first_move(drone)
        elif cmd == "move":
            pawn.move(drone)
        elif cmd == "attack_right":
            pawn.attack_right(drone)
        elif cmd == "attack_left":
            pawn.attack_left(drone)

    elif drone_type == "horse":
        if cmd == "move_up_left":
            horse.move_up_left(drone)
        elif cmd == "move_left_up":
            horse.move_left_up(drone)
        elif cmd == "move_up_right":
            horse.move_up_right(drone)
        elif cmd == "move_right_up":
            horse.move_right_up(drone)
        elif cmd == "move_down_left":
            horse.move_down_left(drone)
        elif cmd == "move_left_down":
            horse.move_left_down(drone)
        elif cmd == "move_down_right":
            horse.move_down_right(drone)
        elif cmd == "move_right_down":
            horse.move_right_down(drone)

    elif drone_type == "elephant":
        if cmd == "right_forward_move":
            elephant.right_forward_move(drone, steps)
        elif cmd == "right_back_move":
            elephant.right_back_move(drone, steps)
        elif cmd == "left_forward_move":
            elephant.left_forward_move(drone, steps)
        elif cmd == "left_back_move":
            elephant.left_back_move(drone, steps)

    elif drone_type == "tower":
        if cmd == "forward_move":
            tower.forward_move(drone, steps)
        elif cmd == "back_move":
            tower.back_move(drone, steps)
        elif cmd == "right_move":
            tower.right_move(drone, steps)
        elif cmd == "left_move":
            tower.left_move(drone, steps)
        elif cmd == "short_castling":
            tower.short_castling(drone)
        elif cmd == "long_castling":
            tower.long_castling(drone)

    elif drone_type == "queen":
        if cmd == "forward_move":
            queen.forward_move(drone, steps)
        elif cmd == "back_move":
            queen.back_move(drone, steps)
        elif cmd == "right_move":
            queen.right_move(drone, steps)
        elif cmd == "left_move":
            queen.left_move(drone, steps)
        elif cmd == "right_forward_move":
            queen.right_forward_move(drone, steps)
        elif cmd == "right_back_move":
            queen.right_back_move(drone, steps)
        elif cmd == "left_forward_move":
            queen.left_forward_move(drone, steps)
        elif cmd == "left_back_move":
            queen.left_back_move(drone, steps)

    elif drone_type == "king":
        if cmd == "left":
            king.left(drone)
        elif cmd == "right":
            king.right(drone)
        elif cmd == "m_up":
            king.m_up(drone)
        elif cmd == "down":
            king.down(drone)
        elif cmd == "left_up":
            king.left_up(drone)
        elif cmd == "right_up":
            king.right_up(drone)
        elif cmd == "left_down":
            king.left_down(drone)
        elif cmd == "right_down":
            king.right_down(drone)
        elif cmd == "short_castling":
            king.short_castling(drone)
        elif cmd == "long_castling":
            king.long_castling(drone)

    if cmd == "end_ flight":
        drone.land()
        break
    sleep(1)


"""implementation of PythonLogger class
"""

import logging

from ._log_level_convertion import to_python_log_level
from .._mprpc_cpp import PythonLoggerHelper, LogLevel

class PythonLogger(PythonLoggerHelper):  # pylint: disable=too-few-public-methods
    """class to write logs using Python's logging module

    Parameters
    ----------
    log_output_level : mprpc.logging.LogLevel
        log output level (default to LogLevel.WARN)
    """

    def __init__(self, log_output_level: LogLevel = LogLevel.WARN):

        super().__init__(self.__write_impl, log_output_level)
        self.logger = logging.getLogger("mprpc")

    # pylint: disable=too-many-arguments
    def __write_impl(self, label: str, filename: str, line: int, function: str,
                     log_level: LogLevel, message: str):
        """write log

        Parameters
        ----------
        label : str
            label
        filename : str
            file name
        line : int
            line number
        function : str
            function name
        log_level : LogLevel
            log level
        message : str
            log message

        Returns
        -------
        None
            none
        """

        log = logging.LogRecord(label, to_python_log_level(
            log_level), filename, line, message, [], None, function, None)
        self.logger.handle(log)


import os
import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

'''
IST 597: Foundations of Deep Learning
Problem 3: Multivariate Regression & Classification

Adapted from Alexander G. Ororbia II and Ankur Mali
@author - Nikhil Sunil Nandoskar

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

# meta-parameters for program
trial_name = 'p6_reg0' # will add a unique sub-string to output of this program
degree = 6 # p, degree of model
beta = 1 # regularization coefficient
alpha = 1.5 # step size coefficient
n_epoch = 5000 # number of epochs (full passes through the dataset)
eps = 0.00001 # controls convergence criterion

# begin simulation
def sigmoid(z):
	return (tf.divide(1,tf.add(tf.cast(1, dtype = tf.float64), tf.exp(-z))))

def predict(X, theta):
    n = sigmoid(theta[0] + tf.matmul(X,theta[1], transpose_b = True))
    u = tf.round(n)
    return (u)

def regress(X, theta):
	return (sigmoid(theta[0] + tf.matmul(X,theta[1], transpose_b = True)))

def bernoulli_log_likelihood(p, y, theta):
	return (tf.add(tf.multiply(y, tf.log(regress(p, theta))),tf.multiply(tf.subtract(tf.cast(1, dtype = tf.float64), y),tf.log(tf.subtract(tf.cast(1, dtype = tf.float64), regress(p, theta))))))

def computeCost(X, y, theta, beta): # loss is now Bernoulli cross-entropy/log likelihood
    m = tf.cast(tf.shape(X), tf.float64)
    beta = tf.cast(beta, dtype = tf.float64)
    return (tf.add(tf.divide(tf.reduce_sum(-bernoulli_log_likelihood(X, y, theta)), m[0]), tf.divide(tf.multiply(beta,tf.reduce_sum(tf.square(theta[1]))), 2*m[0]) ))

def computeGrad(X, y, theta, beta):

    m = tf.cast(tf.shape(X), tf.float64)
    beta = tf.cast(beta, dtype = tf.float64)
    dL_dfy = None # derivative w.r.t. to model output units (fy)
    dL_db = tf.divide(tf.reduce_sum(tf.subtract(regress(X, theta), y)), m[0]) # derivative w.r.t. model weights w
    dL_dw = tf.divide(tf.add(tf.matmul(tf.subtract(regress(X, theta), y),X, transpose_a = True), tf.multiply(beta, theta[1])), m[0]) # derivative w.r.t model bias b
    nabla = (dL_db, dL_dw) # nabla represents the full gradient
    return nabla

path = os.getcwd() + '/data/prob3.dat'
data2 = pd.read_csv(path, header=None, names=['Test 1', 'Test 2', 'Accepted'])

positive = data2[data2['Accepted'].isin([1])]
negative = data2[data2['Accepted'].isin([0])]

#Convert positive and negative samples into tf.Variable
positive_tf_var = tf.Variable(positive)
negative_tf_var = tf.Variable(negative)

x1 = data2['Test 1']
x2 = data2['Test 2']

#Convert x1 and x2 to tensorflow variables
x1_tf_var = tf.Variable(x1)
x2_tf_var = tf.Variable(x2)

# apply feature map to input features x1 and x2
cnt = 0
for i in range(1, degree+1):
	for j in range(0, i+1):
		data2['F' + str(i) + str(j)] = np.power(x1, i-j) * np.power(x2, j)
		cnt += 1

data2.drop('Test 1', axis=1, inplace=True)
data2.drop('Test 2', axis=1, inplace=True)

# set X and y
cols = data2.shape[1]
X2 = data2.iloc[:,1:cols]
y2 = data2.iloc[:,0:1]

# make results reproducible
seed = 1491189
np.random.seed(seed)
tf.set_random_seed(seed)

# convert to numpy arrays and initalize the parameter array theta
X2 = np.array(X2.values)
y2 = np.array(y2.values)
w = np.zeros((1,X2.shape[1]))
b = np.array([0])
theta = (b, w)

#Converting w and b to tensors
w_t = tf.Variable(w, dtype = tf.float64, name = "w")
b_t = tf.Variable(b, dtype = tf.float64, name = "b")

#Convert all numpy variables into tensorflow variables
X2_t = tf.convert_to_tensor(X2, dtype = tf.float64)
y2_t = tf.convert_to_tensor(y2, dtype = tf.float64)

#Creating placeholders for X2 and y2
X2_p = tf.placeholder(dtype = tf.float64, shape = (X2_t.shape[0], 27))
y2_p = tf.placeholder(dtype = tf.float64, shape = (y2_t.shape[0], 1))

init = tf.global_variables_initializer()

L = computeCost(X2_t, y2_t, theta, beta)
cost = []
with tf.Session()as sess:
    sess.run(init)
    print("-1 L = {0}".format(L.eval()))
    cost.append(L.eval())

i = 0
halt = 0
#Initialize graph and all variables
with tf.Session() as sess:
    sess.run(init)
    while(i < n_epoch and halt == 0):
            dL_db, dL_dw = computeGrad(X2_t, y2_t, theta, beta)
            o,k = sess.run([dL_db, dL_dw], feed_dict = {X2_p:X2, y2_p:y2})
            b = theta[0]
            w = theta[1]
		# update rules go here...
            b = b - alpha*o
            w = w - alpha*k
            theta = (b,w)
            L = computeCost(X2_t, y2_t, theta, beta)
            if (cost[- 1] - L.eval()) < eps:
                break
            cost.append(L.eval())
            print(" {0} L = {1}".format(i,L.eval()))
            i += 1

# print parameter values found after the search
    print("w = ",w)
    print("b = ",b)
    saver = tf.train.Saver([w_t, b_t])
    saver.save(sess, os.getcwd() + '/Pb_3_Saved/Model', global_step = i )

#Save everything into saver object in tensorflow
with tf.Session() as sess:
    writer = tf.summary.FileWriter(os.getcwd() + '/Pb_3_Tensorboard', sess.graph)

# Predictions
with tf.Session() as sess:
    sess.run(init)
    predictions = predict(X2, theta)
    m = tf.cast(tf.shape(X2), tf.float64)
    err = tf.subtract(tf.cast(1, dtype = tf.float64), tf.divide(tf.add(tf.matmul(tf.transpose(y2_t), predictions), tf.matmul(tf.transpose(tf.subtract(tf.cast(1, dtype = tf.float64), y2_t)), tf.subtract(tf.cast(1, dtype = tf.float64), predictions))), m[0]))
    print('Error = {0}%'.format(err.eval()*100.))

# make contour plot
xx, yy = np.mgrid[-1.2:1.2:.01, -1.2:1.2:.01]
xx1 = xx.ravel()
yy1 = yy.ravel()
grid = np.c_[xx1, yy1]
grid_nl = []
# re-apply feature map to inputs x1 & x2
#Convert the below feature map into tensorflow environment

for i in range(1, degree+1):
    for j in range(0, i+1):
        feat = np.power(xx1, i-j) * np.power(yy1, j)
        if(len(grid_nl) > 0):
            grid_nl = np.c_[grid_nl, feat]
        else:
            grid_nl = feat

grid_nl_in = tf.convert_to_tensor(grid_nl, dtype = tf.float64)
prob1 = []
with tf.Session() as sess:
    probs = regress(grid_nl_in, theta)
    probs = tf.reshape(probs, shape = xx.shape)
    prob1 = probs.eval()

f, ax = plt.subplots(figsize=(8, 6))
ax.contour(xx, yy, prob1, levels=[.5], cmap="Greys", vmin=0, vmax=.6)
x1 = np.expand_dims(x1, axis=1)
x2 = np.expand_dims(x2, axis=1)
ax.scatter(x1, x2, c=y2, s=50,
           cmap="RdBu", vmin=-.2, vmax=1.2,
           edgecolor="white", linewidth=1)

ax.set(aspect="equal",
       xlim=(-1.5, 1.5), ylim=(-1.5, 1.5),
       xlabel="$X_1$", ylabel="$X_2$")
plt.savefig(os.getcwd() + '/Pb_3_Contour_Fig.jpg')
plt.show()

plt.plot(cost)
plt.title('Loss vs Epoch')
plt.xlabel('Number of epochs')
plt.ylabel('Cost')
plt.savefig(os.getcwd() + '/Pb_3_Loss_Fig.jpg')
plt.show()


def list_op(my_list, index, operation):
    try:
        result = operation(my_list[index])
        return result
    except IndexError:
        return None

my_list = [1, 2, 3, 4, 5]

index = 10
operation = lambda x: x * 2

result = list_op(my_list, index, operation)

if result is not None:
    print("Result: {result}")
else:
    print("Index is out of range.")


from gpt_2 import gpt2
import os

import tensorflow as tf

def train_gpt2(
        csv_path='gpt2_train_data/bertffn_crossentropy.csv',
        steps=100000,
        batch_size=1):
    tf.compat.v1.disable_v2_behavior()
    if not os.path.exists('models/117M'):
        gpt2.download_gpt2()

    sess = gpt2.start_tf_sess()
    gpt2.finetune(sess, csv_path, steps=steps, batch_size=batch_size)


"""preproonsite"""

def main():
    """prepro"""
    money = int(input())
    waterprice = int(input())
    usemoney = money - waterprice
    snack1 = int(input())
    snack2 = int(input())
    snack3 = int(input())
    if usemoney %3 == 0:
        snack1 *= 10
    elif usemoney %3 == 1:
        snack1 *= 15
    elif usemoney %3 == 2:
        snack1 *= 20
    usemoney -= snack1
    print(usemoney)
    if usemoney %3 == 0:
        snack2 *= 12
    elif usemoney %3 == 1:
        snack2 *= 15
    elif usemoney %3 == 2:
        snack2 *= 18
    usemoney -= snack2
    print(usemoney)
    if usemoney %3 == 0:
        snack3 *= 5
    elif usemoney %3 == 1:
        snack3 *= 7
    elif usemoney %3 == 2:
        snack3 *= 9
    usemoney -= snack3
    print(usemoney)
    if usemoney < 0:
        print("Now you have" , money , "left.")
        print("You don't have enough money!")
    else:
        print("Now you have" , usemoney, "left.")
        print("Here's your order!")
        print("Water:" , waterprice , "baht")
        print("Snack number 1:", snack1 , "baht")
        print("Snack number 2:", snack2 , "baht")
        print("Snack number 3:", snack3 , "baht")
main()


# Programmas nosaukums: Trīs masīvu apvienošana. 1.-augošs, 2.-dilstošs, 3.-augošs
# 2. uzdevums (1MPR07_Vladislavs_Babaņins)
# Uzdevuma formulējums: Lietotājs ievada trīs dažāda garuma masīvus, no kuriem pirmais ir sakārtots augošā secībā,
# otrais ir sakārtots dilstošā secībā un trešais sakārtots augošā secībā.
# Lineārā laikā apvienot visus trīs masīvus vienā dilstošā secībā sakārtotā masīvā un izvadīt to uz ekrāna.
# Versija 1.0

import numpy

def izveidot_masivu_ar_garumu(n):
    # Izveido masīvu ar noradīto garumu n
    # n - naturāls skaitlis
    a = numpy.arange(n)
    for i in range(n):
        b = input("Ievadiet " + str(i) + ".elementu ===> ")
        b = is_whole(b, i)
        a[i] = b
    return a

def izvade(x):
    # Izvada masīva elementus pēc kārtas līdz pedējam
    # x - viendimensijas masīvs
    n = len(x)
    s = str(x[0])
    for i in range(1, n):
        s = s + ", " + str(x[i])
    print(s)

def is_whole(x, i):
    # Pārbauda vai simbolu virkne ir vesels skaitlis un ja nē, tad paprasa ievadīt to vēlreiz (bezgalīgi daudz ievādes)
    # Ja simbolu virkne ir vesels skaitlis, tad atgriež to kā int(x)
    # x - pārbaudāma simbolu virkne
    # i - i-tajs elements
    while True:
        try:
            x = int(x)
        except:
            x = input("Kļūda! Ievadiet " + str(i) + ".elementu ===> ")
        else:
            return int(x)

def is_natural(n):
    # Pārbauda vai simbolu virkne ir naturāls skaitlis vai nav
    # Ja ir naturāls skaitlis, tad True. Ja nav tad False.
    # n - simbolu virkne, kuru pārbauda.
    if str(n).isdigit() and float(n) == int(n) and int(n) > 0:
        return True
    else:
        return False

def apvieno(a, b):
    # Apvieno divus sakartotus masīvus a un b, un sakarto tos
    # Lineāra laiks o(n)
    # a - viendimensijas masīvs
    # b - viendimensijas masīvs
    ga = len(a)
    gb = len(b)
    gc = ga + gb
    c = numpy.arange(gc)
    ia = 0
    ib = 0
    ic = 0
    while (ia < ga) and (ib < gb):
        if a[ia] < b[ib]:
            c[ic] = a[ia]
            ia = ia + 1
        else:
            c[ic] = b[ib]
            ib = ib + 1
        ic = ic + 1
    if ia < ga:
        for i in range(ia, ga):
            c[ic] = a[i]
            ic = ic + 1
    else:
        for i in range(ib, gb):
            c[ic] = b[i]
            ic = ic + 1
    return c

def reverse(masivs):
    # Pārkarto masīvā visus elementus pretēji
    # masivs - viendimensijas masīvs
    start_index = 0
    end_index = len(masivs) - 1
    while end_index > start_index:
        temp = masivs[start_index]
        masivs[start_index] = masivs[end_index]
        masivs[end_index] = temp
        start_index = start_index + 1
        end_index = end_index - 1

# ---------------------------------------------------------
# Galvenā programmas daļa
# ---------------------------------------------------------

m = input("Ievadiet 1. masīva izmēru ===> ")

while is_natural(m) == False:
    m = input("Masīva izmērs ir naturāls skaitlis!\nIevadiet masīva izmēru N ===> ")

m = int(m)

print("\nIevadiet sakārota augošā (nedilstoša) secība masīva skaitļus!")
a = izveidot_masivu_ar_garumu(m)

n = input("\nIevadiet 2. masīva izmēru ===> ")

while is_natural(n) == False:
    n = input("Masīva izmērs ir naturāls skaitlis!\nIevadiet masīva izmēru N ===> ")

n = int(n)

print("\nIevadiet sakārota dilstoša (neaugoša) secība masīva skaitļus!")
b = izveidot_masivu_ar_garumu(n)

k = input("\nIevadiet 3. masīva izmēru ===> ")

while is_natural(k) == False:
    n = input("Masīva izmērs ir naturāls skaitlis!\nIevadiet masīva izmēru N ===> ")

k = int(k)

print("\nIevadiet sakārota augošā (nedilstoša) secība masīva skaitļus!")
c = izveidot_masivu_ar_garumu(k)

print("\nPirmais augošā (nedilstoša) secība sakārtots masīvs:")
izvade(a)
print("\nOtrais dilstoša (neaugoša) secība sakārtots masīvs:")
izvade(b)
print("\nTrešais augošā (nedilstoša) secība sakārtots masīvs:")
izvade(c)

reverse(b)

ab = apvieno(a, b)
abc = apvieno(ab, c)

reverse(abc)
print("\nApvienoti visi trīs sakārtoti masīvi dilstoša (neaugoša) secība:")
izvade(abc)

1. Kurss 2. semestris Programmešana un datori II/1MPR07/2uzd_MPR07.py


import functools
import shutil

import pandas as pd
import requests

from typing import Union, Tuple
from abc import abstractmethod
from urllib.parse import urlparse

from tqdm import tqdm
from requests import Response
from pathlib import Path

from tenet.handlers.code_parser import CodeParserHandler
from tenet.handlers.container import ContainerHandler
from tenet.handlers.cwe_list import CWEListHandler
from tenet.handlers.file_parser import FileParserHandler
from tenet.handlers.github import GithubHandler
from tenet.handlers.node import NodeHandler
from tenet.handlers.runner import MultiTaskHandler
from tenet.handlers.sampling import SamplingHandler

class PluginHandler(NodeHandler):
    """
        Plugin handler abstraction
    """
    class Meta:
        label = 'plugin'

    def __init__(self, **kw):
        super().__init__(**kw)
        self._multi_task_handler: MultiTaskHandler = None
        self._code_parser_handler: CodeParserHandler = None
        self._container_handler: ContainerHandler = None
        self._github_handler: GithubHandler = None
        self._cwe_list_handler: CWEListHandler = None
        self._file_parser_handler: FileParserHandler = None
        self._sampling_handler: SamplingHandler = None

    @property
    def github_handler(self):
        if not self._github_handler:
            self._github_handler = self.app.handler.get('handlers', 'github', setup=True)
        return self._github_handler

    @github_handler.deleter
    def github_handler(self):
        self._github_handler = None

    @property
    def cwe_list_handler(self):
        if not self._cwe_list_handler:
            self._cwe_list_handler = self.app.handler.get('handlers', 'cwe_list', setup=True)
        return self._cwe_list_handler

    @cwe_list_handler.deleter
    def cwe_list_handler(self):
        self._cwe_list_handler = None

    @property
    def multi_task_handler(self):
        if not self._multi_task_handler:
            self._multi_task_handler = self.app.handler.get('handlers', 'multi_task', setup=True)
        return self._multi_task_handler

    @multi_task_handler.deleter
    def multi_task_handler(self):
        self._multi_task_handler = None

    @property
    def code_parser_handler(self):
        if not self._code_parser_handler:
            self._code_parser_handler = self.app.handler.get('handlers', 'code_parser', setup=True)
        return self._code_parser_handler

    @code_parser_handler.deleter
    def code_parser_handler(self):
        self._code_parser_handler = None

    @property
    def container_handler(self):
        if not self._container_handler:
            container_handler_class = self.app.handler.get('handlers', 'container')
            working_dir = Path(str(self.path).replace(str(self.app.workdir), str(self.app.bind)))
            self._container_handler = container_handler_class(working_dir=working_dir, output=self.output,
                                                              local_working_dir=self.path)
            self._container_handler._setup(self.app)
        return self._container_handler

    @container_handler.deleter
    def container_handler(self):
        self._container_handler = None

    @property
    def file_parser_handler(self):
        if not self._file_parser_handler:
            self._file_parser_handler = self.app.handler.get('handlers', 'file_parser', setup=True)
        return self._file_parser_handler

    @file_parser_handler.deleter
    def file_parser_handler(self):
        self._file_parser_handler = None

    @property
    def sampling_handler(self):
        if not self._sampling_handler:
            self._sampling_handler = self.app.handler.get('handlers', 'sampling', setup=True)
        return self._sampling_handler

    @sampling_handler.deleter
    def sampling_handler(self):
        self._sampling_handler = None

    @abstractmethod
    def run(self, dataset: pd.DataFrame, **kwargs) -> Union[pd.DataFrame, None]:
        """
            Executes plugin

            :param dataset: dataframe with the dataset resulting from the previous node
            :return: dataframe with the processed dataset
        """
        pass

    @abstractmethod
    def set_sources(self):
        """
            Sets sources of the plugin for sinks of other plugins
        """
        pass

    @abstractmethod
    def get_sinks(self):
        """
            Inits sinks of the plugin with sources of other plugins
        """
        pass

    def plot(self, dataset: pd.DataFrame, **kwargs):
        """
            Plots resulting dataframe

            :param dataset: dataframe with the dataset resulting from the previous node
            :return: dataframe with the processed dataset
        """
        pass

    def convert_labels(self, labels: pd.Series):
        label_map = self.app.get_config('labels_map')
        return labels.apply(lambda l: label_map[l])

    def download_file_from_url(self, url: str, extract: bool = False) -> Union[Tuple[Response, Path], None]:

        if not 'http' in url:
            self.app.lof.warning(f"URL {url} is not valid.")
            return None

        file_path = self.path / Path(urlparse(url).path).name
        extract_file_path = self.path / file_path.stem
        response = requests.get(url, stream=True, allow_redirects=True)

        if response.status_code != 200:
            self.app.log.error(f"Request to {url} returned status code {response.status_code}")
            return None

        total_size_in_bytes = int(response.headers.get('Content-Length', 0))

        if file_path.exists() and file_path.stat().st_size == total_size_in_bytes:
            self.app.log.warning(f"File {file_path} exists. Skipping download...")
        else:
            desc = "(Unknown total file size)" if total_size_in_bytes == 0 else ""
            response.raw.read = functools.partial(response.raw.read, decode_content=True)  # Decompress if needed

            with tqdm.wrapattr(response.raw, "read", total=total_size_in_bytes, desc=desc) as r_raw:
                with file_path.open("wb") as f:
                    shutil.copyfileobj(r_raw, f)

        if extract:
            if not extract_file_path.exists():
                self.app.log.info(f"Extracting file {extract_file_path}...")
                shutil.unpack_archive(file_path, self.path)

            return response, extract_file_path

        return response, file_path


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

from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function

"""Script to commit the doc build outputs into the github-pages repo.

In practice, you should use either actual clean tags from a current build or
something like 'current' as a stable URL for the mest current version of the """

# Imports
import os
import re
import shutil
import sys
from os import chdir as cd

import numpy as np

from subprocess import Popen, PIPE, CalledProcessError, check_call

pages_dir = 'gh-pages'
html_dir = 'build/html'
pdf_dir = 'build/latex'
pages_repo = 'git@github.com:bnoi/scikit-tracker.git'

def sh(cmd):
    """Execute command in a subshell, return status code."""
    return check_call(cmd, shell=True)

def sh2(cmd):
    """Execute command in a subshell, return stdout.

    Stderr is unbuffered from the subshell.x"""
    p = Popen(cmd, stdout=PIPE, shell=True)
    out = p.communicate()[0]
    retcode = p.returncode
    if retcode:
        print(out.rstrip())
        raise CalledProcessError(retcode, cmd)
    else:
        return out.rstrip()

def sh3(cmd):
    """Execute command in a subshell, return stdout, stderr

    If anything appears in stderr, print it out to sys.stderr"""
    p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
    out, err = p.communicate()
    retcode = p.returncode
    if retcode:
        raise CalledProcessError(retcode, cmd)
    else:
        return out.rstrip(), err.rstrip()

def init_repo(path):
    """clone the gh-pages repo if we haven't already."""
    sh("git clone %s %s" % (pages_repo, path))
    here = os.getcwd()
    cd(path)
    sh('git checkout gh-pages')
    cd(here)

# Script starts

if __name__ == '__main__':

    sys.path.append('..')
    import sktracker
    version = sktracker.__version__

    if "dev" in version:
        stable_version = str(np.round(float(version[:3]) - 0.1, 1))
        tag = "dev"
    else:
        tag = version[:3]
        stable_version = tag

    startdir = os.getcwd()
    if not os.path.exists(pages_dir):
        init_repo(pages_dir)
    else:
        cd(pages_dir)
        sh('git checkout gh-pages')
        sh('git pull')
        cd(startdir)

    dest = os.path.join(pages_dir, tag)

    # This is pretty unforgiving: we unconditionally nuke the destination
    # directory, and then copy the html tree in there
    shutil.rmtree(dest, ignore_errors=True)
    shutil.copytree(html_dir, dest)

    try:
        cd(pages_dir)
        branch = sh2('git rev-parse --abbrev-ref HEAD').decode("utf-8")

        if branch != 'gh-pages':
            e = 'On %r, git branch is %r, MUST be "gh-pages"' % (pages_dir,
                                                                 branch)
            raise RuntimeError(e)
        sh("touch .nojekyll")

        sh('rm -f stable')
        sh('ln -s {} stable'.format(stable_version))

        static_dir = "_static"
        shutil.rmtree(static_dir, ignore_errors=True)
        shutil.copytree(os.path.join('..', html_dir, static_dir), static_dir)

        sh('git add . --all')
        sh2('git commit -am "Updated doc release: {}" --allow-empty'.format(version))

        print('Most recent commit:')
        sys.stdout.flush()
        sh('git --no-pager log --oneline HEAD~1..')
    finally:
        cd(startdir)

    print('')
    print('Now verify the build in: %r' % dest)
    print("If everything looks good, run 'git push' inside doc/gh-pages.")


'''
Модуль, который взаимодействует с меню, просит ввести
пользователя какие-либо данные
'''

import sys
from datetime import datetime
from diary import storage

get_connection = lambda: storage.connect('my_diary.sqlite')

def action_add():
	task = input('\nВведите текст задачи: ')
	deadline = input('\nВведите дедлайн задачи или нажмите Enter при его отсутствиии: ')
	deadline = 'Without deadline' if deadline == '' else deadline
	if task:
		with get_connection() as conn:
			storage.add_task(conn, task, deadline)
	else:
		print('\nТекст задачи не может быть пустым')
		action_add()

def action_find_all():
	print('''
	1. Завершённые задачи
	2. Незавершённые задачи
	3. Все задачи
	''')
	c = {
	'1':'Done',
	'2':'Not done',
	'3':'3'
	}
	h = c[input('Выберите тип задач: ')]
	with get_connection() as conn:
		storage.show_all(conn, h)

def action_edit():
	n_id = input('\nВведите id задачи для редактирования: ')
	n_task = input('\nВведите новый текст задачи: ')
	n_deadline = input('\nВведите deadline задачи или оставьте поле пустым: ')
	with get_connection() as conn:
		storage.edit_task(conn, n_id, n_task, n_deadline)

def action_done_task():
	n_id = input('\nВведите id задачи для завершения: ')
	with get_connection() as conn:
		storage.done_task(conn, n_id)

def action_not_done_task():
	n_id = input('\nВведите id задачи: ')
	with get_connection() as conn:
		storage.not_done_task(conn, n_id)

def action_delete():
	a = input('''
	1. Удалить одну задачу
	2. Удалить все задачи

	Введите команду: ''')
	with get_connection() as conn:
		if a == '1':
			n_id = input('\nВведите id задачи для удаления: ')
			storage.del_task(conn, n_id)
		else:
			storage.del_all(conn)

def action_exit():
	sys.exit(0)

def action_show_time():
	print(datetime.today())


#takes in the input
word = list(input())
guesses = list(input())

#i is the number of incorrect guess, arrLoc is just total guesses
i = 0
arrLoc = 0

#while the number of incorrect guesses is not 10
while(i<10):
    #if it was incorrect, add 1 to incorrect
    if(guesses[arrLoc] not in word):
        i+=1

    #delete the letter from the word array
    word = [x for x in word if x != guesses[arrLoc]]
    arrLoc += 1

#if the word array is empty, you won otherwise lost
print("WIN" if len(word)==0 else "LOSE")


from MainWindow import Ui_MainWindow
import sys
from PyQt5 import QtWidgets

class mirrollGUI(QtWidgets.QMainWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        #Creamos nuestra GUI
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        #Establecemos info por defecto
        self.fecha_actual="viernes, 10 de junio del 2022"
        self.hora_actual="18:00 pm"
        self.temperatura_actual="00"
        self.ui.temperatura.setText(self.temperatura_actual)

stylesheet="""
    QMainWindow{
        background:black
    }
"""

#Creamos la app
app = QtWidgets.QApplication(sys.argv)
#Colocamos background
app.setStyleSheet(stylesheet)
#Creamos el visualizador, solo la pantalla
mirrolGUI_window=mirrollGUI()
mirrolGUI_window.show()
sys.exit(app.exec_())


import sys
import time
import wlan_exp.config as wlan_exp_config
import wlan_exp.util as wlan_exp_util
import wlan_exp.ltg as wlan_exp_ltg

import numpy as np

from wlan_exp.prog_atten import ProgAttenController

#-------------------------------------------------------------------------
#  Global experiment variables
#

# NOTE: change these values to match your experiment setup
NETWORK           = '10.0.0.0'
NODE_SERIAL_LIST  = ['W3-a-00001', 'W3-a-00002']

# Set the per-trial duration (in seconds)
TRIAL_TIME        = 5

#-------------------------------------------------------------------------
#  Initialization
#
print("\nInitializing experiment\n")

pa = ProgAttenController()

# Create an object that describes the network configuration of the host PC
network_config = wlan_exp_config.WlanExpNetworkConfiguration(network=NETWORK)

# Create an object that describes the WARP v3 nodes that will be used in this experiment
nodes_config   = wlan_exp_config.WlanExpNodesConfiguration(network_config=network_config,
                                                           serial_numbers=NODE_SERIAL_LIST)

# Initialize the Nodes
#   This command will fail if either WARP v3 node does not respond
nodes = wlan_exp_util.init_nodes(nodes_config, network_config)

# Extract the different types of nodes from the list of initialized nodes
#   NOTE:  This will work for both 'DCF' and 'NOMAC' mac_low projects
n_ap_l  = wlan_exp_util.filter_nodes(nodes=nodes, mac_high='AP',  serial_number=NODE_SERIAL_LIST)
n_sta_l = wlan_exp_util.filter_nodes(nodes=nodes, mac_high='STA', serial_number=NODE_SERIAL_LIST)

# Check that we have a valid AP and STA
if (((len(n_ap_l) == 1) and (len(n_sta_l) == 1))):
    # Extract the two nodes from the lists for easier referencing below
    n_ap = n_ap_l[0]
    n_sta = n_sta_l[0]
else:
    print("ERROR: Node configurations did not match requirements of script.\n")
    print(" Ensure two nodes are ready, one using the AP design, one using the STA design\n")
    sys.exit(0)

#-------------------------------------------------------------------------
#  Setup
#
print("\nExperimental Setup:")

# Set the rate of both nodes to 18 Mbps
rate = wlan_exp_util.wlan_rates[3]

# Put each node in a known, good state
for node in nodes:
    node.set_tx_rate_unicast(rate, curr_assoc=True, new_assoc=True)
    node.reset(log=True, txrx_stats=True, ltg=True, queue_data=True) # Do not reset associations/bss_info

    # Get some additional information about the experiment
    channel  = node.get_channel()

    print("\n{0}:".format(node.name))
    print("    Channel  = {0}".format(wlan_exp_util.channel_to_str(channel)))
    print("    Rate     = {0}".format(wlan_exp_util.tx_rate_to_str(rate)))

print("")

# Check that the nodes are associated.  Otherwise, the LTGs below will fail.
if not n_ap.is_associated(n_sta):
    print("\nERROR: Nodes are not associated.")
    print("    Ensure that the AP and the STA are associated.")
    sys.exit(0)

#-------------------------------------------------------------------------
#  Run Experiments
#
print("\nRun Experiment:")

# Experiments:
#   1) AP -> STA throughput
#   2) STA -> AP throughput
#   3) Head-to-head throughput
#
#   Since this experiment is basically the same for each iteration, we have pulled out
# the main control variables so that we do not have repeated code for easier readability.
#

#attens = [45,46,47,48,49,50,51,52,53,54,55]
attens = np.arange(49,56,0.5)
xputs = [0]*len(attens)

ap_ltg_id  = n_ap.ltg_configure(wlan_exp_ltg.FlowConfigCBR(n_sta.wlan_mac_address, 1400, 0, 0), auto_start=False)

for idx,atten in enumerate(attens):
    pa.set_atten(atten)
    time.sleep(0.100)

    n_ap.ltg_start(ap_ltg_id)

    # Record the initial Tx/Rx stats
    sta_rx_stats_start = n_sta.stats_get_txrx(n_ap)
    ap_rx_stats_start  = n_ap.stats_get_txrx(n_sta)

    # Wait for the TRIAL_TIME
    time.sleep(TRIAL_TIME)

    # Record the ending Tx/Rx stats
    sta_rx_stats_end = n_sta.stats_get_txrx(n_ap)
    ap_rx_stats_end  = n_ap.stats_get_txrx(n_sta)

    n_ap.ltg_stop(ap_ltg_id)
    n_ap.queue_tx_data_purge_all()

    sta_num_bits  = float((sta_rx_stats_end['data_num_rx_bytes'] - sta_rx_stats_start['data_num_rx_bytes']) * 8)
    sta_time_span = float(sta_rx_stats_end['timestamp'] - sta_rx_stats_start['timestamp'])
    sta_xput      = sta_num_bits / sta_time_span
    xputs[idx] = sta_xput

    print('{0} db \t {1} Mbps'.format(atten, sta_xput))

pa.close()


# getDataByHashtags.py                                  By: Samer Al-khateeb
# script used to collect data based on searched hashtag (or list of hashtags)

# Make sure Mastodon.py installed correctly
# To install Mastodon.py follow these steps:
# Open terminal or cmd:
# Mac users type:
#    python3 -m pip install Mastodon.py -–user
# Windows users type:
#    py -m pip install Mastodon.py -–user

from mastodon import Mastodon
import json
import os
import csv
import re
from datetime import datetime

def write_output_to_CSV(biglist):
    # column names
    columnNames = ["hashtagUsedToGetThisRow", "postID", "postContent", "postLanguage", "postBookmarked", "postCreatedAt", "postEditedAt", "postFavourited", "postFavouritedCount", "postReblogsCount", "postRepliesCount", "postSensitive", "postVisibility", "postURL", "postURI", "accountEmail", "accountBot", "accountCreatedAt", "accountDiscoverable", "accountDisplayName", "accountFollowersCount", "accountFollowingCount", "accountGroup", "accountID", "accountLocked", "accountStatusesCount", "accountURL", "accountUsername", "attachedPostUrlAuthorName", "attachedPostUrlAuthorURL", "attachedPostUrlProviderName", "attachedPostUrlProviderUrl", "attachedPostUrlProviderTitle", "attachedPostUrlProviderType", "OtherHashtagsIncludedInPost"]

    # data rows of csv file
    rows = biglist

    # get the current date so we can
	# append it to the CSV output file name
    now = datetime.now()
    dt_string = now.strftime("%m-%d-%Y")

    # name of csv file
    filename = "output{}.csv".format(dt_string)

    # opening the csv file in append mode
    with open(filename, 'a', encoding='utf-8') as csv_output_file:
        # define a variable to check if the file is empty (of size zero)
        fileIsEmpty = os.stat(filename).st_size == 0

        # creating a csv writer object
        csvwriter = csv.writer(csv_output_file)

        # if the file is empty (i.e., has size of 0) write the header or columnNames
        if fileIsEmpty:
            # writing the columnNames
            csvwriter.writerow(columnNames)

        # always write the data rows sent
        csvwriter.writerows(rows)

def search_mastodon(mastodonInstance, searchedHashTag):
	# timeline_hashtag method is used to "Fetch a timeline of
	# toots with a given hashtag. The hashtag parameter should
	# not contain the leading #" source: Mastodon.py
	jsonResponse = mastodonInstance.timeline_hashtag('{}'.format(searchedHashTag))

	# uncomment the line below if you want to see the response returned
	#print(json.dumps(jsonResponse, indent=4, sort_keys=True, default=str))

	# send the JSON Response to be processed and get it back as a list
	outputList = process_response(jsonResponse, searchedHashTag)

	# return the response as a list to the main() function
	return outputList

def process_response(jsonResponse, searchedHashTag):
	# need this so we know which hashtag is
	# associated with the collected row
	hashtagUsedToGetThisRow = searchedHashTag

	# a list that will include all the info
	# extracted from the response
	CSVOutputList = []

	# variable to hold the length of the json response returned
	responseLength = len(jsonResponse)

	# for each item returned, let's extract it's info
	for responseItem in range(responseLength):
		# a local list used to collect other hashtags in the post
		localListForOtherPostHashtags = []

		postID = jsonResponse[responseItem]['id']

		postContentWithHTMLTags = jsonResponse[responseItem]['content']
		# removing the html tags from the post content
		postContent = re.sub(re.compile('<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});'), ' ', postContentWithHTMLTags)

		postLanguage = jsonResponse[responseItem]['language']
		postBookmarked = jsonResponse[responseItem]['bookmarked']
		postCreatedAt = str(jsonResponse[responseItem]['created_at'])
		postEditedAt = str(jsonResponse[responseItem]['edited_at'])
		postFavourited = jsonResponse[responseItem]['favourited']
		postFavouritedCount = jsonResponse[responseItem]['favourites_count']
		postReblogsCount = jsonResponse[responseItem]['reblogs_count']
		postRepliesCount = jsonResponse[responseItem]['replies_count']
		postSensitive = jsonResponse[responseItem]['sensitive']
		postVisibility = jsonResponse[responseItem]['visibility']
		postURL = jsonResponse[responseItem]['url']
		postURI = jsonResponse[responseItem]['uri']
		accountEmail = jsonResponse[responseItem]['account']['acct']
		accountBot = jsonResponse[responseItem]['account']['bot']
		accountCreatedAt = str(jsonResponse[responseItem]['account']['created_at'])
		accountDiscoverable = jsonResponse[responseItem]['account']['discoverable']
		accountDisplayName = jsonResponse[responseItem]['account']['display_name']
		accountFollowersCount = jsonResponse[responseItem]['account']['followers_count']
		accountFollowingCount = jsonResponse[responseItem]['account']['following_count']
		accountGroup = jsonResponse[responseItem]['account']['group']
		accountID = jsonResponse[responseItem]['account']['id']
		accountLocked = jsonResponse[responseItem]['account']['locked']
		accountStatusesCount = jsonResponse[responseItem]['account']['statuses_count']
		accountURL = jsonResponse[responseItem]['account']['url']
		accountUsername = jsonResponse[responseItem]['account']['username']

		try:
			attachedPostUrlAuthorName = jsonResponse[responseItem]['card']['author_name']
		except TypeError as e:
			attachedPostUrlAuthorName = ''

		try:
			attachedPostUrlAuthorURL = jsonResponse[responseItem]['card']['author_url']
		except TypeError as e:
			attachedPostUrlAuthorURL =''

		try:
			attachedPostUrlProviderName = jsonResponse[responseItem]['card']['provider_name']
		except TypeError as e:
			attachedPostUrlProviderName = ''

		try:
			attachedPostUrlProviderUrl = jsonResponse[responseItem]['card']['provider_url']
		except TypeError as e:
			attachedPostUrlProviderUrl = ''

		try:
			attachedPostUrlProviderTitle = jsonResponse[responseItem]['card']['title']
		except TypeError as e:
			attachedPostUrlProviderTitle = ''

		try:
			attachedPostUrlProviderType = jsonResponse[responseItem]['card']['type']
		except TypeError as e:
			attachedPostUrlProviderType = ''

		# creating a list of all the hashatgs mentioned in a post
		ListForOtherPostHashtags = jsonResponse[responseItem]['tags']
		for hashtag in range(len(ListForOtherPostHashtags)):
			hashtagName = ListForOtherPostHashtags[hashtag]['name']
			hashtagURL = ListForOtherPostHashtags[hashtag]['url']
			localListForOtherPostHashtags.append([hashtagName,hashtagURL])

		# creating a list of values (a row)
		CSVOutputRow = [hashtagUsedToGetThisRow, postID, postContent, postLanguage, postBookmarked, postCreatedAt, postEditedAt, postFavourited, postFavouritedCount, postReblogsCount, postRepliesCount, postSensitive, postVisibility, postURL, postURI, accountEmail, accountBot, accountCreatedAt, accountDiscoverable, accountDisplayName, accountFollowersCount, accountFollowingCount, accountGroup, accountID, accountLocked, accountStatusesCount, accountURL, accountUsername, attachedPostUrlAuthorName, attachedPostUrlAuthorURL, attachedPostUrlProviderName, attachedPostUrlProviderUrl, attachedPostUrlProviderTitle, attachedPostUrlProviderType, localListForOtherPostHashtags]
		# adding the row to the output list
		CSVOutputList.append(CSVOutputRow)

	# return formatted list to the search_mastodon() function
	return CSVOutputList

def main():
	mastodonInstance = Mastodon(
	# create an app to get the access token code
    access_token = 'PasteYourAccessTokenKeyHere!',
    api_base_url = 'https://mastodon.social'
	)

	listOfKeywords = ['PasteYourHastagOneHereWithoutPoundSign', 'PasteYourHastagTwoHereWithoutPoundSign']

	# list to hold each reponse list we get from each hashtag
	listOfResponses = []

	for keyword in listOfKeywords:
		# call the search function to get the JSON resposne as formatted list
		responseAsList = search_mastodon(mastodonInstance, keyword)
		# return how many rows we obtained for each hashtag
		print(len(responseAsList))
		# write/append the list to the CSV file
		write_output_to_CSV(responseAsList)

if __name__ == "__main__":
    main()


from django.urls import path
from inicio import views

app_name = 'inicio'

urlpatterns = [
    path('', views.inicio, name='inicio'),
    path('acerca-de', views.acerca_de, name='acerca_de'),
    path('productos/', views.productos, name='productos'),
    path('productos/lista/', views.listar_productos, name='listar_productos'),
    path('productos/crear/', views.crear_producto, name='crear_producto'),
    path('productos/eliminar/<int:pk>/', views.EliminarProducto.as_view(), name='eliminar_producto'),
    path('productos/modificar/<int:pk>/', views.ModificarProducto.as_view(), name='modificar_producto'),
    path('productos/<int:pk>/', views.MostrarProducto.as_view(), name='mostrar_producto'),
]


import re

import pandas as pd

df = pd.read_csv('data/news_unprocessed.csv')

data = {}
for i, id in enumerate(df['URL']):
    text = ''.join([x.lower() for x in df.iloc[i]['Title'] if x.isalpha() or x == ' '])
    text= ' '.join([x for x in text.split()])
    status = df.iloc[i]['Majority Score']
    if status == 2:
        status = 1
    elif status == 3:
        status = 0
    data[id] = {
        'text': text,
        'status': status
    }

new_df = pd.DataFrame().from_dict(data, orient='index', columns=['status', 'text'])

new_df.to_csv(index_label='URL', path_or_buf='news_processed.csv')


import argparse
import datetime
import logging
import os
import pcbnew
import subprocess
import tempfile

from contextlib import contextmanager

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

_LAYER_NAME = {
    pcbnew.F_Cu: 'F.Cu',
    pcbnew.B_Cu: 'B.Cu',
    pcbnew.F_Adhes: 'F.Adhes',
    pcbnew.B_Adhes: 'B.Adhes',
    pcbnew.F_SilkS: 'F.SilkS',
    pcbnew.B_SilkS: 'B.SilkS',
    pcbnew.F_Paste: 'F.Paste',
    pcbnew.B_Paste: 'B.Paste',
    pcbnew.F_Mask: 'F.Mask',
    pcbnew.B_Mask: 'B.Mask',
    pcbnew.Edge_Cuts: 'Edge.Cuts',
    pcbnew.Eco1_User: 'Eco1.User',
    pcbnew.Eco2_User: 'Eco2.User',
    pcbnew.F_Fab: 'F.Fab',
    pcbnew.B_Fab: 'B.Fab',
    #TODO: add the rest
}

@contextmanager
def versioned_board(filename):
    versioned_contents = _get_versioned_contents(filename)
    with tempfile.NamedTemporaryFile(suffix='.kicad_pcb') as temp_pcb:
        logger.debug('Writing to %s', temp_pcb.name)
        temp_pcb.write(versioned_contents)
        temp_pcb.flush()

        logger.debug('Load board')
        board = pcbnew.LoadBoard(temp_pcb.name)
        yield board

def get_layer_name(kicad_layer_id):
    if kicad_layer_id in _LAYER_NAME:
        return _LAYER_NAME[kicad_layer_id]
    else:
        return 'Unknown(%r)' % (kicad_layer_id,)

@contextmanager
def get_plotter(pcb_filename, build_directory):
    with versioned_board(pcb_filename) as board:
        yield GerberPlotter(board, build_directory)

class GerberPlotter(object):
    def __init__(self, board, build_directory):
        self.board = board
        self.build_directory = build_directory
        self.plot_controller = pcbnew.PLOT_CONTROLLER(board)
        self.plot_options = self.plot_controller.GetPlotOptions()
        self.plot_options.SetOutputDirectory(build_directory)

        self.plot_options.SetPlotFrameRef(False)
        self.plot_options.SetLineWidth(pcbnew.FromMM(0.35))
        self.plot_options.SetScale(1)
        self.plot_options.SetUseAuxOrigin(True)
        self.plot_options.SetMirror(False)
        self.plot_options.SetExcludeEdgeLayer(True)

    def plot(self, layer, plot_format):
        logger.info('Plotting layer %s (kicad layer=%r)', get_layer_name(layer), layer)
        layer_name = get_layer_name(layer)
        self.plot_controller.SetLayer(layer)
        self.plot_controller.OpenPlotfile(layer_name, plot_format , 'Plot')
        output_filename = self.plot_controller.GetPlotFileName()

        self.plot_controller.PlotLayer()
        self.plot_controller.ClosePlot()
        return output_filename

    def plot_drill(self):
        board_name = os.path.splitext(os.path.basename(self.board.GetFileName()))[0]
        logger.info('Plotting drill file')
        drill_writer = pcbnew.EXCELLON_WRITER(self.board)
        drill_writer.SetMapFileFormat(pcbnew.PLOT_FORMAT_PDF)

        mirror = False
        minimalHeader = False
        offset = pcbnew.wxPoint(0, 0)
        merge_npth = True
        drill_writer.SetOptions(mirror, minimalHeader, offset, merge_npth)

        metric_format = True
        drill_writer.SetFormat(metric_format)

        generate_drill = True
        generate_map = True
        drill_writer.CreateDrillandMapFilesSet(self.build_directory, generate_drill, generate_map)

        drill_file_name = os.path.join(
            self.build_directory,
            '%s.drl' % (board_name,)
        )

        map_file_name = os.path.join(
            self.build_directory,
            '%s-drl_map.pdf' % (board_name,)
        )
        return drill_file_name, map_file_name

def _get_versioned_contents(filename):
    with open(filename, 'rb') as pcb:
        original_contents = pcb.read()
        version_info = get_version_info()
        return original_contents \
            .replace('COMMIT: deadbeef', 'COMMIT: ' + version_info['revision']) \
            .replace('DATE: YYYY-MM-DD', 'DATE: ' + version_info['date'])

def get_version_info():
    git_rev = subprocess.check_output([
        'git',
        'rev-parse',
        '--short',
        'HEAD',
    ]).strip()

    return {
        'revision': git_rev,
        'date': datetime.date.today().strftime('%Y-%m-%d'),
    }

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Test pcb util')
    parser.add_argument('input_file', help='Input .kicad_pcb file')
    args = parser.parse_args()
    with versioned_board(args.input_file) as board:
        logger.info('Loaded %s', board.GetFileName())
        for module in board.GetModules():
            logger.info('Module %s: %s', module.GetReference(), module.GetValue())


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

class RBFSliding:
    def __init__(self, config):
        """RBFSliding config.
        """
        self.config = config
        self.W = np.array([0.1] * 5).reshape(1, 5)

    def update_weights(self, weights, s, h):
        """Update neural network weights.

        Args:
            weights: (5, 1) numpy array, weights need to be updated.
            s: float, value from sliding mode function.
            h: (1, 5) numpy array, hidden nodes values.

        Returns:
            weights: (5, 1) numpy array, updated weights.
        """
        weights = weights + self.config.gama * s * h
        return weights

    def update_x1_x2(self, x1, x2, fn, ut, delta_t):
        """Update x1 and x2.

        Args:
            x1: float, position value.
            x2: float, velocity value, the derivative of x1.
            fn: float, network approximation.
            ut: float, value from control law.
            delta_t: float, time step.

        Returns:
            x1: float, updated position value.
            x2: float, updated velocity value.
        """
        dx2 = fn + ut
        x2 = x2 + dx2 * delta_t
        x1 = x1 + x2 * delta_t
        return x1, x2

    def get_fn(self, weights, hidden_nodes):
        """Update neural network weights.

        Args:
            weights: (5, 1) numpy array, network weights.
            hidden_nodes: (1, 5) numpy array, hidden nodes values.

        Returns:
            float, network outputs.
        """
        weights = np.reshape(weights, (1, -1))
        hidden_nodes = np.reshape(hidden_nodes, (-1, 1))
        return weights.dot(hidden_nodes).ravel()

    def outputs(self, x1, x2, t, weights):
        """Update x1 and x2.

        Args:
            x1: float, position value.
            x2: float, velocity value, the derivative of x1.
            t: float, current time.
            weights: (5, 1) numpy array, network weights.

        Returns:
            fn: float, network approximation.
            fn_d: float, desired network approximation.
            ut: float, value from control law.
            s: float, value from sliding mode function.
            hidden_nodes: (1, 5) numpy array, hidden nodes values.
        """
        xd = np.sin(t)
        dxd = np.cos(t)
        ddxd = -np.sin(t)
        e = x1 - xd
        de = x2 - dxd
        s = self.config.lama * e + de
        x = np.array([x1, x2]).reshape(2, 1)
        hidden_nodes = np.exp(-np.linalg.norm(x - self.config.c, axis=0)**2 / (2 * self.config.b**2))
        fn = self.get_fn(weights=weights, hidden_nodes=hidden_nodes)
        fn_d = 10 * xd * dxd
        ut = -self.config.lama * de + ddxd - fn - self.config.yita * np.sign(s)

        return fn, fn_d, ut, s, hidden_nodes

    def derivatives(self):
        """Calculate the position and velocity based on RBF network.

        Returns:
            x1_trace: list, position tracking.
            x2_trace: list, velocity tracking..
            fn_trace: list, network approximation.
            fnd_trace: list, desired network approximation.
            time_trace: list, time sequences.
        """
        weights = np.array([0.1] * self.config.hidden_nodes).reshape(-1, 1)
        delta_t = self.config.time_periods / self.config.num_iters
        x1, x2 = 0.0, 0.0
        x1_trace = []
        x2_trace = []
        fn_trace = []
        fnd_trace = []
        time_trace = []
        for i in range(1, self.config.num_iters):
            fn, fn_d, ut, s, h = self.outputs(x1=x1, x2=x2, t=i * delta_t, weights=weights)
            weights = self.update_weights(weights=weights, s=s, h=s)
            x1, x2 = self.update_x1_x2(x1=x1, x2=x2, fn=fn, ut=ut, delta_t=delta_t)
            x1_trace.append(copy.deepcopy(x1))
            x2_trace.append(copy.deepcopy(x2))
            fn_trace.append(copy.deepcopy(fn))
            fnd_trace.append(copy.deepcopy(fn_d))
            time_trace.append(i*delta_t)

        return x1_trace, x2_trace, fn_trace, fnd_trace, time_trace

    def visualization(self, time_trace, x1_trace=None, x2_trace=None, fn_trace=None, fnd_trace=None):
        """Calculate the joint related variables.

        Returns:
            time_trace: list, time sequences.
            q_trace: numpy array or None, joint variables as a function of time.
            dq_trace: numpy array or None, joint variables derivatives as a function of time.
            tau_trace: numpy array or None, joint variables errors betwee qd and q as a function of time.
            qd_trace: numpy array or None, desired joint variables as a function of time.
            dq_d_trace: numpy array or None, desired joint variables derivatives as a function of time.
        """
        if x1_trace is not None:
            fig1 = plt.figure()
            ax = plt.subplot(111)
            ax.plot(time_trace, x1_trace)
            plt.xlabel('Time (s)')
            plt.ylabel('Position Tracking')
            plt.title('Calculated Position')

        if x2_trace is not None:
            fig2 = plt.figure()
            ax = plt.subplot(111)
            ax.plot(time_trace, x2_trace)
            plt.xlabel('Time (s)')
            plt.ylabel('Velocity Tracking')
            plt.title('Calculated Velocity')

        if fn_trace is not None:
            fig3 = plt.figure()
            ax = plt.subplot(111)
            ax.plot(time_trace, fn_trace, label='fn')
            if fnd_trace is not None:
                ax.plot(time_trace, fnd_trace, label='fn_d')
            plt.xlabel('Time (s)')
            plt.ylabel('Network Calculation')
            plt.title('Network Comparison between Calculated and Desired Values')

        plt.show()


def sort_by_frequency(df,col):
    '''groups a column and returns a sorted list of most frequent values'''
    sorted_categories = df.groupby(col).count()['TEXT'].sort_values(ascending=False).index
    return sorted_categories

def get_titles(text):
    '''gets unique section titles in a list of report texts'''
    titles = []
    for reports in text:
        titles+=list(set(re.findall(r"\n\n.*:",reports)))
    return [title.strip().rstrip() for title in titles]

def get_counts(titles):
    '''gets counts of section titles'''
    counts = {}
    for title in titles:
        if title in counts:
            counts[title] += 1
        else:
            counts[title] = 1
    return counts

def format_counts(count_dict):
    '''formats section titles counts as dataframe'''
    counts = pd.DataFrame()
    counts['Title'] = count_dict.keys()
    counts['Counts'] = count_dict.values()
    counts = counts.sort_values('Counts',ascending=False)
    return counts

def get_count_df(text):
    '''accepts a list of reports (strings) and returns sorted list of section titles'''
    titles = get_titles(text)
    count_dict = get_counts(titles)
    count_df = format_counts(count_dict)
    count_df['%'] = count_df['Counts']/len(text)*100
    return count_df


#adding all the edges given an matrix of NxN
n=int(input())
t=0
for i in range(n):
    l=input()
    b=[int(x) for x in l.split(' ')]
    if i==0 or i==n-1:
        t+=sum(b)
    else:
        t+=b[0]+b[n-1]
print(t)


class Students:
    def __init__(self, name, age, grade):
        self.name = name
        self.age = age
        self.grade = grade

    def get_grade(self):
        return self.grade

class Course:
    def __init__(self, name, max_students):
        self.name = name
        self.max_students = max_students
        self.students = []

    def add_students(self, Student, ):
        if len(self.students) < self.max_students:
            self.students.append(Student)
        return

    def average_grade(self):
        value = 0
        for student in self.students:
            value = value + Students.get_grade(student)
        return value / len(self.students)

s1 = Students("mohammad", 22, 95)
s2 = Students("Jonayed", 22, 56)
s3 = Students("Sarkar", 22, 89)
s4 = Students("Arslaan", 22, 65)
s5 = Students("Alp", 22, 95)

Cse = Course("Computer Science and Engineering", 10)
Cse.add_students(s1)
Cse.add_students(s2)
Cse.add_students(s3)
Cse.add_students(s4)
Cse.add_students(s5)
print(Cse.average_grade())
print(Cse.name)

3.Object oriented programming with python/1.Class/2. exercise.py


from warnings import simplefilter
simplefilter(action='ignore', category=FutureWarning)
simplefilter(action='ignore', category=Warning)

import numpy as np
import tensorflow as tf
import cv2
from keras.layers.convolutional import ZeroPadding2D, AveragePooling2D
from keras.models import Model
from keras.layers import Dense, Input, Flatten, Dropout
from keras.applications.mobilenet import MobileNet
from keras.optimizers import Adam
import face_recognition
from PIL import Image

# load model

input_tensor = Input(shape=(224, 224, 3))
model = MobileNet(input_tensor = input_tensor, include_top=False, input_shape=(224, 224, 3), weights='imagenet')
x = model.output
x = ZeroPadding2D()(x)
x = AveragePooling2D((3,3))(x)
x = Flatten()(x)
x = Dropout(0.3)(x)
predictions = Dense(10, activation=None)(x)
model = Model(inputs=input_tensor, outputs=predictions)

model.compile(optimizer=Adam(lr=0.0005),loss='mse',metrics=[tf.keras.metrics.MeanAbsoluteError(),tf.keras.metrics.RootMeanSquaredError()])

model.load_weights('faceDetect-5-4.h5')

# capture camera

cap = cv2.VideoCapture(0)
while(True):
    ret, frame = cap.read()
    faces = face_recognition.face_locations(frame)
    fraw = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    img = frame
    for (top,right,bottom,left) in faces:
        img = cv2.rectangle(img, (left,top),(right,bottom),(0,255,0),2)

        f1 = fraw[top:bottom, left:right]
        rawh, raww = f1.shape[0:2]
        ratioh, ratiow = 224.0 / rawh, 224.0 / raww
        f1 = Image.fromarray(f1)
        f1 = f1.resize((224, 224))
        f1 = np.array([np.array(f1)])
        pre = model.predict(f1 / 255.0)
        f1 = f1[0]
        pre = pre[0]
        pre[0::2] /= ratiow
        pre[1::2] /= ratioh
        pre = pre.astype(np.int)
        pre[0::2] += left
        pre[1::2] += top

        for i in range(len(pre) // 2):
            p1, p2 = pre[i*2], pre[i*2+1]
            cv2.circle(img, (p1,p2), 1, (0,0,255), 2)
        break

    cv2.imshow('frame2',img)
    if cv2.waitKey(5) & 0xFF == ord('q'):       # press 'q' to exit
        break

cap.release()
cv2.destroyAllWindows()


#Mohamed Amal
import mcpi.minecraft as minecraft
import time
import mcpi.block as block
mc = minecraft.Minecraft.create()

def blackHole(entityId):
    loc = mc.entity.getTilePos(entityId)
    x,y,z = loc.x,loc.y,loc.z
    mc.setBlocks(x - 2,y -1,z - 2,x + 2,y + 3,z + 2, 49)
    mc.setBlocks(x - 1,y,z - 1,x + 1,y + 2, z + 1, 0)
    time.sleep(3)
    mc.setBlocks(x - 1,y,z - 1,x + 1,y,z + 1, 119)


"""
This plugin captures data for research of cryptography usage
It looks up common RSA/DSA key generation functions and key sizes
"""

from . nodes import *
from .. import base
from .. import rules
from ...utils import Analyzer

# Key generation functions to lookup
CRYPTO_GEN_KEYS = {
    'cryptography.hazmat.primitives.asymmetric.dsa.generate_private_key': {
        'type': 'dsa', 'lib': 'cryptography'
    },
    'cryptography.hazmat.primitives.asymmetric.dsa.generate_parameters': {
        'type': 'dsa', 'lib': 'cryptography'
    },
    'cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key': {
        'type': 'rsa', 'lib': 'cryptography'
    },
    'cryptography.hazmat.primitives.asymmetric.rsa.generate_parameters': {
        'type': 'rsa', 'lib': 'cryptography'
    },

    'Crypto.PublicKey.DSA.generate': {
        'type': 'dsa', 'lib': 'crypto'
    },
    'Crypto.PublicKey.RSA.generate': {
        'type': 'rsa', 'lib': 'crypto'
    },
    'Cryptodome.PublicKey.DSA.generate': {
        'type': 'dsa', 'lib': 'crypto'
    },
    'Cryptodome.PublicKey.RSA.generate': {
        'type': 'rsa', 'lib': 'crypto'
    }
}

# Minimum safe key sizes
MIN_KEY_SIZES = {
    'rsa': 2048,
    'dsa': 2048
}

class CryptoKeyGeneration(rules.Rule):
    """
    Detection hit to throw when crypto key generation is detected
    """
    pass

@Analyzer.ID('cryptography_generate_keys')
@Analyzer.description("Analyze the generation of cryptography keys")
class CryptoGenKey(base.NodeAnalyzerV2):
    """
    Lookup for function calls in the AST tree that are matching the key generation calls
    Attempt to parse the key type and key size into the detection hit
    """
    def node_Call(self, context):
        f_name = context.node.full_name

        if not isinstance(f_name, str):
            return

        if f_name in CRYPTO_GEN_KEYS:
            target = CRYPTO_GEN_KEYS.get(f_name)
            yield from getattr(self, f'_lib_{target["lib"]}')(context, target)
            return

    def _lib_cryptography(self, context, info):
        try:
            signature = context.node.apply_signature('key_size', backend=None)
        except TypeError:  # Signature call doesn't match parameters/kws
            return
        key_size = signature.args[0]
        if isinstance(key_size, Number):
            key_size = key_size.value
        elif not isinstance(key_size, int):
            return

        yield self._gen_hit(context, info, key_size)

    def _lib_crypto(self, context, info):
        try:
            signature = context.node.apply_signature('bits', randfunc=None, domain=None)
        except TypeError:
            return

        key_size = signature.args[0]
        if isinstance(key_size, Number):
            key_size = key_size.value
        elif not isinstance(key_size, int):
            return

        yield self._gen_hit(context, info, key_size)

    def _gen_hit(self, context, info, key_size=None):
        hit = CryptoKeyGeneration(
            message="Generation of cryptography key detected",
            signature=f"crypto#gen_key#{context.visitor.path}#{context.node.line_no}",
            extra={
                'function': context.node.full_name,
                'key_type': info['type'],
                'key_size': key_size
            }
        )

        if key_size is not None and key_size < MIN_KEY_SIZES.get(info['type'], 0):
            hit.score = 100

        return hit