from __future__ import annotations

from dataclasses import dataclass
from typing import List

import numpy as np

from .board import Board, Column, Tile
from .player import Player
from .utils import clear, is_int, pick1, show

@dataclass
class Game:
    topic: str
    board: Board
    players: List[Player]

    def __post_init__(self):
        i = pick1(range(len(self.players)))
        self.board_control_player = self.players[i]

    def get_player(self, name: str) -> Player:
        for player in self.players:
            if player.name == name:
                return player

        return ValueError(f"No player with that name, {name}.")

    def intro(self):
        clear()
        show("Welcome to Jeopardy!", big=True, wait=True)
        clear()

        show(f"Tonight's topic is {self.topic}", big=True, wait=True)
        clear()

        show(
            f"Our {'players are' if len(self.players) > 1 else 'player is'}",
            big=True,
            wait=True,
        )
        clear()
        for player in self.players:
            player.show_name(big=True, wait=True)
            clear()

        show(
            f"The {'categories are' if len(self.board.categories) > 1 else 'category is'}",
            big=True,
            wait=True,
        )
        clear()
        for column in self.board.columns:
            column.show_category(big=True, wait=True)
            clear()

        show("Good luck!", big=True, wait=True)

    def ask_category(self) -> str:
        category_input = input("Select a category: ")

        while True:
            if category_input == "BACK":
                return "BACK"
            elif category_input == "QUIT":
                return "QUIT"
            elif category_input not in self.board.categories:
                category_input = input("That is not a category. Select a category: ")
            elif category_input not in self.board.categories_playable:
                category_input = input(
                    "There are no more questions for that category. Select a category: "
                )
            else:
                return category_input

    def ask_dollar(self, column: Column) -> str:
        dollar_input = input("Choose a dollar amount: ")

        while True:
            if dollar_input == "BACK":
                return "BACK"
            elif is_int(dollar_input):
                dollar_int = int(dollar_input)

                if dollar_int not in column.dollars:
                    reason = "Not a possible dollar amount."
                elif dollar_int not in column.dollars_playable:
                    reason = "That amount has already been won."
                else:
                    return dollar_input
            else:
                reason = "Enter a number."

            dollar_input = input(f"{reason} Choose a dollar amount: ")

    def show_category_dollar(self, category: str, dollar: int):
        show(f"{category} for ${dollar:,.0f}", big=False, wait=False)

    def ask_who_is_answering(self) -> str:
        who = input("Who? ")

        while True:
            if who == "SKIP":
                return "SKIP"
            elif who not in [player.name for player in self.players]:
                who = input("Not a player. Who? ")
            else:
                return who

    def ask_correct(self) -> str:
        response = input("Correct? ")

        while True:
            if response == "BACK":
                return "BACK"
            elif response in ["y", "Y", "yes", "Yes", "YES"]:
                return "Y"
            elif response in ["n", "N", "no", "No", "NO"]:
                return "N"
            else:
                response = input("Correct? ")

    def handle_outcome(self, name: str, correct: bool, tile: Tile):
        if name != "SKIP":
            player = self.get_player(name)

            if correct == "Y":
                player.award_money(tile.dollar)
                # board control player is the last player to answer a question correctly
                self.board_control_player = player
            else:
                player.award_money(-1 * tile.dollar)

        tile.mark_done()

    def show_player_earnings(self):
        for player in self.players:
            player.show_name_earnings(big=False, wait=False)

    def show_winner(self):
        earnings = [player.earnings for player in self.players]
        lo_to_hi = np.argsort(earnings).tolist()
        hi_to_lo = list(reversed(lo_to_hi))
        best = hi_to_lo[0]
        show(f"Congratulations {self.players[best].name}!", big=True, wait=True)

    def start(self, skip_intro: bool = False):
        if not skip_intro:
            self.intro()

        while not self.board.all_done:
            clear()

            # show the board and the player status to allow for picking of the next question
            self.show_player_earnings()
            self.board_control_player.show_my_board(big=False, wait=False)
            self.board.display()

            category = self.ask_category()
            # this probably isn't needed, just would need to go back after picking a dollar amount
            if category == "BACK":
                continue

            if category == "QUIT":
                break

            column = self.board.get_column(category)

            dollar = self.ask_dollar(column)
            # allow for repicking of category if they want
            if dollar == "BACK":
                continue

            tile = column.get_tile(int(dollar))

            # now focus on just the question that was chosen
            while True:
                clear()
                self.show_player_earnings()
                self.show_category_dollar(category, int(dollar))
                show(tile.question, big=True, wait=False)

                name = self.ask_who_is_answering()

                if name == "SKIP":
                    break

                correct = self.ask_correct()

                if correct == "BACK":
                    continue

                self.handle_outcome(name, correct, tile)

                if correct == "Y":
                    break

            clear()
            show(tile.question, big=False, wait=False)
            show("\n", big=False, wait=False)
            show(tile.answer, big=True, wait=True)

        # wrap up game by showing all player's earnings and congratulating winner
        clear()
        self.show_player_earnings()
        self.show_winner()
        clear()


import os
import json
import shutil
import compress_json
import dateparser
import pandas as pd
import numpy as np
from numba import typed, types
import warnings
from datetime import datetime
from userinput.utils import closest
from tqdm.auto import tqdm
from multiprocessing import Pool, cpu_count
from typing import Dict, Generator, List, Tuple
from .utils import get_available_genomes, get_available_chromosomes, download_chromosome_wrapper, get_genome_informations
from .utils import multiprocessing_gaps
from .utils import extract_sequence, extract_sequences

