#!/usr/bin/env python

# xml parsing help from https://www.geeksforgeeks.org/reading-and-writing-xml-files-in-python/?ref=lbp
# to run you need to do
# `pip3 install beautifulsoup4`
# `pip3 install lxml`

import argparse
import datetime

from bs4 import BeautifulSoup

class Card(object):
    """
    a card from files generated by magic set editor https://magicseteditor.boards.net/page/downloads
    """
    def __init__(self, styling=False, notes="", time_created="", time_modified="", name="", casting_cost="", image="", supertype="", subtype="", rule_text="", flavor_text="", watermark="", power="", toughness="", card_code_text="", image2="", mainframe_image1="", mainframe_image2=""):
       self.styling = styling
       self.notes = notes
       self.timeCreated = time_created
       self.timeModified = time_modified
       self.name = name
       self.castingCost = casting_cost
       self.image = image
       self.superType = supertype
       self.subType = subtype
       self.ruleText = rule_text
       self.flavorText = flavor_text
       self.watermark = watermark
       self.power = power
       self.toughness = toughness
       self.card_code_text = card_code_text
       self.image2 = image2
       self.mainframe_image1 = mainframe_image1
       self.mainframe_image2 = mainframe_image2
       self.rarity = ""

    def __init__(self, cockatrice_card):
        self.styling = False
        self.notes = ""

        dt_date = datetime.datetime.now()
        current_time_str = dt_date.strftime('%y-%m-%d %H:%M:%S')
        self.time_created = current_time_str
        self.time_modified = current_time_str

        # have to parse the passed tag for this info
        self.name = ""
        self.casting_cost = ""
        self.supertype = ""
        self.subtype = ""
        self.rule_text = ""
        self.flavor_text = ""
        self.power = ""
        self.toughness = ""

        # non-creature card:
        # <card>
        # <name>Lavender Town</name>
        # <set picURL="https://i.imgur.com/HEb2JN5.jpeg" rarity="uncommon">PTCG</set>
        # <color/>
        # <manacost/>
        # <type>Land</type>
        # <tablerow>0</tablerow>
        # <text>T: Add B or W.
        #                                 3B, T: each player sacrifices a Pokémon. If all players do, each player returns a Pokémon from their graveyard to the battlefield tapped.</text>
        # </card>

        # creature card
		# <card>
		# 	<name>Squirtle</name>
		# 	<set picURL="https://images.pokemontcg.io/base6/95_hires.png" rarity="common">PTCG</set>
		# 	<color>U</color>
		# 	<manacost>1U</manacost>
		# 	<type>Pokémon - Water</type>
		# 	<pt>1/2</pt>
		# 	<tablerow>2</tablerow>
		# 	<text>2U: Evolve to Wartotle
		# 		Whenever Squirtle blocks a creature, that creature doesn't untap during its controller's next untap step.</text>
		# </card>
        for tag in cockatrice_card:
            if tag.name == 'name':
                self.name = tag.string

            if tag.name == 'manacost':
                self.casting_cost = tag.string

            if tag.name == 'type':
                value = tag.string
                values = value.split('-')
                self.supertype = values[0].strip()

                if len(values) > 1:
                    self.subtype = values[1].strip()

            if tag.name == 'pt':
                value = tag.string
                values = value.split('/')
                self.power = values[0]
                self.toughness = values[1]

            if tag.name == 'text':
                self.rule_text = tag.string

            if tag.name == "set":
                self.rarity = tag['rarity']

                if tag['rarity'] == "mythic":
                    self.rarity = "mythic rare"

        # this is all blank any from the cockatrice info, in future script work this can be merged with existing info
        self.watermark = ""
        self.card_code_text = ""
        self.image = ""
        self.image2 = ""
        self.mainframe_image1 = ""
        self.mainframe_image2 = ""

    def __repr__(self):
        return self.exportAsString()

    def exportAsString(self):
        """
        cards have the following format:

        card:
            has styling: false
            notes:
            time created: 2020-12-06 21:19:30
            time modified: 2020-12-07 15:54:05
            name: Bulbasaur
            casting cost: G
            image: image1
            super type: <word-list-type>Pokémon</word-list-type>
            sub type:
                Grass Poison
            rule text:
                <sym>1G</sym>: <kw-0><nospellcheck>Evolve</nospellcheck></kw-0> to <error-spelling:en_us:/magic.mse-game/magic-words>Ivysaur</error-spelling:en_us:/magic.mse-game/magic-words>
                <sym>T</sym>: Add <sym>G</sym>
                <kw-a><nospellcheck>Reach</nospellcheck></kw-a>
            flavor text: <i-flavor></i-flavor>
            watermark: Pokemon Grass
            rarity: mythic rare
            power: 2
            toughness: 2
            card code text:
            image 2:
            mainframe image:
            mainframe image 2:
        """
        string = "card:\n"
        string += f"\thas styling: {str(self.styling).lower()}\n"
        string += "\tnotes:\n"
        string += f"\ttime created: {self.time_created}\n"
        string += f"\ttime modified: {self.time_modified}\n"
        string += f"\tname: {self.name}\n"
        string += f"\tcasting cost: {self.casting_cost}\n"
        string += f"\timage: {self.image}\n"
        string += f"\tsuper type: <word-list-type>{self.supertype}</word-list-type>\n"
        string += "\tsub type:\n"
        string += f"\t\t{self.subtype}\n"
        string += "\trule text:\n"
        string += f"\t\t{self.rule_text}\n"
        string += f"\tflavor text: <i-flavor>{self.flavor_text}</i-flavor>\n"
        string += f"\twatermark: {self.watermark}\n"
        string += f"\tpower: {self.power}\n"
        string += f"\ttoughness: {self.toughness}\n"
        string += f'\trarity: {self.rarity}\n'
        string += f"\tcard code text: {self.card_code_text}\n"
        string += f"\timage 2: {self.image2}\n"
        string += f"\tmainframe image: {self.mainframe_image1}\n"
        string += f"\tmainframe image 2: {self.mainframe_image2}\n"
        return string

def main():
    """
    Usage:
        - python set_editor_script.py [options] -i input_file -o output_file

    Options:
        -p preserve pre-set image data from the input file

    Example:
        python set_editor_script.py -i ../ptcg_cockatrice.xml -o example_set2.set
    """
    # TODO: we need a version of this functionality that smashes a cockatrice file w/
    # a mtg set file to populate images etc but update the mtg set file with the updated
    # cockatrice info
    parser = argparse.ArgumentParser()

    parser.add_argument('-p', '--preserve', action='store_true', help='preserves image information in the input file')
    parser.add_argument('-i', '--input', type=str, required=True, help='input file')
    parser.add_argument('-o', '--output', type=str, required=True, help='output file, cannot be the same as input file')

    args = parser.parse_args()

    # validate args
    if (args.input == args.output):
        print('Error: input file cannot be the same as output file.')
        return

    # open the input file as XML, input is assumed to be a cockatrice card file
    with open(args.input, 'r') as f:
        data = f.read()
        xmlObjects = BeautifulSoup(data, "xml")

        # grab the list of cards out of the input cockatrice xml file
        allCards = xmlObjects.findAll("card")
        print(f'Retrieved {len(allCards)} cards')

        ripped_cards = []
        for index in range(len(allCards)):
            print(f'card {index}:')

            # grab the info and transform this into the Card instance format above
            cockatrice_card = allCards[index]
            ripped_card = Card(cockatrice_card)
            print(ripped_card.name)
            ripped_cards.append(ripped_card)

        # then open the output file
        with open(args.output, 'w') as output_file:

            # write the header
            output_file.write("""
mse version: 0.3.8
game: magic
stylesheet: m15
set info:
\tsymbol: symbol5.mse-symbol
\tmasterpiece symbol:
styling:
\tmagic-m15:
\t\ttext box mana symbols: magic-mana-small.mse-symbol-font
\t\tinverted common symbol: no
\t\toverlay:
                    """)

            # write each card in the list
            for card in ripped_cards:
                output_file.write(card.exportAsString())

            # write the footer
            output_file.write("""
version control:
\ttype: none
apprentice code:
            """)

    print('Done')

if __name__ == "__main__":
    main()


from operator import add, sub

from _utils import *

inp = get_input(2020, 8)
tape = inp.strip().split("\n")

def step(i, acc):
    op = {"+": add, "-": sub}
    instr, arg = tape[i].split()
    sign, num = arg[:1], arg[1:]
    if instr == "nop":
        i += 1
    elif instr == "acc":
        i += 1
        acc = op[sign](acc, int(num))
    elif instr == "jmp":
        i = op[sign](i, int(num))
    else:
        raise ValueError(i)
    return i, acc

def evaluate(tape, return_state_at_repeated):
    seen, i, acc = set(), 0, 0
    while i + 1 < len(tape):
        seen.add(i)
        i, acc = step(i, acc)
        if i in seen:
            return acc if return_state_at_repeated else None
    return acc

# part 1
print(evaluate(tape, True))

# part 2

def swaps(tape):
    for i in range(len(tape)):
        tape_ = list(tape)
        t = tape_.pop(i)
        instr, arg = t.split()
        if instr == "jmp":
            t = f"nop {arg}"
        elif instr == "nop":
            t = f"jmp {arg}"
        tape_.insert(i, t)
        yield tape_

for tape in swaps(tape):
    acc = evaluate(tape, False)
    if acc:
        print(acc)


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

# Automatic provisioning of wireguard keypair resources.

import nixops.util
import nixops.resources
import logging
from typing import Mapping, Optional, Sequence

logger = logging.getLogger(__name__)

class WgKeypairOptions(nixops.resources.ResourceOptions):
    """Definition of wireguard keypair options."""

    name: str
    enable: bool
    dns: Sequence[str]
    mtu: Optional[int]
    listenPort: int
    persistentKeepalive: Optional[int]
    usePresharedKey: bool
    syncState: bool
    interfaceName: str
    table: Optional[str]
    preUp: str
    preDown: str
    postUp: str
    postDown: str
    baseIpv4: Mapping[str, int]
    addNoWgHosts: bool

class WgKeypairDefinition(nixops.resources.ResourceDefinition):
    """Definition of a wireguard keypair resource."""

    config: WgKeypairOptions

    @classmethod
    def get_type(cls) -> str:
        return "wg-keypair"

    @classmethod
    def get_resource_type(cls) -> str:
        return "wgKeypair"

    def __init__(self, name: str, config: nixops.resources.ResourceEval):
        super().__init__(name, config)
        self.kp_name: str = self.config.name
        self.enable: bool = self.config.enable
        self.dns: Sequence[str] = self.config.dns
        self.mtu: Optional[int] = self.config.mtu
        self.listen_port: int = self.config.listenPort
        self.keepalive: Optional[int] = self.config.persistentKeepalive
        self.use_psk: bool = self.config.usePresharedKey
        self.sync_state: bool = self.config.syncState
        self.interface_name: str = self.config.interfaceName
        self.table: Optional[str] = self.config.table
        self.pre_up: str = self.config.preUp
        self.pre_down: str = self.config.preDown
        self.post_up: str = self.config.postUp
        self.post_down: str = self.config.postDown
        self.base_ipv4: Mapping[str, int] = self.config.baseIpv4
        self.add_no_wg_hosts: bool = self.config.addNoWgHosts

