# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import copy
from collections import OrderedDict
import numpy as np
from astropy.table import Table
from astropy.io import fits
import astropy.units as u
from ..utils.nddata import NDDataArray, BinnedDataAxis
from ..utils.scripts import make_path
from ..utils.fits import energy_axis_to_ebounds, ebounds_to_energy_axis
from ..data import EventList

__all__ = ["CountsSpectrum", "PHACountsSpectrum", "PHACountsSpectrumList"]

log = logging.getLogger("__name__")

class CountsSpectrum(object):
    """Generic counts spectrum.

    Parameters
    ----------
    energy_lo : `~astropy.units.Quantity`
        Lower bin edges of energy axis
    energy_hi : `~astropy.units.Quantity`
        Upper bin edges of energy axis
    data : `~astropy.units.Quantity`, array-like
        Counts

    Examples
    --------
    .. plot::
        :include-source:

        from gammapy.spectrum import CountsSpectrum
        import numpy as np
        import astropy.units as u

        ebounds = np.logspace(0,1,11) * u.TeV
        data = np.arange(10)
        spec = CountsSpectrum(
            energy_lo=ebounds[:-1],
            energy_hi=ebounds[1:],
            data=data,
        )
        spec.plot(show_poisson_errors=True)
    """

    default_interp_kwargs = dict(bounds_error=False, method="nearest")
    """Default interpolation kwargs"""

    def __init__(self, energy_lo, energy_hi, data=None, interp_kwargs=None):
        axes = [
            BinnedDataAxis(
                energy_lo, energy_hi, interpolation_mode="log", name="energy"
            )
        ]

        if interp_kwargs is None:
            interp_kwargs = self.default_interp_kwargs
        self.data = NDDataArray(axes=axes, data=data, interp_kwargs=interp_kwargs)

    @property
    def energy(self):
        return self.data.axis("energy")

    @classmethod
    def from_hdulist(cls, hdulist, hdu1="COUNTS", hdu2="EBOUNDS"):
        """Read OGIP format hdulist"""
        counts_table = Table.read(hdulist[hdu1])
        counts = counts_table["COUNTS"].data
        ebounds = ebounds_to_energy_axis(hdulist[hdu2])
        return cls(
            data=counts, energy_lo=ebounds.lower_bounds, energy_hi=ebounds.upper_bounds
        )

    @classmethod
    def read(cls, filename, hdu1="COUNTS", hdu2="EBOUNDS"):
        """Read from file."""
        filename = make_path(filename)
        with fits.open(str(filename), memmap=False) as hdulist:
            return cls.from_hdulist(hdulist, hdu1=hdu1, hdu2=hdu2)

    def to_table(self):
        """Convert to `~astropy.table.Table`.

        Data format specification: :ref:`gadf:ogip-pha`
        """
        channel = np.arange(self.energy.nbins, dtype=np.int16)
        counts = np.array(self.data.data.value, dtype=np.int32)

        names = ["CHANNEL", "COUNTS"]
        meta = {"name": "COUNTS"}
        return Table([channel, counts], names=names, meta=meta)

    def to_hdulist(self):
        """Convert to `~astropy.io.fits.HDUList`.

        This adds an ``EBOUNDS`` extension to the ``BinTableHDU`` produced by
        ``to_table``, in order to store the energy axis
        """
        table = self.to_table()
        name = table.meta["name"]
        hdu = fits.BinTableHDU(table, name=name)
        ebounds = energy_axis_to_ebounds(self.energy.bins)
        return fits.HDUList([fits.PrimaryHDU(), hdu, ebounds])

    def write(self, filename, **kwargs):
        """Write to file."""
        filename = make_path(filename)
        self.to_hdulist().writeto(str(filename), **kwargs)

    def fill(self, events):
        """Fill with list of events.

        TODO: Move to `~gammapy.utils.nddata.NDDataArray`

        Parameters
        ----------
        events : `~astropy.units.Quantity`, `gammapy.data.EventList`,
            List of event energies
        """
        if isinstance(events, EventList):
            events = events.energy

        energy = events.to(self.energy.unit)
        binned_val = np.histogram(energy.value, self.energy.bins)[0]
        self.data.data = binned_val

    @property
    def total_counts(self):
        """Total number of counts
        """
        return self.data.data.sum()

    def plot(
        self,
        ax=None,
        energy_unit="TeV",
        show_poisson_errors=False,
        show_energy=None,
        **kwargs
    ):
        """Plot as data points.

        kwargs are forwarded to `~matplotlib.pyplot.errorbar`

        Parameters
        ----------
        ax : `~matplotlib.axis` (optional)
            Axis instance to be used for the plot
        energy_unit : str, `~astropy.units.Unit`, optional
            Unit of the energy axis
        show_poisson_errors : bool, optional
            Show poisson errors on the plot
        show_energy : `~astropy.units.Quantity`, optional
            Show energy, e.g. threshold, as vertical line

        Returns
        -------
        ax: `~matplotlib.axis`
            Axis instance used for the plot
        """
        import matplotlib.pyplot as plt

        ax = plt.gca() if ax is None else ax
        counts = self.data.data.value
        x = self.energy.nodes.to_value(energy_unit)
        bounds = self.energy.bins.to_value(energy_unit)
        xerr = [x - bounds[:-1], bounds[1:] - x]
        yerr = np.sqrt(counts) if show_poisson_errors else 0
        kwargs.setdefault("fmt", "")
        ax.errorbar(x, counts, xerr=xerr, yerr=yerr, **kwargs)
        if show_energy is not None:
            ener_val = u.Quantity(show_energy).to_value(energy_unit)
            ax.vlines(ener_val, 0, 1.1 * max(self.data.data.value), linestyles="dashed")
        ax.set_xlabel("Energy [{}]".format(energy_unit))
        ax.set_ylabel("Counts")
        ax.set_xscale("log")
        ax.set_ylim(0, 1.2 * max(self.data.data.value))
        return ax

    def plot_hist(self, ax=None, energy_unit="TeV", show_energy=None, **kwargs):
        """Plot as histogram.

        kwargs are forwarded to `~matplotlib.pyplot.hist`

        Parameters
        ----------
        ax : `~matplotlib.axis` (optional)
            Axis instance to be used for the plot
        energy_unit : str, `~astropy.units.Unit`, optional
            Unit of the energy axis
        show_energy : `~astropy.units.Quantity`, optional
            Show energy, e.g. threshold, as vertical line
        """
        import matplotlib.pyplot as plt

        ax = plt.gca() if ax is None else ax
        kwargs.setdefault("lw", 2)
        kwargs.setdefault("histtype", "step")
        weights = self.data.data.value
        bins = self.energy.bins.to_value(energy_unit)
        x = self.energy.nodes.to_value(energy_unit)
        ax.hist(x, bins=bins, weights=weights, **kwargs)
        if show_energy is not None:
            ener_val = u.Quantity(show_energy).to_value(energy_unit)
            ax.vlines(ener_val, 0, 1.1 * max(self.data.data.value), linestyles="dashed")
        ax.set_xlabel("Energy [{}]".format(energy_unit))
        ax.set_ylabel("Counts")
        ax.set_xscale("log")
        return ax

    def peek(self, figsize=(5, 10)):
        """Quick-look summary plots."""
        import matplotlib.pyplot as plt

        fig, ax = plt.subplots(1, 1, figsize=figsize)
        self.plot_hist(ax=ax)
        return ax

    def copy(self):
        """A deep copy of self."""
        return copy.deepcopy(self)

    def rebin(self, parameter):
        """Rebin.

        Parameters
        ----------
        parameter : int
            Number of bins to merge

        Returns
        -------
        rebinned_spectrum : `~gammapy.spectrum.CountsSpectrum`
            Rebinned spectrum
        """
        if len(self.data.data) % parameter != 0:
            raise ValueError(
                "Invalid rebin parameter: {}, nbins: {}".format(
                    parameter, len(self.data.data)
                )
            )

        # Copy to keep attributes
        retval = self.copy()
        energy = retval.energy
        energy.lo = energy.lo[0::parameter]
        energy.hi = energy.hi[parameter - 1 :: parameter]
        split_indices = np.arange(parameter, len(retval.data.data), parameter)
        counts_grp = np.split(retval.data.data, split_indices)
        counts_rebinned = np.sum(counts_grp, axis=1)
        retval.data.data = counts_rebinned

        return retval