class Genome:
    """Class to automatically retrieve informations and sequences for a Genome from the UCSC Genome Browser assembly database.

    Usage examples
    --------------

    Simply instanziate a new genome
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    .. code:: python

        from ucsc_genomes_downloader import Genome
        hg19 = Genome("hg19")

    Getting gaps regions
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    .. code:: python

        all_gaps = hg19.gaps() # Returns gaps for all chromosomes
        # Returns gaps for chromosome chrM
        chrM_gaps = hg19.gaps(chromosomes=["chrM"])

    Getting filled regions
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    .. code:: python

        all_filled = hg19.filled() # Returns filled for all chromosomes
        # Returns filled for chromosome chrM
        chrM_filled = hg19.filled(chromosomes=["chrM"])

    Removing genome's cache
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    .. code:: python

        hg19.delete()

    """

    def __init__(
        self,
        assembly: str,
        chromosomes: Tuple[str] = None,
        filters: Tuple[str] = ("chru", "chrmt", "scaffold", "contig", "super", "chrbin", "random", "hap", "alt", "fix"),
        verbose: bool = True,
        cache_directory: str = "genomes"
    ):
        """Instantiate a new Genome object.

        Parameters
        ----------
        assembly: str,
            UCSC Genome Browser assembly ID for required genome [1]_.
        chromosomes: Tuple[str] = None,
            Tuple with the chromosomes to download.
            If None (default) all the chromosomes except
            the one filtered out are downloaded.
        filters: Tuple[str] = ("chru", "scaffold", "contig", "super", "chrbin", "random", "hap", "alt", "fix"),
            Tuple containing substring of chromosomes NOT to download.
            If the `chromosomes` parameter is used, no such filter is applied.
        verbose: bool = True,
            Whetever to show a loading bar when retrieving chromosomes.
        cache_directory: str = "genomes",
            Position where to store the downloaded genomes.

        Raises
        ------
        ValueError:
            If the given genome cannot be retrieved either from the given
            cache directory or from the UCSC website [3]_.
        ValueError:
            If the given genome, once the filters have been applied,
            does not contain any chromosome.

        Returns
        -------
        A newly instantiated Genome object.

        References
        ----------
        .. [1] https://genome.ucsc.edu/FAQ/FAQdownloads.html
        """

        self._chromosomes_lenghts = None
        self._genome_informations = None
        self._verbose = verbose
        self._assembly = assembly

        self._cache_directory = os.path.join(cache_directory, self.assembly)

        # If cache is enabled and a directory for the genome
        # exists within the cache we try to load the genome data
        if os.path.exists(self._cache_directory):
            self._genome_informations = self._load_genome_informations()
            self._chromosomes_lenghts = self._load_chromosomes()
        # Otherwise we check if the genome is available
        else:
            available_genomes = get_available_genomes()
            if self.assembly not in available_genomes:
                # If the genome is not available we raise a proper exception
                raise ValueError(
                    (
                        "Given genome {assembly} is not within the available genomes. "
                        "Did you mean to specify the {closest} genomic assembly?"
                    ).format(
                        assembly=self.assembly,
                        closest=closest(
                            self.assembly,
                            available_genomes
                        )
                    ))

        # Download genome informations if list is not already loaded
        if self._genome_informations is None:
            self._genome_informations = get_genome_informations(self.assembly)
            # If cache is enabled we store the obtained genome informations
            self._store_genome_informations()

        # Download chromosomes if list is not already loaded
        if self._chromosomes_lenghts is None:
            self._chromosomes_lenghts = get_available_chromosomes(
                self.assembly)
            # If cache is enabled we store the obtained chromosomes lenghts
            self._store_chromosomes()

        # Filtering chromosomes
        self._chromosomes = typed.Dict.empty(
            types.unicode_type,
            types.unicode_type
        )
        for chrom in self._chromosomes_lenghts:
            if all(target not in chrom.lower() for target in filters) and chromosomes is None or chromosomes is not None and chrom in chromosomes:
                self._chromosomes[str(chrom)] = ""

        # If no chromosome remains after filtering,
        # for instance when the raw data are not yet mapped
        # we raise a userwarning
        if len(self) == 0:
            raise ValueError(
                "No chromosome remaining in chosen genome {assembly}"
                "after executing desired filters"
                "and checking for online availability".format(
                    assembly=self.assembly)
            )

        self.NUCLEOTIDES_MAPPING = typed.Dict.empty(types.string, types.string)

        for src, dst in {
            "a": "t",
            "A": "T",
            "g": "c",
            "G": "C",
            "t": "a",
            "T": "A",
            "c": "g",
            "C": "G",
            "N": "n",
            "n": "N",
        }.items():
            self.NUCLEOTIDES_MAPPING[src] = dst

        self._download()
        self._load()

    def _genome_informations_path(self) -> str:
        """Return path for the JSON file with current genome informations."""
        return "{cache_directory}/genome_informations.json".format(
            cache_directory=self._cache_directory
        )

    def _load_genome_informations(self) -> Dict:
        """Return a dictionary with genome informations if available.

        Raises
        ------
        RuntimeWarning:
            If genome informations are not available
            locally.
        """
        try:
            compress_json.load(self._genome_informations_path())
        except Exception:
            warnings.warn(
                "Failed to load genome {genome} informations. "
                "I will try to download them again afterwards.".format(
                    genome=self.assembly
                ),
                RuntimeWarning
            )
        return None

    def _store_genome_informations(self):
        """Store genome informations into default cache directory."""
        compress_json.dump(
            self._genome_informations,
            self._genome_informations_path()
        )

    def _chromosomes_path(self) -> str:
        """Return path to default chromosomes informations."""
        return "{cache_directory}/chromosomes.json".format(
            cache_directory=self._cache_directory
        )

    def _load_chromosomes(self) -> Dict:
        """Return a dictionary with genome chromosomes if available.

        Raises
        ------
        RuntimeWarning:
            If genome chromosomes are not available
            locally.
        """
        try:
            return compress_json.load(self._chromosomes_path())
        except Exception:
            warnings.warn(
                "Failed to load chromosomes for genome {genome}. "
                "I will try to download them again afterwards.".format(
                    genome=self.assembly
                ),
                RuntimeWarning
            )
        return None

    def _store_chromosomes(self):
        """Store chromosomes informations into default cache directory."""
        compress_json.dump(
            self._chromosomes_lenghts,
            self._chromosomes_path()
        )

    def _chromosome_path(self, chromosome: str) -> str:
        """Return path to the given chromosome.

        Parameters
        ----------
        chromosome: str,
            The chromosome identifier, such as chr1, chrX, chrM...
        """
        return "{cache_directory}/chromosomes/{chromosome}.json.gz".format(
            cache_directory=self._cache_directory,
            chromosome=chromosome
        )

    def _load_chromosome(self, chromosome: str) -> str:
        """Return the nucleotides sequence for the given chromosome.
        Parameters
        ----------
        chromosome: str,
            The chromosome identifier, such as chr1, chrX, chrM...

        Raises
        ------
        RuntimeWarning:
            If given chromosome are not available locally.
        """
        path = self._chromosome_path(chromosome)
        try:
            return compress_json.load(path)["dna"]
        except json.decoder.JSONDecodeError:
            os.remove(path)
            raise Exception(
                "Chromosome at path {path} is corrupt and has been deleted.".format(path=path))

    def delete(self):
        """Remove the genome cache."""
        if os.path.exists(self._cache_directory):
            shutil.rmtree(self._cache_directory)

    def _download(self):
        """Download the missing chromosomes."""
        tasks = [
            {
                "assembly": self.assembly,
                "chromosome": chromosome,
                "start": 0,
                "end": self._chromosomes_lenghts[chromosome],
                "path": self._chromosome_path(chromosome)
            }
            for chromosome in self
            if not self.is_chromosome_cached(chromosome)
        ]
        if len(tasks):
            with Pool(min(cpu_count(), len(tasks))) as p:
                list(tqdm(
                    p.imap(
                        download_chromosome_wrapper,
                        tasks
                    ),
                    desc="Downloading chromosomes for genome {assembly}".format(
                        assembly=self.assembly
                    ),
                    total=len(tasks),
                    disable=not self._verbose,
                    dynamic_ncols=True,
                    leave=False
                ))
                p.close()
                p.join()

    def _load(self):
        """Load into memory all the genome's chromosomes, downloading them when necessary."""
        for chromosome in tqdm(
            self,
            desc="Loading chromosomes for genome {assembly}".format(
                assembly=self.assembly
            ),
            total=len(self),
            disable=not self._verbose,
            dynamic_ncols=True,
            leave=False
        ):
            self._chromosomes[chromosome] = self._load_chromosome(
                chromosome
            )

    def __len__(self) -> int:
        """Return the number of chromosomes in current genome."""
        return len(self._chromosomes)

    def __contains__(self, chromosome: str) -> bool:
        """Return boolean representing if given chromosome is contained in current genome.

        Parameters
        ----------
        chromosome: str,
            The chromosome identifier, such as chr1, chrX, chrM...

        Returns
        -------
        Boolean representing if given chromosome is contained in current genome.
        """
        return chromosome in self._chromosomes

    def __getitem__(self, chromosome: str):
        """Return sequence data for given chromosome.

        Parameters
        ----------
        chromosome: str,
            The chromosome identifier, such as chr1, chrX, chrM...

        Returns
        -------
        String containing sequence data for given chromosome.
        """
        return self._chromosomes[chromosome]

    def items(self) -> Generator:
        """Return generator to iterate through tuples of chromosomes and corresponding sequences."""
        for chromosome in self:
            yield chromosome, self[chromosome]

    def __iter__(self) -> Generator:
        """Return generator to iterate through the genome's chromosomes."""
        for chromosome in self._chromosomes:
            yield chromosome

    def is_chromosome_cached(self, chromosome: str) -> bool:
        """Return a boolean representing if given chromosome is cached.

        Parameters
        ----------
        chromosome: str,
            The chromosome identifier, such as chr1, chrX, chrM...

        Returns
        -------
        Boolean representing if given chromosome is available locally.
        """
        return os.path.exists(self._chromosome_path(chromosome))

    def __str__(self):
        """Return string representation of current genome."""
        return "{organism}, {scientific_name}, {genome}, {date}, {chromosomes} chromosomes".format(
            organism=self.organism,
            scientific_name=self.scientific_name,
            genome=self.assembly,
            date=self.date,
            chromosomes=len(self)
        )

    __repr__ = __str__

    def gaps(self, chromosomes: List[str] = None):
        """Return dataframe in BED format with informations on the gaps.

        Parameters
        ----------
        chromosomes: List[str] = None,
            List of the chromosomes to parse, by default all.

        FAQs
        ----
        Why don't you just retrieve the gaps from the APIs?
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        The gaps track is not always available, therefore for providing a consistent
        usage experience we compute the gaps when required. Additionally, this method
        will work also when you make an offline request, that may sometimes be quite
        useful.

        Returns
        -------
        A DataFrame in BED format containing the gapped regions.
        """
        if chromosomes is None:
            chromosomes = list(self)
        with Pool(min(cpu_count(), len(self))) as p:
            gaps = pd.concat(list(tqdm(
                p.imap(multiprocessing_gaps, (
                    (
                        chromosome, self[chromosome]
                    )
                    for chromosome in chromosomes
                )),
                total=len(chromosomes),
                desc="Rendering gaps in {assembly}".format(
                    assembly=self.assembly
                ),
                leave=False,
                dynamic_ncols=True,
                disable=not self._verbose
            ))).reset_index(drop=True)
            p.close()
            p.join()
        return gaps

    def filled(self,  chromosomes: List[str] = None):
        """Return dataframe with BED-like columns with informations on the gaps.

        Parameters
        ----------
        chromosomes: List[str] = None,
            List of the chromosomes to parse, by default all.

        Returns
        -------
        A DataFrame in BED format containing the filled regions.
        """
        non_gap = []
        gapped_chromosomes = []
        if chromosomes is None:
            chromosomes = list(self)
        for chrom, values in self.gaps(chromosomes).groupby("chrom"):
            # We need to sort by the chromStart
            # as we will need the rows to be ordered
            # to be able to generate the complementary windows
            values = values.sort_values(["chromStart"])
            non_gap_values = pd.DataFrame({
                "chrom": chrom,
                "chromStart": values["chromEnd"][:-1].values,
                "chromEnd": values["chromStart"][1:].values,
            })

            # If the chromosome lenght is not contained
            # within the various chromEnd values it means that
            # the final part of the chromosome is known
            # and therefore considered filled.
            # We need to add this additional row.
            chromosome_lenght = self._chromosomes_lenghts[chrom]
            if not values.chromEnd.isin([chromosome_lenght]).any():
                non_gap_values = non_gap_values.append({
                    "chrom": chrom,
                    "chromStart": values.chromEnd.max(),
                    "chromEnd": chromosome_lenght
                }, ignore_index=True)

            # If the chromosome start, the 0 value,
            # is not contained within the various chromStart values
            # it means that the initial part of the chromosome
            # is known and therefore considered filled.
            # We need to add this additional row.
            if not values.chromStart.isin([0]).any():
                non_gap_values = non_gap_values.append({
                    "chrom": chrom,
                    "chromStart": 0,
                    "chromEnd": values.chromStart.min(),
                }, ignore_index=True)

            non_gap.append(non_gap_values)
            gapped_chromosomes.append(chrom)

        # When a chromosome does not appear to have
        # any gap is considered fully filled
        non_gap.append(pd.DataFrame([
            {
                "chrom": chrom,
                "chromStart": 0,
                "chromEnd": self._chromosomes_lenghts[chrom]
            } for chrom in chromosomes if chrom not in gapped_chromosomes
        ]))
        return pd.concat(non_gap).sort_values(["chrom"]).reset_index(drop=True)

    def extract_sequence(self, chrom: str, chromStart: int, chromEnd: int, strand: str = ".") -> str:
        """Return genomic sequence for given coordinates.

        Parameters
        ------------------------------------
        chrom: str,
            Chromosome to use.
        chromStart: int,
            Position from where to start slicing.
        chromEnd: int,
            Position where to stop the slice.

        Returns
        -------------------------------------
        Sequence of nucleotides.
        """
        return extract_sequence(
            self._chromosomes,
            chrom,
            chromStart,
            chromEnd,
            strand,
            self.NUCLEOTIDES_MAPPING
        )

    def bed_to_sequence(self, bed: pd.DataFrame) -> List[str]:
        """Return bed with an additional column containing the sequences."""
        return extract_sequences(
            self._chromosomes,
            bed.chrom.values.astype(str),
            bed.chromStart.values.astype(int),
            bed.chromEnd.values.astype(int),
            bed.strand.values.astype(str) if "strand" in bed.columns else None,
            self.NUCLEOTIDES_MAPPING
        )

    @property
    def assembly(self) -> str:
        """Return genome's UCSC Genome Browser assembly ID."""
        return self._assembly

    @property
    def date(self) -> datetime:
        """Return release date."""
        return dateparser.parse(self.description.split("(")[0]).date()

    @property
    def organism(self) -> str:
        """Return genome's organism."""
        return self._genome_informations["organism"]

    @property
    def scientific_name(self):
        """Return genome's organism scientific name."""
        return self._genome_informations["scientificName"]

    @property
    def description(self):
        """Return genome's description as provided by UCSC."""
        return self._genome_informations["description"]

    @property
    def path(self):
        """Return genome's path."""
        return self._cache_directory


from random import randrange, choice

def numeros():
  n = []
  for i in range(3):
    n.append(randrange(9))
  return n

def letras():
  l=[]
  alphab =['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',]
  for i in range(4):
    l.append(choice(alphab))
  return l

def placas(numeros,letras):
  placa=[]
  for i in range(7):
    if i <=2:
      placa.append(letras[i])
    elif i == 3:
      placa.append(numeros[0])
    elif i == 4:
      placa.append(letras[3])
    else:
      placa.append(numeros[i-4])
  return placa


from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
from flask import Flask, request, abort
from dotenv import load_dotenv
import os
from os.path import join, dirname
from threading import Thread
import requests
import base64
from datetime import datetime

dotenv_path = join(dirname(__file__), '.env') # path per le var di ambiente
load_dotenv(dotenv_path)# carico le var di ambiente
api_key = os.environ.get('api_key') # settaggio dell'api key
app = Flask(__name__) # istanza flask

notify_users = [] # utenti che hanno richiesto la notifica
enabled_users = []# utenti abilitati alle notifiche
users_areas = [] # var di appoggio
final_diction = {}

def send_alert(id, img_bytes, info_cam):
    params = {'chat_id': id,
              'caption': str(info_cam)}
    files = {'photo': img_bytes}
    url = f'https://api.telegram.org/bot{api_key}/sendPhoto?chat_id={id}'
    requests.post(url, params, files=files)
    return '', 204

@app.route("/notify_telegram", methods=['POST'])
def notify_method():

    str_date_time = datetime.now().strftime("%d-%m-%Y, %H:%M:%S")
    info_cam = f"Data : {str(str_date_time)}\n"
    if not request.json or 'image' not in request.json:
        abort(400)

    im_b64 = request.json['image']
    caption = request.json['caption']

    for key,value in caption.items(): # JSON formatting
        info_cam += f"{key} : {value}\n"
        if key == "Area di competenza":
            area_value = value.upper()

    img_bytes = base64.b64decode(im_b64.encode('utf-8'))
    for id in final_diction[area_value]:
        for observer in notify_users:
            if observer['id'] == id:
                send_alert(id, img_bytes, info_cam)
    return '', 204