class WgKeypairState(nixops.resources.ResourceState[WgKeypairDefinition]):
    """State of a wireguard keypair resource."""

    kp_name: str = nixops.util.attr_property("wgKeypair.name", None, str)
    enable: bool = nixops.util.attr_property("wgKeypair.enable", False, bool)
    dns: Sequence[str] = nixops.util.attr_property("wgKeypair.dns", [], "json")
    mtu: Optional[int] = nixops.util.attr_property("wgKeypair.mtu", None, int)
    addr: str = nixops.util.attr_property("wgKeypair.addr", None, str)
    private: str = nixops.util.attr_property("wgKeypair.private", None, str)
    public: str = nixops.util.attr_property("wgKeypair.public", None, str)
    listen_port: int = nixops.util.attr_property("wgKeypair.listenPort", None, int)
    keepalive: Optional[int] = nixops.util.attr_property(
        "wgKeypair.keepalive", None, int
    )
    use_psk: bool = nixops.util.attr_property("wgKeypair.usePresharedKey", True, bool)
    psk: str = nixops.util.attr_property("wgKeypair.presharedKey", None, str)
    sync_state: bool = nixops.util.attr_property("wgKeypair.syncState", False, bool)
    interface_name: str = nixops.util.attr_property(
        "wgKeypair.interfaceName", None, str
    )
    table: Optional[str] = nixops.util.attr_property("wgKeypair.table", None, str)
    pre_up: str = nixops.util.attr_property("wgKeypair.preUp", "", str)
    pre_down: str = nixops.util.attr_property("wgKeypair.preDown", "", str)
    post_up: str = nixops.util.attr_property("wgKeypair.postUp", "", str)
    post_down: str = nixops.util.attr_property("wgKeypair.postDown", "", str)
    base_ipv4: Mapping[str, int] = nixops.util.attr_property(
        "wgKeypair.baseIpv4", {}, "json"
    )
    add_no_wg_hosts: bool = nixops.util.attr_property(
        "wgKeypair.addNoWgHosts", True, bool
    )

    @classmethod
    def get_type(cls) -> str:
        return "wg-keypair"

    def __init__(self, depl: nixops.deployment.Deployment, name: str, id):
        nixops.resources.ResourceState.__init__(self, depl, name, id)

    @property
    def resource_id(self) -> str:
        return self.kp_name

    def get_definition_prefix(self) -> str:
        return "resources.wgKeypair."

    def create(
        self,
        defn: WgKeypairDefinition,
        check: bool,
        allow_reboot: bool,
        allow_recreate: bool,
    ) -> None:
        self.kp_name = f"nixops-{self.depl.uuid}-{defn.name}"
        self.enable = defn.enable
        self.dns = defn.dns
        self.mtu = defn.mtu
        self.listen_port = defn.listen_port
        self.keepalive = defn.keepalive
        self.use_psk = defn.use_psk
        self.sync_state = defn.sync_state
        self.interface_name = defn.interface_name
        self.table = defn.table
        self.pre_up = defn.pre_up
        self.pre_down = defn.pre_down
        self.post_up = defn.post_up
        self.post_down = defn.post_down
        self.base_ipv4 = defn.base_ipv4
        self.add_no_wg_hosts = defn.add_no_wg_hosts

        self.state = self.UP

    def destroy(self, wipe: bool = False) -> bool:
        if not self.depl.logger.confirm(
            f"are you sure you want to destroy wireguard keypair resource (wg-link) ‘{self.name}’?"
        ):
            return False
        if wipe:
            self.warn("wipe is not supported")
        self.log(f"destroying {self.name} (resource id: {self.kp_name})...")
        return True


import numpy as np
import numpy.typing as npt
import pandas as pd
from scipy import special
from typing import Any

from linearlab.lik.base import Likelihood
from linearlab.link import Link, LogitLink, logit

class _BinomialBase(Likelihood[npt.NDArray[np.int_]]):
    def params(self) -> list[str]:
        return ["p"]

    def prepare_y(self, y: pd.Series | pd.DataFrame) -> tuple[tuple[npt.NDArray[np.int_], npt.NDArray[np.int_]], float]:
        if isinstance(y, pd.Series):
            k = y.to_numpy(dtype=np.bool_).astype(np.int_)
            n = np.ones(y.shape[0], dtype=np.int_)
            logZ = 0.0
        elif isinstance(y, pd.DataFrame) and (y.shape[1] == 2):
            y = y.to_numpy(dtype=np.int_)
            k = y[:,0]
            n = y.sum(axis=1)
            logZ = np.sum(special.gammaln(n+1) - special.gammaln(k+1) - special.gammaln(n-k+1))
        else:
            raise ValueError("binomial needs either bool or n_success,n_failure")
        return (k, n), logZ

class Binomial(_BinomialBase):
    def __init__(self, link:Link) -> None:
        self.link = link

    def __call__(
        self,
        y: tuple[npt.NDArray[np.int_], npt.NDArray[np.int_]],
        eta: npt.NDArray[np.float64],
        out_g: None | npt.NDArray[np.float64],
        out_h: None | npt.NDArray[np.float64],
    ) -> float:
        k, n = y
        p, dp = self.link.inv(eta[0])
        f = np.sum(
            (k * special.logit(p)) +
            (n * special.log1p(-p))
        )
        if out_g is not None:
            out_g[0] = dp * (k - (n * p)) / p / (1 - p)
        if out_h is not None:
            out_h[0,0] = (dp**2) * n / p / (1 - p)
        return f

    def __repr__(self) -> str:
        return f"binomial likelihood ({self.link})"

class BinomialLogit(_BinomialBase):
    def __call__(
        self,
        y: tuple[npt.NDArray[np.int_], npt.NDArray[np.int_]],
        eta: npt.NDArray[np.float64],
        out_g: None | npt.NDArray[np.float64],
        out_h: None | npt.NDArray[np.float64],
    ) -> float:
        k, n = y
        eta = eta[0]
        p = special.expit(eta)
        f = np.sum(
            (k * eta) +
            (n * special.log_expit(-eta))
        )
        if out_g is not None:
            out_g[0] = k - (n * p)
        if out_h is not None:
            out_h[0,0] = n * p * (1 - p)
        return f

    def __repr__(self) -> str:
        return "binomial likelihood (logit link)"

def binomial(link: Link = logit) -> Likelihood:
    if isinstance(link, LogitLink):
        return BinomialLogit()
    else:
        return Binomial(link)


import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
from keras.models import load_model
import time

total_starttime = time.time()

generator = load_model(r'C:\Licenta\GAN_IMAGES\model_16_batch\generator_model_99.h5')

damaged_directory = r"C:\Licenta\GAN_IMAGES\damaged\test"
damaged_dataset = tf.keras.utils.image_dataset_from_directory(damaged_directory,
                                                                  label_mode=None,
                                                                  batch_size=1,
                                                                  image_size=(256, 256),
                                                                  shuffle=False)

### Define a normalization layer ###
normalization_layer = tf.keras.layers.Rescaling(scale=1. / 127.5, offset=-1)

### Normalize the datasets ###
damaged_dataset = damaged_dataset.map(lambda x: normalization_layer(x))

i = 0
for img in (damaged_dataset):
    generated_image = generator(img)
    generated_image = (generated_image[0].numpy() * 127.5 + 127.5).astype(np.uint8)
    tf.keras.preprocessing.image.save_img(r"C:\Licenta\GAN_IMAGES\results_GAN_bs32\16_batch_size_100_epochs/" + str(i) + ".jpg", generated_image)
    i = i + 1

total_endtime = time.time()
print(f'Total execution time: {total_endtime - total_starttime} s')


import tensorflow as tf
import numpy as np

M = 2
K = 1
H = 2

Epoch_num = 1000

X = np.array([[0,0], [0,1], [1,0], [1,1]])
Y = np.array([[0],[1],[1],[0]])

x = tf.placeholder(tf.float32, shape=[None, M])
t = tf.placeholder(tf.float32, shape=[None, K])

W = tf.Variable(tf.random.truncated_normal([M, H]))
b = tf.Variable(tf.zeros([H]))
V = tf.Variable(tf.random.truncated_normal([H, K]))
c = tf.Variable(tf.zeros([K]))

h = tf.nn.sigmoid(tf.matmul(x, W) + b)
y = tf.nn.sigmoid(tf.matmul(h, V) + c)

cross_entropy = - tf.reduce_sum(t * tf.log(y) + (1 - t) * tf.log(1 - y))
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(cross_entropy)
correct_prediction = tf.equal(tf.to_float(tf.greater(y, 0.5)), t)

sess = tf.Session()
sess.run(tf.global_variables_initializer())

for epoch in range(Epoch_num):
    sess.run(train_step, feed_dict={
        x: X,
        t: Y
    })

sess.close()


from django import forms
from .models import Post
from urllib import request
from django.core.files.base import ContentFile
from django.utils.text import slugify

class PostCreateForm(forms.ModelForm):

    def save(self, force_insert=False, force_update=False, commit=True):
        posts = super().save(commit=False)
        name = slugify(posts.title)
        if commit:
            posts.save()
        return posts

    class Meta:
        model = Post
        fields = ('image', 'description')

class ProfileEditForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('image', 'description')


start=ord(input("Enter start character:"))
stop=ord(input("Enter stop range of charcter :"))

for i in range(start,stop+1):
    print(chr(i),end=" ")

print()

while start<=stop:
    print(chr(start),end=" ")
    start=start+1


import pendulum
from airflow import models
from airflow.operators.bash_operator import BashOperator
from datetime import datetime, timedelta

KST = pendulum.timezone("Asia/Seoul")

default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
    'start_date': datetime(2021, 8, 9, tzinfo=KST),
    'email': ['airflow@airflow.com'],
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=5)
}

with models.DAG(
    dag_id='test', description='write date and, hello airflow!',
    schedule_interval='*/10 * * * *', # 10분마다 한번 씩 반복
    default_args=default_args,
    catchup=False
) as dag:

    t1 = BashOperator(
        task_id='write_date',
        bash_command='echo "data now : $(date +%Y)-$(date +%m)-$(date +%d) $(date +%H):$(date +%M):$(date +%S)" >> ~/airflow/test.txt',
        dag=dag
    )

    t2 = BashOperator(
        task_id='write_hello_airflow',
        bash_command='echo "hello airflow!" >> ~/airflow/test.txt',
        dag=dag
    )

    t1 >> t2


class Node:
    def __init__ (self, data):
        self.data = data
        self.prev = None
        self.next = None
    def __str__(self):
        return str(self.data)

class List:
    def __init__(self):
        self.head = None
        self.tail = None
    def __str__(self):
        if (self.head == None):
            return "[]"
        s = "[" + str(self.head)
        t = self.head.next
        while (t != None):
            s = s + " " + str(t)
            t = t.next
        return s + "]"
    def insert(self, x):
        n = Node(x)
        n.next = self.head
        if (self.head != None):
            self.head.prev = n
        self.head = n
        n.prev = None
    def search(self, d):
        t = self.head
        while (t != None and t.data != d):
            t = t.next
        if(t != None):
            return True
        return False
    def delete(self, x):
        t = self.head
        while(t != None and t.data != x):
            t = t.next
        if (t != None):
            if (t.prev != None):
                t.prev.next = t.next
            else:
                self.head = t.next
            if (t.next != None):
                t.next.prev = t.prev
            else:
                t.prev.next = None


from ast import Try
from dataclasses import replace
from os import rename
import sys
import time
from unicodedata import decimal
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from sqlalchemy import create_engine, text
from sqlalchemy.orm import Session