class PHACountsSpectrum(CountsSpectrum):
    """Counts spectrum corresponding to OGIP PHA format.

    The ``bkg`` flag controls whether the PHA counts spectrum represents a
    background estimate or not (this slightly affects the FITS header
    information when writing to disk).

    Parameters
    ----------
    energy_lo : `~astropy.units.Quantity`
        Lower bin edges of energy axis
    energy_hi : `~astropy.units.Quantity`
        Upper bin edges of energy axis
    data : array-like, optional
        Counts
    quality : int, array-like, optional
        Mask bins in safe energy range (1 = bad, 0 = good)
    backscal : float, array-like, optional
        Background scaling factor
    areascal : float, array-like, optional
        Area scaling factor
    is_bkg : bool, optional
        Background or soure spectrum, default: False
    obs_id : int
        Observation identifier, optional
    livetime : `~astropy.units.Quantity`, optional
        Observation livetime
    offset : `~astropy.units.Quantity`, optional
        Field of view offset
    meta : dict, optional
        Meta information
    """

    def __init__(
        self,
        energy_lo,
        energy_hi,
        data=None,
        quality=None,
        backscal=None,
        areascal=None,
        is_bkg=False,
        obs_id=None,
        livetime=None,
        offset=None,
        meta=None,
    ):
        super(PHACountsSpectrum, self).__init__(energy_lo, energy_hi, data)
        if quality is None:
            quality = np.zeros(self.energy.nbins, dtype="i2")
        self._quality = quality
        if backscal is None:
            backscal = np.ones(self.energy.nbins)
        self.backscal = backscal
        if areascal is None:
            areascal = np.ones(self.energy.nbins)
        self.areascal = areascal
        self.is_bkg = is_bkg
        self.obs_id = obs_id
        self.livetime = livetime
        self.offset = offset
        self.meta = meta or OrderedDict()

    @property
    def quality(self):
        """Bins in safe energy range (1 = bad, 0 = good)"""
        return self._quality

    @quality.setter
    def quality(self, quality):
        self._quality = quality

    @property
    def phafile(self):
        """PHA file associated with the observation"""
        if isinstance(self.obs_id, list):
            filename = "pha_stacked.fits"
        else:
            filename = "pha_obs{}.fits".format(self.obs_id)
        return filename

    @property
    def arffile(self):
        """ARF associated with the observation"""
        return self.phafile.replace("pha", "arf")

    @property
    def rmffile(self):
        """RMF associated with the observation"""
        return self.phafile.replace("pha", "rmf")

    @property
    def bkgfile(self):
        """Background PHA files associated with the observation"""
        return self.phafile.replace("pha", "bkg")

    @property
    def bins_in_safe_range(self):
        """Indices of bins within the energy thresholds"""
        idx = np.where(np.array(self.quality) == 0)[0]
        return idx

    @property
    def counts_in_safe_range(self):
        """Counts with bins outside safe range set to 0"""
        data = self.data.data.copy()
        data[np.nonzero(self.quality)] = 0
        return data

    @property
    def lo_threshold(self):
        """Low energy threshold of the observation (lower bin edge)"""
        idx = self.bins_in_safe_range[0]
        return self.energy.lo[idx]

    @lo_threshold.setter
    def lo_threshold(self, thres):
        idx = np.where(self.energy.lo < thres)[0]
        self.quality[idx] = 1

    @property
    def hi_threshold(self):
        """High energy threshold of the observation (upper bin edge)"""
        idx = self.bins_in_safe_range[-1]
        return self.energy.hi[idx]

    @hi_threshold.setter
    def hi_threshold(self, thres):
        idx = np.where(self.energy.lo > thres)[0]
        if len(idx) != 0:
            idx = np.insert(idx, 0, idx[0] - 1)
        self.quality[idx] = 1

    def reset_thresholds(self):
        """Reset energy thresholds (i.e. declare all energy bins valid)"""
        self.quality = np.zeros_like(self.quality)

    def rebin(self, parameter):
        """Rebin.

        See `~gammapy.spectrum.CountsSpectrum`.
        This function treats the quality vector correctly
        """
        retval = super(PHACountsSpectrum, self).rebin(parameter)
        split_indices = np.arange(parameter, len(self.data.data), parameter)
        quality_grp = np.split(retval.quality, split_indices)
        quality_summed = np.sum(quality_grp, axis=1)
        # Exclude groups where not all bins are within the safe threshold
        condition = quality_summed == parameter
        quality_rebinned = np.where(
            condition, np.ones(len(retval.data.data)), np.zeros(len(retval.data.data))
        )
        retval.quality = np.array(quality_rebinned, dtype=int)

        # if backscal is not the same in all channels cannot merge
        if not np.isscalar(retval.backscal):
            if not np.isclose(np.diff(retval.backscal), 0).all():
                raise ValueError("Cannot merge energy dependent backscal")
            else:
                retval.meta.backscal = retval.backscal[0] * np.ones(retval.energy.nbins)

        # average areascal
        areascal_grp = np.split(retval.areascal, split_indices)
        retval.areascal = np.mean(areascal_grp, axis=1)

        return retval

    @property
    def _backscal_array(self):
        """Helper function to always return backscal as an array"""
        if np.isscalar(self.backscal):
            return np.ones(self.energy.nbins) * self.backscal
        else:
            return self.backscal

    def to_table(self):
        """Convert to `~astropy.table.Table`."""
        table = super(PHACountsSpectrum, self).to_table()

        table["QUALITY"] = self.quality
        table["BACKSCAL"] = self._backscal_array
        table["AREASCAL"] = self.areascal

        meta = OrderedDict()
        meta["name"] = "SPECTRUM"
        meta["hduclass"] = "OGIP"
        meta["hduclas1"] = "SPECTRUM"
        meta["corrscal"] = ""
        meta["chantype"] = "PHA"
        meta["detchans"] = self.energy.nbins
        meta["filter"] = "None"
        meta["corrfile"] = ""
        meta["poisserr"] = True
        meta["hduclas3"] = "COUNT"
        meta["hduclas4"] = "TYPE:1"
        meta["lo_thres"] = self.lo_threshold.to_value("TeV")
        meta["hi_thres"] = self.hi_threshold.to_value("TeV")
        meta["exposure"] = self.livetime.to_value("s")
        meta["obs_id"] = self.obs_id

        if not self.is_bkg:
            if self.rmffile is not None:
                meta["respfile"] = self.rmffile

            meta["backfile"] = self.bkgfile
            meta["ancrfile"] = self.arffile
            meta["hduclas2"] = "TOTAL"
        else:
            meta["hduclas2"] = "BKG"

        meta.update(self.meta)

        table.meta = meta
        return table

    @classmethod
    def from_hdulist(cls, hdulist, hdu1="SPECTRUM", hdu2="EBOUNDS"):
        """Create from `~astropy.io.fits.HDUList`."""
        counts_table = Table.read(hdulist[hdu1])
        ebounds = Table.read(hdulist[2])
        emin = ebounds["E_MIN"].quantity
        emax = ebounds["E_MAX"].quantity

        # Check if column are present in the header
        quality = None
        areascal = None
        backscal = None
        if "QUALITY" in counts_table.colnames:
            quality = counts_table["QUALITY"].data
        if "AREASCAL" in counts_table.colnames:
            areascal = counts_table["AREASCAL"].data
        if "BACKSCAL" in counts_table.colnames:
            backscal = counts_table["BACKSCAL"].data

        kwargs = dict(
            data=counts_table["COUNTS"],
            backscal=backscal,
            energy_lo=emin,
            energy_hi=emax,
            quality=quality,
            areascal=areascal,
            livetime=counts_table.meta["EXPOSURE"] * u.s,
            obs_id=counts_table.meta["OBS_ID"],
        )
        if hdulist[1].header["HDUCLAS2"] == "BKG":
            kwargs["is_bkg"] = True
        return cls(**kwargs)

    @classmethod
    def read(cls, filename, hdu1="SPECTRUM", hdu2="EBOUNDS"):
        """Read from file."""
        filename = make_path(filename)
        with fits.open(str(filename), memmap=False) as hdulist:
            return cls.from_hdulist(hdulist, hdu1=hdu1, hdu2=hdu2)

    def to_sherpa(self, name):
        """Convert to `sherpa.astro.data.DataPHA`.

        Parameters
        ----------
        name : str
            Instance name
        """
        from sherpa.utils import SherpaFloat
        from sherpa.astro.data import DataPHA

        table = self.to_table()

        # Workaround to avoid https://github.com/sherpa/sherpa/issues/248
        if np.isscalar(self.backscal):
            backscal = self.backscal
        else:
            backscal = self.backscal.copy()
            if np.allclose(backscal.mean(), backscal):
                backscal = backscal[0]

        return DataPHA(
            name=name,
            channel=(table["CHANNEL"].data + 1).astype(SherpaFloat),
            counts=table["COUNTS"].data.astype(SherpaFloat),
            quality=table["QUALITY"].data,
            exposure=self.livetime.to_value("s"),
            backscal=backscal,
            areascal=self.areascal,
            syserror=None,
            staterror=None,
            grouping=None,
        )

class PHACountsSpectrumList(list):
    """List of `~gammapy.spectrum.PHACountsSpectrum` objects.

    All spectra must have the same energy binning.
    This represent the PHA type II data format.
    See https://heasarc.gsfc.nasa.gov/docs/heasarc/ofwg/docs/spectra/ogip_92_007/node8.html
    """

    def write(self, outdir, **kwargs):
        """Write to file"""
        outdir = make_path(outdir)
        self.to_hdulist().writeto(str(outdir), **kwargs)

    def to_hdulist(self):
        """Convert to `~astropy.io.fits.HDUList`"""
        hdu = fits.BinTableHDU(self.to_table())
        ebounds = energy_axis_to_ebounds(self[0].energy.bins)
        return fits.HDUList([fits.PrimaryHDU(), hdu, ebounds])

    def to_table(self):
        """Convert to `~astropy.table.Table`."""
        is_bkg = self[0].is_bkg
        nbins = self[0].energy.nbins
        spec_num = np.empty([len(self), 1], dtype=np.int16)
        channel = np.empty([len(self), nbins], dtype=np.int16)
        counts = np.empty([len(self), nbins], dtype=np.int32)
        quality = np.empty([len(self), nbins], dtype=np.int32)
        backscal = np.empty([len(self), nbins], dtype=np.int32)
        backfile = list()
        for idx, pha in enumerate(self):
            t = pha.to_table()
            spec_num[idx] = pha.obs_id
            channel[idx] = t["CHANNEL"].data
            counts[idx] = t["COUNTS"].data
            quality[idx] = t["QUALITY"].data
            backscal[idx] = t["BACKSCAL"].data
            backfile.append("bkg.fits[{}]".format(idx))

        meta = self[0].to_table().meta
        meta["hduclas4"] = "TYPE:II"
        meta["ancrfile"] = "arf.fits"
        meta["respfile"] = "rmf.fits"

        data = [spec_num, channel, counts, quality, backscal]
        names = ["SPEC_NUM", "CHANNEL", "COUNTS", "QUALITY", "BACKSCAL"]
        table = Table(data, names=names, meta=meta)

        if not is_bkg:
            table.meta.pop("backfile")
            table["BACKFILE"] = backfile

        return table

    @classmethod
    def read(cls, filename):
        """Read from file."""
        filename = make_path(filename)
        with fits.open(str(filename), memmap=False) as hdulist:
            return cls.from_hdulist(hdulist)

    @classmethod
    def from_hdulist(cls, hdulist):
        """Create from `~astropy.io.fits.HDUList`."""
        energy = ebounds_to_energy_axis(hdulist[2])
        kwargs = dict(energy_lo=energy[:-1], energy_hi=energy[1:])
        if hdulist[1].header["HDUCLAS2"] == "BKG":
            kwargs["is_bkg"] = True

        counts_table = Table.read(hdulist[1])
        speclist = cls()
        for row in counts_table:
            kwargs["data"] = row["COUNTS"]
            kwargs["backscal"] = row["BACKSCAL"]
            kwargs["quality"] = row["QUALITY"]
            kwargs["livetime"] = hdulist[1].header["EXPOSURE"] * u.s
            kwargs["obs_id"] = row["SPEC_NUM"]
            spec = PHACountsSpectrum(**kwargs)
            speclist.append(spec)

        return speclist

{'SherpaFloat': 'sherpa.utils.SherpaFloat', 'DataPHA': 'sherpa.astro.data.DataPHA'}


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('nutep', '0004_auto_20170403_1559'),
    ]

    operations = [
        migrations.CreateModel(
            name='Team',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=150, verbose_name=b'\xd0\x9d\xd0\xb0\xd0\xb8\xd0\xbc\xd0\xb5\xd0\xbd\xd0\xbe\xd0\xb2\xd0\xb0\xd0\xbd\xd0\xb8\xd0\xb5', db_index=True)),
                ('users', models.ManyToManyField(related_name='teams', to=settings.AUTH_USER_MODEL, blank=True)),
            ],
        ),
        migrations.AddField(
            model_name='contract',
            name='owner',
            field=models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True),
        ),
        migrations.AddField(
            model_name='line',
            name='owner',
            field=models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True),
        ),
        migrations.AddField(
            model_name='uploadedtemplate',
            name='owner',
            field=models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True),
        ),
        migrations.AddField(
            model_name='contract',
            name='teams',
            field=models.ManyToManyField(to='nutep.Team', blank=True),
        ),
        migrations.AddField(
            model_name='line',
            name='teams',
            field=models.ManyToManyField(to='nutep.Team', blank=True),
        ),
        migrations.AddField(
            model_name='uploadedtemplate',
            name='teams',
            field=models.ManyToManyField(to='nutep.Team', blank=True),
        ),
    ]


import logging
import requests

from requests import ConnectionError as RequestConnectionError, Session, Timeout, TooManyRedirects
from requests.adapters import HTTPAdapter

_logger = logging.getLogger(__name__)

_DEFAULT_RETRY = 3
_DEFAULT_TIMEOUT = 10

def request(files, retry=_DEFAULT_RETRY, timeout=_DEFAULT_TIMEOUT):
    if len(files) == 0:
        _logger.debug("No matches for HTTP requests")
        return []

    _logger.debug("Timeout for all HTTP requests is %i seconds", timeout)

    http_adaptor = HTTPAdapter(max_retries=retry)
    session = Session()

    for current_file in files:
        for current_url in current_file.urls:
            try:
                session.mount(current_url.url, http_adaptor)
                _logger.debug("Requesting status code for %s", current_url.url)
                current_url.status_code = requests.get(current_url.url, timeout=timeout).status_code
            except Timeout:
                _logger.debug("Waited for %i seconds, giving up getting %s", timeout, current_url.url)
                current_url.status_code = 0
            except TooManyRedirects:
                _logger.debug("Redirection Tango, danced enough with %s", current_url.url)
                current_url.status_code = 0
            except RequestConnectionError:
                _logger.debug("Connection Error occurred while getting %s", current_url.url)
                current_url.status_code = 0

    return files


import utils

def run(contract, methodIds, start_block, end_block):
    '''Detects potential Wash trades for a marketplace's contract'''

    transactions = utils.get_all_transactions(
        contract,
        start_block,
        end_block
    )

    wtd0_count, wtd1_cas, total = 0, [], 0

    for  tx in transactions:

        if tx['input'][:10] in methodIds:

            status, logs = utils.get_logs(tx['hash'])

            if status != 1: # Reverted transaction
                continue

            nft_contract, token_id, A, B = utils.parse_logs(logs)

            if A == None or B == None: # not a standard ERC721
                continue

            associates_A = utils.get_associates(A)
            associates_B = utils.get_associates(B)

            wtd0_count += int(
                utils.wtd0(A, B, associates_A, associates_B)
            )
            wtd1_cas.append(
                utils.wtd1(A, B, associates_A, associates_B)
            )

            total += 1

    return (wtd0_count, wtd1_cas, total)