def load_file():
        with open('users_areas.txt') as f:
            contents = f.readlines()
            for element in contents:
                try:
                    splitting = element.split(" ")
                    clearing = splitting[1].strip()
                    enabled_users.append(int(splitting[0]))
                    users_areas.append((clearing.upper(), int(splitting[0])))
                except (IndexError, ValueError):
                    continue

        for i in users_areas:
            if i[0] in final_diction.keys():
                nuova_lista = []
                old = final_diction[i[0]]
                new = i[1]
                old.append(new)
                nuova_lista.append(old)
                nuova_lista.append(new)
                final_diction[i[0]] = old
            else:
                final_diction[i[0]] = ['a', i[1]]

        for key, value in final_diction.items():
            value.pop(0)

        #print(f"Enabled users {enabled_users}\n")
        #print(f"Users areas : {users_areas}\n")
        #print(f"final diction: {final_diction}\n")

# Funzione /start per il bot
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    user = update.effective_user
    await update.message.reply_text(f"Ciao {user['first_name']} premi /help per il menù dei comandi disponibili.")

# Funzione /help per il bot
async def help(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text("I comandi disponibili sono:\n "+\
                                    "/start -> Messaggio di Benvenuto\n"+\
                                    "/help -> Questo Messaggio\n"+\
                                    "/content -> Informazioni riguardanti il bot\n"+\
                                    "/notify -> Inizio invio notifiche\n"+\
                                    "/unnotify -> Termine invio notifiche\n")

# Funzione /content per il bot
async def content(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text("Questo Bot è progettato per allertare quando una telecamera riconosce un abbondono di rifiuti\n"+\
                                    "Con il comando /notify puoi attivare le notifiche;\n"+\
                                    "Con il comando /unnotify puoi disattivarle")

# Funzione /notify per il bot
async def notify(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    user = update.effective_user
    if user['id'] in enabled_users:
        if user in notify_users:
            await update.message.reply_text(f"Sei già presente nella lista dei notificabili")
        else:
            notify_users.append(user)
            await update.message.reply_text(f"Sei stato aggiunto nella lista dei notificabili")
    else:
        await update.message.reply_text(f"Lei non è presente nella lista dei notificabili")

# Funzione /unnotify per il bot
async def unnotify(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    user = update.effective_user
    if user['id'] in enabled_users:
        if user in notify_users:
            await update.message.reply_text("Sei Stato Rimosso dalla lista dei notificabili")
            notify_users.remove(user)
        else:
            await update.message.reply_text('Non sei presente nella lista degli osservatori, effettuare la /notify se si vuole ricevere le notifiche')
    else:
        await update.message.reply_text(f"Lei non è presente nella lista dei notificabili")

# Funzione echo dei messaggi per il bot
async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text(update.message.text)

# debug Function
async def test(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    utenti = ''.join(str(notify_users))
    await update.message.reply_text(utenti)

def main() -> None:
    load_file()
    """Start del bot."""
    # Crea l'applicazione e gli passa l'api token del proprio bot
    application = Application.builder().token(str(api_key)).build()

    # Comandi che rispondono
    application.add_handler(CommandHandler("start", start))
    application.add_handler(CommandHandler("help", help))
    application.add_handler(CommandHandler("content", content))
    application.add_handler(CommandHandler("notify", notify))
    application.add_handler(CommandHandler("unnotify", unnotify))
    application.add_handler(CommandHandler("test", test))

    #Comando che fa una semplice echo
    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))

    application.run_polling()

def task():
    # run the flask istance
    try:
        app.run()
    except:
        pass

if __name__ == "__main__":
    thread = Thread(target=task)
    thread.daemon = True
    thread.start()
    main()


#! /usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0+

import argparse
import sys

from assayist.processor.container_analyzer import ContainerAnalyzer
from assayist.processor.container_go_analyzer import ContainerGoAnalyzer
from assayist.processor.container_rpm_analyzer import ContainerRPMAnalyzer
from assayist.processor.loose_artifact_analyzer import LooseArtifactAnalyzer
from assayist.processor.main_analyzer import MainAnalyzer
from assayist.processor.post_analyzer import PostAnalyzer
from assayist.processor.error import AnalysisFailure

parser = argparse.ArgumentParser(description='Run the Assayist analyzers on a Koji build')
parser.add_argument('--input-dir', type=str,
                    help='The directory containing the "metadata" directory')
args = parser.parse_args()

input_dir = args.input_dir or '.'

analyzers = [MainAnalyzer, ContainerAnalyzer, ContainerRPMAnalyzer, ContainerGoAnalyzer,
             LooseArtifactAnalyzer, PostAnalyzer]
analyzer_failures = []

for analyzer in analyzers:
    print(f'Running {analyzer.__name__}...')
    try:
        analyzer(input_dir).main()
    except AnalysisFailure as error:
        # Don't continue if the main analyzer failed since other analyzers rely on it
        if analyzer == MainAnalyzer:
            print('MainAnalyzer failed with the following:\n{}'.format(error),
                  file=sys.stderr)
            sys.exit(3)

        analyzer_failures.append(str(error))

if analyzer_failures:
    print('The following were error(s) encountered during the analysis:\n{}'.format(
        '\n'.join(analyzer_failures)), file=sys.stderr)
    sys.exit(3)


import numpy as np
import os
import sys
import tensorflow as tf

import matplotlib.pyplot as plt
from PIL import Image
from timeit import default_timer as timer

from object_detection.utils import ops as utils_ops

# if tf.__version__ < '1.4.0':
#     raise ImportError(
#         'Please upgrade your tensorflow installation to v1.4.* or later!')

from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util

# MODEL_NAME = 'ssdlite_mobilenet_v2_coco'
# PATH_TO_FROZEN_GRAPH = MODEL_NAME + '/frozen_inference_graph.pb'
# PATH_TO_LABELS = MODEL_NAME + '/mscoco_label_map.pbtxt'
# NUM_CLASSES = 90

PATH_TO_FROZEN_GRAPH = './checkpoint/save_17958/frozen_inference_graph.pb'
PATH_TO_LABELS = './data/pascal_label_map.pbtxt'
NUM_CLASSES = 1

detection_graph = tf.Graph()
with detection_graph.as_default():
    od_graph_def = tf.GraphDef()
    with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid:
        serialized_graph = fid.read()
        od_graph_def.ParseFromString(serialized_graph)
        tf.import_graph_def(od_graph_def, name='')

label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(
    label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)

def load_image_into_numpy_array(image):
    (im_width, im_height) = image.size
    return np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8)

# For the sake of simplicity we will use only 2 images:
# image1.jpg
# image2.jpg
# If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.
PATH_TO_TEST_IMAGES_DIR = './test_images'
TEST_IMAGE_PATHS = [os.path.join(
    PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 2)]
print(TEST_IMAGE_PATHS)

# Size, in inches, of the output images.
# IMAGE_SIZE = (450, 300)

def run_inference_for_single_image(image, graph):
    with graph.as_default():
        with tf.Session() as sess:
            # Get handles to input and output tensors
            ops = tf.get_default_graph().get_operations()
            all_tensor_names = {
                output.name for op in ops for output in op.outputs}
            tensor_dict = {}
            for key in [
                'num_detections', 'detection_boxes', 'detection_scores',
                'detection_classes', 'detection_masks'
            ]:
                tensor_name = key + ':0'
                if tensor_name in all_tensor_names:
                    tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
                        tensor_name)
            if 'detection_masks' in tensor_dict:
                # The following processing is only for single image
                detection_boxes = tf.squeeze(
                    tensor_dict['detection_boxes'], [0])
                detection_masks = tf.squeeze(
                    tensor_dict['detection_masks'], [0])
                # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
                real_num_detection = tf.cast(
                    tensor_dict['num_detections'][0], tf.int32)
                detection_boxes = tf.slice(detection_boxes, [0, 0], [
                                           real_num_detection, -1])
                detection_masks = tf.slice(detection_masks, [0, 0, 0], [
                                           real_num_detection, -1, -1])
                detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
                    detection_masks, detection_boxes, image.shape[0], image.shape[1])
                detection_masks_reframed = tf.cast(
                    tf.greater(detection_masks_reframed, 0.5), tf.uint8)
                # Follow the convention by adding back the batch dimension
                tensor_dict['detection_masks'] = tf.expand_dims(
                    detection_masks_reframed, 0)
            image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')

            # Run inference
            output_dict = sess.run(tensor_dict, feed_dict={
                                   image_tensor: np.expand_dims(image, 0)})

            # all outputs are float32 numpy arrays, so convert types as appropriate
            output_dict['num_detections'] = int(
                output_dict['num_detections'][0])
            output_dict['detection_classes'] = output_dict[
                'detection_classes'][0].astype(np.uint8)
            output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
            output_dict['detection_scores'] = output_dict['detection_scores'][0]
            if 'detection_masks' in output_dict:
                output_dict['detection_masks'] = output_dict['detection_masks'][0]
    return output_dict

if True:
    import cv2
    video_path = './keras-yolo3-master/1_720.mp4'
    vid = cv2.VideoCapture(video_path)
    if not vid.isOpened():
        raise IOError("Couldn't open webcam or video")
    video_FourCC    = int(vid.get(cv2.CAP_PROP_FOURCC))
    video_fps       = vid.get(cv2.CAP_PROP_FPS)
    video_size      = (int(vid.get(cv2.CAP_PROP_FRAME_WIDTH)),
                        int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT)))
    accum_time = 0
    curr_fps = 0
    fps = "FPS: ??"
    prev_time = timer()

    isOutput = False
    if isOutput:
        out = cv2.VideoWriter('./out.mp4', video_FourCC, video_fps, video_size)

    count = 0

    while True:
        return_value, frame = vid.read()
        image = Image.fromarray(frame)
        image_np = load_image_into_numpy_array(image)

        if True:
        # if curr_fps == 12 :
            image_np_expanded = np.expand_dims(image_np, axis=0)
            output_dict = run_inference_for_single_image(image_np, detection_graph)
            vis_util.visualize_boxes_and_labels_on_image_array(
                image_np,
                output_dict['detection_boxes'],
                output_dict['detection_classes'],
                output_dict['detection_scores'],
                category_index,
                instance_masks=output_dict.get('detection_masks'),
                use_normalized_coordinates=True,
                line_thickness=7,
                min_score_thresh=0.3)

            curr_time = timer()
            exec_time = curr_time - prev_time
            prev_time = curr_time
            accum_time = accum_time + exec_time

        count = count + 1
        curr_fps = curr_fps + 1
        if accum_time > 1:
            accum_time = accum_time - 1
            fps = "FPS: " + str(curr_fps)
            curr_fps = 0

        result = image_np

        red, green, blue = result.T
        result = np.array([blue, green, red])
        result = result.transpose()

        im = Image.fromarray(result).convert('RGB')
        im.save("./out_images/out" + str(count) + ".jpeg")

        # cv2.putText(result, text=fps, org=(3, 15), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.50, color=(255, 0, 0), thickness=2)
        # cv2.namedWindow("result", cv2.WINDOW_NORMAL)
        # cv2.imshow("result", result)
        if isOutput:
            out.write(result)
        # if cv2.waitKey(1) & 0xFF == ord('q'):
        #     break