class CodigoTestado3():
    def limparPreco(preco):
            if preco == None or preco == '':
                return -1
            try:
                preco = preco.replace('R$ ','')
                preco = preco.replace(',','.')
                preco = float(preco)
            except:
                preco = -1
            return preco

    # FUNCÕES PAGUE MENOS
    def coletar_preco_paguemenos(medicamento, driver):
        driver.get(medicamento['link'])
        try:
            preco = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, '/html/body/div[2]/div/div[1]/div/div/div/div[4]/div/div/div/section/div/div/div/div[1]/div[2]/div/div[3]/div/div[5]/div/div[1]/div[1]/div/div[2]/div/div[2]/span/span'))
            )
            preco = preco.text
        except:
            try:
                preco = WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.XPATH, '/html/body/div[2]/div/div[1]/div/div/div/div[4]/div/div/div/section/div/div/div/div[1]/div[2]/div/div[3]/div/div[5]/div/div/div[1]/div/div[2]/div/div/span/span'))
                )
                preco = preco.text
            except:
                preco = '-1'
        medicamento['preco'] = CodigoTestado3.limparPreco(preco)

    def coletar_paguemenos(driver):
        medicamentos_paguemenos = [
           # {
            #    'idfarmacia': 1,
             #   'idmedicamento': 1,

              #  'preco': -1
            #}, #dipirona
            {
                'idfarmacia': 1,
                'idmedicamento': 2,
                'link': 'https://www.paguemenos.com.br/advil-400mg-leve-8-pague-6-capsulas/p',
                'preco': -1
            }, #advil
            {
                'idfarmacia': 1,
                'idmedicamento': 3,
                'link': 'https://www.paguemenos.com.br/engov-com-12-comprimidos/p',
                'preco': -1
            }, #engov
            {
                'idfarmacia': 1,
                'idmedicamento': 4,
                'link': 'https://www.paguemenos.com.br/neosaldina-com-10-drageas/p',
                'preco': -1
            }, #neosaldina
            {
                'idfarmacia': 1,
                'idmedicamento': 5,
                'link': 'https://www.paguemenos.com.br/dorflex-36-comprimidos/p',
                'preco': -1
            }, #dorflex
            {
                'idfarmacia': 1,
                'idmedicamento': 6,
                'link': 'https://www.paguemenos.com.br/novalgina-1g-10-comprimidos/p',
                'preco': -1
            }, #novalgina
            {
                'idfarmacia': 1,
                'idmedicamento': 7,
                'link': 'https://www.paguemenos.com.br/sal-de-fruta-eno-efervescente-2-saches-de-5g/p',
                'preco': -1
            }, #eno
            {
                'idfarmacia': 1,
                'idmedicamento': 8,
                'link': 'https://www.paguemenos.com.br/neosoro-solucao-nasal-adulto-com-30-ml/p',
                'preco': -1
            }, #neosoro
            {
                'idfarmacia': 1,
                'idmedicamento': 9,
                'link': 'https://www.paguemenos.com.br/merthiolate-spray-30ml/p',
                'preco': -1
            }, #mertthiolate
            {
                'idfarmacia': 1,
                'idmedicamento': 10,
                'link': 'https://www.paguemenos.com.br/estomazil-em-po-sem-sabor-5g-com-6-envelope/p',
                'preco': -1
            }, #estomazil
            {
                'idfarmacia': 1,
                'idmedicamento': 11,
                'link': 'https://www.paguemenos.com.br/allegra-60mg-com-10-comprimidos/p',
                'preco': -1
            }, #allegra
            {
                'idfarmacia': 1,
                'idmedicamento': 12,
                'link': 'https://www.paguemenos.com.br/descongestionante-vick-vaporub-30g/p',
                'preco': -1
            }, #vic vaborrub
            {
                'idfarmacia': 1,
                'idmedicamento': 13,
                'link': 'https://www.paguemenos.com.br/polaramine-2mg-caixa-com-20-comprimidos/p',
                'preco': -1
            }, #polaramine
            {
                'idfarmacia': 1,
                'idmedicamento': 14,
                'link': 'https://www.paguemenos.com.br/dramin-b6-com-30-comprimidos/p',
                'preco': -1
            }, #dramin
            {
                'idfarmacia': 1,
                'idmedicamento': 15,
                'link': 'https://www.paguemenos.com.br/espironolactona-25mg-com-30-comprimidos-generico-geolab/p',
                'preco': -1
            }, #espironolactona
            {
                'idfarmacia': 1,
                'idmedicamento': 16,
                'link': 'https://www.paguemenos.com.br/insulina-novolin-r-10ml/p',
                'preco': -1
            } #insulina
        ]
        for medicamento in medicamentos_paguemenos:
            CodigoTestado3.coletar_preco_paguemenos(medicamento, driver)
        return medicamentos_paguemenos

    def registrarDados(lista, sessao):
        for preco in lista:
            sessao.execute(text("INSERT INTO preco (numpreco, preco, idfarmacia, idmedicamento) VALUES (now(), :preco, :idfarmacia, :idmedicamento)"), preco)


import os
import pytest

from path import Path

from . import initialize_git_repo_and_commit, prepare_project

DIST_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '../dist'))

# Test if package can be imported to allow testing on
# conda-forge where ``pytest-virtualenv`` is not available.
try:
    import pytest_virtualenv  # noqa: F401
    HAS_PYTEST_VIRTUALENV = True
except ImportError:
    HAS_PYTEST_VIRTUALENV = False

@pytest.mark.skipif(not HAS_PYTEST_VIRTUALENV,
                    reason="pytest_virtualenv not available. See #228")
def test_source_distribution(virtualenv):
    sdists = Path(DIST_DIR).files(match="*.tar.gz") if Path(DIST_DIR).exists() else []
    if not sdists:
        pytest.skip("no source distribution available")
    assert len(sdists) == 1

    virtualenv.run("pip install %s" % sdists[0])
    assert "scikit-build" in virtualenv.installed_packages()

    prepare_project("hello-no-language", virtualenv.workspace, force=True)
    initialize_git_repo_and_commit(virtualenv.workspace, verbose=False)

    virtualenv.run("python setup.py bdist_wheel")

@pytest.mark.skipif(not HAS_PYTEST_VIRTUALENV,
                    reason="pytest_virtualenv not available. See #228")
def test_wheel(virtualenv):
    wheels = Path(DIST_DIR).files(match="*.whl") if Path(DIST_DIR).exists() else []
    if not wheels:
        pytest.skip("no wheel available")
    assert len(wheels) == 1

    virtualenv.run("pip install %s" % wheels[0])
    assert "scikit-build" in virtualenv.installed_packages()

    prepare_project("hello-no-language", virtualenv.workspace, force=True)
    initialize_git_repo_and_commit(virtualenv.workspace, verbose=False)

    virtualenv.run("python setup.py bdist_wheel")


class FileManager:

    def load_file(self, filename):
        file_data = None
        while file_data is None:
            try:
                file_handle = open(filename, 'r')
            except FileNotFoundError:
                print("{} not found.".format(filename))
                print("please try an alternative filename")
                filename = input("> ")
            else:
                file_data = []
                for line in file_handle.readlines():
                    file_data.append(line)
                file_handle.close()
        return file_data

    def save_file(self, file_data, filename):
        file_handle = open(filename, 'a')
        file_handle.write('hello, world')  # trailing newline req'd?
        file_handle.close()

# --------------------------

if __name__ == "__main__":

    print("test1: file read")
    file_manager = FileManager()
    file_data = file_manager.load_file('test.txt')
    for line in file_data:
        print(line)

    print("test2: file write")
    file_manager = FileManager()
    file_manager.save_file("dummy data", 'test.txt')


class MyArray():
    def __init__(self, size):
        self.size = size
        self.items = [None] * size
        self.index = 0

    def insert(self, item):
        if (self.size == self.index):
            newItems = [None] * self.size * 2
            for i in range(self.size):
                newItems[i] = self.items[i]
            self.items = newItems
            self.size = self.size * 2

        self.items[self.index] = item
        self.index += 1

    def removeAt(self, index):
        deleted = None
        if index < 0 or index > self.size - 1:
            raise Exception("Index out of range")
        else:
            for i in range(index, self.size):
                if i + 1 < self.size:
                    if self.items[i] != None:
                        deleted = self.items[i]
                        self.items[i] = self.items[i + 1]
                else:
                    self.items[i] = None
            self.index -= 1
        return deleted

    def indexOf(self, item):
        for i in range(self.index):
            if self.items[i] == item:
                print(i)
                return i
        return -1

    def getItem(self, index):
        return self.items[index]

    def printItems(self):
        for i in range(self.index):
            print("Item "+ str(i) + ": " + str(self.items[i]))

    def max(self):
        max = -1
        for i in range(self.index):
            if self.items[i] > max:
                max = self.items[i]
        print("Max: " + str(max))
        return max

    def intersect(self, first_array, second_array):
        dict = {}
        for i in range(first_array.index):
            if first_array.getItem(i) not in dict:
                dict[first_array.getItem(i)] = 1
            else:
                dict[first_array.getItem(i)] += 1

        for i in range(second_array.index):
            if second_array.getItem(i) not in dict:
                dict[second_array.getItem(i)] = 1
            else:
                dict[second_array.getItem(i)] += 1

        for key in dict:
            if (dict[key] > 1):
                print("Intersecting: " + str(key))

    def reverse(self):
        for i in range(self.index - 1, - 1, - 1):
            print("Item "+ str(i) + ": " + str(self.items[i]))

    def insertAt(self, item, index):
        for i in range(self.index, index , -1):
            self.items[i] = self.items[i - 1]
        self.items[index] = item

class ArrayStack(MyArray):
    def __init__(self, size):
        super().__init__(size)

    def push(self, value):
        self.insert(value)

    def pop(self):
        return self.removeAt(self.index - 1)

    def peek(self):
        return self.items[self.index - 1]

    def is_empty(self):
        return self.index == 0

    def print_stack(self):
        self.printItems()

class TwoStacks():
    def __init__(self, capacity):
        self.stack = ArrayStack(capacity)
        self.index1 = -1
        self.index2 = capacity
        self.count = 0
        self.capacity = capacity

    def push1(self, value):
        if self.count == self.capacity:
            raise Exception("Stack is full")
        self.index1 += 1
        self.stack.items[self.index1] = value
        self.count += 1

    def push2(self, value):
        if self.count == self.capacity:
            raise Exception("Stack is full")
        self.index2 -= 1
        self.stack.items[self.index2] = value
        self.count += 1

    def pop1(self):
        if self.index1 == -1:
            raise Exception("Stack is empty, nothing to pop")
        self.stack.items[self.index1] = None
        self.index1 -= 1
        self.count -= 1

    def pop2(self):
        if self.index2 == self.capacity:
            raise Exception("Stack is empty, nothing to pop")
        self.stack.items[self.index2] = None
        self.index2 += 1
        self.count -= 1

    def is_empty1(self):
        return self.index1 == -1

    def is_empty2(self):
        return self.index2 == self.capacity

    def is_full1(self):
        return self.count == self.capacity

    def is_full2(self):
        return self.count == self.capacity

    def print_two_stacks(self):
        print(self.stack.items)

two_stacks = TwoStacks(10)
print(two_stacks.is_empty1())
print(two_stacks.is_empty2())
two_stacks.push1(1)
two_stacks.push1(1)
two_stacks.push1(1)
two_stacks.push1(1)
print(two_stacks.is_empty1())
print(two_stacks.is_full1())
print(two_stacks.is_full2())
two_stacks.push2(2)
two_stacks.push2(2)
two_stacks.push2(2)
two_stacks.push2(2)
two_stacks.push2(2)
two_stacks.push2(2)
print(two_stacks.is_full1())
print(two_stacks.is_full2())
print(two_stacks.is_empty2())
two_stacks.pop1()
two_stacks.pop1()
two_stacks.print_two_stacks()
two_stacks.pop2()
two_stacks.pop2()
two_stacks.pop2()
two_stacks.pop2()
two_stacks.print_two_stacks()


import sys
import os
from shutil import copyfile
import subprocess

def check_dir(path):
		directory = os.path.dirname(path)
		if not os.path.exists(path):
			return False
		return True

def check_and_create(path):
		if (check_dir(path) == False):
			os.makedirs(path)