WYVERN_V1 = '0x7Be8076f4EA4A4AD08075C2508e481d6C946D12b'

ranges = [
    [6652089, 6652239],
    [7486211, 7486311],
    [7704798, 7704898],
]

for start_block, end_block in ranges:

    print(run(WYVERN_V1, ['0xab834bab'], start_block, end_block))


import cv2 as cv
import numpy as np
import os

def resize_frame(frame, scale=0.75):
    return cv.resize(frame, (int(frame.shape[1] * scale), int(frame.shape[0] * scale)), interpolation=cv.INTER_AREA)

def rotate(img, angle, rot_point=None):
    (h, w) = img.shape[:2]

    if rot_point is None:
        rot_point = (w // 2, h // 2)

    rot_matrix = cv.getRotationMatrix2D(rot_point, angle, 1.0)

    return cv.warpAffine(img, rot_matrix, (w, h))

images = os.listdir("./animal_photos/")

cropped = cv.imread("./animal_photos/" + images[4])[350:-1000, 200:-200]
img = resize_frame(cropped, 0.21)

cv.imshow("eagle", img)

blank1 = np.zeros(img.shape[:2], dtype="uint8")

rectangle_mask = cv.rectangle(blank1, (img.shape[1] // 8, img.shape[0] // 8),
                              (img.shape[1] // 8 * 7, img.shape[0] // 8 * 7), 255, -1)

custom_mask = rectangle_mask

for i in range(30):
    custom_mask = cv.bitwise_or(custom_mask, rotate(custom_mask, 12))

cv.imshow("custom_masked", cv.bitwise_and(img, img, mask=custom_mask))

cv.waitKey(0)


from django.contrib import admin
from .models import Product, Photo, Tag, Category

class PhotoInline(admin.StackedInline):
    model = Photo

class TagInline(admin.TabularInline):
    model = Tag.product_set.through

class CategoryInline(admin.TabularInline):
    model = Category.product_set.through

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    inlines = [PhotoInline, TagInline, CategoryInline]

admin.site.register(Photo)
admin.site.register(Tag)
admin.site.register(Category)


import airflow
from airflow.example_dags.subdags.subdag import subdag
from airflow.models import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.subdag_operator import SubDagOperator
from subdag_1 import sub_dag_1
from subdag_2 import sub_dag_2

args = {
    'owner': 'Airflow',
    'start_date': airflow.utils.dates.days_ago(2),
}
main_dag = DAG(
    dag_id= 'lead_dag',
    default_args=args,
    schedule_interval="@once",
)
start = DummyOperator(
    task_id='start',
    dag=main_dag,
)

section_1 = SubDagOperator(
    task_id= 'child_dag1',
    subdag = sub_dag_1(main_dag.dag_id,'child_dag1',main_dag.schedule_interval),
    dag=main_dag,
)
section_2 = SubDagOperator(
    task_id= 'child_dag2',
    subdag = sub_dag_2(main_dag.dag_id,'child_dag2',main_dag.schedule_interval),
    dag=main_dag,
)

end = DummyOperator(
    task_id='end',
    dag=main_dag,
)
#dependencies
start >> section_1 >> section_2 >> end


import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from utils import weights_init

class convLSTMCell(nn.Module):
    def __init__(self, in_channels, in_feature_channels, out_feature_channels, kernel_size, stride = 1, padding = 0, dilation = 1, groups = 1, bias = True):
        super(convLSTMCell, self).__init__()
        self.out_feature_channels = out_feature_channels
        self.conv = nn.Conv2d(in_channels + in_feature_channels, 4 * out_feature_channels, kernel_size, stride, padding, dilation, groups, bias)
        self.apply(weights_init)

    def forward(self, x, hidden_states):
        hx, cx = hidden_states
        combined = torch.cat([x, hx], dim=1)
        A = self.conv(combined)
        (ai, af, ao, ag) = torch.split(A, self.out_feature_channels, dim = 1)#it should return 4 tensors
        i = F.sigmoid(ai)
        f = F.sigmoid(af)
        o = F.sigmoid(ao)
        g = F.tanh(ag)

        next_c = f * cx + i * g
        next_h = o * F.tanh(next_c)
        return next_h, next_c

class convLSTM(nn.Module):
    def __init__(self, in_channels, in_feature_channels, out_feature_channels):
        super(convLSTM, self).__init__()
        self.cell_1 = convLSTMCell(in_channels, in_feature_channels, out_feature_channels, 3, stride = 1, padding = 2, dilation = 2)
        self.cell_2 = convLSTMCell(in_channels, out_feature_channels, out_feature_channels, 5, stride = 1, padding = 2)
        self.cell_3 = convLSTMCell(in_channels, out_feature_channels, out_feature_channels, 3, stride = 1, padding = 1)
        # self.cell_4 = convLSTMCell(in_channels, feature_channels, 3, stride = 1, padding = 1)
        # self.cell_5 = convLSTMCell(in_channels, feature_channels, 5, stride = 1, padding = 4, dilation = 2)
        # self.cell_6 = convLSTMCell(in_channels, feature_channels, 5, stride = 1, padding = 2)
        self.softmax = nn.Softmax(dim=1)
        self.logsoftmax = nn.LogSoftmax(dim=1)
        self.apply(weights_init)

    def forward(self, x, hidden_states):
        hx, cx = hidden_states
        hx, cx = self.cell_1(x, (hx, cx))
        hx, cx = self.cell_2(x, (hx, cx))
        hx, cx = self.cell_3(x, (hx, cx))
        x = self.softmax(hx)
        y = self.logsoftmax(hx)

        # _x = F.avg_pool2d(x, kernel_size = 2, stride = 2)
        # hx = F.avg_pool2d(hx, kernel_size = 2, stride = 2)
        # cx = F.avg_pool2d(cx, kernel_size = 2, stride = 2)

        # hx, cx = self.cell_3(_x, (hx, cx))
        # hx, cx = self.cell_4(_x, (hx, cx))

        # hx = F.upsample(hx, scale_factor = 2, mode = 'bilinear', align_corners = True)
        # cx = F.upsample(cx, scale_factor = 2, mode = 'bilinear', align_corners = True)

        # hx, cx = self.cell_5(x, (hx, cx))
        # hx, cx = self.cell_6(x, (hx, cx))
        return x, cx, y

if __name__ == '__main__':
    net = convLSTM(3, 1)
    x = Variable(torch.zeros(1, 3, 256, 256))
    hx = Variable(torch.zeros(1, 1, 256, 256))
    cx = Variable(torch.zeros(1, 1, 256, 256))
    hx, cx = net(x, (hx, cx))
    print(hx.size(), cx.size())


import streamlit as st
import cv2
import speech_recognition as sr
import threading
import face_recognition
import pyaudio
import time

# Create a button to stop the webcam
stop_button = st.sidebar.button("Stop Webcam")

# Création d'un contrôle de valeur dans la barre latérale
temps = st.sidebar.slider("Sélectionnez un temps d'enregistrement en secondes", 0, 60, 5)

def detect_face(img):
    # Convertir l'image en RGB
    rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    # Détecter les visages dans l'image
    faces = face_recognition.face_locations(rgb, model='hog')

    # Pour chaque visage détecté, détecter l'âge, le genre et les émotions
    for (top, right, bottom, left) in faces:
        # Dessiner un rectangle autour du visage détecté
        cv2.rectangle(img, (left, top), (right, bottom), (255, 0, 0), 2)

    return img

def main():
    st.title("Contrôle de la caméra par commande vocale")

    # Initialiser l'enregistreur vocal
    CHUNK = 1024
    FORMAT = pyaudio.paInt16
    CHANNELS = 1
    RATE = 44100
    RECORD_SECONDS = 30
    p = pyaudio.PyAudio()

    while True:
        r = sr.Recognizer()
        with sr.Microphone() as source:
            st.write("Dites 'Démarrer' pour démarrer la caméra.")
            r.adjust_for_ambient_noise(source)
            audio = r.listen(source)
            try:
                text = r.recognize_google(audio, language='fr-FR')
                st.write("Vous avez dit : " + text)
                cap = cv2.VideoCapture(0) # 0 pour la webcam intégrée, 1 pour une webcam externe
                stframe = st.empty() # Créer un espace vide pour afficher l'image

                if "démarrer" in text.lower():
                    #st.write("Démarrage de la caméra...")
                    #cap = cv2.VideoCapture(0) # 0 pour la webcam intégrée, 1 pour une webcam externe
                    stframe = st.empty() # Créer un espace vide pour afficher l'image

                    cap.set(cv2.CAP_PROP_FPS, 60)
                    fourcc = cv2.VideoWriter_fourcc(*'MJPG')
                    cap.set(cv2.CAP_PROP_FOURCC, fourcc)
                    out = cv2.VideoWriter('record.avi',fourcc, 20.0, (640,480))

                    count = 0
                    while True:
                        count += 1
                        ret, frame = cap.read()
                        if ret:
                            frame = cv2.flip(frame, 1)

                            # Appeler la fonction de détection de visage dans un thread séparé seulement une image sur deux pour accélérer le traitement
                            #if count % 2 == 0:
                            thread = threading.Thread(target=detect_face, args=(frame))
                            thread.start() # Lancer le thread
                            thread.join() # Attendre la fin du thread pour continuer

                            # Afficher l'image dans Streamlit
                            stframe.image(frame, channels="BGR")
                            out.write(frame)

                        if cap.get(cv2.CAP_PROP_POS_MSEC) >= temps*1000:
                            st.write("Fin de l'enregistrement")
                            break
                        cap.release()
                        cv2.destroyAllWindows()
                else:
                    st.write("Commande non reconnue.")
                    break
            except sr.UnknownValueError:
                st.write("répète on comprend pas")

        if stop_button:
        # Stop the webcam video stream
            cap.release()

if __name__ == "__main__":
    main()


#!/usr/bin/env python3

import sys, os, argparse
from fastapi import FastAPI, Response, Path
from fastapi.testclient import TestClient
import uvicorn

try:
    from langfontfinder import LFF
except ImportError:
    sys.path.append(os.path.join(os.path.dirname(__file__), "..", "..", "lib"))
    from langfontfinder import LFF

version = "0.1"

datadir = os.getenv(
    "LFFPATH", os.path.join(os.path.dirname(__file__), "..", "..", "testdata")
)
rulesfile = os.getenv("LFFRULES", os.path.join(datadir, "fontrules.json"))
familiesfile = os.getenv("LFFFONTS", os.path.join(datadir, "families.json"))

# parser = argparse.ArgumentParser()
# parser.add_argument('-r','--rules',default=rulesfile,help='fontrules.json')
# parser.add_argument('-f','--fonts',default=familiesfile,help='families.json')
# args = parser.parse_args()

ruleset = LFF(rulesfile, familiesfile)

lffapp = FastAPI(version=version)

@lffapp.get("/lang/{ltag}", summary="lang/{ltag}", name="lang")
async def lang(response: Response, ltag: str = Path("", description="Language tag")):
    """ Given a language tag, returns font location information as json object. """
    res = ruleset.get(ltag)
    if res is None:
        response.status_code = 404
    return res

@lffapp.get("/family/{familyid}", summary="family/{familyid}", name="family")
async def family(response:Response, familyid: str = Path("", description="Font family id")):
    """ Given a familyid returns the font family json object. """
    res = ruleset.getfamily(familyid)
    if res is None:
        response.status_code = 404
    return res

@lffapp.get("/status")
async def status():
    res = {"version": version}
    return res

if __name__ == "__main__":
    uvicorn.run(lffapp)


from torch.utils import data
import torch
import torchvision
import torchvision.transforms as transforms
import pandas as pd
import os
from PIL import Image

class fathomnetDataLoader(data.Dataset):
    def __init__(self, root_image, label_path, is_train = True):
        super(fathomnetDataLoader, self).__init__()
        self.image_dir = root_image + "/train" if is_train else root_image + "/test"
        self.label_path = label_path
        self.is_train = is_train
        if is_train:
            self.transform =  transforms.Compose([
            transforms.RandomHorizontalFlip(),
            transforms.ToTensor(),
            torchvision.transforms.Resize((512, 512)),
            transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
             ])
        else:
            self.transform = transforms.Compose([
            transforms.ToTensor(),
            torchvision.transforms.Resize((512, 512)),
            transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
        ])

        if is_train:
            data_annotation = pd.read_csv(label_path)
            self.images = data_annotation['id']
            self.label = data_annotation['categories']
        else:
            self.images =[i[:-4] for i in os.listdir(self.image_dir)]
        self.num_classes = 133

    def __len__(self):
        return len(self.images)

    def __getitem__(self, idx):
        image_path = os.path.join(self.image_dir, self.images[idx] + ".png")
        image = Image.open(image_path).convert('RGB')
        image = self.transform(image)

        if self.is_train:
            label = [int(i) for i in self.label[idx][1:-1].split(',')]
            label_tensor = torch.zeros(self.num_classes)
            label_tensor[label] = 1
            return image, label_tensor
        else:
            return image, image_path

class FathomNetLoader(data.Dataset):
    def __init__(self, root='./datasets/train', annFile="./datasets/train.json", transform=None, target_transform=None):
        super().__init__()
        """
        Args:
            - root (string): Root dir where images are downloaded to
            - annFile (string): Path to json annotation file
            - transform (callable, optional): A function/transform that takes  in an PIL image and return a transformed version. E.g, `transforms.ToTensor()`
            - target_transform (callable, optional): takes in the target and transforms it
        """
        from pycocotools.coco import COCO
        self.root = root
        self.coco = COCO(annFile)
        self.n_classes = 290
        self.ids = list(self.coco.imgs.keys())
        self.transform = transform
        self.target_transform = target_transform
        self.split = self.root[-4:]

    def __getitem__(self, index):
        """
        Args:
            index (int): Index

        Returns:
            tuple: Tuple (image, target). target is the object returned by ``coco.loadAnns``.
        """
        coco = self.coco
        img_id = self.ids[index]
        if self.split == 'test':
            label = []
        else:
            ann_ids = coco.getAnnIds(imgIds=img_id)
            target = coco.loadAnns(ann_ids)[0]['category_id']
            target = int(target)

            label = torch.zeros(self.n_classes)
            label[target] = 1

        path = coco.loadImgs(img_id)[0]['file_name']

        img = Image.open(os.path.join(self.root, path)).convert('RGB')
        if self.transform is not None:
            img = self.transform(img)

        if self.target_transform is not None:
            label = self.target_transform(label)

        if self.split == 'eval':
            return img, path
        else:
            return img, label

    def __len__(self):
        return len(self.ids)

    def __repr__(self):
        fmt_str = 'Dataset ' + self.__class__.__name__ + '\n'
        fmt_str += '    Number of datapoints: {}\n'.format(self.__len__())
        fmt_str += '    Root Location: {}\n'.format(self.root)
        tmp = '    Transforms (if any): '
        fmt_str += '{0}{1}\n'.format(tmp, self.transform.__repr__().replace('\n', '\n' + ' ' * len(tmp)))
        tmp = '    Target Transforms (if any): '
        fmt_str += '{0}{1}'.format(tmp, self.target_transform.__repr__().replace('\n', '\n' + ' ' * len(tmp)))
        return fmt_str


import datetime

from pyalgotrade import bar
from pyalgotrade.barfeed import membf
from pyalgotrade import dataseries
from pyalgotrade.barfeed import csvfeed

# Example BarFeed for dataframes with data for a single instrument.
class DataFrameMulitpleBarFeed(membf.BarFeed):
    # @dataframes : Dict [key = instrument, value = df]
    # @instruments : key of Dict
    def __init__(self, dataframes, frequency,  timezone=None, maxLen=dataseries.DEFAULT_MAX_LEN):
        if isinstance(timezone, int):
            raise Exception("timezone as an int parameter is not supported anymore. Please use a pytz timezone instead.")

        if frequency not in [bar.Frequency.DAY, bar.Frequency.WEEK]:
            raise Exception("Invalid frequency.")

        membf.BarFeed.__init__(self, frequency, maxLen)
        #csvfeed.BarFeed.__init__(self, frequency, maxLen)
        self.__dfs = dataframes
        self.__instruments = dataframes.keys()
        self.__timezone = timezone
        self.__sanitizeBars = False
        self.__barFilter = None

    def getBarFilter(self):
        return self.__barFilter

    def setBarFilter(self, barFilter):
        self.__barFilter = barFilter

    def sanitizeBars(self, sanitize):
        self.__sanitizeBars = sanitize

    def barsHaveAdjClose(self):
        return True

    def addMultipleBars(self, timezone=None):
        if isinstance(timezone, int):
            raise Exception("timezone as an int parameter is not supported anymore. Please use a pytz timezone instead.")

        if timezone is None:
            timezone = self.__timezone

        for instrument in self.__instruments:
            # add one bars series into BarFeed
            self.addBarsFromSequence(instrument, self.newBasicBar(self.__dfs[instrument]))

    # put df data quotes into bar.BasicBars sequence
    # bars : sequence of bar.BasicBars
    def newBasicBar(self, df):
        bars = []
        for index in df.index :
            date = df["Date"][index]
            dateandtime = datetime.datetime(date.year, date.month, date.day)
            bars.append(bar.BasicBar(dateandtime,
                    df["Open"][index],
                    df["High"][index],
                    df["Low"][index],
                    df["Close"][index],
                    df["Volume"][index],
                    df["AdjClose"][index],
                    self.getFrequency()))
        return bars


from typing import List

import pytest
from llama_index.indices.managed.vectara.base import VectaraIndex
from llama_index.schema import Document

#
# For this test to run properly, please setup as follows:
# 1. Create a Vectara account: sign up at https://console.vectara.com/signup
# 2. Create a corpus in your Vectara account, with a "filter attribute" called "test_num".
# 3. Create an API_KEY for this corpus with permissions for query and indexing
# 4. Setup environment variables:
#    VECTARA_API_KEY, VECTARA_CORPUS_ID and VECTARA_CUSTOMER_ID
#

def get_docs() -> List[Document]:
    inputs = [
        {
            "text": "This is test text for Vectara integration with LlamaIndex",
            "metadata": {"test_num": "1"},
        },
        {
            "text": "And now for something completely different",
            "metadata": {"test_num": "2"},
        },
        {
            "text": "when 900 years you will be, look as good you will not",
            "metadata": {"test_num": "3"},
        },
        {
            "text": "when 850 years you will be, look as good you will not",
            "metadata": {"test_num": "4"},
        },
    ]
    docs: List[Document] = []
    for inp in inputs:
        doc = Document(
            text=str(inp["text"]),
            metadata=inp["metadata"],  # type: ignore
        )
        docs.append(doc)
    return docs

def remove_docs(index: VectaraIndex, ids: List) -> None:
    for id in ids:
        index._delete_doc(id)

def test_simple_retrieval() -> None:
    docs = get_docs()
    try:
        index = VectaraIndex.from_documents(docs)
    except ValueError:
        pytest.skip("Missing Vectara credentials, skipping test")

    assert isinstance(index, VectaraIndex)
    qe = index.as_retriever(similarity_top_k=1)
    res = qe.retrieve("how will I look?")
    assert len(res) == 1
    assert res[0].node.get_content() == docs[2].text

    remove_docs(index, index.doc_ids)

def test_mmr_retrieval() -> None:
    docs = get_docs()
    try:
        index = VectaraIndex.from_documents(docs)
    except ValueError:
        pytest.skip("Missing Vectara credentials, skipping test")

    assert isinstance(index, VectaraIndex)

    # test with diversity bias = 0
    qe = index.as_retriever(
        similarity_top_k=2,
        n_sentences_before=0,
        n_sentences_after=0,
        vectara_query_mode="mmr",
        mmr_k=10,
        mmr_diversity_bias=0.0,
    )
    res = qe.retrieve("how will I look?")
    assert len(res) == 2
    assert res[0].node.get_content() == docs[2].text
    assert res[1].node.get_content() == docs[3].text

    # test with diversity bias = 1
    qe = index.as_retriever(
        similarity_top_k=2,
        n_sentences_before=0,
        n_sentences_after=0,
        vectara_query_mode="mmr",
        mmr_k=10,
        mmr_diversity_bias=1.0,
    )
    res = qe.retrieve("how will I look?")
    assert len(res) == 2
    assert res[0].node.get_content() == docs[2].text
    assert res[1].node.get_content() == docs[0].text

    remove_docs(index, index.doc_ids)

def test_retrieval_with_filter() -> None:
    docs = get_docs()
    try:
        index = VectaraIndex.from_documents(docs)
    except ValueError:
        pytest.skip("Missing Vectara credentials, skipping test")

    assert isinstance(index, VectaraIndex)
    qe = index.as_retriever(similarity_top_k=1, filter="doc.test_num = '1'")
    res = qe.retrieve("how will I look?")
    assert len(res) == 1
    assert res[0].node.get_content() == docs[0].text

    remove_docs(index, index.doc_ids)

def test_file_upload() -> None:
    try:
        index = VectaraIndex()
    except ValueError:
        pytest.skip("Missing Vectara credentials, skipping test")

    file_path = "docs/examples/data/paul_graham/paul_graham_essay.txt"
    id = index.insert_file(file_path)

    assert isinstance(index, VectaraIndex)

    # test query with Vectara summarization (default)
    query_engine = index.as_query_engine(similarity_top_k=3)
    res = query_engine.query("What software did Paul Graham write?")
    assert "paul graham" in str(res).lower() and "software" in str(res).lower()

    # test query with VectorStoreQuery (using OpenAI for summarization)
    query_engine = index.as_query_engine(similarity_top_k=3, summary_enabled=False)
    res = query_engine.query("What software did Paul Graham write?")
    assert "paul graham" in str(res).lower() and "software" in str(res).lower()

    remove_docs(index, [id])


import curses
import json
import textwrap
from telegramData import *
from VSplit import *
from HSplit import *
from ContactList import *
from ChatWindow import *
from InputWindow import *
from curses import ascii

mWin=curses.initscr()
curses.noecho()
curses.cbreak()
mWin.keypad(True)
curses.start_color()

curses.init_pair(1,curses.COLOR_CYAN,curses.COLOR_BLACK)
curses.init_pair(2,curses.COLOR_GREEN,curses.COLOR_BLACK)

leftRight=VSplit(mWin,10,10)

topBottom=HSplit(leftRight.right,1,1)

cl=ContactList(leftRight.left)
cl.loadList(liste)
cl.redraw()

cw=ChatWindow(topBottom.top)
cw.loadChat(chat)
cw.redraw()

iw=InputWindow(topBottom.bottom)
iw.redraw()

def close(errorText=""):
	curses.nocbreak()
	mWin.keypad(False)
	curses.echo()
	curses.endwin()
	if(errorText != ""):
		print(errorText)
	exit()

inp=0;

while(True):
	inp=mWin.getch()

	if(inp==curses.KEY_UP):
		cl.prevContact()
	elif(inp==curses.KEY_DOWN):
		cl.nextContact()
	elif(inp==curses.KEY_RESIZE):
		if(not leftRight.refresh()):
			close("error: window too small")
		if(not topBottom.refresh()):
			close("error: window to small")
		cw.redraw()
		cl.redraw()
		iw.redraw()
	elif(iw.processInput(inp)):
		iw.redraw()
	else:
		break
	if(not leftRight.refresh()):
		close("error: window too small")
	if(not topBottom.refresh()):
		close("error: window to small")
	mWin.refresh()

close(str(inp))


import fasttext
import pandas as pd, numpy as np
from sklearn.metrics import accuracy_score, precision_score
from sklearn.model_selection import train_test_split
'''
train = pd.read_csv('../data/train_set.csv')
test = pd.read_csv('../data/test_set.csv')

def func(x):
    return x.word_seg + " __label__" + str(x['class'])

train['word_seg'] = train.apply(func, axis = 1)

Y = train['class'].values
#fasttext_train = train.loc[:, ['word_seg']]

X_train, X_val, Y_train, Y_val = train_test_split(train, Y, test_size = 0.2)
fasttext_train = X_train.loc[:, ['word_seg']]
fasttext_val = X_val.loc[:, ['word_seg']]

fasttext_train.to_csv('tuning/fasttext_trainset.txt', index = None, header = None)
'''

clf = fasttext.supervised(input_file = 'tuning/fasttext_trainset.txt', output = 'tuning/fasttext_model', label_prefix = '__label__',
                         bucket = 2000000, word_ngrams = 1, ws = 20, epoch=40, silent = 0)

train_data = X_train.word_seg.values.tolist()
val_data = X_val.word_seg.values.tolist()

res = clf.predict(train_data)
y_pred = []
for i in res:
    y_pred.append(int(i[0]))
train_acc = accuracy_score(Y_train, y_pred)

res = clf.predict(val_data)
y_pred = []
for i in res:
    y_pred.append(int(i[0]))
val_acc = accuracy_score(Y_val, y_pred)

print(train_acc, val_acc)

clf = fasttext.supervised(input_file = 'fasttext_trainset.txt', output = 'fasttext_model', label_prefix = '__label__',
                         bucket = 2000000, word_ngrams = 2, ws = 20, epoch=40, silent = 0)

#test_data = test.word_seg.values.tolist()
test = pd.read_csv('../data/test_set.csv')
test_data = test.word_seg.values.tolist()

res = clf.predict(test_data)
y_pred = []
for i in res:
    y_pred.append(int(i[0]))

test_pred = pd.DataFrame(columns = ['id', 'class'])
test_pred.id = test.id.values
test_pred['class'] = (y_pred)
test_pred.to_csv('../sub/sub_fasttext_baseline.csv',index=None)


from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse

bot_router = APIRouter()
from config.settings import templates
from config.logger import logging

@bot_router.get("/policy", response_class=HTMLResponse)
async def add_user_workouts(request: Request):
    # logging.debug(f"Что в запросе? {await request.body()}")
    return templates.TemplateResponse(
        name="policy.html",
        context={"request": request}
    )

@bot_router.get("/")
async def root():
    return {"message": "Hello World"}


from datetime import datetime, timedelta
from cs50 import SQL

grades_dict = {
    "9MWF": "Class 9 MWF",
    "9TTS": "Class 9 TTS",
    "9MOR": "Isucceed Achievers 6 AM",
    "10TTS": "Class 10-Diligent Squad",
    "11MWF": "Class 11",
    "12MWF": "Class 12",
    "12AM": "Class 12 AM",
    "diya": "Diya",
    "neel": "Neel",
    "sakshi": "Sakshi",
    "vedant": "Vedant",
    "dhiya": "Dhiya",
}
database = "homework.db"
name = "Bhawna Teacher"

def process_time(time_str):
    try:
        time_obj = datetime.strptime(time_str, "%H:%M")
        formatted_time = time_obj.strftime("%I:%M %p")
        return formatted_time
    except:
        pass
    return "None"

def process_date(date_str):
    try:
        date_obj = datetime.strptime(date_str, "%Y-%m-%d")
        formatted_date = date_obj.strftime("%d %B %Y")
        return formatted_date
    except:
        pass
    return "None"

def process_text(text):
    text = str(text)
    text = text.replace("<", "<")
    text = text.replace(">", ">")
    text = text.replace("&", "&lamp;")
    text = text.replace("\"", """)
    text = text.replace("\'", "'")

    return text

def process_homework(assignments):
    for assignment in assignments:
        assignment["grade"] = grades_dict[assignment["grade"]]
        assignment["date_given"] = process_date(assignment["date_given"])
        assignment["due_date"] = process_date(assignment["due_date"])

        assignment["title"] = process_text(assignment["title"])
        assignment["description"] = process_text(assignment["description"])
    return assignments

def process_exams(exams):
    for exam in exams:
        exam["grade"] = grades_dict[exam["grade"]]
        exam["exam_time"] = process_time(exam["exam_time"])
        exam["exam_date"] = process_date(exam["exam_date"])

        exam["title"] = process_text(exam["title"])
        exam["portion"] = process_text(exam["portion"])
    return exams

def process_outline(outlines):
    for outline in outlines:
        outline["grade"] = grades_dict[outline["grade"]]
        outline["class_date"] = process_date(outline["class_date"])
        outline["time"] = process_time(outline["time"])

        outline["title"] = process_text(outline["title"])
        outline["description"] = process_text(outline["description"])
    return outlines

def process_timetable(timetables):
    for timetable in timetables:
        try:
            timetable["grade"] = grades_dict[timetable["grade"]]
        except Exception:
            pass
        timetable["class_date"] = process_date(timetable["class_date"])
        timetable["start_time"] = process_time(timetable["start_time"])
        timetable["end_time"] = process_time(timetable["end_time"])

        timetable["grade"] = process_text(timetable["grade"])
        timetable["description"] = process_text(timetable["description"])
    return timetables

def process_worksheet(worksheets):
    for worksheet in worksheets:
        worksheet["grade"] = grades_dict[worksheet["grade"]]
        worksheet["given_date"] = process_date(worksheet["given_date"])

        worksheet["title"] = process_text(worksheet["title"])
        worksheet["publication"] = process_text(worksheet["publication"])
        worksheet["notes"] = process_text(worksheet["notes"])
    return worksheets

def process_guest(guest_lecture):
    for guest in guest_lecture:
        guest["grade"] = grades_dict[guest["grade"]]
        guest["date_given"] = process_date(guest["date_given"])

        guest["title"] = process_text(guest["title"])
        guest["description"] = process_text(guest["description"])
    return guest_lecture

def format_homework(id):
    db = SQL(f"sqlite:///{database}")
    assignments = db.execute("SELECT * FROM homework WHERE homework_id = ? ", id)
    assignments = process_homework(assignments)
    assignment = assignments[0]
    title = "Homework Schedule"
    schedule = f'Isucceed Coaching Class-Homework Schedule\nTitle: {assignment["title"]}\nClass: {assignment["grade"]}\nSubject: {assignment["subject"]}\nDescription: {assignment["description"]}\nDue Date: {assignment["due_date"]}\n{name}'
    return (title, schedule)

def format_exam(id):
    db = SQL(f"sqlite:///{database}")
    exams = db.execute("SELECT * FROM exam WHERE exam_id = ?", id)
    exams = process_exams(exams)
    exam = exams[0]
    title = "Exam Schedule"
    schedule = f'Isucceed Coaching Class-Exam Schedule\nTitle: {exam["title"]}\nClass: {exam["grade"]}\nSubject: {exam["subject"]}\nPortion: {exam["portion"]}\nDate: {exam["exam_date"]}\nTime: {exam["exam_time"]}\nMarks: {exam["marks"]}\n{name}'
    return (title, schedule)

def format_outline(id):
    db = SQL(f"sqlite:///{database}")
    outlines = db.execute("SELECT * FROM outline WHERE outline_id = ?", id)
    outlines = process_outline(outlines)
    outline = outlines[0]
    title = "Class Outline"
    schedule = f'Isucceed Coaching Class-Class Outline\nTitle: {outline["title"]}\nClass: {outline["grade"]}Time: {outline["time"]}\nSubject: {outline["subject"]}\nDescription: {outline["description"]}\nDate: {outline["class_date"]}\n{name}'
    return (title, schedule)

def format_timetable(id):
    db = SQL(f"sqlite:///{database}")
    timetables = db.execute("SELECT * FROM timetable WHERE timetable_id = ?", id)
    timetables = process_timetable(timetables)
    timetable = timetables[0]
    title = "Class Schedule"
    schedule = f'Isucceed Coaching Class-Class Schedule\nClass: {timetable["grade"]}\nSubject: {timetable["subject"]}\nDate: {timetable["class_date"]}\nTime: {timetable["start_time"]} - {timetable["end_time"]}\n{name}'
    return (title, schedule)

def format_worksheet(id):
    db = SQL(f"sqlite:///{database}")
    worksheets = db.execute("SELECT * FROM worksheet WHERE worksheet_id = ?", id)
    worksheets = process_worksheet(worksheets)
    worksheet = worksheets[0]
    title = "Worksheet Issued"
    schedule = f'Isucceed Coaching Class-Worksheet Record Schedule\nTitle: {worksheet["title"]}\nClass: {worksheet["grade"]}\nSubject: {worksheet["subject"]}\nDate: {worksheet["given_date"]}\nCopies: {worksheet["copies"]}\nNotes: {worksheet["notes"]}\n{name}'
    return (title, schedule)

def format_guest(id):
    db = SQL(f"sqlite:///{database}")
    guests = db.execute("SELECT * FROM guest WHERE guest_id = ?", id)
    guests = process_guest(guests)
    guest = guests[0]
    title = "Guest Lecture"
    schedule = f'Isucceed Coaching Class-Guest Lecture\nTitle: {guest["title"]}\nClass: {guest["grade"]}\nSubject: {guest["subject"]}\nDate: {guest["date_given"]}\nDuration: {guest["duration"]}\nDescription: {guest["description"]}\n{name}'
    return (title, schedule)

def homework_from_session(session):
    db = SQL(f"sqlite:///{database}")
    if session[0] == "G":
        assignments = db.execute("SELECT * FROM homework WHERE grade = ? ORDER BY due_date DESC", session.removeprefix("GH"))
    if session[0] == "D":
        assignments = db.execute("SELECT * FROM homework WHERE due_date = ? ORDER BY grade", session.removeprefix("DH"))
    if session[0] == "A":
        assignments = db.execute("SELECT * FROM homework ORDER BY due_date DESC")

    assignments = process_homework(assignments)

    return assignments

def exam_from_session(session):
    db = SQL(f"sqlite:///{database}")
    if session[0] == "G":
        exams = db.execute("SELECT * FROM exam WHERE grade = ? ORDER BY exam_date DESC", session.removeprefix("GE"))
    if session[0] == "D":
        exams = db.execute("SELECT * FROM exam WHERE exam_date = ? ORDER BY grade", session.removeprefix("DE"))
    if session[0] == "A":
        exams = db.execute("SELECT * FROM exam ORDER BY exam_date DESC")

    exams = process_exams(exams)

    return exams

def outline_from_session(session):
    db = SQL(f"sqlite:///{database}")
    if session[0] == "G":
        outlines = db.execute("SELECT * FROM outline WHERE grade = ? ORDER BY class_date DESC", session.removeprefix("GO"))
    if session[0] == "D":
        outlines = db.execute("SELECT * FROM outline WHERE class_date = ? ORDER BY grade", session.removeprefix("DO"))
    if session[0] == "A":
        outlines = db.execute("SELECT * FROM outline ORDER BY class_date DESC")

    outlines = process_outline(outlines)

    return outlines

def timetable_from_session(session):
    db = SQL(f"sqlite:///{database}")
    if session[0] == "G":
        timetables = db.execute("SELECT * FROM timetable WHERE grade = ? ORDER BY class_date DESC", session.removeprefix("GT"))
    if session[0] == "D":
        timetables = db.execute("SELECT * FROM timetable WHERE class_date = ? ORDER BY start_time", session.removeprefix("DT"))
    if session[0] == "A":
        timetables = db.execute("SELECT * FROM timetable ORDER BY class_date DESC, start_time")

    timetables = process_timetable(timetables)

    return timetables

def worksheet_from_session(session):
    db = SQL(f"sqlite:///{database}")
    if session[0] == "G":
        worksheets = db.execute("SELECT * FROM worksheet WHERE grade = ? ORDER BY given_date", session.removeprefix("GW"))
    if session[0] == "D":
        worksheets = db.execute("SELECT * FROM worksheet WHERE given_date = ? ORDER BY grade", session.removeprefix("DW"))
    if session[0] == "A":
        worksheets = db.execute("SELECT * FROM worksheet ORDER BY given_date")

    worksheets = process_worksheet(worksheets)

    return worksheets

def guest_from_session(session):
    db = SQL(f"sqlite:///{database}")
    if session[0] == "G":
        guests = db.execute("SELECT * FROM guest WHERE grade = ? ORDER BY date_given DESC", session.removeprefix("GL"))
    if session[0] == "D":
        guests = db.execute("SELECT * FROM guest WHERE class_date = ? ORDER BY grade", session.removeprefix("DL"))
    if session[0] == "A":
        guests = db.execute("SELECT * FROM guest ORDER BY date_given DESC")

    guests = process_guest(guests)

    return guests

def add_timedelta_to_time(time, delta):
    datetime_time = datetime.strptime(time, "%H:%M")
    time_delta = timedelta(minutes=delta)

    new_time = datetime_time + time_delta
    result = new_time.strftime("%H:%M")

    return result


import time
import numpy_financial as npf
import numpy as np
import warnings
import string
import matplotlib.pyplot as mp

class SavingEvaluate(object):
    def __init__(self):
        self.all_charts = string.punctuation + string.whitespace
        warnings.filterwarnings('ignore', category=DeprecationWarning)
        warnings.filterwarnings('ignore', category=RuntimeWarning)

        self.saving_year = 0
        self.rate = 0
        self.pmt = 0
        self.first_deposit = 0

    def future_value(self):
        future_value = npf.fv(self.rate, self.saving_year, -self.pmt, -self.first_deposit)
        future_net_income = np.round((future_value-self.first_deposit-(self.saving_year*self.pmt)), 1)
        print('以每年 %d 元投資%.2f%%年利率，%d 年後可領回: \033[1;30;43m %d \033[0m 元'
              % (self.pmt, self.rate*100, self.saving_year, int(future_value)))
        print('總淨利為: \033[1;30;43m%.1f \033[0m 元' % future_net_income)

        money = self.first_deposit
        fvs = [self.first_deposit]
        for i in range(1, self.saving_year+1):
            money += money*self.rate + self.pmt
            fvs.append(money)

        mp.figure('Future Value', facecolor='lightgray')
        mp.title('Future Value', fontsize=24)
        mp.xlabel('Year', fontsize=20)
        mp.ylabel('Money', fontsize=20)
        mp.grid(":")
        mp.tick_params(labelsize=12)
        mp.plot(fvs, 'o-', label='Cash Flows')
        for x, y in zip(range(self.saving_year+1), fvs):
            mp.text(x+0.1, y+30, '%.3f' % y, ha='center', va='bottom', fontsize=13)
        mp.legend(loc='upper left', fontsize= 14)
        mp.show()

    def irr(self, nwp):
        cash_flows = [-self.first_deposit]
        for i in range(self.saving_year):
            cash_flows.append(nwp)
        solution = npf.irr(cash_flows) * 100

        money = self.first_deposit
        irrs = [self.first_deposit]
        for i in range(1, self.saving_year+1):
            money += money*self.rate - nwp
            irrs.append(money)

        irr_net_income = np.round(irrs[-1]-(self.first_deposit - nwp*self.saving_year), 1)

        print("依照您輸入的相關數據，本存錢方案的 IRR 為 : \033[1;30;43m %.3f%% \033[0m 元" % solution)
        print('最後可領回 : \033[1;30;43m %.3f \033[0m 元' % irrs[-1])
        print('總淨利為: \033[1;30;43m%.1f \033[0m 元' % irr_net_income)

        mp.figure('IRR', facecolor='lightgray')
        mp.title('IRR', fontsize=24)
        mp.xlabel('Year', fontsize=20)
        mp.ylabel('Money', fontsize=20)
        mp.grid(":")
        mp.tick_params(labelsize=12)
        mp.plot(irrs, 'o-', label='Cash Flows')
        for x, y in zip(range(self.saving_year+1), irrs):
            mp.text(x+0.1, y, '%.3f' % y, ha='center', va='bottom', fontsize=13)
        mp.legend(loc='upper right', fontsize=14)
        mp.show()

    def pay_all_at_once(self):
        all_in = npf.fv(self.rate, self.saving_year, 0, -self.first_deposit)
        all_in_net_income = np.round(all_in-self.first_deposit, 3)
        print('以每年 %d 元投資%.2f%%年利率，%d 年後可領回: \033[1;30;43m %.3f \033[0m 元'
              % (self.pmt, self.rate*100, self.saving_year, all_in))
        print('總淨利為: \033[1;30;43m%.3f \033[0m 元' % all_in_net_income)

        money = self.first_deposit
        plio = [self.first_deposit]
        for i in range(1, self.saving_year+1):
            money += money*self.rate
            plio.append(money)

        mp.figure('Pay All', facecolor='lightgray')
        mp.title('Pay All', fontsize=24)
        mp.xlabel('Year', fontsize=20)
        mp.ylabel('Money', fontsize=20)
        mp.grid(":")
        mp.tick_params(labelsize=12)

        mp.plot(plio, 'o-', label='Cash Flows')
        for x, y in zip(range(self.saving_year+1), plio):
            mp.text(x+0.1, y, '%.3f' % y, ha='center', va='bottom', fontsize=13)
        mp.legend(loc='upper left', fontsize=14)
        mp.show()

    def present_value(self, money, future_value):
        present_value = npf.pv(self.rate, self.saving_year, -money, future_value)
        print("如果要拿回 %d 元，%.2f%%年利率, 為期%d年。" % (future_value, self.rate*100, self.saving_year))
        print('須先始存:\033[1;30;43m %d \033[0m 元。' % abs(np.floor(present_value)))

    def start(self):
        while True:
            username = input('請輸入您的名字: ')
            for i in username:
                if i in self.all_charts:
                    print('請輸入有效名字。')
                    continue
            if username.isalpha() is True:
                print('有效名字 :%s，您好!' % username)
                time.sleep(1)
                break
        while True:
            try:
                plan = int(input('請選擇存錢方案\n'
                                 '【1】年初存一筆，各按年底存入\n'
                                 '【2】年初存一筆，各按年底提領\n'
                                 '【3】整付整存 \n'
                                 '【4】想知道設定的存錢年底到期後可領回共多少，年初須存入之金額 \n: '))
            except ValueError as e:
                print('請輸入1~4的數字，非文字或其他。\n')
                continue
            else:
                if 1 <= plan <= 4:
                    self.saving_year = int(input("請輸入存錢總年期數： "))
                    if self.saving_year < 1:
                        print('存錢總年期數須大於1年。\n')
                        continue
                    self.rate = float(input("請輸入欲查詢的年利率(大於或是等於1)： ")) / 100
                    print('\n您好:%s，您選擇【%d】方式。為期 %d年 存錢方案，%.2f%% 年利率。' % (username, plan, self.saving_year, self.rate*100))

                    if plan == 1:
                        self.first_deposit = int(input("請輸入期初存入金額： "))
                        self.pmt = int(input("請輸入各按年存入金額： "))
                        cash_flows = [-self.first_deposit]
                        for i in range(self.saving_year):
                            cash_flows.append(self.pmt)
                        self.future_value()
                    elif plan == 2:
                        self.first_deposit = int(input("請輸入期初存入金額： "))
                        nwp = int(input("請輸入各按年提領金額： "))
                        self.irr(nwp)
                    elif plan == 3:
                        self.first_deposit = int(input("請輸入一次性存入金額： "))
                        self.pay_all_at_once()
                    elif plan == 4:
                        future_value = int(input("請輸入最後想領回金額： "))
                        money = int(input("請輸入各按年存入金額： "))
                        self.present_value(money, future_value)
                    break

if __name__ == "__main__":
    run = SavingEvaluate()
    ask = input('您好，歡迎進入存錢方案: 1)進入選擇 2)退出 ')
    if ask == '1':
        run.start()


#!/usr/bin/env python
import _strptime
from github import Github
from github.GithubException import UnknownObjectException
import os
import sys
import traceback
import time

MAX_PR_WALKING=int(os.environ.get('MAX_PR_WALKING', '5'))

print('Running {}'.format(' '.join(sys.argv)))

github = Github(os.environ['GITHUB_OAUTH_USER'], os.environ['GITHUB_OAUTH_TOKEN'])
repo = github.get_repo(os.environ['TRAVIS_REPO_SLUG'])

release_name = os.environ['PROJECT_VERSION']
release_tag = 'v' + release_name
release_body = os.environ['TRAVIS_COMMIT_MESSAGE']
commit_id = os.environ['TRAVIS_COMMIT']

draft_release = os.environ.get('GITHUB_DRAFT_RELEASE', '0')
pre_release = os.environ.get('GITHUB_PRERELEASE', '1')

is_draft_release = draft_release == '1' or draft_release.lower() == 'true'
is_prerelease = pre_release == '1' or pre_release.lower() == 'true'

print('release_tag={}, commit_id={}'.format(release_tag, commit_id))

pr = None

pr_number = os.environ.get('TRAVIS_PULL_REQUEST', 'false')
if pr_number and pr_number != 'false':
    try:
        pr = repo.get_pull(int(pr_number))
    except ValueError:
        pass

def find_pr():
    all_pulls = [pr for pr in repo.get_pulls(state='closed', sort='updated')]
    all_pulls.reverse()
    for index, merged_pr in enumerate(all_pulls):
        if index >= MAX_PR_WALKING:
            break
        if merged_pr.merge_commit_sha == commit_id:
            return merged_pr
    return None

if not pr:
    retry = 0
    while not pr and retry < 5:
        time.sleep(retry * 10)
        try:
            pr = find_pr()
            break
        except:
            traceback.print_exc()
            retry += 1

if pr:
    release_body='''## {}
{}

### Commit message:
```
{}
```
'''.format(pr.title, pr.body, release_body)

release = None
try:
    release = repo.get_release(release_tag)
except UnknownObjectException:
    release = repo.create_git_release(release_tag, release_name, release_body, draft=is_draft_release, prerelease=is_prerelease, target_commitish=commit_id)

print('Release created/updated: ' + release_tag)
for asset in sys.argv[1:]:
    print(' - deploying asset: ' + asset)
    release.upload_asset(asset)


#精装
from common.myunit import StartEnd
from businessView.hardcover import Hardcover
import unittest
import logging

class TestHardcover(StartEnd):
    # @unittest.skip('test_todayrecomend')
    def test_todayrecomend(self):
        logging.info('======test_todayrecomend=====')
        h = Hardcover(self.driver)
        try:
            self.assertTrue(h.todayrecomend())
        except BaseException as error:
            self.add_img()
            raise error

    # @unittest.skip('test_heavyfine')
    def test_heavyfine(self):
        logging.info('======test_heavyfine=====')
        h = Hardcover(self.driver)
        try:
            self.assertTrue(h.heavyfine())
        except BaseException as error:
            self.add_img()
            raise error

    # @unittest.skip('test_newalbum')
    def test_newalbum(self):
        logging.info('======test_newalbum=====')
        h = Hardcover(self.driver)
        try:
            self.assertTrue(h.newalbum())
        except BaseException as error:
            self.add_img()
            raise error

    # @unittest.skip('test_buyalbums')
    def test_buyalbums(self):
        logging.info('======test_buyalbums=====')
        h = Hardcover(self.driver)
        try:
            self.assertTrue(h.buyalbums())
        except BaseException as error:
            self.add_img()
            raise error

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


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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy.exceptions import DropItem
import re

class ListExtractionPipeline(object):
    def process_item(self, item, spider):
        for key in item.keys():
            if (item[key]):
                if (type(item[key]) is list):
                    length = len(item[key])
                    if (length > 0):
                        if key not in item.__class__.LIST_KEYS:
                            item[key] = item[key][0]
                        spider.crawler.stats.inc_value(key + '_list_len_' + str(length))
                    else:
                        item[key] = None
                        spider.crawler.stats.inc_value(key + '_empty_list')
                else:
                    spider.crawler.stats.inc_value(key + '_not_list')
            else:
                item[key] = None
                spider.crawler.stats.inc_value(key + '_no_value')
        return item

class NamePipeline(object):
    def process_item(self, item, spider):
        if (item['name'] is None):
            raise DropItem("Missing name")
        return item

class SeenNamePipeline(object):
    def __init__(self):
        self.name_seen = set()

    def process_item(self, item, spider):
        if (item['name'] in self.name_seen):
            raise DropItem("Duplicate name %s" % item)
        self.name_seen.add(item['name'])
        return item

class TelephoneSanitizePipeline(object):
    def process_item(self, item, spider):
        item = self.helper(item, 'telephone', spider)
        item = self.helper(item, 'fax', spider)
        return item

    def helper(self, item, field, spider):
        if (field in item) and (item[field] is not None):
            telephone = item[field]
            phone_list = telephone.split(',')
            if len(phone_list) == 1:
                phone_list = phone_list[0].split('/')
            phone_result = []
            for phone in phone_list:
                phone = phone.replace('(852)', '')
                phone = phone.replace('852-', '')
                phone = re.sub(r"\D", "", phone)
                if len(phone) != 8:
                    spider.crawler.stats.inc_value('invalid_' + field)
                phone_result.append(phone)
            item[field] = phone_result
        return item


import ansidocs.main as ansidocs
import argparse
from os import path
import logging

logger = logging.getLogger(__name__)

def parseArgs():
    parser = argparse.ArgumentParser()
    parser.add_argument('--verbose', '-v', dest="verbose", action='count', default=0,
                        help="Increase program verbosity, use multiple 'v' for more logging")
    parser.add_argument('--quiet', '-q', dest="quiet", action='store_true',
                        help="Only display errors")

    parser.add_argument("-c", "--config-dir", dest="config_dir",
                        help="Path to the config dir",
                        default=path.join(path.expanduser('~'), '.ansidocs'))

    subparsers = parser.add_subparsers(title='subcommands',
                                       description='valid subcommands',
                                       help='additional help')
    gen_parser = subparsers.add_parser("generate", aliases=["gen"], help="Generate or update an existing readme")
    gen_parser.add_argument("-d", "--directory", dest="directory", default=".",
                            help="Directory where readme should be generated")
    gen_parser.add_argument("-l", "--layout", dest="force_layout", required=False,
                            help="Force a layout for the project specified. Default is to let the program auto " +
                            "determine the layout")

    test_parser = subparsers.add_parser("test", help="Test if the existing readme matches the expected readme")

    conf_parser = subparsers.add_parser("config", help="Create or refresh your config directory")
    conf_parser.add_argument("-r", "--refresh-configs", dest="refresh_configs",
                             help="If flag is set, config dir will be removed and recreated with defaults",
                             action='store_true')

    gen_parser.set_defaults(func=gen)
    conf_parser.set_defaults(func=conf)
    test_parser.set_defaults(func=test)

    return parser.parse_args()

def determine_log_level(verbose: int, starting_level: str = "WARNING"):
    # https://docs.python.org/3/library/logging.html#levels
    verbose_level_int = verbose * 10
    calculated_level = logging.getLevelName(starting_level) - verbose_level_int
    if calculated_level < 10:
        calculated_level = 10   # this is the minimum we support, debug
    return logging.getLevelName(calculated_level)

def main():
    args = parseArgs()
    if args.quiet:
        # override any other logging configs
        logging.basicConfig(level=logging.ERROR)
    args.func(args)

def gen(args):
    logging.basicConfig(level=determine_log_level(args.verbose))
    ansidocs.generate(
        directory=args.directory,
        config_dir=args.config_dir,
        force_layout=args.force_layout
    )

def conf(args):
    logging.basicConfig(level=determine_log_level(args.verbose, starting_level="INFO"))
    ansidocs.init_config_dir(
        config_dir=args.config_dir,
        refresh_configs=args.refresh_configs
    )

def test():
    pass


import matplotlib.pyplot as plt
import numpy as np
# fractions实现输出分数显示
from fractions import Fraction

def my_sum(*args):
    """求和"""
    result = 0
    for x in args:
        result += x
    return result

def my_power(x, n):
    """计算幂"""
    y = 1
    if type(n) is int:
        if n > 0:
            for i in range(n):
                y = y * x
            return y
        elif n == 0:
            return 1
        else:
            for i in range(-n):
                y = y * x
            return Fraction(1, y)
    else:
        print('ValueError!')

def my_sin(num):
    """绘制正弦函数图像"""
    x = np.linspace(0, 2 * np.pi)
    plt.plot(np.sin(num * x))
    plt.show()

def my_equal():
    """绘制饼图"""
    # test
    # a = [16065, 4998, 2802, 1484, 1076]
    # b = ["income", "traffic", "eat", "shopping", "live"]
    dataList = []
    dataLabel = []

    for i in range(3):
        dataLabel.append(input('way{}:'.format(i + 1)))
        dataList.append(int(input('money:')))

    plt.rcParams['font.sans-serif'] = ['KaiTi']  # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

    plt.figure()
    plt.pie(dataList, labels=dataLabel, colors=["r", "y", "g", "b", "c", "m"], autopct="%1.2f%%")
    # 显示图例
    plt.legend()
    plt.title("年度消费\n总计：{}".format(np.sum(dataList)))
    # 将当前的图形变成圆形，默认为椭圆
    plt.axis("equal")

    plt.show()


from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from django.core.mail import EmailMessage
from django.utils.translation import ugettext_lazy as _
from django.template.loader import get_template, render_to_string
from django.template import Context
from django_extensions.db.models import TimeStampedModel
from django.conf import settings
from object_permissions.models import ObjectPermission
import django_filters

class ProjectManager(models.Manager):
    def for_user(self, user):
        '''
        Returns queryset with projects that user can_view (in case of admin - all projects)
        '''
        qs = self.get_query_set()
        if not user.is_superuser:
            qs = self.get_query_set().filter(permissions__user=user,permissions__can_view=True)
        return qs

class Project(TimeStampedModel):
    name = models.CharField(max_length=50, verbose_name=_('name'))
    description = models.TextField(verbose_name=_('description'))
    repository_path = models.CharField(max_length=300, null=True, blank=True, verbose_name=_('repository path'), help_text=_('Enter local, absolute Mercurial repository path'))
    # reverse generic relation - for convenience
    permissions = generic.GenericRelation(ObjectPermission, verbose_name=_('permissions'))
    objects = ProjectManager()

    class Meta:
        verbose_name = _('project')
        verbose_name_plural = _('projects')

    def __unicode__(self):
        return unicode(self.name)

    @models.permalink
    def get_absolute_url(self):
        return ('project_detail_url', (), {'object_id': self.pk})

class Version(TimeStampedModel):
    name = models.CharField(max_length=50, verbose_name=_('name'))
    start_date = models.DateTimeField(verbose_name=_('start date'))
    due_date = models.DateTimeField(verbose_name=_('deadline'))
    is_closed = models.BooleanField(default=False, verbose_name=_('is closed?'))
    project = models.ForeignKey(Project)

    class Meta:
        verbose_name = _('version')
        verbose_name_plural = _('versions')

    def __unicode__(self):
        return unicode(self.name)

class Status(TimeStampedModel):
    name = models.CharField(max_length=50, verbose_name=_('name'))
    is_closed = models.BooleanField(default=False, verbose_name=_('is closed?'))

    def __unicode__(self):
        return unicode(self.name)

    class Meta:
        verbose_name = _('status')
        verbose_name_plural = _('statuses')

class Priority(models.Model):
    name = models.CharField(max_length=50, verbose_name=_('name'))
    value = models.SmallIntegerField(verbose_name=_('value'))

    def __unicode__(self):
        return unicode(self.name)

    class Meta:
        verbose_name = _('priority')
        verbose_name_plural = _('priorities')

class Category(models.Model):
    name = models.CharField(max_length=100, verbose_name=_('name'))

    class Meta:
        verbose_name = _('category')
        verbose_name_plural = _('categories')

    def __unicode__(self):
        return unicode(self.name)

class Ticket(TimeStampedModel):
    title = models.CharField(max_length=300, verbose_name=_('title'))
    description = models.TextField(verbose_name=_('description'))
    version = models.ForeignKey(Version,blank=True,null=True)
    status = models.ForeignKey(Status,blank=True,null=True)
    priority = models.ForeignKey(Priority,blank=True,null=True)
    project = models.ForeignKey(Project)
    author = models.ForeignKey(User, related_name="created_tickets")
    workers = models.ManyToManyField(User, related_name=_("tickets"),blank=True)
    related = models.ManyToManyField("self",through="RelatedTickets",symmetrical=False,blank=True)
    category = models.ForeignKey(Category,blank=True,null=True)
    observers = models.ManyToManyField(User, related_name=_('observed_tickets'), blank=True, null=True)

    class Meta:
        verbose_name = _('ticket')
        verbose_name_plural = _('tickets')

    def __unicode__(self):
        return unicode(self.title)

    @models.permalink
    def get_absolute_url(self):
        return ('ticket_detail_url', (), {'project_id': self.project.pk, 'object_id': self.pk})

    def send_mails(self, action):
        current_site = Site.objects.get_current()
        url =  '%s%s' % (current_site, self.get_absolute_url())
        d = Context({'url':url, 'title':self.title, 'content':self.description})
        subject = render_to_string('core/ticket_%s_subject.txt' % action, {'title':self.title}).replace('\n', '')
        message = render_to_string('core/ticket_%s_message.html' % action, d)
        recipients = []
        recipients.append(self.author.email)
        recipients.extend([user.email for user in self.observers.all()])
        recipients.extend([user.email for user in self.workers.all()])
        recipients = list(set(recipients))
        from_email = settings.DEFAULT_FROM_EMAIL
        msg = EmailMessage(subject, message, from_email, recipients)
        msg.content_subtype = 'html'
        msg.send()

class RelatedTickets(models.Model):
    first = models.ForeignKey(Ticket,related_name=_("first_set"))
    second = models.ForeignKey(Ticket,related_name=_("second_set"))
    RELATION_CHOICES = (
            ('D',_('duplicates')),
            ('B',_('is blocked by')),
            ('R',_('is related to')),
            )
    relation = models.CharField(max_length=1,choices=RELATION_CHOICES)

class Role(models.Model):
    name = models.CharField(max_length=50, verbose_name=_('name'))

    def __unicode__(self):
        return unicode(self.name)

class News(TimeStampedModel):
    title = models.CharField(max_length=300, verbose_name=_('title'))
    content = models.TextField(verbose_name=_('content'))
    project = models.ForeignKey(Project)
    author = models.ForeignKey(User)

    class Meta:
        verbose_name = _('news')
        verbose_name_plural = _('news')

    def __unicode__(self):
        return unicode(self.title)

    @models.permalink
    def get_absolute_url(self):
        return ('news_detail_url', (),  {'project_id' : self.project.pk, 'object_id' : self.pk})


import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np

class ImageWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        super(ImageWidget, self).__init__(parent)

        # Interpret image data as row-major instead of col-major
        pg.setConfigOptions(imageAxisOrder='row-major')

        pg.mkQApp()
        self.win = pg.GraphicsLayoutWidget()
        self.win.setWindowTitle('pyqtgraph example: Image Analysis')

        # A plot1 area (ViewBox + axes) for displaying the image
        #self.plot1 = self.win.addItem() # addPlot()

        self.vb = pg.ViewBox(enableMouse=True, enableMenu=True)

        # Item for displaying image data
        self.item = pg.ImageItem()
        self.vb.addItem(self.item)
        self.win.addItem(self.vb, row=0, col=1)

        #self.vb.setAspectLocked()
        #self.vb.setRange(xRange=(0, 10), yRange=(0, 10))

        # Item for x-axis
        self.win.nextRow()
        self.xaxis = MyStringAxis(orientation="bottom", linkView=self.vb)
        self.xaxis.setLabel(text="x axis", units="arb.")
        self.yaxis = pg.AxisItem(orientation="left", linkView=self.vb)
        self.yaxis.setLabel(text="y axis", units="arb.")
        self.win.addItem(self.xaxis, row=1, col=1)
        self.win.addItem(self.yaxis, row=0, col=0)

        # Custom ROI for selecting an image region
        self.ROI = pg.ROI([-8, 14], [6, 5])
        self.ROI.addScaleHandle([0.5, 1], [0.5, 0.5])
        self.ROI.addScaleHandle([0, 0.5], [0.5, 0.5])
        self.vb.addItem(self.ROI)
        self.ROI.setZValue(10)  # make sure ROI is drawn above image

        # Isocurve drawing
        self.iso = pg.IsocurveItem(level=0.8, pen='g')
        self.iso.setParentItem(self.item)
        self.iso.setZValue(5)

        # Contrast/color control
        self.hist = pg.HistogramLUTItem()
        self.hist.setImageItem(self.item)
        self.win.addItem(self.hist, row=0, col=2)

        # Draggable line for setting isocurve level
        self.isoLine = pg.InfiniteLine(angle=0, movable=True, pen='g')
        self.hist.vb.addItem(self.isoLine)
        self.hist.vb.setMouseEnabled(y=False) # makes user interaction a little easier
        self.isoLine.setValue(0.8)
        self.isoLine.setZValue(1000) # bring iso line above contrast controls

        # Another plot1 area for displaying ROI data
        self.plot2 = self.win.addPlot(row=2, col=0, colspan=2)
        self.plot2.setMaximumHeight(250)
        self.win.resize(800, 800)
        self.win.show()

        # Generate image self.data
        self.data = np.random.normal(size=(200, 100))
        self.data[20:80, 20:80] += 2.
        self.data = pg.gaussianFilter(self.data, (3, 3))
        self.data += np.random.normal(size=(200, 100)) * 0.1
        self.item.setImage(self.data)
        self.hist.setLevels(self.data.min(), self.data.max())

        # build isocurves from smoothed self.data
        self.iso.setData(pg.gaussianFilter(self.data, (2, 2)))

        # set position and scale of image
        #self.item.scale(0.2, 0.2)
        #self.item.translate(-50, 0)

        ticks = np.arange(self.data.shape[1])
        tickDictMajor = []
        for i, tick in enumerate(ticks):
            tickDictMajor.append(str(i**2))
        self.xaxis.set_tick_dict(dict(enumerate(tickDictMajor)))

        #strings = self.xaxis.tickValues()

        # zoom to fit imageo
        #self.vb.autoRange()

        self.ROI.sigRegionChanged.connect(self.updatePlot)
        self.updatePlot()

        self.isoLine.sigDragged.connect(self.updateIsocurve)

    # Callbacks for handling user interaction
    def updatePlot(self):
        selected = self.ROI.getArrayRegion(self.data, self.item)
        self.plot2.plot(selected.mean(axis=0), clear=True)

    def updateIsocurve(self):
        self.iso.setLevel(self.isoLine.value())

class MyStringAxis(pg.AxisItem):
    def __init__(self, *args, **kwargs):
        pg.AxisItem.__init__(self, *args, **kwargs)
        self.x_values = None
        self.x_strings = None

    def set_tick_dict(self, xdict):

        self.x_values = np.asarray(list(xdict.keys())) + 0.5
        self.x_strings = np.asarray(list(xdict.values()))

    def tickStrings(self, values, scale, spacing):
        strings = []
        for v in values:
            # vs is the original tick value
            vs = v * scale
            # if we have vs in our values, show the string
            # otherwise show nothing
            if vs in self.x_values:
                # Find the string with x_values closest to vs
                vstr = self.x_strings[np.abs(self.x_values - vs).argmin()]
            else:
                vstr = ""
            strings.append(vstr)
        return strings

    def tickSpacing(self, minVal, maxVal, size, offset=0.5):
        """Return values describing the desired spacing and offset of ticks.

        This method is called whenever the axis needs to be redrawn and is a
        good method to override in subclasses that require control over tick locations.

        The return value must be a list of tuples, one for each set of ticks::

            [
                (major tick spacing, offset),
                (minor tick spacing, offset),
                (sub-minor tick spacing, offset),
                ...
            ]
        """
        # First check for override tick spacing
        if self._tickSpacing is not None:
            return self._tickSpacing

        dif = abs(maxVal - minVal)
        if dif == 0:
            return []

        ## decide optimal minor tick spacing in pixels (this is just aesthetics)
        optimalTickCount = max(2., np.log(size))

        ## optimal minor tick spacing
        optimalSpacing = dif / optimalTickCount

        ## the largest power-of-10 spacing which is smaller than optimal
        p10unit = 10 ** np.floor(np.log10(optimalSpacing))

        ## Determine major/minor tick spacings which flank the optimal spacing.
        intervals = np.array([1., 2., 10., 20., 100.]) * p10unit
        minorIndex = 0
        while intervals[minorIndex + 1] <= optimalSpacing:
            minorIndex += 1

        levels = [
            (intervals[minorIndex + 2], offset),
            (intervals[minorIndex + 1], offset),
            # (intervals[minorIndex], offset)    ## Pretty, but eats up CPU
        ]

        if self.style['maxTickLevel'] >= 2:
            ## decide whether to include the last level of ticks
            minSpacing = min(size / 20., 30.)
            maxTickCount = size / minSpacing
            if dif / intervals[minorIndex] <= maxTickCount:
                levels.append((intervals[minorIndex], offset))

        return levels

## Start Qt event loop unless running in interactive mode or using     pyside.
if __name__ == '__main__':

    app = QtGui.QApplication([])
    app.setStyle(QtGui.QStyleFactory.create("Cleanlooks"))

    image_widget = ImageWidget()

    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore,     'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()


#!/usr/bin/python3
# usage: python action-github-issue-notification.py
# export  as env variable
#########################################################################################################
# coding=utf-8

import os
from github import Github

def search_open_issues(auth, github_org: str, github_repo: str, custom_label: str, branch_label: str) -> int:
    repo = auth.get_repo(github_org + "/" + github_repo)
    open_issues = repo.get_issues(state='open', labels=[custom_label, branch_label])
    return open_issues.totalCount

def create_issue(auth, github_org: str, github_repo: str, custom_label: str, branch_label: str) -> None:
    repo = auth.get_repo(github_org + "/" + github_repo)
    repo.create_issue(title=custom_label + " failure", labels=[custom_label, branch_label])

def main():
    # setting env variables
    github_token = os.environ["GITHUB_TOKEN"]
    github_org = os.environ["GITHUB_ORG"]
    github_repo = os.environ["GITHUB_REPO"]
    custom_label = os.environ["GITHUB_CUSTOM_LABEL"]
    branch_label = os.environ["GITHUB_BRANCH_LABEL"]

    auth = Github(github_token)
    # checking if issue already exist
    open_issues_count = search_open_issues(auth, github_org, github_repo, custom_label, branch_label)

    # if issues doesn't exist create one with labels
    if open_issues_count == 0:
        create_issue(auth, github_org, github_repo, custom_label, branch_label)
    else:
        print('not creating issue, already exist........')

main()


# (c) @AbirHasan2005

import asyncio
from configs import Config
from pyrogram import Client
from pyrogram.types import Message
from pyrogram.errors import UserDeactivatedBan
from helpers.forwarder import ForwardMessage

async def Kanger(c: Client, m: Message):
    await m.edit(text=f"Checking `{str(Config.FORWARD_FROM_CHAT_ID[0])}` ...")
    await asyncio.sleep(2)
    try:
        ForwardFromChat = await c.get_chat(chat_id=Config.FORWARD_FROM_CHAT_ID[0])
        await m.edit(text=f"Successfully Linked with `{ForwardFromChat.title}` !")
    except Exception as err:
        await m.edit(text=f"Sorry, can't get **Forward From Chat**!\n\n**Error:** `{err}`")
        return 400
    await asyncio.sleep(2)
    for i in range(len(Config.FORWARD_TO_CHAT_ID)):
        await m.edit(text=f"Checking `{Config.FORWARD_TO_CHAT_ID[i]}` ...")
        await asyncio.sleep(2)
        try:
            ForwardToChat = await c.get_chat_member(chat_id=Config.FORWARD_TO_CHAT_ID[i], user_id=(await c.get_me()).id)
            if not ForwardToChat.permissions.can_send_messages:
                await m.edit(text=f"Sorry, you don't have permission to send messages in {ForwardToChat.title} !")
                return 400
            await m.edit(text=f"Successfully Linked with `{ForwardToChat.title}` !")
            await asyncio.sleep(2)
        except Exception as err:
            await m.edit(text=f"Sorry, can't get **Forward To Chat**!\n\n**Error:** `{err}`")
            return 400
    await asyncio.sleep(2)
    await m.edit(text="Trying to Forward Now ...")
    async for message in c.iter_history(chat_id=Config.FORWARD_FROM_CHAT_ID[0], reverse=True):
        await asyncio.sleep(Config.SLEEP_TIME)
        try:
            try_forward = await ForwardMessage(c, message)
            if try_forward == 400:
                return 400
        except UserDeactivatedBan:
            print("Congratulations!\nYour Account Banned Successfully!\nI already told you use a Fake Account. Hope you remember.")
            break
        except Exception as err:
            await c.send_message(chat_id="me", text=f"#ERROR: `{err}`")
    await m.edit(text="Channel Files Successfully Kanged!\n\n© A Forwarder Userbot by @AbirHasan2005")


import pickle
import streamlit as st

model = pickle.load(open('model.pkl' , 'rb'))

html_temp = """

Modal Price Prediction

			"""

#st.markdown(bg , unsafe_allow_html = True)
st.markdown(html_temp , unsafe_allow_html = True)

st.markdown('### Choose your Max Price & Min Price')

Max_Price= st.number_input("Max Price")
Min_Price = st.number_input("Min Price")

if st.button("Predict"):
	result = model.predict([[Max_Price , Min_Price]])

	st.success('Your Modal Price is {} Rs'.format(result))

	st.balloons()


#!/usr/bin/python3
"""base module"""

import csv
import json

class Base:
    """class Base"""

    __nb_objects = 0

    def __init__(self, id=None):
        """initialization"""

        if id is None:
            Base.__nb_objects += 1
            self.id = Base.__nb_objects
        else:
            self.id = id

    @staticmethod
    def to_json_string(list_dictionaries):
        """from dict to json"""

        if list_dictionaries is None or list_dictionaries == []:
            return "[]"
        return json.dumps(list_dictionaries)

    @classmethod
    def save_to_file(cls, list_objs):
        """from object to dict to file using json"""

        from models.rectangle import Rectangle
        from models.square import Square
        ls = list(cls.to_dictionary(i) for i in list_objs)
        with open("{}.json".format(cls.__name__), 'w') as f:
            f.write(cls.to_json_string(ls))

    @staticmethod
    def from_json_string(json_string):
        """from json to dict"""

        if json_string is None or json_string == '':
            return []
        return json.loads(json_string)

    @classmethod
    def create(cls, **dictionary):
        """ create an instance"""

        dum = cls(1, 1)
        dum.update(**dictionary)
        return dum

    @classmethod
    def load_from_file(cls):
        """load data from file"""

        try:
            with open('{}.json'.format(cls.__name__), 'r') as f:
                read = cls.from_json_string(f.read())
            return [cls.create(**i) for i in read]
        except FileNotFoundError:
            return []

    @classmethod
    def save_to_file_csv(cls, list_objs):
        """save to a csv file"""

        from models.rectangle import Rectangle
        from models.square import Square
        ls = list(cls.to_dictionary(i) for i in list_objs)
        with open('{}.csv'.format(cls.__name__), 'w') as f:
            writer = csv.writer(f, lineterminator='\n')
            for i in ls:
                if cls is Rectangle:
                    writer.writerow([i['id'], i['width'],
                                     i['height'], i['x'], i['y']])
                elif cls is Square:
                    writer.writerow([i['id'], i['size'], i['x'], i['y']])

    @classmethod
    def load_from_file_csv(cls):
        """ load from a csv file"""

        from models.rectangle import Rectangle
        from models.square import Square
        try:
            with open('{}.csv'.format(cls.__name__), 'r') as f:
                reader = csv.reader(f)
                keys_rect = ['id', 'width', 'height', 'x', 'y']
                keys_sq = ['id', 'size', 'x', 'y']
                dictionary = {}
                ls = []
                for row in reader:
                    for i, value in enumerate(row):
                        if cls is Rectangle:
                            dictionary[keys_rect[i]] = int(value)
                        elif cls is Square:
                            dictionary[keys_sq[i]] = int(value)
                    ls.append(dictionary)
                    dictionary = {}
            return [cls.create(**i) for i in ls]
        except FileNotFoundError:
            return []