if  False:
    # image = Image.open(image_path)
    image = Image.open('./test_images/image5.jpg')
    image_np = load_image_into_numpy_array(image)

    image_np_expanded = np.expand_dims(image_np, axis=0)

    output_dict = run_inference_for_single_image(image_np, detection_graph)
    # print(output_dict['detection_scores'])
    vis_util.visualize_boxes_and_labels_on_image_array(image_np,
                                                       output_dict['detection_boxes'],
                                                       output_dict['detection_classes'],
                                                       output_dict['detection_scores'],
                                                       category_index,
                                                       instance_masks=output_dict.get(
                                                           'detection_masks'),
                                                       use_normalized_coordinates=True,
                                                       line_thickness=8,
                                                       min_score_thresh=0.1)

    # plt.figure(figsize=IMAGE_SIZE)
    plt.imshow(image_np)
    # plt.imshow(image)
    plt.show()

# floyd run --gpu --env tensorflow-1.9 --data tigerfloyd/datasets/tf_lebronjames/1:/data --data tigerfloyd/datasets/sdd_mobilenet/1:/model --data tigerfloyd/datasets/tf_ob/3:tf_ob --tensorboard 'bash ./run.sh'


# coding=utf-8
"""
Created on 2019-05-05
@author: Four
Project: operation-活动
"""
import sys
import time
import unittest
from Utils.log import Logger
from selenium import webdriver
from Constant.Constant_Path import *
from Constant.Page_element_path import *
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from Utils.Login_User import login_user, Operation_Center
from selenium.webdriver.common.action_chains import ActionChains
from Utils.Selection_Menu import Fixed_Window, is_frame_page, Selection_Menu
from Utils.DriverWait import Wait_Click, Send_Key, Send_Picture, page_Refresh, page_scrolling, public_time, select_list
logger_message = Logger()
send_time = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))  # 获取当前时间