if __name__=='__main__':
#Need to error check

	#What should we call the file?
	fileName = input("sb file name: ")
	fileName = fileName + ".sb"
	#How much time should the script run?
	runTime = input("Input run time (HH:MM:SS): ")
	#Number of CPUS
	CPUs = input("Number of CPUs: ")
	#Memory per CPU
	memory = input("Memory per CPU (GB): ")
	#Job name
	jobName = input("Name of job: ")

	#Let's write
	f = open(fileName, "a+")
	f.write("#!/bin/bash --login\n")

	f.write("#SBATCH --time="+ str(runTime) + "\n")
	f.write("#SBATCH -n "+ str(CPUs) +"\n")
	f.write("#SBATCH -c 1\n")
	f.write("#SBATCH --mem-per-cpu=" +str(memory) +"G\n")
	f.write("SBATCH --job-name " + str(jobName) + "\n")

	f.write("env\n")
	f.write("conda activate opencv35\n")

	f.write("export LD_LIBRARY_PATH=/mnt/home/f0008668/lib/libsdp.so:$LD_LIBRARY_PATH\n")
	f.write("cd Binary-Image-Segmentation/\n")
	f.write("HOSTFILE=$SLURM_JOB_ID.hostfile\n")
	f.write("srun hostname -s > $HOSTFILE\n")
	f.write("srun python -m scoop --hostfile $HOSTFILE -n "+ str(CPUs) + " main.py\n")

	f.write("module load powertools\n")
	f.write("js $SLURM_JOB_ID\n")

	f.close()

	#Now let's edit the script
	#Mutation chance
	mutProb = input("Specify the mutation chance (e.g. 0.75): ")
	#flipping chance (Each value of mutated value)
	flipProb = input ("Specify the flipping chance (e.g. 0.76): ")
	#Crossover  chance
	crProb = input("Specify the crossover chance: ")
	#Generations
	gens = input("Total number of generations: ")
	#Population
	pop = input("Total population: ")
	name = input("Name of new python script: ")

	#copyfile(src, dst)

	foundPop = False
	foundGen = False
	foundMut = False
	foundFlip = False
	foundCross = False

	prog = open("main.py", "r")

	popFolder = "POP="+str(pop)
	genFolder = "GEN="+str(gens)
	endFileName = "MUT="+str(mutProb)+"_FLIP="+str(flipProb)+"_CROSS="+str(crProb)+".txt"
	filePath = popFolder + "/" + genFolder
	check_and_create(filePath)
	exeFile = filePath + "/" + name
	dest = open(exeFile, "w+")
	for line in prog:
		#We have a few keywords to look for
		if "POPULATION" in line and foundPop == False:
			popString = "POPULATION = "+ pop + "\n"
			dest.write(popString)
			foundPop = True
			continue
		elif "GENERATIONS" in line and foundGen == False:
			genString = "GENERATIONS = "+gens+ "\n"
			dest.write(genString)
			foundGen = True
			continue
		elif "MUTATION" in line and foundMut == False:
			mutString = "MUTATION = "+mutProb + "\n"
			dest.write(mutString)
			foundMut = True
			continue
		elif "FLIPPROB" in line and foundFlip == False:
			flipString = "FLIPPROB = "+flipProb + "\n"
			dest.write(flipString)
			foundFlip = True
			continue
		elif "CROSSOVER" in line and foundCross == False:
			crosString = "CROSSOVER = "+crProb + "\n"
			dest.write(crosString)
			foundCross = True
			continue
		else:
			dest.write(line)
	prog.close()

	dest.close()
	chdir = "cd "+filePath
	runString = "python "+name +">> "+filePath + "/" + endFileName
	subprocess.call(chdir)
	subprocess.call(runString)

	#Sort by population first


from pathlib import Path
import shelve

class PID():
    P = Path('C:\\','Users','leouh', 'Documents', 'Rb_Controller')
    def __init__(self):
        with shelve.open('config') as config:
            self.cfg = dict(config)
        self.Ts = 1/self.cfg['freq']
        if self.cfg['ki']:
            self.taui = self.cfg['kp']/self.cfg['ki']
        self.taud = self.cfg['kd']/self.cfg['kp']

    integral_error = 0
    integral_error2 = 0
    prev_t = 0
    prev_t2 = 0

    upper_lim = 28
    lower_lim = 0

    settlecount = 0
    active_controller = 1

    def settle_update(self, t, t_target,error,slope):
        within_error = error and self.cfg['max_fluctuations'] > abs(t_target - t)
        within_slope = slope and self.cfg['settle_slope'] >= abs(t - self.prev_t) / self.Ts

        if within_error or within_slope:
            self.settlecount += 1
        else:
            self.settlecount = 0

    def settle_check(self,slope,timed):
        if slope and timed:
            res = self.settlecount > self.cfg['settle_wait_time']*self.cfg['freq'] or \
                self.settlecount > self.cfg['slope_length']*self.cfg['freq']
        elif slope:
            res = self.settlecount > self.cfg['slope_length']*self.cfg['freq']
        elif timed:
            res = self.settlecount > self.cfg['settle_wait_time']*self.cfg['freq']
        else:
            res = False
        return res

    def swap_controller(self,to):
        if to == self.active_controller:
            return
        if to == 1:
            self.integral_error = self.integral_error2*self.cfg['ki2']/self.cfg['ki']
        if to == 2:
            self.integral_error2 = self.integral_error*self.cfg['ki']/self.cfg['ki2']
        self.active_controller = to

    # Simple PID controller. Explicitly dealing with wind-up
    def update(self, t, t_target):
        error = t_target - t
        p = self.cfg['kp'] * error
        i = self.cfg['ki'] * self.integral_error * self.Ts
        derivative = t - self.prev_t
        d = self.cfg['kd'] * derivative / self.Ts
        self.prev_t = t
        pidout = p + i + d
        if self.lower_lim < pidout < self.upper_lim:
            self.integral_error += error
        else:
            self.integral_error = 0
        return max(min(pidout,self.upper_lim),self.lower_lim)

    def update2(self, t, t_target):
        error = t_target - t
        p = self.cfg['kp2'] * error
        i = self.cfg['ki2'] * self.integral_error2 * self.Ts
        derivative = t - self.prev_t2
        d = self.cfg['kd2'] * derivative / self.Ts
        self.prev_t2 = t
        pidout = p + i + d
        if self.lower_lim < pidout < self.upper_lim:
            self.integral_error2 += error
        else:
            self.integral_error2 = 0
        return max(min(pidout,self.upper_lim),self.lower_lim)


  # Write a script that takes a string of words and a letter from the user.
# Find the index of first occurrence of the letter in the string. For example:
#
# String input: hello world
# Letter input: o
# Result: 4

result = ""
entry = input("please enter a string of words:\n\n  words: ")
print("thanks!")
letter = input("what letter are you looking for?\n\n  letter: ")
print("great, let's take a look!")
flag = True

while flag:

    for i in entry:
        if i == letter:
            result = entry.index(i)
            print(result)
            flag = False
            break
    else:
        print("uh oh. looks like the letter you're looking for doesn't reside in the string of words you've provided!")
        flag = False
        break


# -*- coding: utf-8 -*-
__author__ = 'apsmi'

import asynchat, socket, struct, pickle

IN_BUF_SIZE  = 128 * (2**10) # размер  входящего буфера сокета
OUT_BUF_SIZE = 128 * (2**10) # размер исходящего буфера сокета

LEN_TERM = 4

# сокет, принимающий соединение от клиентов
class Client(asynchat.async_chat):

    def __init__(self, addr):
        asynchat.async_chat.__init__(self)
        self.ibuffer = []
        self.obuffer = b""
        self.imes = [] #b""

        # создаем сокет
        self.create_socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.bind(('', 0))
        client_port = self.socket.getsockname()[1]

        # подключаемся к диспетчеру, отправляем ему свой клиентский порт
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.bind(('', 0))
        sock.sendto(struct.pack('L', client_port), addr)

        # получем серверный udp порт
        buf, _ = sock.recvfrom(4)
        server_port = struct.unpack('L',buf)[0]
        sock.close()

        self.ac_in_buffer_size = IN_BUF_SIZE
        self.ac_out_buffer_size = OUT_BUF_SIZE

        self.addr = (addr[0], server_port)
        self.set_terminator(LEN_TERM)
        self.state = "len"

    def handle_close(self):
        #print(self.socket.getsockname())
        self.close()

    def writable(self):
        return len(self.obuffer) > 0

    def handle_write(self):
        sent = self.sendto(self.obuffer, self.addr)
        self.obuffer = self.obuffer[sent:]

    def collect_incoming_data(self, data):
        self.ibuffer.append(data)

    def found_terminator(self):
        dataframe = b"".join(self.ibuffer)
        self.ibuffer = []
        if self.state == "len":
            self.state = "data"
            length = struct.unpack('L',dataframe)[0]
            self.set_terminator(length)
        elif self.state == "data":
            self.state = "len"
            self.set_terminator(LEN_TERM)
            self.imes.append(pickle.loads(dataframe))
            if self.imes == "exit":
                self.close()


import argparse
import os
import os.path

import pandas