class Operation_Activity(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.option = webdriver.ChromeOptions()
        cls.option.add_argument('disable-infobars')
        cls.browser = webdriver.Chrome(options=cls.option)
        cls.browser.maximize_window()
        cls.browser.get(Constant_path().LOGIN_URL)

    def add_activity(self, name, image, activity_type, piece, money, apply_product, together, product_name):
        u"""添加活动"""
        try:
            Wait_Click(self.browser, Activity().add_activity)
            Send_Key(self.browser, Activity().promotion_subject, name)  # 促销主题
            Send_Key(self.browser, Activity().promotion_time, public_time(days=2))  # 促销时间
            Send_Picture(self.browser, Activity().promotion_photo, Add_product_information_path().carousel_product % format(image))  # 促销首图
            Wait_Click(self.browser, Activity().activity_type % format(activity_type))  # 促销规则
            if activity_type == 1:  # 满减活动
                Wait_Click(self.browser, Activity().type_piece)
                Send_Key(self.browser, Activity().type_piece, piece)
                Wait_Click(self.browser, Activity().type_money)
                Send_Key(self.browser, Activity().type_money, money)
            elif activity_type == 2:    # 满折活动
                Wait_Click(self.browser, Activity().type_piece)
                Send_Key(self.browser, Activity().type_piece, piece)
                Wait_Click(self.browser, Activity().type_money)
                Send_Key(self.browser, Activity().type_money, money)
            Wait_Click(self.browser, Activity().apply_product % format(apply_product))  # 适用商品：1.全部 2.指定
            if apply_product == 1:
                pass
            elif apply_product == 2:
                Wait_Click(self.browser, Activity().add_product)
                Send_Key(self.browser, Activity().query_product_name, product_name)
                Wait_Click(self.browser, Activity().query_product_name_button)
                Wait_Click(self.browser, Activity().select_product % format(2))
                Wait_Click(self.browser, Activity().product_ensure)
            Wait_Click(self.browser, Activity().discount_coupon_together % format(together))  # 是否能与优惠券：1.是 2.否
            page_scrolling(self, scroll=1)  # 下滚
            Wait_Click(self.browser, Activity().activity_ensure)
        except Exception as Error:
            logger_message.logwarning(u"%s\t方法名：%s\t异常%s" % (send_time, sys._getframe().f_code.co_name, Error))
            raise

    def query_activity(self, name):
        try:
            Wait_Click(self.browser, Activity().query_activity_status)
            select_list(self, name=name, get_list=Activity().query_activity_status_list)
        except Exception as Error:
            logger_message.logwarning(u"%s\t方法名：%s\t异常%s" % (send_time, sys._getframe().f_code.co_name, Error))
            raise

    @unittest.skip('无条件跳过')
    def test_add_Activity(self):
        u"""添加活动"""
        login_user(self, LoginName=u'zhangyang1', LoginPwd=u"960418")
        Operation_Center(self)
        Fixed_Window(self)
        Selection_Menu(self, Operation_path().Production_Management)
        ActionChains(self.browser).send_keys(Keys.PAGE_DOWN).perform()
        Selection_Menu(self, Production_Management_path().Activity)
        is_frame_page(self, Production_Management_frame().Activity_frame)
        self.add_activity(name='活动主题', image=10, activity_type=1, piece=1,
                          money=1, apply_product=2, together=1, product_name='西门子')

    # @unittest.skip('无条件跳过')
    def test_query_Activity(self):
        u"""查询活动"""
        login_user(self, LoginName=u'zhangyang1', LoginPwd=u"960418")
        Operation_Center(self)
        Fixed_Window(self)
        Selection_Menu(self, Operation_path().Production_Management)
        ActionChains(self.browser).send_keys(Keys.PAGE_DOWN).perform()
        Selection_Menu(self, Production_Management_path().Activity)
        is_frame_page(self, Production_Management_frame().Activity_frame)
        self.query_activity(name='未开始')

    @classmethod
    def tearDownClass(cls):
        time.sleep(1)
        # cls.browser.quit()

if __name__ == "__main__":
    unittest.main()


# short_desc: generic classifier
import numpy as np
from PIL import Image
from typing import List, Tuple, Callable, Collection
from onnxruntime import InferenceSession, get_available_providers

def preprocess(image: Image):
    image = image.convert("RGB")
    return np.array(image)

def softmax(x: np.ndarray):
    """Compute softmax values for each sets of scores in x."""
    e_x = np.exp(x - np.max(x))
    return e_x / e_x.sum()

class Classifier:
    def __init__(self,
                 model_file: str,
                 labels: Collection[str],
                 image_size: Tuple[int, int],
                 preprocess: Callable = preprocess,
                 providers: List = get_available_providers()):
        self.model = InferenceSession(
            model_file,
            providers=providers
        )
        self.preprocess = preprocess
        self.image_size = image_size
        self.input_name = self.model.get_inputs()[0].name
        self.labels = labels

    def __call__(self, images: Collection[Image]):
        # Forward pass
        inputs = self.preprocess(images)
        logits, = self.model.run(None, {self.input_name: inputs})
        logits = logits.flatten()
        softmaxs = softmax(logits)

        # Result
        label_idx = np.argmax(softmaxs)
        label = self.labels[label_idx]
        confidence = softmaxs[label_idx]

        result = dict(label=label,
                      label_idx=label_idx,
                      logits=logits,
                      softmaxs=softmaxs,
                      confidence=confidence)
        return result


from array import array
from GeneticAlgorithm.GeneticAlgorithm import GeneticAlgorithm
"""
This version of the Genetic Algorithm defines "convergence" as "reaching the
specified number of generations without a change in the maximum observed
fitness"
"""
class FitnessChange(GeneticAlgorithm):

    def __init__(self):
        super(FitnessChange,self).__init__()

    def selection(self,population:list, fitnessFunction)->tuple:
        fitnessDict = {}
        for individual in range(len(population)):
            fitnessDict[individual] = fitnessFunction(population[individual])
        fittest = self.getKeyOfMaxValue(fitnessDict)
        fittestScore = fitnessDict[fittest]
        fitnessDict.pop(fittest)
        secondFittest = self.getKeyOfMaxValue(fitnessDict)
        fitnessDict.pop(secondFittest)
        return (population[fittest],population[secondFittest], fittestScore)

    def run(self,genomeLength:int,targetGenerations:int,fitnessFunction)->array:
        generationsWithoutChange = 0
        population = self.generateInitialPopulation(genomeLength)
        parent1, parent2,fittestScore = self.selection(population, fitnessFunction)
        child1,child2 = self.crossoverHelper(parent1,parent2)
        self.mutationHelper(child1)
        self.mutationHelper(child2)
        population = [parent1,parent2,child1,child2]
        while(generationsWithoutChange < targetGenerations):
            print(f"Fitness:\t{fittestScore}")
            parent1, parent2, newFittestScore = self.selection(population, fitnessFunction)

            if(newFittestScore <= fittestScore):
                generationsWithoutChange+=1
            else:
                generationsWithoutChange = 0
            fittestScore = newFittestScore

            child1,child2 = self.crossoverHelper(parent1,parent2)
            self.mutationHelper(child1)
            self.mutationHelper(child2)
            population = [parent1,parent2,child1,child2]
        return parent1
def fitnessFunction(genome: array)-> float:
            f = 0
            for gene in genome:
                if(gene == 1):
                    f+=1
            return f
def main():
    genomeLength = 10
    ga = FitnessChange()
    best = ga.run(genomeLength,genomeLength**1.50732421875,fitnessFunction)
    print(best)
if __name__ == '__main__':
    main()


#!/usr/bin/env python

'Take Photo Tests.'

import os
import sys
import unittest
os.environ['take_photo_disable_rotation_adjustment'] = '0'
import take_photo
import numpy as np
try:
    import farmware_tools
except ImportError:
    FT_IMPORTED = False
else:
    FT_IMPORTED = True
try:
    import cv2
except ImportError:
    CV2_IMPORTED = False
else:
    CV2_IMPORTED = True
try:
    from unittest import mock
except ImportError:
    import mock

OUTPUT_FILENAME = 'output.txt'

def read_output_file(output_file):
    'Read test output file.'
    output_file.close()
    with open(OUTPUT_FILENAME, 'r') as output_file:
        output = output_file.read().lower()
    sys.stdout = sys.__stdout__
    print('')
    print(os.environ)
    print('>' * 20)
    print(output)
    print('<' * 20)
    return output

os.environ.clear()
ENVS = [
    'take_photo_logging',
    'camera',
    'IMAGES_DIR',
    'take_photo_width',
    'take_photo_height',
    'take_photo_disable_rotation_adjustment',
    'CAMERA_CALIBRATION_total_rotation_angle',
    'FARMBOT_OS_VERSION',
    'FARMWARE_URL',
    'FARMWARE_TOKEN',
    'FARMWARE_API_V2_REQUEST_PIPE',
    'FARMWARE_API_V2_RESPONSE_PIPE',
]

def re_import():
    try:
        reload(take_photo)
    except NameError:
        import importlib
        importlib.reload(take_photo)

def _prepare_fuser_mock(**kwargs):
    def _fuser_mock(*_args):
        if kwargs.get('missing'):
            try:
                MissingError = FileNotFoundError
            except NameError:
                MissingError = OSError
            raise MissingError
        if kwargs.get('busy'):
            return b' 1 2 3'
        else:
            import subprocess
            raise subprocess.CalledProcessError
    return _fuser_mock

def _prepare_mock_capture(**kwargs):
    def mocked_video_capture(*_args):
        'Used by mock.'
        class MockVideoCapture():
            'Mock cv2.VideoCapture'

            @staticmethod
            def isOpened():
                'is camera open?'
                ret = kwargs.get('isOpened')
                return True if ret is None else ret

            @staticmethod
            def getBackendName():
                'get capture backend'
                if kwargs.get('raise_backend'):
                    raise NameError('mock error')
                return 'mock'

            @staticmethod
            def grab():
                'get frame'
                ret = kwargs.get('grab_return')
                return True if ret is None else ret

            @staticmethod
            def read():
                'get image'
                if kwargs.get('raise_read'):
                    raise NameError('mock error')
                default_return = True, np.zeros([10, 10, 3], np.uint8)
                return kwargs.get('read_return') or default_return

            @staticmethod
            def set(*_args):
                'set parameter'
                return

            @staticmethod
            def release():
                'close camera'
                return

        if kwargs.get('raise_open'):
            raise IOError('mock error')
        return MockVideoCapture()
    return mocked_video_capture

def _prepare_mock_socket(**_kwargs):
    def mocked_socket(*_args):
        class MockSocket():
            @staticmethod
            def connect(_): return
            @staticmethod
            def sendall(req): print(req)
            @staticmethod
            def recv(_): return
            @staticmethod
            def close(): return
        return MockSocket()
    return mocked_socket

class TakePhotoTest(unittest.TestCase):
    'Test Take Photo.'

    def setUp(self):
        for env in ENVS:
            try:
                del os.environ[env]
            except KeyError:
                pass
        os.environ['IMAGES_DIR'] = '/tmp'
        os.environ['take_photo_disable_rotation_adjustment'] = '0'
        self.outfile = open(OUTPUT_FILENAME, 'w')
        sys.stdout = self.outfile

    def test_default(self):
        'Test default Take Photo.'
        re_import()
        take_photo.take_photo()
        output = read_output_file(self.outfile)
        self.assertGreater(output.count('[ '), 3)
        self.assertLess(output.count('send_message'), 3)
        self.assertFalse('rotated' in output)

    def test_quiet(self):
        'Test quiet log level.'
        os.environ['take_photo_logging'] = 'quiet'
        re_import()
        take_photo.take_photo()
        output = read_output_file(self.outfile)
        self.assertFalse('[ ' in output)

    def test_verbose(self):
        'Test verbose log level.'
        os.environ['take_photo_logging'] = 'verbose'
        re_import()
        take_photo.take_photo()
        output = read_output_file(self.outfile)
        self.assertFalse('[ ' in output)
        if FT_IMPORTED:
            self.assertGreater(output.count('send_message'), 3)

    def test_timed_verbose(self):
        'Test timed verbose log level.'
        os.environ['take_photo_logging'] = 'verbose_timed'
        re_import()
        take_photo.take_photo()
        output = read_output_file(self.outfile)
        self.assertTrue('[ ' in output)
        if FT_IMPORTED:
            self.assertGreater(output.count('send_message'), 3)

    @unittest.skipIf(FT_IMPORTED, '')
    @mock.patch('requests.post', mock.Mock())
    def test_verbose_legacy(self):
        'Test verbose log level with legacy log.'
        os.environ['take_photo_logging'] = 'verbose'
        os.environ['FARMWARE_URL'] = 'url'
        os.environ['FARMWARE_TOKEN'] = 'token'
        re_import()
        take_photo.take_photo()
        output = read_output_file(self.outfile)
        self.assertFalse('[ ' in output)

    @mock.patch('os.listdir', mock.Mock(side_effect=lambda _: ['video0']))
    @mock.patch('os.path.exists', mock.Mock())
    @mock.patch('cv2.VideoCapture', _prepare_mock_capture())
    def test_capture_success(self):
        'Test image capture.'
        del os.environ['IMAGES_DIR']
        re_import()
        take_photo.take_photo()
        output = read_output_file(self.outfile)
        self.assertTrue('saved' in output)
        self.assertTrue('directory does not exist' in output)

    @mock.patch('os.listdir', mock.Mock(
        side_effect=lambda _: ['video0', 'video1', 'video2']))
    def test_not_at_port(self):
        'Test not at video ports.'
        del os.environ['IMAGES_DIR']
        re_import()
        take_photo.take_photo()
        output = read_output_file(self.outfile)
        self.assertFalse('saved' in output)

    @mock.patch('os.listdir', mock.Mock(side_effect=lambda _: ['video0']))
    @mock.patch('os.path.exists', mock.Mock())
    @mock.patch('cv2.VideoCapture', _prepare_mock_capture(raise_open=True))
    def test_camera_open_error(self):
        'Test error on camera open.'
        re_import()
        take_photo.take_photo()
        output = read_output_file(self.outfile)
        self.assertTrue('mock error' in output)
        self.assertTrue('could not connect' in output)

    @mock.patch('os.listdir', mock.Mock(side_effect=lambda _: ['video0']))
    @mock.patch('os.path.exists', mock.Mock())
    @mock.patch('cv2.VideoCapture', _prepare_mock_capture(raise_backend=True))
    def test_camera_get_backend_error(self):
        'Test error on get backend.'
        re_import()
        take_photo.take_photo()
        output = read_output_file(self.outfile)
        self.assertTrue('not available' in output)

    @mock.patch('os.listdir', mock.Mock(side_effect=lambda _: ['video0']))
    @mock.patch('os.path.exists', mock.Mock())
    @mock.patch('cv2.VideoCapture', _prepare_mock_capture(raise_read=True))
    def test_camera_read_error(self):
        'Test error on camera read.'
        re_import()
        take_photo.take_photo()
        output = read_output_file(self.outfile)
        self.assertTrue('mock error' in output)
        self.assertTrue('image capture error' in output)

    @mock.patch('os.listdir', mock.Mock(side_effect=lambda _: ['video0']))
    @mock.patch('os.path.exists', mock.Mock())
    @mock.patch('subprocess.check_output',
                mock.Mock(side_effect=_prepare_fuser_mock(missing=True)))
    @mock.patch('cv2.VideoCapture', _prepare_mock_capture())
    def test_camera_no_busy_check(self):
        'Test unable to check if camera is busy.'
        re_import()
        take_photo.take_photo()
        output = read_output_file(self.outfile)
        self.assertTrue('unable to check' in output)

    @mock.patch('os.listdir', mock.Mock(side_effect=lambda _: ['video0']))
    @mock.patch('os.path.exists', mock.Mock())
    @mock.patch('subprocess.check_output',
                mock.Mock(side_effect=_prepare_fuser_mock(busy=True)))
    @mock.patch('cv2.VideoCapture', _prepare_mock_capture())
    def test_camera_busy(self):
        'Test camera busy.'
        re_import()
        take_photo.take_photo()
        output = read_output_file(self.outfile)
        self.assertTrue('attempting to close' in output)

    @mock.patch('os.listdir', mock.Mock(side_effect=lambda _: ['video0']))
    @mock.patch('os.path.exists', mock.Mock())
    @mock.patch('cv2.VideoCapture', _prepare_mock_capture(isOpened=False))
    def test_camera_not_open(self):
        'Test camera not open.'
        re_import()
        take_photo.take_photo()
        output = read_output_file(self.outfile)
        self.assertTrue('could not connect' in output)

    @mock.patch('os.listdir', mock.Mock(side_effect=lambda _: ['video0']))
    @mock.patch('os.path.exists', mock.Mock())
    @mock.patch('cv2.VideoCapture',
                _prepare_mock_capture(read_return=(False, None)))
    def test_no_image(self):
        'Test no image.'
        re_import()
        take_photo.take_photo()
        output = read_output_file(self.outfile)
        self.assertTrue('no image' in output)

    @mock.patch('os.listdir', mock.Mock(side_effect=lambda _: ['video0']))
    @mock.patch('os.path.exists', mock.Mock())
    @mock.patch('cv2.VideoCapture', _prepare_mock_capture(grab_return=False))
    def test_no_grab_image(self):
        'Test no grab return.'
        re_import()
        take_photo.take_photo()
        output = read_output_file(self.outfile)
        self.assertTrue('could not get frame' in output)

    @mock.patch('os.listdir', mock.Mock(side_effect=lambda _: ['video0']))
    @mock.patch('os.path.exists', mock.Mock())
    @mock.patch('os.path.isdir', mock.Mock())
    @mock.patch('cv2.VideoCapture', _prepare_mock_capture())
    def test_rotated(self):
        'Test image rotation.'
        os.environ['CAMERA_CALIBRATION_total_rotation_angle'] = '45'
        re_import()
        take_photo.take_photo()
        output = read_output_file(self.outfile)
        self.assertTrue('rotated' in output)
        self.assertFalse('directory does not exist' in output)

    @mock.patch('os.listdir', mock.Mock(side_effect=lambda _: ['video0']))
    @mock.patch('os.path.exists', mock.Mock())
    @mock.patch('os.path.isdir', mock.Mock())
    @mock.patch('cv2.VideoCapture', _prepare_mock_capture())
    def test_large_rotation(self):
        'Test large image rotation.'
        os.environ['CAMERA_CALIBRATION_total_rotation_angle'] = '75'
        re_import()
        take_photo.take_photo()
        output = read_output_file(self.outfile)
        self.assertTrue('rotated' in output)
        self.assertFalse('directory does not exist' in output)

    def test_none_camera(self):
        'Test none camera selection.'
        os.environ['camera'] = 'none'
        re_import()
        take_photo.take_photo()
        output = read_output_file(self.outfile)
        self.assertTrue('no camera selected' in output)
        self.assertFalse('USB' in output)

    def test_rpi_camera(self):
        'Test rpi camera selection.'
        os.environ['camera'] = 'rpi'
        re_import()
        take_photo.take_photo()
        output = read_output_file(self.outfile)
        self.assertTrue('raspberry pi' in output)
        self.assertTrue('raspistill' in output)
        self.assertTrue('-w 640 -h 480' in output)
        self.assertFalse('-md 3' in output)
        self.assertFalse('USB' in output)

    def test_rpi_camera_small_size(self):
        'Test capture with rpi camera selection and small size inputs.'
        os.environ['camera'] = 'rpi'
        os.environ['take_photo_width'] = '200'
        os.environ['take_photo_height'] = '100'
        re_import()
        take_photo.take_photo()
        output = read_output_file(self.outfile)
        self.assertTrue('raspistill' in output)
        self.assertTrue('-w 200 -h 100' in output)
        self.assertFalse('-md 3' in output)

    def test_rpi_camera_large_size(self):
        'Test capture with rpi camera selection and large size inputs.'
        os.environ['camera'] = 'rpi'
        os.environ['take_photo_width'] = '2000'
        os.environ['take_photo_height'] = '2000'
        re_import()
        take_photo.take_photo()
        output = read_output_file(self.outfile)
        self.assertTrue('raspistill' in output)
        self.assertTrue('-md 3' in output)
        self.assertFalse('-w' in output)

    @mock.patch('cv2.imread', mock.Mock(side_effect=lambda _:
                                        np.zeros([10, 10, 3], np.uint8)))
    @mock.patch('os.remove', mock.Mock())
    @mock.patch('subprocess.call', mock.Mock(side_effect=lambda _: 0))
    def test_rpi_camera_capture(self):
        'Test rpi camera capture success.'
        os.environ['camera'] = 'rpi'
        re_import()
        take_photo.take_photo()
        output = read_output_file(self.outfile)
        self.assertTrue('raspberry pi' in output)
        self.assertTrue('image captured' in output)

    @mock.patch('subprocess.call', mock.Mock(side_effect=lambda _: 1))
    def test_rpi_camera_capture_failure(self):
        'Test rpi camera capture failure.'
        os.environ['camera'] = 'rpi'
        re_import()
        take_photo.take_photo()
        output = read_output_file(self.outfile)
        self.assertTrue('raspberry pi' in output)
        self.assertTrue('not detected' in output)

    @mock.patch('subprocess.call', mock.Mock(side_effect=lambda _: 0))
    def test_quick_rpi_camera(self):
        'Test quick capture with rpi camera selection.'
        os.environ['take_photo_disable_rotation_adjustment'] = '1'
        os.environ['camera'] = 'rpi'
        with self.assertRaises(SystemExit):
            re_import()
        output = read_output_file(self.outfile)
        self.assertTrue('raspistill' in output)
        self.assertFalse('fswebcam' in output)
        self.assertFalse('no camera selected' in output)

    @mock.patch('os.listdir', mock.Mock(side_effect=lambda _: ['video0']))
    @mock.patch('subprocess.call', mock.Mock(side_effect=lambda _: 0))
    def test_quick_usb_camera(self):
        'Test quick capture with usb camera selection.'
        os.environ['take_photo_disable_rotation_adjustment'] = '1'
        os.environ['camera'] = 'usb'
        with self.assertRaises(SystemExit):
            re_import()
        output = read_output_file(self.outfile)
        self.assertFalse('raspistill' in output)
        self.assertTrue('fswebcam' in output)
        self.assertFalse('no camera selected' in output)

    @mock.patch('os.listdir', mock.Mock(side_effect=lambda _: ['video0']))
    @mock.patch('subprocess.call', mock.Mock(side_effect=lambda _: 0))
    def test_quick_usb_camera_image_size(self):
        'Test quick capture with usb camera and image size selection.'
        os.environ['take_photo_disable_rotation_adjustment'] = '1'
        os.environ['take_photo_width'] = '200'
        os.environ['take_photo_height'] = '100'
        os.environ['camera'] = 'usb'
        with self.assertRaises(SystemExit):
            re_import()
        output = read_output_file(self.outfile)
        self.assertFalse('raspistill' in output)
        self.assertTrue('fswebcam' in output)
        self.assertTrue('200x100' in output)
        self.assertFalse('no camera selected' in output)

    @mock.patch('subprocess.call', mock.Mock(side_effect=lambda _: 0))
    def test_quick_usb_camera_missing_port(self):
        'Test quick capture with usb camera selection, video port missing.'
        os.environ['take_photo_disable_rotation_adjustment'] = '1'
        os.environ['camera'] = 'usb'
        with self.assertRaises(SystemExit):
            re_import()
        output = read_output_file(self.outfile)
        self.assertFalse('raspistill' in output)
        self.assertFalse('fswebcam' in output)
        self.assertFalse('no camera selected' in output)
        self.assertTrue('not detected' in output)

    def test_quick_none_camera(self):
        'Test quick capture with none camera selection.'
        os.environ['take_photo_disable_rotation_adjustment'] = '1'
        os.environ['camera'] = 'none'
        with self.assertRaises(SystemExit):
            re_import()
        output = read_output_file(self.outfile)
        self.assertFalse('raspistill' in output)
        self.assertFalse('fswebcam' in output)
        self.assertTrue('no camera selected' in output)

    @unittest.skipIf(sys.version_info[0] < 3, '')
    @mock.patch('socket.socket', _prepare_mock_socket())
    def test_quick_none_camera_with_log(self):
        'Test quick capture with none camera selection and log.'
        os.environ['FARMWARE_API_V2_REQUEST_PIPE'] = ''
        os.environ['FARMWARE_API_V2_RESPONSE_PIPE'] = ''
        os.environ['take_photo_disable_rotation_adjustment'] = '1'
        os.environ['camera'] = 'none'
        with self.assertRaises(SystemExit):
            re_import()
        output = read_output_file(self.outfile)
        self.assertFalse('raspistill' in output)
        self.assertFalse('fswebcam' in output)
        self.assertTrue('no camera selected' in output)

    def test_quick_none_camera_quiet(self):
        'Test quick capture with none camera selection: quiet.'
        os.environ['take_photo_disable_rotation_adjustment'] = '1'
        os.environ['camera'] = 'none'
        os.environ['take_photo_logging'] = 'quiet'
        with self.assertRaises(SystemExit):
            re_import()
        output = read_output_file(self.outfile)
        self.assertFalse('no camera selected' in output)

    @unittest.skipIf(CV2_IMPORTED, '')
    def test_opencv_missing(self):
        'Test for cv2 import error.'
        with self.assertRaises(SystemExit):
            re_import()
        output = read_output_file(self.outfile)
        self.assertTrue('import error' in output)

    def tearDown(self):
        self.outfile.close()
        sys.stdout = sys.__stdout__
        os.remove(OUTPUT_FILENAME)


name = 'HLT_JetMET_ntuple'

from CRABClient.UserUtilities import config, getUsernameFromSiteDB
config = config()

config.General.workArea = 'crab_'+name
config.General.transferOutputs = True
config.General.transferLogs = True
config.General.requestName = 'EGamama'

config.JobType.pluginName = 'Analysis'
config.JobType.psetName = 'hlt_path_withFilter.py'
#config.JobType.maxMemoryMB = 2400
config.JobType.numCores = 4
config.JobType.outputFiles = ['hltJetMetNtuple.root']

config.Data.inputDBS = 'global'
config.Data.splitting ='FileBased'# 'EventAwareLumiBased'
#config.Data.publication = False
#config.Data.lumiMask = '/afs/cern.ch/user/m/mdjordje/public/2018JSON/Cert_322407-323775_13TeV_PromptReco_Collisions18_JSON.txt'
config.Data.publication = False

config.Data.inputDataset = '/EGamma/Run2018C-v1/RAW'
config.Data.unitsPerJob =100# 10000#1000
#config.Data.totalUnits = 1000000
config.Data.outputDatasetTag = 'EGamma'
config.Site.storageSite = 'T2_IN_TIFR'
config.Data.outLFNDirBase = '/store/user/%s/t3store2/HLT_JetMET_ntupels_10062019' % (getUsernameFromSiteDB())


#!/usr/bin/env python
import rospy
import numpy as np
from math import pi, sin, cos
from inspector.msg import PclData
from geometry_msgs.msg import Point

def trans_points(data):
    pub = rospy.Publisher("inspector/pclData2", PclData, queue_size = 10)
    #initialziations, rotation matrices, and kinect location
    out=PclData()
    cent=Point()
    rotx=np.array([[1,0, 0 ,0],[0, cos(pi/2), -sin(-pi/2) ,0],[0 ,sin(-pi/2) ,cos(pi/2) ,0 ],[0 ,0 ,0 ,1]])
    roty=np.array([[cos(pi/2) ,0, sin(-pi/2), 0],[0 ,1 ,0 ,0],[-sin(-pi/2) ,0 ,cos(pi/2) ,0],[0, 0, 0, 1]])
    kin_loc=np.array([[1.565],[-0.335],[-0.12],[1]])

    #do the transformation
    exact=data.centroid
    bot_loc=np.array([[float(exact.x)],[float(exact.y)],[float(exact.z)],[1]])
    kinect_to_bottle=rotx.dot(roty.dot(bot_loc))
    baxter_to_bottle=kinect_to_bottle+kin_loc

    #store the transformed information into a new message
    cent.x=float(baxter_to_bottle[0])
    cent.y=float(baxter_to_bottle[1])
    cent.z=float(baxter_to_bottle[2])
    out.centroid=cent
    out.height=data.height
    out.width=data.width
    out.ratio=data.ratio

    #publish the message
    pub.publish(out)

if __name__ == '__main__':
    #initializations
    rospy.init_node("pcl_transform")
    rospy.Subscriber("/pclData",PclData, trans_points)
    rospy.spin()


import time
import qrcode
import sys

def generado_Codigo():
    print("***********************************************************************************************")
    print("Hola mundo! Soy fcoterroba, puedes visitar mi web en www.fcoterroba.com")
    time.sleep(2)
    print("Este es un programa que te pide un enlace o texto y te genera un código QR en formato PNG.")
    time.sleep(3)
    codificar = input(f"COMENCEMOS!\n¿Qué palabra o enlace quieres que te codifique en QR? ")
    print("Codificando...")
    time.sleep(3)
    img = qrcode.make(codificar)
    f = open(codificar+"_QR.png", "wb")
    img.save(f)
    print(f"LISTO!\nTienes la imagen correctamente creado con el nombre {codificar}_QR.png")
    time.sleep(2)
    preguntar_Opcion()

def preguntar_Opcion():
    opcion = input(f"¿Qué quieres hacer ahora? (H)acer otro código | (S)alir del programa\n")
    if opcion=='h' or opcion=='H':
        generado_Codigo()
    else:
        time.sleep(0.4)
        print("Hasta pronto! No olvides visitar mi web www.fcoterroba.com")
        sys.exit()

generado_Codigo()


from flask import Blueprint, redirect, render_template, request, flash, url_for
from app import db
from models import Course, Category, User, Review
from tools import CoursesFilter, ImageSaver
from flask_login import current_user

bp = Blueprint('courses', __name__, url_prefix='/courses')

PER_PAGE = 4

COURSE_PARAMS = ['author_id', 'name', 'category_id', 'short_desc', 'full_desc']
REVIEW_PARAMS = ['rating', 'text']

def params(param):
    return {p: request.form.get(p) for p in param }

def search_params():
    return {
        'name': request.args.get('name'),
        'category_ids': request.args.getlist('category_ids')
    }

@bp.route('/')
def index():
    page = request.args.get('page', 1, type=int)

    courses = CoursesFilter(**search_params()).perform()
    pagination = courses.paginate(page, PER_PAGE)
    courses = pagination.items

    categories = Category.query.all()

    return render_template('courses/index.html',
                            courses=courses,
                            categories=categories,
                            pagination=pagination,
                            search_params=search_params()
                            )

@bp.route('/new')
def new():
    categories = Category.query.all()
    users = User.query.all()
    return render_template('courses/new.html',
                            categories=categories,
                            users=users
                            )

@bp.route('/create', methods=['POST'])
def create():

    f = request.files.get('background_img')
    if f and f.filename:
        img = ImageSaver(f).save()

    course = Course(**params(COURSE_PARAMS), background_image_id = img.id)
    db.session.add(course)
    db.session.commit()

    flash(f'Курс {course.name} был успешно создан.')
    return redirect(url_for('courses.index'))

@bp.route('/<int:course_id>')
def show(course_id):
    course = Course.query.get(course_id)
    reviews = Review.query.filter(Review.course_id == course_id).order_by(Review.created_at.desc()).limit(5)

    curr_review = None
    if current_user.is_authenticated:
        curr_review = Review.query.filter(Review.course_id == course_id).filter(Review.user_id == current_user.id).first()

    return render_template('courses/show.html', course=course, reviews=reviews, curr_review=curr_review)

@bp.route('/<int:course_id>/reviews')
def reviews(course_id):
    page = request.args.get('page', 1, type=int)
    reviews = Review.query.filter(Review.course_id == course_id).order_by(Review.created_at.desc())
    sort_type = request.args.get('filters')

    if sort_type == 'new_first':
        reviews = Review.query.filter(Review.course_id == course_id).order_by(Review.created_at.desc())
    elif sort_type == 'old_first':
        reviews = Review.query.filter(Review.course_id == course_id).order_by(Review.created_at.asc())
    elif sort_type == 'pos_first':
        reviews = Review.query.filter(Review.course_id == course_id).order_by(Review.rating.desc())
    elif sort_type == 'neg_first':
        reviews = Review.query.filter(Review.course_id == course_id).order_by(Review.rating.asc())

    pagination = reviews.paginate(page, PER_PAGE)
    reviews = pagination.items

    curr_review = None
    if current_user.is_authenticated:
        curr_review = Review.query.filter(Review.course_id == course_id).filter(Review.user_id == current_user.id).first()

    return render_template('courses/reviews.html', reviews=reviews, course_id=course_id, pagination=pagination, curr_review=curr_review)

@bp.route('/<int:course_id>/reviews/create', methods=['POST'])
def create_review(course_id):
    new_review = Review(**params(REVIEW_PARAMS), course_id=course_id, user_id=current_user.id)
    db.session.add(new_review)

    course = Course.query.get(course_id)
    course.rating_num += 1
    course.rating_sum += int(new_review.rating)

    db.session.commit()
    flash(f'Комментарий был успешно создан.')

    return redirect(url_for('courses.show', course_id=course_id))


#!/usr/bin/env python
"""
Create desktop shortcuts for Darwin / MacOS
"""
import os
import sys
import shutil

from .shortcut import shortcut, get_pyexe
from .linux import get_homedir, get_desktop
from . import UserFolders

scut_ext = 'app'
ico_ext = ('icns',)

def get_startmenu():
    "get start menu location"
    return ''

def get_folders():
    """get user-specific folders

    Returns:
    -------
    Named tuple with fields 'home', 'desktop', 'startmenu'

    Example:
    -------
    >>> from pyshortcuts import get_folders
    >>> folders = get_folders()
    >>> print("Home, Desktop, StartMenu ",
    ...       folders.home, folders.desktop, folders.startmenu)
    """
    return UserFolders(get_homedir(), get_desktop(), get_startmenu())

def make_shortcut(script, name=None, description=None, icon=None, working_dir=None,
                  folder=None, terminal=True, desktop=True,
                  startmenu=True, executable=None):
    """create shortcut

    Arguments:
    ---------
    script      (str) path to script, may include command-line arguments
    name        (str, None) name to display for shortcut [name of script]
    description (str, None) longer description of script [`name`]
    icon        (str, None) path to icon file [python icon]
    working_dir (str, None) directory where to run the script in
    folder      (str, None) subfolder of Desktop for shortcut [None] (See Note 1)
    terminal    (bool) whether to run in a Terminal [True]
    desktop     (bool) whether to add shortcut to Desktop [True]
    startmenu   (bool) whether to add shortcut to Start Menu [True] (See Note 2)
    executable  (str, None) name of executable to use [this Python] (see Note 3)

    Notes:
    ------
    1. `folder` will place shortcut in a subfolder of Desktop and/or Start Menu
    2. Start Menu does not exist for Darwin / MacOSX
    3. executable defaults to the Python executable used to make shortcut.
    """
    if not desktop:
        return

    userfolders = get_folders()
    if working_dir is None:
        working_dir = ''

    scut = shortcut(script, userfolders, name=name, description=description,
                    working_dir=working_dir, folder=folder, icon=icon)

    osascript = '%s %s' % (scut.full_script, scut.arguments)
    osascript = osascript.replace(' ', '\\ ')
    prefix = os.path.normpath(sys.prefix)
    if executable is None:
        executable = get_pyexe()

    executable = os.path.normpath(executable)
    if os.path.realpath(scut.full_script) == os.path.realpath(executable):
        executable = ''

    if not os.path.exists(scut.desktop_dir):
        os.makedirs(scut.desktop_dir)

    dest = os.path.join(scut.desktop_dir, scut.target)

    if os.path.exists(dest):
        shutil.rmtree(dest)

    os.mkdir(dest)
    os.mkdir(os.path.join(dest, 'Contents'))
    os.mkdir(os.path.join(dest, 'Contents', 'MacOS'))
    os.mkdir(os.path.join(dest, 'Contents', 'Resources'))

    opts = dict(name=scut.name,
                desc=scut.description,
                script=scut.full_script,
                workdir=scut.working_dir,
                args=scut.arguments,
                prefix=prefix,
                exe=executable,
                osascript=osascript)

    info = """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
  <key>CFBundleGetInfoString</key> <string>{desc:s}</string>
  <key>CFBundleName</key> <string>{name:s}</string>
  <key>CFBundleExecutable</key> <string>{name:s}</string>
  <key>CFBundleIconFile</key> <string>{name:s}</string>
  <key>CFBundlePackageType</key> <string>APPL</string>
  </dict>
</plist>
"""

    text = ['#!/bin/bash',
            "export EXE={exe:s}",
            "export SCRIPT={script:s}",
            "export ARGS='{args:s}'"]

    if scut.working_dir not in (None, ''):
        text.append("cd {workdir:s}")

    if terminal:
        text.append("""osascript -e 'tell application "Terminal"
   do script "'${{EXE}}\ {osascript:s}'"
end tell
'
""")
    else:
        text.append("$EXE $SCRIPT $ARGS")

    text.append('\n')
    text = '\n'.join(text)

    with open(os.path.join(dest, 'Contents', 'Info.plist'), 'w') as fout:
        fout.write(info.format(**opts))

    ascript_name = os.path.join(dest, 'Contents', 'MacOS', scut.name)
    with open(ascript_name, 'w') as fout:
        fout.write(text.format(**opts))

    os.chmod(ascript_name, 493)  # = octal 755 / rwxr-xr-x
    icon_dest = os.path.join(dest, 'Contents', 'Resources', scut.name + '.icns')
    shutil.copy(scut.icon, icon_dest)
    return scut


import requests
import simplejson
from configuration import conf
import os
from obj.paper import Paper

usernames, passwords = conf.github_auth

class RepoInfoCrawler:
    def __init__(self, paper_obj):
        assert(isinstance(paper_obj, Paper))
        self.repo_name = paper_obj.repo_name
        self.repo_owner = paper_obj.repo_owner
        self.repo_exist = True
        if not self.check_repo_in_disk():
            self.repo_exist = False
        self.url = 'https://api.github.com/repos/' + self.repo_owner + '/' + self.repo_name

    @staticmethod
    def save_path(repo_owner, repo_name):
        if not os.path.exists(conf.info_path):
            os.makedirs(conf.meta_path)
        save_path = os.path.join(conf.info_path, repo_owner)
        if not os.path.exists(save_path):
            os.makedirs(save_path)
        save_path = os.path.join(save_path, repo_name + '.json')
        return save_path

    def check_repo_in_disk(self):
        this_repo_path = os.path.join(conf.repo_path, self.repo_owner, self.repo_name)
        return os.path.exists(this_repo_path)

    def check_data_in_disk(self):
        this_info_path = os.path.join(conf.info_path, self.repo_owner, self.repo_name+'.json')
        return os.path.exists(this_info_path)

    def crawl_to_disk(self):
        if not self.repo_exist:
            return False
        if self.check_data_in_disk():
            return False
        print(self.url)
        response = requests.get(self.url, auth=(usernames[0], passwords[0]))
        with open(RepoInfoCrawler.save_path(self.repo_owner, self.repo_name), 'w+', encoding='utf-8') as f:
            f.write(response.text)
        return True

def print_repo_info():
    owner = 'trakaros'
    repo = 'MPIIGaze.json'
    f_path = os.path.join(conf.info_path, owner, repo)
    with open(f_path, 'r', encoding='utf-8') as f:
        json_obj = simplejson.load(f)
        import pprint
        pprint.pprint(json_obj)

if __name__ == '__main__':
    print_repo_info()


import pickle
import time
import torch
import gc
from TheGAN import LevyGAN
from hyperopt import fmin, tpe, hp, STATUS_OK, Trials

config = {
    'w dim': 3,
    'noise size': 61,
    'which generator': 10,
    'which discriminator': 10,
    'generator symmetry mode': 'Hsym',
    'leakyReLU slope': 0.2,
    'test bsz': 65536,
    'unfixed test bsz': 65536,
    'joint wass dist bsz': 2048,
    'num tests for 2d': 4,
    'W fixed whole': [1.0, -0.5, -1.2, -0.3, 0.7, 0.2, -0.9, 0.1, 1.7],
    'should draw graphs': True,
    'do timeing': False
}

training_config = {
    'num epochs': 9,
    'max iters': None,
    'num Chen iters': 5000,
    'optimizer': 'Adam',
    'lrG': 0.000001,
    'lrD': 0.000002,
    'num discr iters': 3,
    'beta1': 0.2,
    'beta2': 0.98,
    'Lipschitz mode': 'gp',
    'weight clipping limit': 0.01,
    'gp weight': 5.0,
    'bsz': 1024,
    'compute joint error': True,
    'print reports': True,
    'descriptor': '',
    'custom Chen lrs': {
            0: (0.0000000001, 0.00000000003),
            1010: (0.0000001, 0.000001),
            3010: (0.000002, 0.00001),
            4010: (0.00001, 0.00005),
        },
    'custom lrs': {
            0: (0.00001, 0.0001),
            3: (0.000001, 0.00001),
            5: (0.0000001, 0.000001),
            8: (0.00001, 0.00005)
        },
}

short_tr_conf = training_config.copy()
short_tr_conf['num Chen iters'] = 20

for gen in range(10,11):
    for discr in range(10,11):
        for trials in range(8):
            torch.cuda.empty_cache()
            gc.collect()

            config['which generator'] = gen
            config['which discriminator'] = discr
            # training_config['descriptor'] = "CLASSIC"
            # levG = LevyGAN(config)
            # levG.classic_train(training_config)
            # report = levG.test_results['best score report']
            # line = f"CLASSIC gen: {gen}, discr: {discr}, {report}\n"
            # f.write(line)

            training_config['descriptor'] = "CHEN"
            levG = LevyGAN(config)
            levG.should_draw_graphs = False
            levG.chen_train(short_tr_conf, save_models=False)
            levG.should_draw_graphs = True
            levG.chen_train(training_config)
            report = levG.test_results['best score report']
            levG.joint_wass_dist_bsz = 20000
            levG.load_dicts(descriptor="CHEN_max_scr")
            levG.do_tests(comp_joint_err=True, save_best_results=False)
            joint_errs = levG.test_results['joint wass errors']
            print()
            line = f"CHEN gen: {gen}, discr: {discr}, num{levG.serial_number}, best joint: {joint_errs} {report}\n"
            with open("net_test_report.txt", "a+") as f:
                f.write(line)

            # a bit more classical training
            training_config['descriptor'] = "CLAS"
            levG.joint_wass_dist_bsz = 4096
            levG.reset_test_results()
            levG.classic_train(training_config)
            report = levG.test_results['best score report']
            levG.joint_wass_dist_bsz = 20000
            levG.load_dicts(descriptor="CLAS_max_scr")
            levG.do_tests(comp_joint_err=True, save_best_results=False)
            joint_errs = levG.test_results['joint wass errors']
            line = f"CLS+ gen: {gen}, discr: {discr}, num{levG.serial_number}, best joint: {joint_errs} {report}\n"
            with open("net_test_report.txt", "a+") as f:
                f.write(line)


"""
This script is referenced by our TerraForm config as an external data source. It
prints the current deployment's Elasticsearch node IDs as JSON to STDOUT. If the
list of node IDs contains fewer items than the number of placeholders in the
Cloudwatch dashboard template, the output is padded with dummy entries.

Note that Terraform requires the object given to an external data source is a
map of string values, so the list of node IDs is JSON-encoded and later
converted back into a list when processed in the Terraform config.
"""
import json
import logging
from typing import (
    Sequence,
)

import jq
from more_itertools import (
    padded,
)

from azul import (
    config,
    require,
)
from azul.es import (
    ESClientFactory,
)
from azul.logging import (
    configure_script_logging,
)

log = logging.getLogger(__name__)

# How many times to try getting the node IDs from AWS before giving up.
max_attempts = 10

def main() -> None:
    node_ids = get_node_ids()
    data = prepare_node_ids(node_ids)
    print(json.dumps(data))

def get_node_ids() -> Sequence[str]:
    """
    Return a list of ES node IDs used by the current deployment.
    """
    es_client = ESClientFactory.get()
    nodes = es_client.nodes.info()
    return sorted(nodes['nodes'].keys())

def prepare_node_ids(node_ids: Sequence[str]) -> dict[str, str]:
    """
    Return the given node IDs in a data structure that TerraForm can use as an
    external data source.
    """
    # The list of nodes IDs is appended with dummy entries to ensure the length
    # matches the number of placeholders in the template. If our list had fewer
    # items than there are matches in the template, Terraform would throw an
    # "Invalid index" error.
    num_placeholders = node_placeholder_count()
    require(num_placeholders > 0,
            'Error: No node ID placeholders found in template file')
    # The dashboard will not allow an empty string as a node ID value, causing
    # the error `Invalid metric field type, only "String" type is allowed`
    # during deploy. For this reason we pad the list with a dummy value.
    node_ids = list(padded(node_ids, 'none', num_placeholders))
    return {
        'nodes': json.dumps(node_ids)  # TerraForm only accepts string values
    }

def node_placeholder_count() -> int:
    """
    Return the number of unique ES node ID placeholders found in the Cloudwatch
    dashboard template file.
    """
    with open(config.cloudwatch_dashboard_template) as f:
        body = json.load(f)
    filters = [
        # Indexing from end so we don't have to deal with the `...` placeholder.
        # The last three elements are the `Client ID` dimension name, its value
        # and the options object.
        # https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/CloudWatch-Metric-Widget-Structure.html#CloudWatch-Metric-Widget-Metrics-Array-Format
        '.widgets[].properties.metrics[]?[-4]',
        'values',
        'capture(' + json.dumps(r'local\.nodes\[(?<x>[0-9]+)\]') + ').x',
        'tonumber',
    ]
    max_index = max(jq.all('|'.join(filters), body))
    return max_index + 1

if __name__ == '__main__':
    configure_script_logging(log)
    main()


# -*- coding: utf-8 -*-
#每条QSS样式都由两部分组成:1.选择器2. 声明
#QPushButton {color: red}

import sys
from PySide.QtGui import QApplication,QWidget,QPushButton,QLabel,QVBoxLayout,QHBoxLayout

class Demo(QWidget):
	def __init__(self):
		super(Demo,self).__init__()
		self.button1 = QPushButton('super class', self)
		self.button2 = SubButton()

		self.h_layout = QHBoxLayout()
		self.h_layout.addWidget(self.button1)
		self.h_layout.addWidget(self.button2)
		self.setLayout(self.h_layout)

class SubButton(QPushButton):
	def __init__(self):
		super(SubButton, self).__init__()
		self.setText('subclass')

if __name__ == '__main__':
	app = QApplication(sys.argv)
	demo = Demo()
	qss = 'QPushButton {color: red}'
	demo.setStyleSheet(qss)
	demo.show()
	sys.exit(app.exec_())


maior=int(input())
menor=int(input())
total=0

#ordenando os números em uma lista
lista = [maior,menor]
lista.sort()
maior = lista[1]
menor = lista[0]

#condição necessária para números pares
if menor%2 == 0:
    menor = menor + 1
    for n in range(menor,maior,2):
        total = total + n #ou total += n
        #use aquio o comando 'print('lista dos números %d somados' %n)' para saber quais números você está somando
    print(total)

#condição necessária para números ímpares
elif menor %2 != 0:
    menor = menor + 1
    for n in range(menor + 1, maior, 2):
        total = total + n  # ou total += n
        #use o aqui o comando 'print('lista dos números %d somados' %n)' para saber quais números você está somando
    print (total)


import cv2
import numpy as np

circles = []  # cember koordinatlarini alacak bos liste tanimlandi

img = cv2.imread(r"C:\Users\suley\Desktop\software\materials\opencv_materials\golgeler.jpg")
row, col, hc = img.shape
# img = cv2.resize(img, (int(col / 4), int(row / 4)))
r, c, h = img.shape
print("r", r)
print("c", c)
print("h", h)

def mouse(event, x, y, flags, params):  # farede sag tusa tiklandiginda o anki koordinati donduren fonskiyon tanimlandi
    if event == cv2.EVENT_LBUTTONDOWN:  # sag tusa basilinca bos listeye koordinatlar tupple olarak gonderildi
        circles.append((x, y))
        print(x, y)
        print(circles)

cv2.namedWindow("img")  # mouse islevinin caliacagi pencere tanimlandi
cv2.setMouseCallback("img", mouse)  # pencere uzerinde mouse hareketleri

cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

print(circles)

solust = np.array([[circles[0][0], circles[0][1]]])
sagust = np.array([[circles[1][0], circles[1][1]]])
solalt = np.array([[circles[2][0], circles[2][1]]])
sagalt = np.array([[circles[3][0], circles[3][1]]])

print("solust", solust)
print("sagust", sagust)
print("solalt", solalt)
print("sagalt", sagalt)

mypoints = np.array([solust, sagust, solalt, sagalt])
print(mypoints)
mypoints = np.float32(mypoints)
pts2 = np.float32([[0, 0], [891, 0], [0, 630], [891, 630]])
matrix = cv2.getPerspectiveTransform(mypoints, pts2)

dst = cv2.warpPerspective(img, matrix, (891, 630))

cv2.imshow("dst", dst)
cv2.waitKey(0)
cv2.destroyAllWindows()


from numpy import sin, cos, pi, sqrt, shape, linspace, meshgrid, zeros, mod
from math import factorial
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d as mp3d
def Shperical2Cartesian(r, theta, phi):
    x = r*sin(theta)*cos(phi)
    y = r*sin(theta)*sin(phi)
    z = r*cos(theta)
    return x, y, z
def Legendre_Poly(n, x):
    if n == 0:
        p = 1
    elif n == 1:
        p = x
    else:
        p = (1/n)*((2*n-1)* x* Legendre_Poly(n-1, x) - (n-1)* Legendre_Poly(n-2, x))
    return p
def Asso_Leg(l,m,x):
    try:
        if m == 0:
            p = Legendre_Poly(l,x)
        elif m > 0:
            p = (1/ sqrt(1-x**2))*((l-m+1)* x* Asso_Leg(l,m-1,x) - (l+m-1)* Asso_Leg(l-1,m-1,x))

        elif m < 0:
            m = abs(m)
            p = ((-1)**m)*(factorial(l-m)/ factorial(l+m))* Asso_Leg(l,m,x)
    except ZeroDivisionError:
        p = 0
    return p
l = int(input('Azimuthal quantum number "l": '))
if l<0:
    print('"l" can not be a negative number')

m = int(input('Magnetic quantum number "m": '))
if m>l or m<(-l):
    print('quantum number "m" belong to "[-l,l]" ')
K = sqrt( ((2*l+1)* factorial(l-abs(m)))/(4*pi*factorial(l+abs(m))) )
phi = linspace(0, 2*pi, 100)
tht = linspace(0, pi, 100)

phi,tht = meshgrid(phi,tht)
p,q = shape(phi)
Y = zeros([p,q])

for i in range(0+1,p-1):
    for j in range(0+1,q-1):
        if m>0:
            Y[i,j] = sqrt(2)*K*cos(m*phi[i,j])* Asso_Leg(l,m,cos(tht[i,j]))
        elif m<0:
            Y[i,j] = sqrt(2)*K*sin(abs(m)*phi[i,j])* Asso_Leg(l, abs(m), cos(tht[i,j]))
        elif m == 0:
            Y[i,j] = K* Legendre_Poly(l, cos(tht[i,j]))

p,q = shape(Y)

for i in range(0,p):
    for j in range(0,q):
        if Y[i,j]<0:
            tht[i,j] = tht[i,j]+pi
x,y,z = Shperical2Cartesian(Y, tht, phi)

fig = plt.figure('Harmonics')
ax = fig.add_subplot(111, projection='3d')

ax.plot_surface(x,y,z, cmap = 'cool', edgecolor = 'k')

plt.title('Spherical Harmonics', fontsize = 14, fontweight = 'bold')
ax.set_xlabel('X', fontsize =12, fontweight = 'bold')
ax.set_ylabel('Y', fontsize =12, fontweight = 'bold')
ax.set_zlabel('Z', fontsize =12, fontweight = 'bold')

plt.show()


#serialize.py
import json

from graph import *
from hypergraph import *

class MyJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Graph):
            dct = obj.__dict__.copy()
            dct.pop('edges', None)
            dct.pop('trace_recode', None)
            return dct
        elif isinstance(obj, HyperGraph):
            dct = obj.__dict__.copy()
            dct.pop('trace_recode', None)
            return dct
        elif isinstance(obj, Node):
            dct = obj.__dict__.copy()
            dct.pop('edges_in', None)
            dct.pop('edges_out', None)
            dct.pop('trace', None)
            return dct
        elif isinstance(obj, HyperNode):
            dct = obj.__dict__.copy()
            dct.pop('trace')
            dct.pop('hyperedges')
            dct['hyperedges'] = list(obj.__dict__['hyperedges'])
            return dct
        elif isinstance(obj, HyperEdge):
            dct = obj.__dict__.copy()
            dct.pop('trace')
            dct.pop('middle_hover_trace')
            dct.pop('hypernodes')
            dct['hypernodes'] = list(obj.__dict__['hypernodes'])
            return dct
        elif isinstance(obj, nx.Graph):
            return {'name': 'nx.Graph', 'data': nx.adjacency_data(obj)}
        elif isinstance(obj, nx.DiGraph):
            return {'name': 'nx.DiGraph', 'data': nx.adjacency_data(obj)}
        elif isinstance(obj, np.ndarray):
            return {'name': 'np.array', 'data': obj.tolist()}
        elif isinstance(obj, list):
            return [MyJSONEncoder.default(self, x) for x in obj]
        return json.JSONEncoder.default(self, obj)

def MyJSONDecode(dct):
    if isinstance(dct, dict) and 'name' in dct:
        name = dct['name']
        #if name == 'Graph':
        #    print('decoding graph', dct)
        dct.pop('name', None)
        if name == 'nx.Graph':
            return nx.adjacency_graph(dct['data'], directed=False)
        elif name == 'nx.DiGraph':
            return nx.adjacency_graph(dct['data'], directed=True)
        elif name == 'np.array':
            return np.array(dct['data'])
        return getattr(modules[__name__], name)(**dct)
    return dct