def main():
    parser = argparse.ArgumentParser(description='Quick helper for getting model accuracies', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('inputs', nargs = '+', help='input CSVs')
    parser.add_argument('--nrows', help='num lines', type = int, default=None)
    args = parser.parse_args()

    for p in args.inputs:
        try:
            df = pandas.read_csv(p, nrows = args.nrows)
        except EOFError:
            print(f"{os.path.abspath(p).split('.')[0]} EOF")
        else:
            print(f"{os.path.abspath(p).split('.')[0]} {df['model_correct'].mean() * 100:.2f}%")

if __name__ == "__main__":
    main()


from tkinter import *

from date.SQL import executeSQL

class FFCview:
    def __init__(self):
        self.root=Tk()
        self.root.title="四角码转换器"

        self.l_character = Label(self.root, text="汉字")
        l.grid(row=1, column=0, sticky=W)

        self.root.mainloop()

if __name__ == '__main__':
    a=FFCview()


## For example, if you pass '12345' the function returns all the sum of single digit
## in this case, the function will return 1+2+3+4+5 = 15

def sum_func(n):
    ## Base case when number is single digit by itself, when a number only contains 1 digit.
    if len(str(n)) == 1:
        return n
    else:
        ## n % 10 returns the last digit, for example, 12345 % 10 = 5 (last digit)
        ## n // 10 (Python 3), n / 10 (Python 2). trims the last digit leaving remaining number
        ## 12345 // 10 = 1234 (We want to pass this number into function to perform recursion)
        ## Overall
        ## 12345 is passed , 5 + sum_func(1234) => 5 + 4 + sum_fun(123) => 5 + 4 + 3 + sum_fun(12) + .. + 1

        return (n % 10 ) + sum_func (n // 10)

## Testing

print(sum_func(12345)) ## should return 15!

recursion/sum of single digit/sum_of_single_digit.py


# savers
from sqlalchemy import exc

from src import db_manager

def save_page_to_db(page):
    try:
        db_manager.session.add(page)
        db_manager.session.commit()
    except exc.SQLAlchemyError as e:
        db_manager.handel_exception(e, True, 'save_page', page.url)
    return True

def save_site_to_db(site):
    try:
        db_manager.session.add(site)
        db_manager.session.commit()
    except exc.SQLAlchemyError as e:
        db_manager.handel_exception(e, True, 'save_site', site.domain)
    return True

def save_link_to_db(link):
    try:
        db_manager.session.add(link)
        db_manager.session.commit()
    except exc.SQLAlchemyError as e:
        db_manager.handel_exception(e, True, 'save_link', link.to_page)
    return True

def save_image_to_db(image):
    try:
        db_manager.session.add(image)
        db_manager.session.commit()
    except exc.SQLAlchemyError as e:
        db_manager.handel_exception(e, True, 'save_image', image.url)
    return True

def save_page_image_to_db(page_image):
    try:
        db_manager.session.add(page_image)
        db_manager.session.commit()
    except exc.SQLAlchemyError as e:
        db_manager.handel_exception(e, True, 'save_page_image', page_image.image_id)
    return True

def save_page_data_to_db(page_data):
    try:
        db_manager.session.add(page_data)
        db_manager.session.commit()
    except exc.SQLAlchemyError as e:
        db_manager.handel_exception(e, True, 'save_page_data', page_data.page_id)
    return True

### saving documents

def save_documents_to_db(doc_array, page_id):
    for doc in doc_array:
        save_document_to_db(doc, page_id)

    return True

def save_document_to_db(url, page_id):
    return True

### saving images

def save_images_to_db(img_array, page_id):
    for img in img_array:
        save_document_to_db(img, page_id)

    return True


import sys
sys.stdin = open("양팔저울.txt")

def comp_kg(k, left, right, kgs):
    global cnt
    if sum(left) < sum(right):
        return
    if k == N:
        # print(left, right)
        cnt += 1
        return
    else:
        comp_kg(k+1, left+[kgs[k]], right, kgs)
        comp_kg(k+1, left, right+[kgs[k]], kgs)

def powerset(k, n, l):      # n: 원소의 갯수, k: 현재depth

    if k == N:          # Basis Part
        # print(n)
        comp_kg(0, [], [], n)
    else:               # Inductive Part
        for i in range(len(kg)):
            if A[i] == 1:
                continue
            A[i] = 1        # k번 요소 O
            powerset(k+1, n + [kg[i]], l)  # 다음 요소 포함 여부 결정
            A[i] = 0       # k번 요소 X

T = int(input())
for tc in range(1, T+1):
    N = int(input())
    kg = list(map(int, input().split()))
    A = [0 for _ in range(N)]  # 원소의 포함여부 저장 (0, 1)
    cnt = 0
    powerset(0, [], 0)
    print('#{} {}'.format(tc, cnt))


# SOFTEX-RECIFE
# Aluno: Fábio de Tássio

# Atividade 02 do módulo 02 (Dominar as diferentes estruturas condicionais lógicas)

# Desenvolva um código que utilize as seguintes características de um veículo:
# - Quantidade de rodas;
# - Peso bruto em quilogramas;
# - Quantidade de pessoas no veículo.
# Com essas informações, o programa mostrará qual é a melhor categoria de habilitação para o veículo informado a partir das condições:
# A: Veículos com duas ou três rodas;
# B: Veículos com quatro rodas, que acomodam até oito pessoas e seu peso é de até 3500 kg;
# C: Veículos com quatro rodas ou mais e com peso entre 3500 e 6000 kg;
# D: Veículos com quatro rodas ou mais e que acomodam mais de oito pessoas;
# E: Veículos com quatro rodas ou mais e com mais de 6000 kg

# Ínicio
qtd_rodas = int(input('Digite a quantidade de rodas:'))
qtd_pessoas = int(input('Digite a quantidade de pessoas:'))
Peso = int(input('Didite o peso do veículo:'))

if qtd_rodas == 2 or qtd_rodas == 3:
    print('Categoria A')
elif qtd_rodas == 4 and qtd_pessoas <= 8 and Peso <= 3500:
    print('Categoria B')
elif qtd_rodas >= 4 and qtd_pessoas <= 8 and Peso >= 3500 and Peso <= 6000:
    print('Categoria C')
elif qtd_rodas >= 4 and qtd_pessoas > 8 and Peso <= 6000:
    print('Categoria D')
elif qtd_rodas >= 4 and Peso > 6000:
    print('Categoria E')
else:
    print('O veículo não se enquadra em nenhuma categoria!')


import socket
import threading
import re

def thread_client(client_socket):
    try:
        while True:
            data = client_socket.recv(1024).decode()

            if not data:
                break

            match = re.match(r'^([0-9]+)([+\-*/])([0-9]+)$', data)
            if match:
                num1, operator, num2 = match.groups()
                num1, num2 = int(num1), int(num2)
                if operator == '+':
                    result = num1 + num2
                    print(f"{num1} + {num2} = {result}")
                elif operator == '-':
                    result = num1 - num2
                    print(f"{num1} - {num2} = {result}")
                elif operator == '*':
                    result = num1 * num2
                    print(f"{num1} * {num2} = {result}")
                elif operator == '/':
                    if num2 != 0:
                        result = num1 / num2
                        print(f"{num1} / {num2} = {result}")
                    else:
                        client_socket.send("Zero division error".encode())
                        continue
                else:
                    client_socket.send("Invalid operator".encode())
                    continue

                client_socket.send(str(result).encode())
            else:
                client_socket.send("Invalid operation".encode())
    except Exception as e:
        print(f"Error: {e}")
    finally:
        client_socket.close()

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('0.0.0.0', 54632)
server_socket.bind(server_address)
server_socket.listen(5)
print("Server is listening...")

while True:
    client_socket, client_address = server_socket.accept()
    print(f"{client_address} connected.")

    client_handler = threading.Thread(target=thread_client, args=(client_socket,))
    client_handler.start()


try:
    nombre = str(input("\nIngrese su nombre: "))
    edad = int(input("Ingrese su edad: "))
    identificacion = int(input("Ingrese su identificacion: "))

    if edad >= 18:
        print("\nTu, {}, identificado con numero {} eres mayor de edad".format(nombre,identificacion))
    else:
        print("\nTu, {}, identificado con numero {} eres menor de edad".format(nombre,identificacion))
except:
    print("\nEl dato ingresado no es valido")
print("")


#!/usr/bin/env python

#
#   A class to control mu-del converters
#
#   Incomplete
#   7DEC11 - Kyle Eberhart

import telnetlib
import logging
from multiprocessing import Process
from multiprocessing import Queue as Q
import queue
import time

class ConvProcess(object):
    '''
    A converter controller that runs in a seperate process, for smoother
    GUI operation. in_queue is how you send commands, out_queue is where
    data comes back.
    '''

    def __init__(self, **kwargs):
        '''
        Initialize our queues and other startup tasks.
        '''
        self.in_queue = Q()
        self.out_queue = Q()
        self.process = None
        self.address = kwargs.get('address', None)
        self.port = kwargs.get('port', None)
        self.converter_target = None

    def connect(self):
        '''
        start the converter communication process, feed it some queues.
        '''
        self.process = Process(target=self._connect,
                               args=(self.in_queue,
                                     self.out_queue))
        self.process.daemon = 1
        self.process.start()

    def command(self, message):
        '''
        send a command to the converter, using the in_q.
        '''
        self.in_queue.put(message)

    def disconnect(self):
        '''
        disconnect from the converter and terminate the process.
        '''
        self.in_queue.put('disconnect')

    def kill_process(self):
        '''
        kill the child process.
        '''
        self.in_queue.put('kill')
        self.process.join()
        self.process = None
        self.converter_target = None

    def _connect(self, in_q, out_q):
        '''
        The converter connection and processing loop.
        '''
        self.converter_target = Converter(address=self.address,
                                          port=self.port)
        self.converter_target.connect()
        while True:
            try:
                conv_command = in_q.get_nowait()
                if conv_command == 'disconnect':
                    self.converter_target.disconnect()
                    out_q.put("Requesting converter process termination.")
                elif conv_command == 'kill':
                    break
                elif 'freq' in conv_command:
                    self.converter_target.setFreq(conv_command[1])
                elif 'atten' in conv_command:
                    self.converter_target.setAtten(conv_command[1])
                elif 'mute' in conv_command:
                    if conv_command[1]:
                        self.converter_target.setMute()
                    else:
                        self.converter_target.unsetMute()
            except Queue.Empty:
                try:
                    if self.converter_target is not None:
                        self.converter_target.getStatus()
                        out_q.put({'freq' : self.converter_target.frequency,
                                   'atten' : self.converter_target.attenuation,
                                   'status' : self.converter_target.statusCode,
                                   'mute' : self.converter_target.mute})
                except EOFError:
                    out_q.put("Status attempt failed!")
                    self.converter_target.disconnect()
                    out_q.put("Requesting converter process termination.")
            time.sleep(1)

    def __del__(self):
        '''
        clean up correctly if possible.
        '''
        if self.process:
            self.disconnect()
            self.kill_process()

class Converter(object):

    def __init__(self, address='192.168.1.3', port=4004):
        self.logger = logging.getLogger(__name__)
        self.address = address
        self.port = port
        self.target = None
        self.errorMsg = None

    def __repr__(self):
        return "<MuDelConverter('%s', '%s')" % (self.address, self.port)

    def connect(self):
        '''
        connect to the converter, and determine the converter type
        '''
        self.target = telnetlib.Telnet(self.address, self.port)
        self.target.write('<?\r'.encode('ascii'))
        self.status = self.target.read_until(b'randomString', 2).decode('ascii')

        if 'MDC-1627F1K-7' in self.status:
            self.type = 'MDC-1627F1K-7'
        elif 'MDC-2125F1K-72' in self.status:
            self.type = 'MDC-2125F1K-72'
        elif 'MUC-7-1627-F1K' in self.status:
            self.type = 'MUC-7-1627-F1K'
        else:
            self.errorMsg = "Converter model unknown: %s" % self.status
            self.logger.debug(self.errorMsg)
            raise RuntimeError(self.errorMsg)

    def disConnect(self):
        '''
        disconnect from the converter
        '''
        self.target.close()
        self.target = None

    def getStatus(self):
        if self.target is None:
            self.connect()
        self.target.write('<S\r'.encode('ascii'))
        self.status = self.target.read_until(b'SomeCrazyString', 2).decode('ascii')
        if self.type == 'MDC-1627F1K-7' or self.type == 'MUC-7-1627-F1K':
            myStatus = self.status[1:].split(',')
            self.frequency = (float(myStatus[0]) + 1600000) / 1000
            self.attenuation =  (float(myStatus[1]) / 5)
            if int(myStatus[2]) is 1:
                self.statusCode = "Normal Operation"
            elif int(myStatus[2]) is 2:
                self.statusCode = "Synth Lock Lost"
            elif int(myStatus[2]) is 3:
                self.statusCode = "Synth 2 Lock Lost"
            elif int(myStatus[2]) is 4:
                self.statusCode = "Synth 3 Lock Lost"
            elif int(myStatus[2]) is 5:
                self.statusCode = "Local Osc Lock Lost"
            elif int(myStatus[2]) is 6:
                self.statusCode = "Aux Input 2 Alarm"
            elif int(myStatus[2]) is 7:
                self.statusCode = "Aux Input 3 Alarm"
            elif int(myStatus[2]) is 8:
                self.statusCode = "Aux Input 4 Alarm"
            elif int(myStatus[2]) is 9:
                self.statusCode = "Reference Osc Lost"
            else:
                self.statusCode = "Unknown"
            self.mute = bool(int(myStatus[3][0:1]))

        if self.type == 'MDC-2125F1K-72':
            myStatus = self.status[1:].split(',')
            self.frequency = (float(myStatus[0]) + 2100000) / 1000
            self.attenuation =  (float(myStatus[1]) / 5)
            if int(myStatus[2]) is 1:
                self.statusCode = "Normal Operation"
            elif int(myStatus[2]) is 2:
                self.statusCode = "Synth Lock Lost"
            elif int(myStatus[2]) is 3:
                self.statusCode = "Synth 2 Lock Lost"
            elif int(myStatus[2]) is 4:
                self.statusCode = "Synth 3 Lock Lost"
            elif int(myStatus[2]) is 5:
                self.statusCode = "Local Osc Lock Lost"
            elif int(myStatus[2]) is 6:
                self.statusCode = "Aux Input 2 Alarm"
            elif int(myStatus[2]) is 7:
                self.statusCode = "Aux Input 3 Alarm"
            elif int(myStatus[2]) is 8:
                self.statusCode = "Aux Input 4 Alarm"
            elif int(myStatus[2]) is 9:
                self.statusCode = "Reference Osc Lost"
            else:
                self.statusCode = "Unknown"
            self.mute = None

        return {'Freq': self.frequency, 'Atten': self.attenuation, 'Code': self.statusCode, 'Mute': self.mute}

    def setFreq(self, freq):
        '''
        set the converter frequency
        '''
        if self.target is None:
            self.connect()
        if self.type == 'MDC-1627F1K-7' or self.type == 'MUC-7-1627-F1K':
            stepValue = (int((float(freq) * 1000)) - 1600000)
            if stepValue < 0:
                stepValue = 0
            if stepValue > 1100000:
                stepValue = 1100000
            self.target.write('<X1{}\r'.format(stepValue).encode('ascii'))
            self.target.read_until(b'SomeCrazyString', 2).decode('ascii')
        elif self.type == 'MDC-2125F1K-72':
            stepValue = (int((float(freq) * 1000)) - 2100000)
            if stepValue < 0:
                stepValue = 0
            if stepValue > 400000:
                stepValue = 400000
            self.target.write('<{}\r'.format(stepValue).encode('ascii'))
            self.target.read_until(b'SomeCrazyString', 2).decode('ascii')
        else:
            self.errorMsg = "Unknown converter type, no freq change"
            self.logger.debug(self.errorMsg)
            raise RuntimeError(self.errorMsg)

    def setAtten(self, atten):
        if self.target is None:
            self.connect()
        if self.type == 'MDC-1627F1K-7' or self.type == 'MUC-7-1627-F1K':
            stepValue = int(float(atten) * 5)
            if stepValue < 0:
                stepValue = 0
            if stepValue > 150:
                stepValue = 150
            self.target.write('<A1{}\r'.format(stepValue).encode('ascii'))
            self.target.read_until(b'SomeCrazyString', 2).decode('ascii')
        elif self.type == 'MDC-2125F1K-72':
            stepValue = int(float(atten) * 5)
            if stepValue < 0:
                stepValue = 0
            if stepValue > 150:
                stepValue = 150
            self.target.write('<A{}\r'.format(stepValue).encode('ascii'))
            self.target.read_until(b'SomeCrazyString', 2).decode('ascii')
        else:
            self.errorMsg = "Unknown converter type, no atten change"
            raise RuntimeError(self.errorMsg)

    def setMute(self):
        if self.target is None:
            self.connect()
        if self.type == 'MDC-2125F1K-72':
            self.errorMsg = "This D/C doesn't support muting"
            raise RuntimeError(self.errorMsg)
        self.target.write('<M1\r'.encode('ascii'))
        self.target.read_until(b'SomeCrazyString', 2).decode('ascii')

    def unsetMute(self):
        if self.target is None:
            self.connect()
        if self.type == 'MDC-2125F1K-72':
            self.errorMsg = "This D/C doesn't support muting"
            raise RuntimeError(self.errorMsg)
        self.target.write('<M0\r'.encode('ascii'))
        self.target.read_until(b'SomeCrazyString', 2).decode('ascii')

    def setConfig(self, **kwargs):
        '''
        configure the whole converter in one bang
        '''
        if 'Freq' in kwargs:
            self.setFreq(kwargs['Freq'])
        if 'Atten' in kwargs:
            self.setAtten(kwargs['Atten'])
        if 'Mute' in kwargs:
            if kwargs['Mute'] is True:
                self.setMute()
            if kwargs['Mute'] is False:
                self.unsetMute()

    def close(self):
        if self.target is not None:
            self.disConnect()

if __name__ == "__main__":
    # run a test, or just set things up...
    import argparse
    import sys

    logging.basicConfig(filename='Mudelconverter.log',
                        filemode='w',
                        level=logging.INFO)

    parser = argparse.ArgumentParser(description='Configure a MuDel Converter',
                                    formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('-f', '--freq', help='Set the frequency in MHz.')
    parser.add_argument('-a', '--atten', help='Set the attenuation in dB.')
    parser.add_argument('-m', '--mute', help='Toggle the mute.')
    parser.add_argument('dest', help='IP address of the target device.')
    args = parser.parse_args()
    config = vars(args)

    if config['dest'] is not None:
        try:
            ip, port = config['dest'].split(':')
        except ValueError as err:
            print('\nIt doesn\'t seem like a port was specified.')
            print('\txxx.xxx.xxx.xxx:ppp')
            print('Where xxx is the IP octet and ppp is the port number.\n')
            sys.exit()
        try:
            converter = Converter(ip, port)
            converter.connect()
            print('\n')
#            print(converter.status)
        except RuntimeError as err:
            print('\nConnection to converter failed!!!')
            print(err)
            print('\n')
            sys.exit()
        try:
            converter.getStatus()
            print('---- Current Status ----')
            print('Freq:  {} MHz'.format(converter.frequency))
            print('Atten: {} dB'.format(converter.attenuation))
            print('LO:    {}'.format(converter.statusCode))
            print('Mute:  {}'.format(converter.mute))
            print('\n')
        except RuntimeError as err:
            print('\nStatus fetch failed!!!')
            print(err)
            print('\n')
            sys.exit()

    if config['freq'] is not None:
        # set the frequency, check the input formatting first.
        converter.setFreq(config['freq'])

    if config['atten'] is not None:
        # set the attenuation, check the input formatting first.
        converter.setAtten(config['atten'])

    if config['mute'] is not None:
        # always unmute the converter.
        converter.unsetMute()

    converter.getStatus()
    print('---- Final Status ----')
    print('Freq:  {} MHz'.format(converter.frequency))
    print('Atten: {} dB'.format(converter.attenuation))
    print('LO:    {}'.format(converter.statusCode))
    print('Mute:  {}'.format(converter.mute))
    print('\n')

    converter.close()
    sys.exit()


import sys
import xbmc, xbmcplugin, xbmcgui, xbmcaddon

# -- Constants ----------------------------------------------
ADDON_ID = 'plugin.video.entertain'
FANART = xbmcaddon.Addon(id=ADDON_ID).getAddonInfo('path') + '/fanart.jpg'

# -- Settings -----------------------------------------------
settings = xbmcaddon.Addon(id=ADDON_ID)
quality = 1 + int(settings.getSetting("quality"))
channelimage = int(settings.getSetting("channelimage"))
categories = 1 + int(settings.getSetting("categories"))

# -- I18n ---------------------------------------------------
language = xbmcaddon.Addon(id=ADDON_ID).getLocalizedString

# -- Functions ----------------------------------------------
def getIconUrl(filename=False):
	return getResourceUrl('icons', filename)

def getThumbnailUrl(filename=False):
	return getResourceUrl('thumbnails', filename)

def getPosterUrl(filename=False):
	return getResourceUrl('poster', filename)

def getFanartUrl(filename=False):
	return getResourceUrl('fanart', filename)

def getResourceUrl(reskind, filename=False):
	if (not filename):
		filename = 'default.jpg'
	retUrl = xbmcaddon.Addon(id=ADDON_ID).getAddonInfo('path') + '/resources/' + reskind + '/' + filename
	return xbmc.translatePath(retUrl)

def addEntertainChannel(url,name,all=False,icon=False,thumbnail=False,poster=False,fanart=False,plot='',genre=language(30090),year='2014',duration='90',hdurl=False,chancat=1):
	if (chancat & categories):
		if (not hdurl):
			addChannel(url,name,all,icon,thumbnail,poster,fanart,plot,genre,year,duration)
		else:
			if (quality & 1):
				addChannel(url,name,all,icon,thumbnail,poster,fanart,plot,genre,year,duration)
			if (quality & 2):
				addChannel(hdurl,name + " HD",all,icon,thumbnail,poster,fanart,plot,genre,year,duration)

def addChannel(url,name,all=False,icon=False,thumbnail=False,poster=False,fanart=False, plot='', genre=language(30090),year='2014',duration='90'):
	iconUrl = getIconUrl(icon if (icon) else all)
	thumbnailUrl = getThumbnailUrl(thumbnail if (thumbnail) else all)
	posterUrl = getPosterUrl(poster if (poster) else all)
	fanartUrl = getFanartUrl(fanart if (fanart) else all)
	logoUrl = thumbnailUrl if ( channelimage ) else posterUrl
	li = xbmcgui.ListItem(name, iconImage=iconUrl, thumbnailImage=logoUrl)
	li.setProperty('IsPlayable', 'true')
	li.setProperty('Poster_Image', posterUrl)
	li.setProperty('Fanart_Image', fanartUrl)
	li.setInfo(type = 'Video', infoLabels = {
		"Title": name,
		"Plot": plot,
		"Year": year,
		"Genre": genre,
		"Duration": duration,
		"Art(thumb)": thumbnailUrl,
		"Art(poster)": posterUrl,
		"Art(fanart)": fanartUrl
		 })
	xbmcplugin.addDirectoryItem(int(sys.argv[1]), url, li, False)

# -- Main Code ----------------------------------------------

# TODO: can't figure out how to set fanart for root/back folder of plugin
# http://trac.xbmc.org/ticket/8228?
xbmcplugin.setPluginFanart(int(sys.argv[1]), FANART)
xbmcplugin.setContent(int(sys.argv[1]), 'movies')

# -- General Channels
if (settings.getSetting("cat_general") == "true"):
	# -- Public Channels
	addEntertainChannel ('rtp://@239.35.10.4:10000', 'Das Erste', year='1954', plot=language(30101), all='das-erste.jpg', hdurl='rtp://@239.35.10.1:10000')
	addEntertainChannel ('rtp://@239.35.10.5:10000', 'ZDF', year='1963', plot=language(30102), all='zdf.jpg', hdurl='rtp://@239.35.10.2:10000')
	# -- RTL Group
	addEntertainChannel ('rtp://@239.35.20.10:10000', 'RTL', year='1984', genre=language(30090), plot=language(30130), chancat=2)
	addEntertainChannel ('rtp://@239.35.20.11:10000', 'VOX', year='1993', genre=language(30090), plot=language(30131), chancat=2)
	addEntertainChannel ('rtp://@239.35.20.22:10000', 'RTL II', year='1993', genre=language(30090), plot=language(30132), chancat=2)

# -- Regional Channels
if (settings.getSetting("cat_regional") == "true"):
	# -- Public Channels
	addEntertainChannel ('rtp://@239.35.10.13:10000', 'BR Nord', year='1949', genre=language(30091), plot=language(30103), all='BR.jpg')
	addEntertainChannel ('rtp://@239.35.10.7:10000', 'BR Süd', year='1949', genre=language(30091), plot=language(30103), all='BR.jpg', hdurl='rtp://@239.35.10.49:10000')
	addEntertainChannel ('rtp://@239.35.10.8:10000', 'hr-fernsehen', genre=language(30091), plot=language(30124), all='hr.jpg', hdurl='rtp://@239.35.10.60:10000')
	addEntertainChannel ('rtp://@239.35.10.9:10000', 'MDR Sachsen', year='1992', genre=language(30091), plot=language(30104), all='mdr.jpg', hdurl='rtp://@239.35.10.61:10000')
	addEntertainChannel ('rtp://@239.35.10.29:10000', 'MDR Sachsen-Anhalt', year='1992', genre=language(30091), plot=language(30104), all='mdr.jpg')
	addEntertainChannel ('rtp://@239.35.10.30:10000', 'MDR Thüringen', year='1992', genre=language(30091), plot=language(30104), all='mdr.jpg')
	addEntertainChannel ('rtp://@239.35.10.10:10000', 'NDR Niedersachsen', year='1954', genre=language(30091), plot=language(30105), hdurl='rtp://@239.35.10.50:10000')
	addEntertainChannel ('rtp://@239.35.10.31:10000', 'NDR Hamburg', year='1954', genre=language(30091), plot=language(30105))
	addEntertainChannel ('rtp://@239.35.10.32:10000', 'NDR Mecklenburg-Vorpommern', year='1954', genre=language(30091), plot=language(30105))
	addEntertainChannel ('rtp://@239.35.10.33:10000', 'NDR Schleswig-Holstein', year='1954', genre=language(30091), plot=language(30105))
	addEntertainChannel ('rtp://@239.35.10.12:10000', 'Radio Bremen TV', year='1945', genre=language(30091), plot=language(30106))
	addEntertainChannel ('rtp://@239.35.10.14:10000', 'rbb Berlin', year='2003', genre=language(30091), plot=language(30107), hdurl='rtp://@239.35.10.62:10000')
	addEntertainChannel ('rtp://@239.35.10.34:10000', 'rbb Brandenburg', year='2003', genre=language(30091), plot=language(30107))
	addEntertainChannel ('rtp://@239.35.10.15:10000', 'SR Fernsehen', year='1957', genre=language(30091), plot=language(30108))
	addEntertainChannel ('rtp://@239.35.10.16:10000', 'SWR Baden-Würtenberg', year='1998', genre=language(30091), plot=language(30109), hdurl='rtp://@239.35.10.51:10000')
	addEntertainChannel ('rtp://@239.35.10.17:10000', 'SWR Rheinland-Pfalz', year='1998', genre=language(30091), plot=language(30109), hdurl='rtp://@239.35.10.52:10000')
	addEntertainChannel ('rtp://@239.35.10.18:10000', 'WDR Köln', year='1956', genre=language(30091), plot=language(30110), hdurl='rtp://@239.35.10.53:10000')
	addEntertainChannel ('rtp://@239.35.10.35:10000', 'WDR Aachen', year='1956', genre=language(30091), plot=language(30110))
	addEntertainChannel ('rtp://@239.35.10.36:10000', 'WDR Bielefeld', year='1956', genre=language(30091), plot=language(30110))
	addEntertainChannel ('rtp://@239.35.10.37:10000', 'WDR Bonn', year='1956', genre=language(30091), plot=language(30110))
	addEntertainChannel ('rtp://@239.35.10.38:10000', 'WDR Dortmund', year='1956', genre=language(30091), plot=language(30110))
	addEntertainChannel ('rtp://@239.35.10.39:10000', 'WDR Duisburg', year='1956', genre=language(30091), plot=language(30110))
	addEntertainChannel ('rtp://@239.35.10.40:10000', 'WDR Düsseldorf', year='1956', genre=language(30091), plot=language(30110))
	addEntertainChannel ('rtp://@239.35.10.41:10000', 'WDR Essen', year='1956', genre=language(30091), plot=language(30110))
	addEntertainChannel ('rtp://@239.35.10.42:10000', 'WDR Münster', year='1956', genre=language(30091), plot=language(30110))
	addEntertainChannel ('rtp://@239.35.10.43:10000', 'WDR Siegen', year='1956', genre=language(30091), plot=language(30110))
	addEntertainChannel ('rtp://@239.35.10.44:10000', 'WDR Wuppertal', year='1956', genre=language(30091), plot=language(30110))
	# -- RTL Group
	addEntertainChannel ('rtp://@239.35.20.5:10000', 'RTL NRW', year='1984', genre=language(30091), plot=language(30130), chancat=2)
	addEntertainChannel ('rtp://@239.35.20.6:10000', 'RTL HB NDS', year='1984', genre=language(30091), plot=language(30130), chancat=2)
	addEntertainChannel ('rtp://@239.35.20.63:10000', 'RTL HH SH', year='1984', genre=language(30091), plot=language(30130), chancat=2)
	addEntertainChannel ('rtp://@239.35.20.64:10000', 'RTL Hessen', year='1984', genre=language(30091), plot=language(30130), chancat=2)

# -- Cultural Channels
if (settings.getSetting("cat_cultural") == "true"):
	# -- Public Channels
	addEntertainChannel ('rtp://@239.35.10.6:10000', '3sat', year='1984', genre=language(30092), plot=language(30111), all='3sat.jpg', hdurl='rtp://@239.35.10.47:10000')
	addEntertainChannel ('rtp://@239.35.10.20:10000', 'ARTE', year='1991', genre=language(30092), plot=language(30112), all='arte.jpg', hdurl='rtp://@239.35.10.3:10000')
	addEntertainChannel ('rtp://@239.35.10.21:10000', 'Einsfestival', year='1997', genre=language(30092), plot=language(30113), hdurl='rtp://@239.35.10.58:10000')
	addEntertainChannel ('rtp://@239.35.10.23:10000', 'zdf.kultur', year='2011', genre=language(30092), plot=language(30114), hdurl='rtp://@239.35.10.54:10000')

# -- Special Interest
if (settings.getSetting("cat_special") == "true"):
	# -- Public Channels
	addEntertainChannel ('rtp://@239.35.10.19:10000', 'KiKa', year='1997', genre=language(30093), plot=language(30115), hdurl='rtp://@239.35.10.11:10000')
	addEntertainChannel ('rtp://@239.35.10.22:10000', 'PHOENIX', year='1997', genre=language(30093), plot=language(30116), hdurl='rtp://@239.35.10.48:10000')
	addEntertainChannel ('rtp://@239.35.10.24:10000', 'BR-alpha', year='1998', genre=language(30093), plot=language(30117))
	addEntertainChannel ('rtp://@239.35.10.26:10000', 'EinsPlus', year='1997', genre=language(30093), plot=language(30118), hdurl='rtp://@239.35.10.59:10000')
	# -- RTL Group
	addEntertainChannel ('rtp://@239.35.20.39:10000', 'Super RTL', year='1995', genre=language(30093), plot=language(30133), chancat=2)
	addEntertainChannel ('rtp://@239.35.20.59:10000', 'RTLNITRO', year='2012', genre=language(30093), plot=language(30135), chancat=2)

# -- News Channels
if (settings.getSetting("cat_news") == "true"):
	# -- Public Channels
	addEntertainChannel ('rtp://@239.35.20.44:10000', 'Deutsche Welle', year='1992', genre=language(30094), plot=language(30120))
	addEntertainChannel ('rtp://@239.35.10.25:10000', 'tagesschau24', year='1997', genre=language(30094), plot=language(30121), hdurl='rtp://@239.35.10.63:10000')
	addEntertainChannel ('rtp://@239.35.10.28:10000', 'ZDFinfo', year='1997', genre=language(30094), plot=language(30122), hdurl='rtp://@239.35.10.56:10000')
	addEntertainChannel ('rtp://@239.35.10.27:10000', 'ZDFneo', year='2009', genre=language(30094), plot=language(30123), hdurl='rtp://@239.35.10.55:10000')
	# -- RTL Group
	addEntertainChannel ('rtp://@239.35.20.47:10000', 'n-tv', year='1992', genre=language(30094), plot=language(30134), chancat=2)

xbmcplugin.endOfDirectory(int(sys.argv[1]))


print("Hello, world!")

name = input("Name: ")
print("Hello, " + name)
print(f"Hello, {name}")

n = input("Number: ")

if n.isdigit():
    n = int(n)
    if n > 0:
        print(f"{n} is positive")
    elif n < 0:
        print(f"{n} is negative")
    else:
        print("Number is zero")
else:
    print("No es un número entero válido.")

#Define a list of names
names = ["Víctor", "Pablo", "Paula", "María"]

print(names)
ans = int(input("Wanna add any other name? Press 1 for yes, 0 for no: "))
if ans == 1:
    newName = input("Name to append: ")
    names.append(newName)
print(names)

names.sort()
print(names)

ciclos = {
    "Víctor": "ADE",
    "Marta": "DAW"
    }

print("Víctor estudia " + ciclos["Víctor"])

addNew = int(input("Quieres añadir otro alumno? 1 YES 0 NO: "))
if addNew == 1:
    nombreAdd = input("Ingresa el nombre: ")
    cicloAdd = input("Ingresa el ciclo: ")
    ciclos[nombreAdd] = cicloAdd
    print(ciclos)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import argparse, codecs, sys

# Parseur de ligne de commande
parser = argparse.ArgumentParser(description="Sorts or inverts lines or characters from a file.")
parser.add_argument('-f', help="input file")
# seul -l ou -c est permis
lorc = parser.add_mutually_exclusive_group()
lorc.add_argument('-l', help='line sort (default)', action='store_true')
lorc.add_argument('-c', help='character sort', action='store_true')
parser.add_argument('mode', help='either "sort" or "invert"')
args = parser.parse_args()

# Lecture du fichier
lines = []
try:
	with codecs.open(args.f, 'r', encoding='utf8') as f:
		for line in f.readlines():
			# on élimine les retours à la ligne en vue de l'éventuel tri
			lines.append(line.rstrip('\n'))
except IOError:
	sys.exit('Error: file not found')

# Opérations sur le texte
# (si le paramètre -c est spécificié, chaque ligne est aussi
#	 triée ou inversée; le paramètre -l n'est jamais vérifié,
#  mais l'utilisateur peut l'utiliser pour se "rassurer")
if args.mode == 'sort':
	# tri selon l'ordre de Python
	if args.c:
		for i in range(0, len(lines)):
			lines[i] = ''.join(sorted(lines[i]))
	lines.sort()
elif args.mode == 'invert':
	# inversion
	# (c'est peu efficace de procéder à l'inversion explicitement,
	#  mais c'est plus clair, et 'sort' est bien pire de toute façon!)
	if args.c:
		for i in range(0, len(lines)):
			lines[i] = lines[i][::-1]
	lines.reverse()
else:
	# si un mode erroné est spécifié, les lignes ne sont pas modifiées
	sys.exit("Error: unrecognized mode (must be either 'sort' or 'invert')")

# Impression
for line in lines:
	sys.stdout.write(line+'\n')


import datetime as dt
from dateutil import parser
import os
import pandas as pd
import numpy as np
from scipy import interpolate
from matplotlib import mlab
from selenium import webdriver
import bs4

from timeout import timeout

class DECStation:
    def __init__(self, number, name, lon, lat):
        self.number = number
        self.name = name
        self.lon = lon
        self.lat = lat

    def get_station_url(self):
        """ Get url for a particular station"""
        url =  'http://www.nyaqinow.net/StationReportFast.aspx?&ST_ID=%s' %self.number

        return url

def get_stations():
    """Get the stations"""
    all_stations = {

        #DEC group 1
        #Long Island
        'Babylon': DECStation(46, 'Babylon', -73.41919, 40.74529),
        'Eisenhower Park': DECStation(53, 'Eisenhower Park', -73.58549, 40.74316),
        'Suffolk County': DECStation(36, 'Suffolk County', -73.05754, 40.82799),

        #DEC group 2
        #Manhattan
        'CCNY': DECStation(73, 'CCNY', -73.94825, 40.81976),
        'IS 143': DECStation(56, 'IS 143', -73.93059, 40.84888),
        'PS 19': DECStation(75, 'PS 19', -73.98446, 40.73000),
        'Division Street': DECStation(60, 'Division Street', -73.99518, 40.71436),

        #Staten Island
        'Fresh Kills West': DECStation(61, 'Fresh Kills West', -74.19832, 40.58027),
        'Port Richmond': DECStation(80, 'Port Richmond', -74.13719, 40.63307),
        'Susan Wagner': DECStation(49, 'Susan Wagner', -74.12525, 40.59664),

        #Bronx
        'IS 52': DECStation(24, 'IS 52', -73.9020, 40.8162),
        'IS 74': DECStation(8, 'IS 74', -73.88553, 40.81551),
        'NYBG': DECStation(57, 'NYBG', -73.87809, 40.86790),

        #Queens
        'Maspeth': DECStation(13, 'Maspeth', -73.89313, 40.72698),
        'Queens College': DECStation(62, 'Queens College', -73.82153, 40.73614),

        #Brooklyn
        'PS 274': DECStation(6, 'PS 274', -73.92769, 40.69454),
        'PS 314': DECStation(10, 'PS 314', -74.01871, 40.64182),

        #DEC group 3
        #North
        'White Plains': DECStation(34, 'White Plains', -73.76366, 41.05192),
        'Millbrook': DECStation(25, 'Millbrook', -73.74136, 41.78555)

    }

    return all_stations

def parse_to_float(x):
    try:
        return float(x)
    except:
        return np.nan

def get_station_raw_data(stations, start_date, end_date):
    """
    Download the station data from airnow website
    """

    # Defaults
    website_cols = ['Date Time', 'O3', 'PM25C', 'SO2', 'CO']
    polished_names = ['Date Time', 'station', 'lon', 'lat', 'PM25', 'O3', 'SO2', 'CO']

    # Load into one dataframe
    all_data = pd.DataFrame()

    chrome_bin = os.environ.get('GOOGLE_CHROME_SHIM')
    if chrome_bin:
        options = webdriver.ChromeOptions()
        options.binary_location = chrome_bin
        driver = webdriver.Chrome(chrome_options = options)
    else:
        driver = webdriver.Chrome()

    for name, station in stations.items():

        # Navigate to the webpage
        url = station.get_station_url()

        driver.get(url)
        driver.find_element_by_id('btnGenerateReport').click()

        # Scrape the content
        content = driver.page_source

        soup = bs4.BeautifulSoup(content)
        table = soup.find(attrs={'id': 'C1WebGrid1'})

        df = pd.read_html(str(table), header=0, flavor='bs4')[0]

        # Keep columns and parse
        cols_keep = list(set(df.columns).intersection(set(website_cols)))
        df = df[cols_keep]

        df['Date Time'] = df['Date Time'].map(pd.to_datetime)
        col_nulls = {}
        for col in df.columns:
            if col != 'Date Time':
                df[col] = df[col].map(parse_to_float)
                col_nulls[col] = pd.isnull(df[col])

        df_nulls = pd.DataFrame(col_nulls)
        all_nulls = df_nulls.apply(min, axis = 1)

        # Filter out bad dates and NaNs
        df_filtered = df[-(all_nulls | pd.isnull(df['Date Time']))]

        # Add missing columns
        cols_add = set(website_cols) - set(df_filtered.columns)
        for col in cols_add:
            df_filtered[col] = np.nan

        df_filtered['station'] = name
        df_filtered['lon'] = station.lon
        df_filtered['lat'] = station.lat

        df_filtered.rename(columns = {'PM25C': 'PM25'}, inplace = True)

        all_data = all_data.append(df_filtered, ignore_index=True)

    driver.quit()

    return all_data

def calculate_stations_aqi_data(station_data, breakpoints, aq_variables):
    """
    24 hours for PM2.5, 1 hours for O3
    """

    station_grouped = station_data.groupby(['station', 'lon', 'lat'])

    stations_PM25_24hr = station_grouped.agg({'PM25':
        lambda x: np.mean(x.tail(1))})
    stations_O3_1hr = station_grouped.agg({'O3':
        lambda x: np.mean(x.tail(1)) * 1000})  # x 1000 to get to ppb
    stations_O3_8hr = station_grouped.agg({'O3':
        lambda x: np.mean(x.tail(8)) * 1000})  # x 1000 to get to ppb

    stations_PM25_24hr.columns = ['PM25_24hr']
    stations_O3_1hr.columns = ['O3_1hr']
    stations_O3_8hr.columns = ['O3_8hr']

    stations_out = stations_PM25_24hr.join(stations_O3_1hr).join(stations_O3_8hr)

    stations_out['AQI'] = stations_out.apply(lambda x: calculate_aqi(x, breakpoints), axis=1)

    stations_out.reset_index(level=[0,1,2], inplace=True)
    stations_out = stations_out[['station', 'lon', 'lat', 'PM25_24hr', 'O3_8hr', 'AQI']]
    stations_out.columns = ['station', 'lon', 'lat', 'PM25', 'O3', 'AQI']

    stations_out = pd.melt(stations_out, id_vars=['station', 'lon', 'lat'], value_vars=aq_variables)
    stations_out = stations_out.dropna()

    return stations_out

def calculate_aqi(station_obs, breakpoints):
    """
    Given a station's cross-sectional data, calculate AQI
    """

    aqi = 0
    for name, value in station_obs.iteritems():
        aqi = max(aqi, calculate_score(value, breakpoints, name))

    return aqi

def calculate_score(value, breakpoints, name):
    """
    Return the score for a scale
    """

    if np.isnan(value):
        return 0
    if value < 0:
        value = 0

    ndx = breakpoints[breakpoints[name] > value].index[0]

    if ndx == 0:
        return 0

    index_l = breakpoints.ix[ndx - 1, 'Index']
    index_h = breakpoints.ix[ndx, 'Index']
    conc_l = breakpoints.ix[ndx - 1, name]
    conc_h = breakpoints.ix[ndx, name]

    out = (float(index_h - index_l) / float(conc_h - conc_l)) * \
          float(value - conc_l) + index_l

    return 0 if np.isnan(out) else out

def get_interpolated_grid_data(station_data, aq_variables, data_dir = '/app/static/'):
    """
    Given a melted dataframe of cross-sectional station data
    (pertaining to one time stamp), output the corresponding grid data
    """

    locs_file = os.path.join(data_dir, 'grid_locs.csv')
    locs = pd.read_csv(locs_file)

    lon_locs = np.unique(locs['c_lon'].values)
    lat_locs = np.unique(locs['c_lat'].values)

    locs_data = locs[['gr_id']]

    # For each air quality variable, interpolate across the grid given available stations
    for aq_v in aq_variables:

        station_data_aqv = station_data[station_data['variable'] == aq_v]

        #
        # Find nearest station
        #

        nearest_station = interpolate.griddata((station_data_aqv['lon'].values, station_data_aqv['lat'].values),
                                               station_data_aqv['station'].values,
                                               (locs['c_lon'].values, locs['c_lat'].values), method='nearest')

        nearest_station_df = pd.DataFrame({'gr_id': locs['gr_id'].values,
                                           'station': nearest_station,
                                           'c_lon': locs['c_lon'].values, 'c_lat': locs['c_lat'].values})

        nearest_station_df = pd.merge(nearest_station_df, station_data_aqv, on='station')

        #
        # Interpolate using Delaunay triangulation, filling the holes with nearest neighbor
        #

        # lon x lat - melted lons change first
        aq_v_interpolated = mlab.griddata(station_data_aqv['lat'].values, station_data_aqv['lon'].values,
                                          station_data_aqv['value'].values, lat_locs, lon_locs, interp='linear')

        # Out of area locations
        out_of_area_locs = pd.melt(pd.DataFrame(aq_v_interpolated.mask))
        out_of_area_locs = locs_data['gr_id'][out_of_area_locs['value']].values

        aq_v_data = aq_v_interpolated.data

        # For grid points that are out of range of triangulation, use closest station
        for ooa_loc in out_of_area_locs:
            near_station_dat = nearest_station_df[nearest_station_df['gr_id'] == ooa_loc]

            xx = lon_locs.searchsorted(near_station_dat['c_lon'])
            yy = lat_locs.searchsorted(near_station_dat['c_lat'])

            aq_v_data[xx, yy] = near_station_dat['value']

        new_col = pd.melt(pd.DataFrame(aq_v_data))

        locs_data[aq_v] = new_col['value']

    return locs_data

def predict_stations_data(stations_dat, forecast_periods):
    """
    Predict the stations data into the future
    """
    last_time = stations_dat['Date Time'].max()
    stations_grouped = stations_dat.groupby(['station', 'lat', 'lon'])

    all_forecasts = pd.DataFrame()

    for fp in range(1, forecast_periods + 1):
        station_preds = stations_grouped.apply(predict_station).reset_index(drop=True)
        station_preds['Date Time'] = last_time + dt.timedelta(hours=fp)

        all_forecasts = all_forecasts.append(station_preds)

    return all_forecasts

def predict_station(var_series):
    """
    Predict the next in the time series
    """
    last_value = var_series[-1:]

    return last_value

def get_breakpoints(data_dir = '/app/static'):
    breaks_file = os.path.join(data_dir, 'breakpoints.csv')
    breakpoints = pd.read_csv(breaks_file)

    return breakpoints

@timeout(90)
def main():
    """
    Main function: times out after 90 seconds
    """
    print('Begin main')

    aq_variables = ['PM25', 'O3', 'AQI']
    hist_periods = 5
    forecast_periods = 7

    all_stations = get_stations()
    breakpoints = get_breakpoints()

    #Dates for current period
    end_date = dt.date.today()
    start_date = end_date - dt.timedelta(1)

    print('Get station data')

    station_data_raw = get_station_raw_data(all_stations, start_date, end_date)

    print('Finished getting station data')

    stations_ffilled = station_data_raw.groupby('station').fillna(method='ffill')
    stations_ffilled['station'] = station_data_raw['station']

    stations_predictions = predict_stations_data(stations_ffilled, forecast_periods)

    all_station_data = stations_ffilled.append(stations_predictions)

    time_stamps = all_station_data['Date Time'].unique()[
                    -(hist_periods+forecast_periods):]

    all_grid_data = pd.DataFrame()

    print('Calculating AQI and Interpolating over grid')
    for ts in time_stamps:
        station_time = all_station_data[all_station_data['Date Time'] <= ts]

        # Current station data
        stations_output = calculate_stations_aqi_data(station_time, breakpoints, aq_variables)

        # Interpolate the grid data
        current_grid_data = get_interpolated_grid_data(stations_output, aq_variables)

        current_grid_data['time'] = ts
        all_grid_data = all_grid_data.append(current_grid_data)

    print('Finished main')

    return all_grid_data


n,m,x,y,k = map(int,input().split())
arr = []
dx = [0,0,-1,1]
dy = [1,-1,0,0]

for _ in range(n):
    arr.append(list(map(int,input().split())))

command = list(map(int,input().split()))

dice = [0]*6

def diceMove(x):
    if x == 1:
        tmp = dice[4]
        dice[4] = dice[1]
        dice[1] = dice[5]
        dice[5] = dice[0]
        dice[0] = tmp
    elif x == 2:
        tmp = dice[5]
        dice[5] = dice[1]
        dice[1] = dice[4]
        dice[4] = dice[0]
        dice[0] = tmp
    elif x == 3:
        tmp = dice[3]
        dice[3] = dice[1]
        dice[1] = dice[2]
        dice[2] = dice[0]
        dice[0] = tmp
    else:
        tmp = dice[2]
        dice[2] = dice[1]
        dice[1] = dice[3]
        dice[3] = dice[0]
        dice[0] = tmp

for c in command:
    if 0 > x + dx[c-1] or x + dx[c-1] >= n or 0 > y + dy[c-1] or y + dy[c-1] >= m:
        continue
    diceMove(c)
    x += dx[c-1]
    y += dy[c-1]
    if arr[x][y] == 0:
        arr[x][y] = dice[1]
    else:
        dice[1] = arr[x][y]
        arr[x][y] = 0
    print(dice[0])


from fractions import Fraction
from wick.index import Idx
from wick.operator import FOperator, Tensor
from wick.expression import Term, Expression, AExpression
from wick.wick import apply_wick
from wick.convenience import E1, E2, commute

i = Idx(0, "occ")
a = Idx(0, "vir")
j = Idx(1, "occ")
b = Idx(1, "vir")

T1 = E1("t", ["occ"], ["vir"])
T2 = E2("t", ["occ"], ["vir"])
T = T1 + T2

L1 = E1("L", ["vir"], ["occ"])
L2 = E2("L", ["vir"], ["occ"])
L = L1 + L2

# ov block
operators = [FOperator(a, True), FOperator(i, False)]
pvo = Expression([Term(1, [], [Tensor([i, a], "")], operators, [])])

PT = commute(pvo, T)
PTT = commute(PT, T)
mid = pvo + PT + Fraction('1/2')*PTT
full = L*mid
out = apply_wick(full)
out.resolve()
final = AExpression(Ex=out)
print("P_{ov} = ")
print(final)

# vv block
operators = [FOperator(a, True), FOperator(b, False)]
pvv = Expression([Term(1, [], [Tensor([b, a], "")], operators, [])])

PT = commute(pvv, T)
PTT = commute(PT, T)
mid = pvv + PT + Fraction('1/2')*PTT
full = L*mid
out = apply_wick(full)
out.resolve()
final = AExpression(Ex=out)
final.sort_tensors()
print("P_{vv} = ")
print(final)

# oo block
operators = [FOperator(j, False), FOperator(i, True)]
poo = Expression([Term(-1, [], [Tensor([j, i], "")], operators, [])])

PT = commute(poo, T)
PTT = commute(PT, T)
mid = poo + PT + Fraction('1/2')*PTT
full = L*mid
out = apply_wick(full)
out.resolve()
final = AExpression(Ex=out)
final.sort_tensors()
print("P_{oo} = ")
print(final)

# vo block
operators = [FOperator(i, True), FOperator(a, False)]
pvo = Expression([Term(1, [], [Tensor([a, i], "")], operators, [])])

PT = commute(pvo, T)
PTT = commute(PT, T)
mid = pvo + PT + Fraction('1/2')*PTT
full = mid + L*mid
out = apply_wick(full)
out.resolve()
final = AExpression(Ex=out)
final.sort_tensors()
print("P_{vo} = ")
print(final)


#!/usr/bin/env python3
"""
author: huchiwen
language :python3

"""

def main():
    A = [1,2,3]
    B = [1,89,3]
    res =0

    result  = (len(A) == len(B))
    if result:
      for i in range(0,len(A)):
          res+=A[i]*B[i]
      print(res)
    else:
      print("list not equal")

if __name__ == "__main__":
    main()