import warnings
import numpy
import copy
from .BaseCatalogModels import BaseCatalogObj
from lsst.sims.catalogs.db import ChunkIterator, CompoundCatalogDBObject
from lsst.sims.utils import ObservationMetaData

__all__ = ["GalaxyObj", "GalaxyTileObj", "GalaxyBulgeObj",
           "GalaxyDiskObj", "GalaxyAgnObj", "ImageAgnObj", "LensGalaxyObj",
           "GalaxyTileCompoundObj"]

class GalaxyObj(BaseCatalogObj):
    """
    Note: building a catalog out of this object will directly call the
    'galaxy' table.  This table only contains objects for

    -2.5 deg < RA < 2.5 deg, -2.5 deg < Dec < 2.5 deg

    In order to cover the whole sky, call one of the objects that
    inherits from GalaxyTileObj
    """
    objid = 'galaxyBase'

    #: This is the base table for the galaxies
    # tableid = 'final_clone_db'
    tableid = 'galaxy'
    idColKey = 'id'
    raColName = '((CAST(ra AS NUMERIC(9,6))%360.)+360.)%360.'
    decColName = 'dec'
    objectTypeId = 24

    doRunTest = True
    testObservationMetaData = ObservationMetaData(boundType='circle', pointingRA=0.0, pointingDec=0.0,
                                                  boundLength=0.01, mjd=52000., bandpassName='r', m5 = 22.0)

    #: Numpy can't cast a NoneType to an integer.  This works with floats
    #: as None is cast to nan, but for integers this raises and exception.
    #: Typically it's not an issue as ints are usually ids of some sort,
    #: but in the case of the base galaxy catalog, it's possible for the
    #: varsimobjid to be None if the object does not contain an AGN.
    #: I'm over riding the _postprocess_results method to take care of this.
    #: I could also have refactored my database table so that no integer values
    #: contain NULL values.
    dbDefaultValues = {'varsimobjid': -1, 'myid': -1}

    #: The following maps column names to database schema.  The tuples
    #: must be at least length 2.  If column name is the same as the name
    #: in the DB the mapping element may be None.  The rest of the tuple
    #: should be formatted like a numpy.dtype.  If ommitted, the dtype
    #: is assumed to be float.
    columns = [('galid', None, str, 30),
               ('raJ2000', 'ra*PI()/180.'),
               ('decJ2000', 'dec*PI()/180.'),
               ('raJ2000Bulge', 'bra*PI()/180.'),
               ('decJ2000Bulge', 'bdec*PI()/180.'),
               ('raJ2000Disk', 'dra*PI()/180.'),
               ('decJ2000Disk', 'ddec*PI()/180.'),
               ('raJ2000Agn', 'agnra*PI()/180.'),
               ('decJ2000Agn', 'agndec*PI()/180.'),
               ('magNormBulge', 'magnorm_bulge'),
               ('magNormDisk', 'magnorm_disk'),
               ('magNormAgn', 'magnorm_agn'),
               ('sedFilenameBulge', 'sedname_bulge', str, 40),
               ('sedFilenameDisk', 'sedname_disk', str, 40),
               ('sedFilenameAgn', 'sedname_agn', str, 40),
               ('majorAxisBulge', 'a_b*PI()/648000.'),
               ('minorAxisBulge', 'b_b*PI()/648000.'),
               ('positionAngleBulge', 'pa_bulge*PI()/180.'),
               ('sindexBulge', 'bulge_n', int),
               ('majorAxisDisk', 'a_d*PI()/648000.'),
               ('minorAxisDisk', 'b_d*PI()/648000.'),
               ('positionAngleDisk', 'pa_disk*PI()/180.'),
               ('sindexDisk', 'disk_n', int),
               ('internalExtinctionModelBulge', 'ext_model_b', str, 3),
               ('internalAvBulge', 'av_b'),
               ('internalRvBulge', 'rv_b'),
               ('internalExtinctionModelDisk', 'ext_model_d', str, 3),
               ('internalAvDisk', 'av_d'),
               ('internalRvDisk', 'rv_d'),
               ('lsst_u', 'u_ab'),
               ('lsst_g', 'g_ab'),
               ('lsst_r', 'r_ab'),
               ('lsst_i', 'i_ab'),
               ('lsst_z', 'z_ab'),
               ('lsst_y', 'y_ab')]

    def _final_pass(self, results):
        """This is to map the values from 0 - 2*PI() as ra goes negative currently"""
        for ra in ('raJ2000', 'raJ2000Bulge', 'raJ2000Disk', 'raJ2000Agn'):
            if ra in results.dtype.names:
                results[ra] = results[ra]%(numpy.pi*2.)
        return results

class GalaxyTileObj(BaseCatalogObj):
    """
    This is the parent class for galaxy BaseCatalogObjs that sample the whole
    sky (rather than just a very small patch as in GalaxyObj)
    """

    objid = 'galaxyTiled'
    #: This is the base table for the galaxies
    tableid = 'galaxy'
    # componentSubset must be one of "ALL" (default), "AGN", "BULGE", "DISK"
    componentSubset = 'ALL'
    raColName = 'ra'
    decColName = 'dec'
    objectTypeId = 25

    doRunTest = True
    testObservationMetaData = ObservationMetaData(boundType='circle', pointingRA=173.0, pointingDec=-60.0,
                                                  boundLength=0.01, mjd=52000., bandpassName='r', m5=22.0)

    #: Numpy can't cast a NoneType to an integer.  This works with floats
    #: as None is cast to nan, but for integers this raises and exception.
    #: Typically it's not an issue as ints are usually ids of some sort,
    #: but in the case of the base galaxy catalog, it's possible for the
    #: varsimobjid to be None if the object does not contain an AGN.
    #: I'm over riding the _postprocess_results method to take care of this.
    #: I could also have refactored my database table so that no integer values
    #: contain NULL values.
    dbDefaultValues = {'varsimobjid': -1, 'myid': -1}

    #: The following maps column names to database schema.  The tuples
    #: must be at least length 2.  If column name is the same as the name
    #: in the DB the mapping element may be None.  The rest of the tuple
    #: should be formatted like a numpy.dtype.  If ommitted, the dtype
    #: is assumed to be float.
    columns = [('galtileid', None, numpy.int64),
               ('galid', None, str, 30),
               ('raJ2000', 'ra'),
               ('decJ2000', 'dec'),
               ('raJ2000Bulge', 'bra*PI()/180.'),
               ('decJ2000Bulge', 'bdec*PI()/180.'),
               ('raJ2000Disk', 'dra*PI()/180.'),
               ('decJ2000Disk', 'ddec*PI()/180.'),
               ('raJ2000Agn', 'agnra*PI()/180.'),
               ('decJ2000Agn', 'agndec*PI()/180.'),
               ('magNormBulge', 'magnorm_bulge'),
               ('magNormDisk', 'magnorm_disk'),
               ('magNormAgn', 'magnorm_agn'),
               ('sedFilenameBulge', 'sedname_bulge', str, 40),
               ('sedFilenameDisk', 'sedname_disk', str, 40),
               ('sedFilenameAgn', 'sedname_agn', str, 40),
               ('majorAxisBulge', 'a_b*PI()/648000.'),
               ('minorAxisBulge', 'b_b*PI()/648000.'),
               ('positionAngleBulge', 'pa_bulge*PI()/180.'),
               ('sindexBulge', 'bulge_n', int),
               ('majorAxisDisk', 'a_d*PI()/648000.'),
               ('minorAxisDisk', 'b_d*PI()/648000.'),
               ('positionAngleDisk', 'pa_disk*PI()/180.'),
               ('sindexDisk', 'disk_n', int),
               ('internalExtinctionModelBulge', 'ext_model_b', str, 3),
               ('internalAvBulge', 'av_b'),
               ('internalRvBulge', 'rv_b'),
               ('internalExtinctionModelDisk', 'ext_model_d', str, 3),
               ('internalAvDisk', 'av_d'),
               ('internalRvDisk', 'rv_d'),
               ('lsst_u', 'u_ab'),
               ('lsst_g', 'g_ab'),
               ('lsst_r', 'r_ab'),
               ('lsst_i', 'i_ab'),
               ('lsst_z', 'z_ab'),
               ('lsst_y', 'y_ab')]

    def _get_column_query(self, colnames=None):
        raise NotImplementedError("We are calling a stored procedure so "
                                  "no need to loop over columns")

    def _final_pass(self, results):
        """Modify the results of raJ2000 and decJ2000 to be in radians
        **Parameters**

            * results : Structured array of results from query

        **Returns**

            * results : Modified structured array

        """

        results['raJ2000'] = numpy.radians(results['raJ2000'])
        results['decJ2000'] = numpy.radians(results['decJ2000'])
        return results

    def getIdColKey(self):
        return 'galtileid'

    def query_columns(self, colnames=None, chunk_size=None, obs_metadata=None, constraint=None,
                      limit=None):
        """Execute a query

        **Parameters**

            * colnames : list or None
              a list of valid column names, corresponding to entries in the
              `columns` class attribute.  If not specified, all columns are
              queried.
            * chunksize : int (optional)
              if specified, then return an iterator object to query the database,
              each time returning the next `chunksize` elements.  If not
              specified, all matching results will be returned.
            * obs_metadata : object (optional)
              object containing information on the observation including the region of the sky
              to query and time of the observation.
            * constraint : string (optional)
              if specified, the predicate is added to the query verbatim using AND
            * limit:
              This kwarg is not actually used.  It exists to preserve the same interface
              as other definitions of query_columns elsewhere in CatSim.  If not None,
              a warning will be emitted, pointing out to the user that 'limit' is not used.

        **Returns**

            * result : structured array or iterator
              If chunksize is not specified, then result is a structured array of all
              items which match the specified query with columns named by the column
              names in the columns class attribute.  If chunksize is specified,
              then result is an iterator over structured arrays of the given size.

        """
        if colnames is None:
            colnames = [k for k in self.columnMap.keys()]

        # We know that galtileid comes back with the query, but we don't want
        # to add it to the query since it's generated on the fly.
        #
        # 25 August 2015
        # The code below has been modified to remove all column names
        # that contain 'galtileid.'  This is to accommodate the
        # CompoundInstanceCatalog and CompoundDBObject classes, which
        # mangle column names such that they include the objid of the
        # specific CatalogDBObject that is asking for them.
        query_colnames = copy.deepcopy(colnames)
        for name in query_colnames:
            if 'galtileid' in name:
                query_colnames.remove(name)

        mappedcolnames = ["%s as %s"%(self.columnMap[x], x) for x in query_colnames]
        mappedcolnames = ",".join(mappedcolnames)

        if obs_metadata is not None and obs_metadata.bounds is not None:
            if obs_metadata.bounds.boundType == 'circle':
                regionStr = 'REGION CIRCLE J2000 %f %f %f'%(obs_metadata.bounds.RAdeg,
                                                            obs_metadata.bounds.DECdeg,
                                                            60.*obs_metadata.bounds.radiusdeg)
            elif obs_metadata.bounds.boundType == 'box':
                regionStr = 'REGION RECT J2000 %f %f %f %f'%(obs_metadata.bounds.RAminDeg,
                                                             obs_metadata.bounds.DECminDeg,
                                                             obs_metadata.bounds.RAmaxDeg,
                                                             obs_metadata.bounds.DECmaxDeg)
            else:
                raise RuntimeError("GalaxyTileObj does not know about boundType %s "
                                   % obs_metadata.bounds.boundType)
        else:
            regionStr = 'REGION CIRCLE J2000 180. 0. 10800.'
            warnings.warn("Searching over entire sky "
                          "since no bounds specified. "
                          "This could be a very bad idea "
                          "if the database is large")

        query = """EXECUTE [LSSTCATSIM].[dbo].[GalaxySearch2015]
                   @ApertureStr = '%s', @ColumnNames = '%s',
                   @ComponentSubset = '%s' """ % (regionStr, mappedcolnames, self.componentSubset)

        if constraint is not None:
            query += ", @WhereClause = '%s'"%(constraint)

        if limit is not None:
            warnings.warn("You specified a row number limit in your query of a GalaxyTileObj "
                          "daughter class.  Because of the way GalaxyTileObj is searched, row "
                          "number limits are not possible.  If you really want to limit the number "
                          "of rows returned by you query, consider using GalaxyObj (note that you "
                          "will have to you limit your search to -2.5<RA<2.5 -2.25<Dec<2.25 -- both in "
                          "degrees -- as this is the only region where galaxies exist in GalaxyObj).")

        return ChunkIterator(self, query, chunk_size)

class GalaxyTileCompoundObj(CompoundCatalogDBObject, GalaxyTileObj):
    """
    This is a daughter class of CompoundCatalogDBObject that specifically
    inherits from GalaxyTileObj.  This is necessary because GalaxyTileObj
    implements a custom query_columns that executes a stored procedure
    on fatboy (as opposed to the generic query_columns implemented in
    CatalogDBObject, which converts self.columns into a SQL
    query in the most naive way possible).
    """

    doRunTest = False  # because this is not like other CatalogDBObjects
                       # and should not be tested in the same way

    _table_restriction = ['galaxy']

    def _final_pass(self, results):
        for name in results.dtype.fields:
            if 'raJ2000' in name or 'decJ2000' in name:
                results[name] = numpy.radians(results[name])

        return results

class GalaxyBulgeObj(GalaxyTileObj):
    objid = 'galaxyBulge'
    componentSubset = 'BULGE'
    raColName = 'ra'
    decColName = 'dec'
    objectTypeId = 26
    doRunTest = True
    testObservationMetaData = ObservationMetaData(boundType='circle', pointingRA=10.0, pointingDec=-45.0,
                                                  boundLength=0.01, mjd=53000., bandpassName='r', m5=22.0)
    #: The following maps column names to database schema.  The tuples
    #: must be at least length 2.  If column name is the same as the name
    #: in the DB the mapping element may be None.  The rest of the tuple
    #: should be formatted like a numpy.dtype.  If ommitted, the dtype
    #: is assumed to be float.
    columns = [('galtileid', None, numpy.int64),
               ('galid', None, str, 30),
               ('componentra', 'bra*PI()/180.'),
               ('componentdec', 'bdec*PI()/180.'),
               #: This is actually a problem with the stored procedure.
               #: We need to be able to map columns other than
               #: just ra/dec to raJ2000/decJ2000.  This gets
               #: important when we start perturbing the three galaxy components
               ('raJ2000', 'ra'),
               ('decJ2000', 'dec'),
               ('magNorm', 'magnorm_bulge'),
               ('magNormBulge', 'magnorm_bulge'),
               ('sedFilename', 'sedname_bulge', str, 40),
               ('sedFilenameBulge', 'sedname_bulge', str, 40),
               ('majorAxis', 'a_b*PI()/648000.'),
               ('minorAxis', 'b_b*PI()/648000.'),
               ('positionAngle', 'pa_bulge*PI()/180.'),
               ('sindex', 'bulge_n', int),
               ('halfLightRadius', 'BulgeHalfLightRadius*PI()/648000.'),
               ('internalExtinctionModel', 'ext_model_b', str, 3),
               ('internalAv', 'av_b'),
               ('internalRv', 'rv_b'),
               ('internalAvBulge', 'av_b'),
               ('internalRvBulge', 'rv_b'),
               ('lsst_u', 'u_ab'),
               ('lsst_g', 'g_ab'),
               ('lsst_r', 'r_ab'),
               ('lsst_i', 'i_ab'),
               ('lsst_z', 'z_ab'),
               ('lsst_y', 'y_ab')]

class GalaxyDiskObj(GalaxyTileObj):
    objid = 'galaxyDisk'
    componentSubset = 'DISK'
    raColName = 'ra'
    decColName = 'dec'
    objectTypeId = 27
    doRunTest = True
    testObservationMetaData = ObservationMetaData(boundType='circle', pointingRA=66.0, pointingDec=-80.0,
                                                  boundLength=0.01, mjd=53730., bandpassName='r', m5=22.0)
    #: The following maps column names to database schema.  The tuples
    #: must be at least length 2.  If column name is the same as the name
    #: in the DB the mapping element may be None.  The rest of the tuple
    #: should be formatted like a numpy.dtype.  If ommitted, the dtype
    #: is assumed to be float.
    columns = [('galtileid', None, numpy.int64),
               ('galid', None, str, 30),
               ('componentra', 'dra*PI()/180.'),
               ('componentdec', 'ddec*PI()/180.'),
               #: This is actually a problem with the stored procedure.
               #: We need to be able to map columns other than
               #: just ra/dec to raJ2000/decJ2000.  This gets
               #: important when we start perturbing the three galaxy components
               ('raJ2000', 'ra'),
               ('decJ2000', 'dec'),
               ('magNorm', 'magnorm_disk'),
               ('magNormDisk', 'magnorm_disk'),
               ('sedFilename', 'sedname_disk', str, 40),
               ('sedFilenameDisk', 'sedname_disk', str, 40),
               ('majorAxis', 'a_d*PI()/648000.'),
               ('minorAxis', 'b_d*PI()/648000.'),
               ('positionAngle', 'pa_disk*PI()/180.'),
               ('sindex', 'disk_n', int),
               ('halfLightRadius', 'DiskHalfLightRadius*PI()/648000.'),
               ('internalExtinctionModel', 'ext_model_d', str, 3),
               ('internalAv', 'av_d'),
               ('internalRv', 'rv_d'),
               ('internalAvDisk', 'av_d'),
               ('internalRvDisk', 'rv_d'),
               ('lsst_u', 'u_ab'),
               ('lsst_g', 'g_ab'),
               ('lsst_r', 'r_ab'),
               ('lsst_i', 'i_ab'),
               ('lsst_z', 'z_ab'),
               ('lsst_y', 'y_ab')]

class GalaxyAgnObj(GalaxyTileObj):
    objid = 'galaxyAgn'
    componentSubset = 'AGN'
    raColName = 'ra'
    decColName = 'dec'
    objectTypeId = 28
    doRunTest = True
    testObservationMetaData = ObservationMetaData(boundType='circle', pointingRA=234.0, pointingDec=-15.0,
                                                  boundLength=0.01, mjd=51000., bandpassName='r', m5=22.0)
    #: The following maps column names to database schema.  The tuples
    #: must be at least length 2.  If column name is the same as the name
    #: in the DB the mapping element may be None.  The rest of the tuple
    #: should be formatted like a numpy.dtype.  If ommitted, the dtype
    #: is assumed to be float.
    columns = [('galtileid', None, numpy.int64),
               ('galid', None, str, 30),
               ('componentra', 'agnra*PI()/180.'),
               ('componentdec', 'agndec*PI()/180.'),
               #: This is actually a problem with the stored procedure.
               #: We need to be able to map columns other than
               #: just ra/dec to raJ2000/decJ2000.  This gets
               #: important when we start perturbing the three galaxy components
               ('raJ2000', 'ra'),
               ('decJ2000', 'dec'),
               ('magNorm', 'magnorm_agn'),
               ('magNormAgn', 'magnorm_agn'),
               ('sedFilename', 'sedname_agn', str, 40),
               ('sedFilenameAgn', 'sedname_agn', str, 40),
               ('variabilityParameters', 'varParamStr', str, 256),
               ('lsst_u', 'u_ab'),
               ('lsst_g', 'g_ab'),
               ('lsst_r', 'r_ab'),
               ('lsst_i', 'i_ab'),
               ('lsst_z', 'z_ab'),
               ('lsst_y', 'y_ab')]

class ImageAgnObj(BaseCatalogObj):
    objid = 'imageagn'
    tableid = 'image'
    idColKey = 'galid'
    raColName = 'ra'
    decColName = 'dec'
    objectTypeId = 29
    doRunTest = True
    #: all sky since this is a small set.
    testObservationMetaData = ObservationMetaData(mjd=53000., bandpassName='r', m5=22.0)

    dbDefaultValues = {'varsimobjid': -1, 'myid': -1}
    #: The following maps column names to database schema.  The tuples
    #: must be at least length 2.  If column name is the same as the name
    #: in the DB the mapping element may be None.  The rest of the tuple
    #: should be formatted like a numpy.dtype.  If ommitted, the dtype
    #: is assumed to be float.
    columns = [('galid', 'id', int),
               ('raJ2000', 'ra*PI()/180.'),
               ('decJ2000', 'dec*PI()/180.'),
               ('magNorm', 'magnorm_agn'),
               ('sedFilename', 'sedname_agn', str, 40),
               ('variabilityParameters', 'varParamStr', str, 256),
               ('lsst_u', 'u_ab'),
               ('lsst_g', 'g_ab'),
               ('lsst_r', 'r_ab'),
               ('lsst_i', 'i_ab'),
               ('lsst_z', 'z_ab'),
               ('lsst_y', 'y_ab')]

class LensGalaxyObj(BaseCatalogObj):
    objid = 'lensgalaxy'
    tableid = 'lens'
    idColKey = 'galid'
    raColName = 'ra'
    decColName = 'dec'
    objectTypeId = 30
    doRunTest = True
    #: all sky since this is a small set.
    testObservationMetaData = ObservationMetaData(mjd=53000., bandpassName='r', m5=22.0)

    dbDefaultValues = {'varsimobjid': -1, 'myid': -1, 'variabilityParameters': None}
    #: The following maps column names to database schema.  The tuples
    #: must be at least length 2.  If column name is the same as the name
    #: in the DB the mapping element may be None.  The rest of the tuple
    #: should be formatted like a numpy.dtype.  If ommitted, the dtype
    #: is assumed to be float.
    columns = [('galid', 'id', int),
               ('raJ2000', 'ra_bulge*PI()/180.'),
               ('decJ2000', 'dec_bulge*PI()/180.'),
               ('magNorm', 'magnorm_bulge'),
               ('sedFilename', 'sedname_bulge', str, 40),
               ('lsst_u', 'u_ab'),
               ('lsst_g', 'g_ab'),
               ('lsst_r', 'r_ab'),
               ('lsst_i', 'i_ab'),
               ('lsst_z', 'z_ab'),
               ('lsst_y', 'y_ab')]


import sys
class Solution:
    def findMin(self, nums: List[int]) -> int:
        low=0
        high=len(nums)-1
        ans=sys.maxsize
        if nums[low]<=nums[high]:
            return nums[low]
        else:
            while low<=high:
                mid=(low+high)//2
                if nums[low]<=nums[mid]:
                    ans=min(ans,nums[low])
                    low=mid+1
                elif nums[mid]<=nums[high]:
                    ans=min(ans,nums[mid])
                    high=mid-1
        return ans


# Bridget Hester
# April 1 2022
# This program will get the number of pints in a drive, open files,
# and display information.

#Lab 10-3 Blood Drive

#the main function
def main():
  endProgram = 'no'
  print
  while endProgram == 'no':
    option = 0
    print
    print ('Enter 1 to enter in new data and store to file')
    print ('Enter 2 to display data from the file')
    option = input('Enter now ->')
    print

    # declare variables
    pints = [0] * 7
    totalPints = 0
    averagePints = 0

    if option == 1:
      # function calls
      pints = getPints(pints)
      totalPints = getTotal(pints, totalPints)
      averagePints = getAverage(totalPints, averagePints)
      writeToFile(averagePints, pints)

    else:
        readFromFile(averagePints, pints)
        counter=0
        for counter in range(6):
            outFile = 0
            outFile.write(str(pints[counter]) + '\n')
            outFile.write('Average Pints')
            outFile.write(str(averagePints) + '\n\n')
            outFile.close
    raw_input = 0
    endProgram = raw_input('Do you want to end program? (Enter no or yes): ')
    while not (endProgram == 'yes' or endProgram == 'no'):
      print ('Please enter a yes or no')
      endProgram = raw_input('Do you want to end program? (Enter no or yes): ')

#the getPints function
def getPints(pints):
  counter = 0
  while counter < 7:
      pints[counter] = input('Enter pints collected: ')
      counter = counter + 1
  return pints

#the getTotal function
def getTotal(pints, totalPints):
  counter = 0
  while counter < 7:
    totalPints = totalPints + pints[counter]
    counter = counter + 1
  return totalPints

#the getAverage function
def getAverage(totalPints, averagePints):
  averagePints = float(totalPints) / 7
  return averagePints

#the writeToFile function
def writeToFile(averagePints, pints):
    outFile = open('Blood.txt', 'a')
    print ('Pints Each Hour', outFile)

    for counter in range(6):
      outFile.write(str(pints[counter]) + '\n')
    outFile.write('Average Pints'+ '\n')
    outFile.write(str(averagePints) + '\n\n')
    outFile.close

#the readFromFile function
def readFromFile(averagePints, pints):
  inFile= open('Blood.txt', 'r')
  str1 = inFile.read()
  print (str1)
  for counter in range(6):
    pints[counter]= inFile.read()
  str2 = inFile.read()
  print (str2)
  averagePints = inFile.read()
  print (averagePints)

main()


class Edge:
    def __init__(self, item, weight, dest):
        self.item = item
        self.weight = weight
        self.next = dest

class GraphAL:

    def __init__(self, vertices, directed, weighted= False):
        self.al = [None] * vertices
        self.directed = directed
        self.weighted = weighted
        self.representation = 'AL'

    def is_valid_vertex(self, u):
        return 0 <= u < len(self.al)

    def add_vertex(self):
        self.al.append(None)
        return len(self.al) - 1

    def insert_edge(self, src, dest, weight=1.0):
        if not self.is_valid_vertex(src) or not self.is_valid_vertex(dest):
            return

        self.al[src] = Edge(dest, weight, self.al[src])

        if not self.directed:
            self.al[dest] = Edge(src, weight, self.al[dest])

    def delete_edge(self, src, dest):
        self.__delete_edge(src, dest)

        if not self.directed:
            self.__delete_edge(dest, src)

    def num_vertices(self):
        return len(self.al)

    def vertices_reachable_from(self, src):
        reachable_vertices = set()

        temp = self.al[src]

        while temp is not None:
            reachable_vertices.add(temp.item)
            temp = temp.next

        return reachable_vertices

    def vertex_indegree(self, v):
        if not self.is_valid_vertex(v):
            return

        in_degree_count = 0

        for i in range(len(self.al)):
            temp = self.al[i]

            while temp is not None:
                if temp.item == v:
                    in_degree_count += 1
                    break

                temp = temp.next

        return in_degree_count

    def compute_indegree_every_vertex(self):

        indegrees = []
        for i in range(len(self.al)):
            indegrees.append(self.vertex_indegree(i))

        return indegrees


from flask import (Flask, render_template, flash, url_for, request,
      jsonify,send_file,send_from_directory, redirect)
from forms import FeatureForm, FileForm
import pickle
import numpy as np
import pandas as pd
from werkzeug.utils import secure_filename
from bing_image_search import search_image
import uuid
import os

app = Flask(__name__)
app.config['SECRET_KEY'] = "flask machine learning model"

@app.route("/", methods = ['GET', 'POST'])
def home():
    feature_form = FeatureForm()
    file_form = FileForm()
    with open ("static/final_svm_model.pkl",'rb') as pickle_file:
          model = pickle.load(pickle_file)

    if feature_form.validate_on_submit():
        sepal_length= feature_form.sepal_length.data
        sepal_width = feature_form.sepal_width.data
        petal_length = feature_form.petal_length.data
        petal_width = feature_form.petal_width.data

        data = np.array([sepal_length,sepal_width, petal_length, petal_width]).reshape(1,-1)
        prediction= model.predict(data)
        predict_result = ""

        if prediction == 0:
            predict_result = 'setosa'
        elif prediction == 1:
            predict_result =  'versicolor'
        else :
            predict_result = 'virginica'

        #image_file_name = str(uuid.uuid4())
        #image_file = image_file_name + ".png"
        #search_image(predict_result, image_file)

        return render_template("home.html", feature_form=feature_form, file_form = file_form, result = predict_result)

    elif file_form.validate_on_submit():
        file = file_form.test_file.data #FileStorage object

        try:
            data= pd.read_csv(file,sep=' ', delimiter=r"\s+",index_col=False)
            prediction = model.predict(data)

        except Exception:
            return  "Something went worng. PLEASE CHECK THE FILE AGAIN"
        prediction = prediction.astype(str)
        prediction[prediction == '0'] = 'setosa'
        prediction[prediction == '1'] = 'versicolor'
        prediction[prediction == '2'] = 'virginica'

        prediction_file_name = str(uuid.uuid4())
        predict_result_file = prediction_file_name + ".txt"
        np.savetxt("static/prediction/"+ predict_result_file,  prediction, newline="\r\n" , fmt="%s")
        return redirect(url_for('predict_txt', filename=predict_result_file))

    return render_template("home.html", feature_form=feature_form, file_form = file_form)

@app.route('/getPrediction/<filename>') #
def predict_txt(filename):
     return send_from_directory('static/prediction',filename,as_attachment=True)


'''
    Given a linked list of size N.
    Reverse every k nodes (where k is an input to the function) in the linked list.
'''

class Node:
    # initializing the Node
     def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    # Initializing the LinkedList
    def __init__(self):
        self.head = None

    # To insert a node at the last position (Pushing)
    def insert_at_end(self, new_data):
        # If the linked list is empty
        if self.head is None:
            self.head = Node(new_data)

        # Adding the new node at the end of the linked list
        else:
            new_node = Node(new_data)
            current = self.head

            # Traversing the linked list till we reach the last node
            while current.next:
                current = current.next

            current.next = new_node

    # Printing the node data in order
    def display(self):
        current = self.head

        # Traversing the linked list
        while current.next is not None:
            print(f'{current.data} -> ', end=' ')
            current = current.next

        print(current.data)

    # Function to reverse a linked list in groups of k
    def reversal(self, head, k):
        # if LinkedList is empty
        if head is None:
            return None

        current = head
        next = None
        prev = None
        count = 0

        # Initially traversing k elements through current pointer and reversing them
        while current is not None and count < k:
            next = current.next
            current.next = prev
            prev = current
            current = next
            count += 1

        # If current pointer doesn't indicate the end of linked list,
        # we recursively call the function to perform similar group wise reversal
        # for the following groups of k elements
        if next is not None:
            head.next = self.reversal(next, k)

        # We return the pointer pointing to the head of the new reversed linked list
        return prev

if __name__ == '__main__':
    ll_obj = LinkedList()

    N = int(input('Enter number of elements to insert: '))

    for i in range(N):
        val = int(input(f'Enter element {i}: '))
        ll_obj.insert_at_end(val)

    print('The linked list is: ')
    ll_obj.display()

    k = int(input('Enter group size: '))

    ll_obj.head = ll_obj.reversal(ll_obj.head, k)

    print('The new linked list is: ')
    ll_obj.display()

'''
    For reversal function:
        Time complexity: O(n)
        Space complexity: O(1)

    Sample input/output:

    Enter number of elements to insert: 8
    Enter element 0: 1
    Enter element 1: 2
    Enter element 2: 3
    Enter element 3: 4
    Enter element 4: 5
    Enter element 5: 5
    Enter element 6: 6
    Enter element 7: 7
    The linked list is:
    1 ->  2 ->  3 ->  4 ->  5 ->  5 ->  6 ->  7
    Enter group size: 3
    The new linked list is:
    3 ->  2 ->  1 ->  5 ->  5 ->  4 ->  7 ->  6
'''


#!/usr/bin/python3

import sys

o = None
ol = list()

for line in sys.stdin:
    p, k, v = line.strip().split()
    if o != k:
        ol.sort()
        for i in ol:
            print('%s\t%s'%(o, i))
        o = k
        del ol
        ol = list()
    ol.append(v)

ol.sort()
for i in ol:
    print('%s\t%s'%(o, i))


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

import copy
from unittest import TestCase
from unittest.mock import Mock, call, patch

import torch

from steganogan import decoders
from tests.utils import assert_called_with_tensors

class TestBasicDecoder(TestCase):

    class TestDecoder(decoders.BasicDecoder):
        def __init__(self):
            pass

    def setUp(self):
        self.test_decoder = self.TestDecoder()

    @patch('steganogan.decoders.nn.Conv2d', autospec=True)
    def test__covn2d(self, conv2d_mock):
        """Conv2d must be called with given args and kernel_size=3 and padding=1"""

        # run
        result = self.test_decoder._conv2d(2, 4)

        # asserts
        assert result == conv2d_mock.return_value
        conv2d_mock.assert_called_once_with(
            in_channels=2,
            out_channels=4,
            kernel_size=3,
            padding=1
        )

    @patch('steganogan.decoders.nn.Sequential')
    @patch('steganogan.decoders.nn.Conv2d')
    @patch('steganogan.decoders.nn.BatchNorm2d')
    def test___init__(self, batchnorm_mock, conv2d_mock, sequential_mock):
        """Test the init params and that the layers are created correctly"""

        # run
        decoders.BasicDecoder(2, 5)

        # assert
        expected_batch_calls = [call(5), call(5), call(5)]
        assert batchnorm_mock.call_args_list == expected_batch_calls

        expected_conv_calls = [
            call(in_channels=3, out_channels=5, kernel_size=3, padding=1),
            call(in_channels=5, out_channels=5, kernel_size=3, padding=1),
            call(in_channels=5, out_channels=5, kernel_size=3, padding=1),
            call(in_channels=5, out_channels=2, kernel_size=3, padding=1),
        ]
        assert conv2d_mock.call_args_list == expected_conv_calls

    def test_upgrade_legacy_without_version(self):
        """Upgrade legacy must create self._models from conv1, conv2, conv3, conv4"""

        # setup
        self.test_decoder.layers = Mock(return_value=torch.Tensor([[5, 6], [7, 8]]))

        # run
        self.test_decoder.upgrade_legacy()

        # assert
        assert self.test_decoder._models == [self.test_decoder.layers]
        assert self.test_decoder.version == '1'

    @patch('steganogan.decoders.nn.Sequential', autospec=True)
    def test_upgrade_legacy_with_version_1(self, sequential_mock):
        """The object must be the same and not changed by the method"""

        # setup
        decoder = decoders.BasicDecoder(1, 1)
        expected = copy.deepcopy(decoder)

        # run
        decoder.upgrade_legacy()

        # assert
        assert decoder.__dict__ == expected.__dict__

    def test_forward_1_layer(self):
        """If there is only one layer it must be called with image as the only argument."""

        # setup
        layer1 = Mock(return_value=torch.Tensor([[5, 6], [7, 8]]))
        self.test_decoder._models = [layer1]

        # run
        image = torch.Tensor([[1, 2], [3, 4]])
        result = self.test_decoder.forward(image)

        # assert
        assert (result == torch.Tensor([[5, 6], [7, 8]])).all()

        call_1 = call(torch.Tensor([[1, 2], [3, 4]]))
        assert_called_with_tensors(layer1, [call_1])

    def test_forward_more_than_2_layers(self):
        """If there are more than 2 layers, they must be called adding data to each result"""

        # setup
        layer1 = Mock(return_value=torch.Tensor([[5, 6], [7, 8]]))
        layer2 = Mock(return_value=torch.Tensor([[9, 10], [11, 12]]))
        layer3 = Mock(return_value=torch.Tensor([[13, 14], [15, 16]]))
        self.test_decoder._models = [layer1, layer2, layer3]

        # run
        image = torch.Tensor([[1, 2], [3, 4]])
        result = self.test_decoder.forward(image)

        # asserts
        call_layer_1 = call(torch.Tensor([[1, 2], [3, 4]]))
        call_layer_2 = call(torch.Tensor([[5, 6], [7, 8]]))
        call_layer_3 = call(torch.Tensor([[5, 6, 9, 10], [7, 8, 11, 12]]))

        assert_called_with_tensors(layer1, [call_layer_1])
        assert_called_with_tensors(layer2, [call_layer_2])
        assert_called_with_tensors(layer3, [call_layer_3])

        assert (result == torch.Tensor([[13, 14], [15, 16]])).all()

class TestDenseDecoder(TestCase):

    class TestDecoder(decoders.DenseDecoder):
        def __init__(self):
            pass

    def test_upgrade_legacy_without_version(self):
        """Upgrade legacy must create self._models from conv1, conv2, conv3, conv4"""

        # setup
        test_decoder = self.TestDecoder()  # instance an empty decoder
        test_decoder.conv1 = Mock(return_value=torch.Tensor([[5, 6], [7, 8]]))
        test_decoder.conv2 = Mock(return_value=torch.Tensor([[9, 10], [11, 12]]))
        test_decoder.conv3 = Mock(return_value=torch.Tensor([[13, 14], [15, 16]]))
        test_decoder.conv4 = Mock(return_value=torch.Tensor([[17, 18], [19, 20]]))

        # run
        test_decoder.upgrade_legacy()

        # assert
        expected_models = [
            test_decoder.conv1,
            test_decoder.conv2,
            test_decoder.conv3,
            test_decoder.conv4,
        ]
        assert test_decoder._models == expected_models
        assert test_decoder.version == '1'

    @patch('steganogan.decoders.nn.Sequential', autospec=True)
    def test_upgrade_legacy_with_version_1(self, sequential_mock):
        """The object must be the same and not changed by the method"""

        # setup
        decoder = decoders.DenseDecoder(1, 1)
        expected = copy.deepcopy(decoder)

        # run
        decoder.upgrade_legacy()

        # assert
        assert decoder.__dict__ == expected.__dict__

    @patch('steganogan.decoders.nn.Sequential')
    @patch('steganogan.decoders.nn.Conv2d')
    @patch('steganogan.decoders.nn.BatchNorm2d')
    def test___init__(self, batchnorm_mock, conv2d_mock, sequential_mock):
        """Test the init params and that the layers are created correctly"""

        # run
        decoders.DenseDecoder(2, 5)

        # assert
        expected_batch_calls = [call(5), call(5), call(5)]
        assert batchnorm_mock.call_args_list == expected_batch_calls

        expected_conv_calls = [
            call(in_channels=3, out_channels=5, kernel_size=3, padding=1),
            call(in_channels=5, out_channels=5, kernel_size=3, padding=1),
            call(in_channels=10, out_channels=5, kernel_size=3, padding=1),
            call(in_channels=15, out_channels=2, kernel_size=3, padding=1),
        ]
        assert conv2d_mock.call_args_list == expected_conv_calls


import math
import os
import random
import re
import sys

# Complete the solve function below.
def solve(s):
    s_split = s.split()
    caps = []
    for t in s_split:
        if t.isdigit():
            caps.append(t)
        else:
            u = t.capitalize()
            caps.append(u)

    new_s = ' '.join(caps)
    return new_s

if __name__ == '__main__':

    s = raw_input()

    result = solve(s)

    print(result)


# -*- coding: utf-8 -*-
"""
Created on Thu Sep 26 18:10:33 2019

@author: Fabio La Gioia
"""
import os
import cv2
from skimage import io

def create_dataset(path):
    """
    Loading images from the directory defined by the path.
    This method performs the image segmentation.
    Parameters:
    ----------
    - path: directory path
    """
    for file in os.listdir(path):
        image = cv2.cvtColor(cv2.imread(path + "/" + file), cv2.COLOR_BGR2RGB)
        height, width = image.shape[:2]
        step = 384
        height = height - (height % step)
        width = width - (width % step)
        c = 0
        for y in range(0, height, step):
            for x in range(0, width, step):
                crop = image[y : y+step, x : x + step]
                io.imsave(os.getcwd() + "/tiles/" + str(c) + "-" + file, crop)
                c+=1


import logging
import json

from odoo import http
from odoo.http import request
from odoo.osv import expression

_logger = logging.getLogger(__name__)

class AppProductBrand(http.Controller):

    FIELDNAMES = ['id', 'name', 'active']
    FIELDFILTERS = ['id', 'name']

    @http.route('/app/product_brand', type='http', methods=['GET'], auth='public', website=False, sitemap=False)
    def app_product_brand_movil(self, limit=20, offset=0, **kwargs):
        data = {'status': 200, 'msg': 'Success'}
        domain = expression.AND([[('active', '=', True)]])
        for key in kwargs:
            if key in self.FIELDFILTERS:
                if key == 'name':
                    search_domain = self._get_search_domain(kwargs.get(key))
                    domain = expression.AND([domain, search_domain])
                else:
                    value = kwargs.get(key)
                    domain = expression.AND([domain, [(key, '=', int(value))]])

        # Search Read
        brand_ids = request.env['product.brand'].sudo().search_read(domain=domain, fields=self.FIELDNAMES,
                                                                    limit=int(limit), offset=int(offset),
                                                                    order='name asc')
        all_brand_count = request.env['product.brand'].sudo().search_count(domain)
        brand_count = len(brand_ids)
        if brand_count > 0:
            data.update({'data': brand_ids, 'count': brand_count, 'total_count': all_brand_count})
        else:
            data.update({'status': 204, 'msg': 'No hay marcas de productos', 'count': 0, 'data': False})

        return json.dumps(data)

    @staticmethod
    def _get_search_domain(search):
        domain = []
        if search:
            for srch in search.split(" "):
                domain.append([('name', 'ilike', srch.capitalize())])

        return expression.OR(domain)


# -*- coding: utf-8 -*-
import re
from lib import normalize, regex, kuzuha
from lib.nlp import cabocha

re_chokuon = re.compile(r'[ゃゅょャュョ]')

class Senryu(object):

    @staticmethod
    def is_valid575(tokens):
        if tokens[0] in ('に', 'は', 'か', 'が', 'や', 'を', 'で', 'と', 'の', 'も'):
            return False
        if ''.join(tokens)[-1] == 'っ':
            return False
        return True

    @staticmethod
    def is_valid_pos(feature):
        if feature[0] in ('助詞'):
            return False
        if feature[1] in ('接尾'):
            return False
        return True

    def extract575(self, text):
        phase = 0
        count = 0
        parts = []
        tokens = []
        yomi_count = []
        features = []
        for chunk in cabocha.parse(text):
            for token in chunk['tokens']:
                length = 0
                feature = token.feature.split(',')
                if feature[0] == '記号':
                    length = 0
                elif len(feature) >= 8:
                    length = len(re_chokuon.sub('', feature[7]))
                else:
                    length = len(re_chokuon.sub('', token.surface))
                yomi_count.append(length)
                tokens.append(token.surface)
                features.append(feature)
                if phase == 2 and sum(yomi_count) == 17 and self.is_valid575(tokens):
                    return ''.join(tokens)
                elif phase == 2 and sum(yomi_count) == 14 and yomi_count[-1] == 2:
                    if not self.is_valid_pos(feature):
                        return None
                elif phase == 2 and sum(yomi_count) == 13:
                    if not self.is_valid_pos(feature):
                        return None
                elif phase == 1 and sum(yomi_count) == 12:
                    phase = 2
                elif phase == 1 and sum(yomi_count) == 7 and yomi_count[-1] == 2:
                    if not self.is_valid_pos(feature):
                        return None
                elif phase == 1 and sum(yomi_count) == 6:
                    if not self.is_valid_pos(feature):
                        return None
                elif phase == 0 and sum(yomi_count) == 5:
                    phase = 1
                elif phase == 0 and sum(yomi_count) > 5 and yomi_count:
                    yomi_count.pop(0)
                    tokens.pop(0)
                    features.pop(0)
                elif phase == 0 and length > 5:
                    phase = 0
                    yomi_count = []
                    tokens = []
                    features = []

    def run(self):
        _filter = kuzuha.build_hour_filter(1)
        for post in kuzuha.search(_filter=_filter, sort=[('_score', 'desc')]):
            text = normalize.normalize(post['text'], repeat=4)
            text = regex.re_html_tag.sub('', text)
            text = regex.re_url.sub('', text)
            result = self.extract575(text)
            if result:
                return result + ' #みさお川柳'


import csv
import pandas as pd

import logging
import random
import re
import time

from outreach.search import google_search_with_timeout
from outreach.scraping import scrape_website_with_timeout
from outreach.cleaning import clean_email, clean_business_name

# Proxy settings  insert your own credentials
username = ''
password = ''
proxy = f"socks5h://{username}:{password}@gate.smartproxy.com:7000"
proxies = {
    'http': proxy,
    'https': proxy
}

# Load the xls file
df = pd.read_excel('list_data.xlsx')

# Set up logging
logging.basicConfig(filename='scraping_errors.log', level=logging.ERROR)

# Define a function to generate email guesses
def guess_emails(business_name):
    # Remove non-alphanumeric characters
    clean_name = re.sub(r'\W+', '', business_name)
    return f'{clean_name}@gmail.com, info@{clean_name}.com'

# Prompt the user for the number of links to process
num_links = int(input("Enter the number of links to process: "))

# Iterate over the DataFrame
for index, row in df.head(num_links).iterrows():
    start_time = time.time()
    print(f"Processing link {index+1} of {num_links}...")
    link = google_search_with_timeout(row)
    if link is None:  # Skip this row if google_search took too long
        continue
    print(f"Found link: {link} (Time taken: {time.time() - start_time} seconds)")
    df.loc[index, 'Link'] = link
    start_time = time.time()
    contact_info = scrape_website_with_timeout(link)
    if contact_info is None:  # Skip this row if scrape_website took too long
        continue
    print(f"Found contact info: {contact_info} (Time taken: {time.time() - start_time} seconds)")
    email_matches = ', '.join(contact_info[0]) if contact_info[0] else guess_emails(row['Legal Business Name'])
    df.loc[index, 'Emails'] = email_matches
    df.loc[index, 'Phone Numbers'] = ', '.join(contact_info[1]) if contact_info[1] else ''
    df.loc[index, 'Contact Form Link'] = contact_info[2] if contact_info[2] else ''
    time.sleep(random.uniform(1, 3))

# Save the DataFrame back to an xls file
df.to_excel('schoolInfo.xlsx', index=False)
print("Done!")

# Read the excel file
df = pd.read_excel('first5000.xlsx')

# Apply clean_business_name function to the 'Legal Business Name' column
df['Legal Business Name'] = df['Legal Business Name'].apply(clean_business_name)

# Iterate over the rows of the dataframe
for i, row in df.iterrows():
    # If Emails is empty, fill with guessed emails
    if pd.isnull(row['Emails']):
        business_name = row['Legal Business Name']
        guessed_emails = f"{business_name}@gmail.com, info@{business_name}.com"
        df.loc[i, 'Emails'] = guessed_emails
    else:
        # Check for duplicate emails
        email_list = row['Emails'].split(", ")
        # Remove duplicates by converting the list to a set, then convert back to list
        email_list = list(set(email_list))
        # Join the emails back into a string, separated by commas
        email_str = ", ".join(email_list)
        # Replace the email cell with the cleaned emails
        df.loc[i, 'Emails'] = email_str

# Create a copy of the dataframe
df_cleaned = df.copy()

# Apply clean_email function to 'Emails' column
df_cleaned['Emails'] = df_cleaned['Emails'].apply(clean_email)

# Save the cleaned dataframe to a new excel file
df_cleaned.to_excel('cleanedEmails5000.xlsx', index=False)

# Load the Excel file
df = pd.read_excel('cleanedEmails5000.xlsx')

# Select the third column. Note that Python uses 0-indexing, so the third column would be index 2.
third_column = df.iloc[:, 2]

# Save the third column to a CSV file
third_column.to_csv('third_column.csv', index=False)

# Open the input and output files
with open('third_column.csv', 'r') as infile, open('output.csv', 'w', newline='') as outfile:
    # Create a CSV writer for the output file
    writer = csv.writer(outfile)

    # Read the input file line by line
    for line in infile:
        # Split the line into emails
        emails = line.strip().split(',')

        # Write each email to the output file
        for email in emails:
            writer.writerow([email.strip()])  # strip() is used to remove leading/trailing whitespace

# Regular expression pattern for matching email addresses
pattern = re.compile(r'([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)')

# Open the input and output files
with open('output.csv', 'r') as infile, open('cleaned_output.csv', 'w', newline='') as outfile:
    # Create a CSV writer for the output file
    writer = csv.writer(outfile)

    # Read the input file line by line
    for line in infile:
        # Remove quotes
        line = line.replace('"', '')

        # Find the email address in the line
        match = pattern.search(line)

        # If an email address was found, write it to the output file
        if match:
            writer.writerow([match.group(1)])


from flask import Flask
from flask.ext.cors import CORS
from peewee import *

# config - aside from our database, the rest is for use by Flask
DATABASE = 'atto.db'
DEBUG = True
SECRET_KEY = 'hin6bab8ge25*r=x&+5$0kn=-#log$pt^#@vrqjld!^2ci@g*b'

app = Flask(__name__)
app.config.from_object('config.Configuration')
CORS(app)

database = SqliteDatabase(DATABASE)


from django.contrib import admin

from one.libraries.utils.admin import MasterModelAdmin
from one.masterdata.sku.models import SKU
from one.masterdata.uomconversion.admin import UOMConversionInline

@admin.register(SKU)
class SKUAdmin(MasterModelAdmin):
    inlines = [UOMConversionInline]

    def get_fieldsets(self, request, obj=None):
        fieldsets = super().get_fieldsets(request, obj)
        fieldsets[0][1]["fields"] += (
            "quantity_type",
            "base_uom",
            "point",
            "markup",
        )
        return fieldsets

    def get_list_display(self, request):
        list_display = super().get_list_display(request)
        return list_display + (
            "base_uom",
            "point",
            "markup",
        )


#!/usr/bin/python3

# ## {R2D2919B742E} ##
# ###########################################################################
# What if magic existed?
# What if a place existed where your every thought and dream come to life.
# There is only one catch: it has to be written down.
# Such a place exists, it is called programming.
#    - Scott Taylor Reph, RightThumb.com
# ###########################################################################
# ## {C3P0D40fAe8B} ##
##################################################
import sys, time
##################################################
import _rightThumb._construct as __
appDBA=__.clearFocus(__name__,__file__);__.appReg=appDBA;
def focus(parentApp='',childApp='',reg=True):
	global appDBA;f=__.appName(appDBA,parentApp,childApp);
	if reg:__.appReg=f;
	return f
import _rightThumb._base3 as _
fieldSet=_.l.vars(focus(),__name__,__file__,appDBA)
_.load()
##################################################
_v = __.imp('_rightThumb._vars')
_str = __.imp('_rightThumb._string')
##################################################
def sw():
	pass
	_.switches.register( 'Text', '-t,-text' )
	_.switches.register( 'Files', '-f,-fi,-file,-files','file.txt', isData='data', description='Files' )

# __.setting('require-list',['Pipe','Files','Plus'])
__.setting('require-list',[])
__.setting('receipt-log')
__.setting('receipt-file')
__.setting('myFileLocations-skip-validation',False)
__.setting('require-pipe',False)
__.setting('require-pipe||file',False)
__.setting('pre-error',False)
__.setting('switch-raw',[])

_.appInfo[focus()] = {
	# 'app': '8facG-jo0Cxk',
	'file': 'ws.py',
	'liveAppName': __.thisApp( __file__ ),
	'description': 'returns word dic of word stems',
		# _.ail(1,'subject')+
		# _.aib('one')+
	'categories': [
						'meta',
						'listener',
						'meta listener',
				],
	'usage': [
						# 'epy another',
						# 'e nmap',
						# '',
	],
	'relatedapps': [
						# 'p another -file file.txt',
						# '',
	],
	'prerequisite': [
						# 'p another -file file.txt',
						# '',
	],
	'examples': [
						_.hp('p ws -t scientific information systematic process testing '),
						_.linePrint(label='simple',p=0),
						'',
	],
	'columns': [
					# { 'name': 'name', 'abbreviation': 'n' },
					# { 'name': '{1}', 'abbreviation': '{0}', 'sort': '{2}' },
	],
	'aliases': [
					# 'this',
					# 'app',
	],
	'notes': [
					# {},
	],
}

_.appData[focus()] = {
		'start': __.startTime,
		'uuid': '',
		'audit': [],
		'pipe': False,
		'data': {
					'field': {'sent': [], 'received': [] }, # { 'label': '', 'context': [],  }
					'table': {'sent': [], 'received': [] },
		},
	}

def triggers():
	_.switches.trigger( 'Files', _.myFileLocations, vs=True )
	_.switches.trigger( 'Ago', _.timeAgo )
	_.switches.trigger( 'Folder', _.myFolderLocations )
	_.switches.trigger( 'URL', _.urlTrigger )
	_.switches.trigger( 'Duration', _.timeFuture )

_.l.conf('clean-pipe',True)
_.l.sw.register( triggers, sw )

########################################################################################
# START

processWordStem = None
def wordStem(word):
	global processWordStem
	if processWordStem is None:
		from nltk.stem import PorterStemmer
		processWordStem = PorterStemmer()
	return processWordStem.stem(word)

added=False
def stim(word):
	global c3po
	global added
	if word in c3po: return c3po[word];
	c3po[word]=wordStem(word)
	added=True
	return c3po[word]

def clean_D():
	global added
	global c3po
	c3={}
	for k in c3po:
		if not k==c3po[k]:
			c3[k]=c3po[k]
		else:
			added=True
	c3po=c3
def action():
	load()
	global c3po
	global added
	if _.switches.isActive('Text'):
		data = ' '.join(_.switches.values('Text'))
	elif _.isData():
		data = ' '.join(_.isData())
	data=_str.do('.sh',data)
	data = data.replace('\n',' ')
	data=_str.do('dup',data,' ')
	data=_str.do('be',data,' ')

	# clean_D()

	for word in data.split(' '): stim(word);
	if added: _.saveTableDB(c3po,'app-word-stems.index');

	_.pr( simplejson.dumps(c3po, indent=4, sort_keys=False) )

simplejson = __.imp('simplejson')

def load():
	global c3po
	c3po = _.getTableDB( 'app-word-stems.index' )

########################################################################################
if __name__ == '__main__':
	action()
	__.isExit()


import customFunctions as func

with open('TestFile.txt', 'w') as fileobj:
    fileobj.write('New line in file\nThis is confusing to write like this\nWhat the heck')

with open('TestFile.txt', 'r') as fileobj:
    lines = fileobj.readlines()
    func.print_function("File content:", lines)

func.newLine()

with open('TestFile.txt', 'r') as fileobj:
    content = fileobj.read()
    split_lines = content.split('\n')
    func.print_function(r"Split file content (\n):",split_lines)

func.newLine()

fileobj = open('TestFile.txt', 'r')
position = fileobj.tell()
func.print_function("Find position in file (.tell):", position)

fileobj.read()
end_position = fileobj.tell()
func.print_function("Find position in file (after read):", end_position)
print('Close object')
fileobj.close()

func.newLine()

fileobj = open('TestFile.txt', 'r')
fileobj.seek(10)
position = fileobj.tell()
func.print_function("Use .seek to move to specific position (i.e. 10th):", position)

func.newLine()

print('Start file again')
fileobj.seek(0)
firstTen = fileobj.read(10)
func.print_function("Read next 10 characters using .read:", firstTen)
position = fileobj.tell()
func.print_function("Find position:", position)
print('Close object')
fileobj.close()

func.newLine()

with open('TestFile.txt', 'rb') as fileobj:
    func.print_function('Read file bytes using \'rb\' instead of \'r\':', type(fileobj.read()))
    fileobj.close()


#!/usr/bin/env python3

## Author: Joel Ong <joel.ong@yale.edu>
## Yale University Dept. of Astronomy

'''
2D polynomial fits; some parts adapted from EXPRES pipeline
'''

#import numpy as lib
import jax.numpy as lib

from .coupling import ν_to_ω
from .poly2d import polyfit2d

def asymptotic_ν_g(n_g, ΔΠ0, max_N2, ε_g, α=0, ν_max=0, l=1):
    '''
    Asymptotic relation for the g-mode frequencies
    in terms of a fundamental period offset (defined by the
    maximum Brunt-Vaisala frequency), the asymptotic g-mode period
    spacing, the g-mode phase offset, and an optional curvature term.
    '''
    ΔΠ_l = ΔΠ0 / lib.sqrt(l * (l + 1))
    P0 = 1 / (lib.sqrt(max_N2) / ν_to_ω)
    if ν_max:
        P_max = 1 / ν_max
    else:
        P_max = 0
    n_max = (P_max - P0) / ΔΠ_l - ε_g
    P = P0 + ΔΠ_l * (n_g + ε_g + α * (n_g - n_max)**2)
    return 1/P

def fit_poly(n_p, n_g, ν_p, ν_g, L, D, n_low=None, order=2):
    '''
    Fit upper-triangular matrix coefficients describing 2D polynomials
    of degree n for the scaled coupling and overlap matrices.
    '''

    assert len(n_p) == len(ν_p) and len(n_g) == len(ν_g)
    assert len(n_p) + len(n_g) == len(L)
    assert len(L) == len(D)

    N_π = len(n_p)

    L_scaled = L[:N_π, N_π:] / (ν_g * ν_to_ω)**2
    D_scaled = D[:N_π, N_π:] / (ν_g[None,:]) * (ν_p[:,None])

    if n_low is None:
        n_low = min(int(lib.max(n_g)/10), 10)

    if n_low == 0:
        s = slice(None, None)
    else:
        s = slice(None, -1 * n_low)

    j_L = polyfit2d(n_p[:, None], n_g[None, s], L_scaled[:,s], order)
    j_D = polyfit2d(n_p[:, None], n_g[None, s], D_scaled[:,s], order)

    p_L = j_L['x']
    p_D = j_D['x']

    return {
        'p_L': p_L, 'p_D': p_D,
        'L_scaled': L_scaled,
        'D_scaled': D_scaled
    }


import datetime
import json
import subprocess
from pathlib import Path

from platformdirs import user_cache_dir, user_config_dir

from requests.auth import AuthBase

class RestishAuth(AuthBase):
    def __init__(self, section):
        self.section = section
        self._auth_header = None

    @property
    def auth_header(self):
        if not self._auth_header:
            restish_config_path = Path(user_config_dir("restish"))
            with open(restish_config_path / "apis.json", "r") as f:
                apis = json.load(f)

            if self.section not in apis:
                raise ValueError(
                    f"Section {self.section!r} not found in restish APIs."
                )

            def read_cache():
                restish_cache_path = Path(user_cache_dir("restish"))
                with open(restish_cache_path / "cache.json", "r") as f:
                    cache = json.load(f)
                return cache

            cache = read_cache()

            has_token = False
            if f"{self.section}:default" in cache:
                now = datetime.datetime.now().isoformat()
                token = cache[f"{self.section}:default"]
                if token["expires"][: len(now)] > now:
                    has_token = True

            if not has_token:
                subprocess.check_call(
                    ["restish", self.section],
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL,
                )
                token = read_cache()[f"{self.section}:default"]

            self._auth_header = " ".join((token["type"], token["token"]))
        return self._auth_header

    def __call__(self, request):
        request.headers["Authorization"] = self.auth_header
        return request


from database.data_manager.init_queries import exchange_table_name, currency_table_name, securities_table_name, data_vendor_table_name
from database.data_manager.data_access import connect_as_user

def exchange_exists(exchange_name='', exchange_abbrev='') -> bool:
    query = f"SELECT ID FROM {exchange_table_name} WHERE exchange_name = '{exchange_name}' OR abbrev = '{exchange_abbrev}'"
    return does_exist(query)

def currency_exists(currency_name='', currency_abbrev='') -> bool:
    query = f"SELECT ID FROM {currency_table_name} WHERE currency_name = '{currency_name}' OR abbrev = '{currency_abbrev}'"
    return does_exist(query)

def security_exists(security_name='', security_abbrev='') -> bool:
    query = ''
    if len(security_name) == 0 and len(security_abbrev) == 0:
        return False
    elif len(security_name) > 0:
        query = f"SELECT ID FROM {securities_table_name} WHERE security_name = '{security_name}'"
        return does_exist(query)
    elif len(security_abbrev) > 0:
        query = f"SELECT ID FROM {securities_table_name} WHERE abbrev = '{security_abbrev}'"
        return does_exist(query)
    else:
        query = f"SELECT ID FROM {securities_table_name} WHERE security_name = '{security_name}' AND abbrev = '{security_abbrev}'"
        return does_exist(query)

def data_vendor_exists(vendor_name='', website=''):
    query = f"SELECT ID FROM {data_vendor_table_name} WHERE vendor_name = '{vendor_name}' OR website_url = '{website}'"
    return does_exist(query)

def does_exist(query) -> bool:
    conn = connect_as_user()
    cursor = conn.cursor()
    cursor.execute(query)
    res = cursor.fetchall()
    does_exist = len(res) > 0
    return does_exist


from pig_util import outputSchema

from py2neo import neo4j
from py2neo import node, rel

@outputSchema('nodeCreated:int')
def createNode(nodeValue, sLabel):
    if nodeValue:
        graph_db = neo4j.GraphDatabaseService("http://localhost:7474/db/data/")
        batch = neo4j.WriteBatch(graph_db)
        alice=batch.create(node(name=nodeValue,label=sLabel))
        results=batch.submit()
        return 1
    else:
        return 0

@outputSchema('nodeCreated:int')
def createRelationship(fromNode, toNode, sRelationship):
    if fromNode:
        graph_db = neo4j.GraphDatabaseService("http://localhost:7474/db/data/")
        ref_node = graph_db.node(fromNode)
        to_node = graph_db.node(toNode)
        aliceRel=graph_db.create(rel(ref_node,sRelationship,to_node))
        return 1
    else:
        return 0

#myudf.py
@outputSchema('nodeCreated:int')
def createBillNode(nodeValue, sLabel, sTitle, sUpdated, sBillType,sBillNumber,sIntroducedAt,sStatus,sStatusAt):
    if nodeValue:
        graph_db = neo4j.GraphDatabaseService("http://localhost:7474/db/data/")
        foundNode,=graph_db.create(node(name=nodeValue))
        foundNode.add_labels(sLabel)
        foundNode["title"]=sTitle
        foundNode["updateDate"]=sUpdated
        foundNode["billType"]=sBillType
        foundNode["billNumber"]=sBillNumber
        foundNode["introducedAt"]=sIntroducedAt
        foundNode["status"]=sStatus
        foundNode["statusDate"]=sStatusAt
        return 1
    else:
        return 0

#myudf.py
@outputSchema('nodeUpdated:int')
def updateBillNode(nodeID, sTitle, sUpdated, sBillType,sBillNumber,sIntroducedAt,sStatus,sStatusAt):
    if nodeID:
        graph_db = neo4j.GraphDatabaseService("http://localhost:7474/db/data/")
        foundNode= graph_db.node(nodeID)
        foundNode["title"]=sTitle
        foundNode["updateDate"]=sUpdated
        foundNode["billType"]=sBillType
        foundNode["billNumber"]=sBillNumber
        foundNode["introducedAt"]=sIntroducedAt
        foundNode["status"]=sStatus
        foundNode["statusDate"]=sStatusAt
        return 1
    else:
        return 0


import numpy as np
import matplotlib.pyplot as plt

n_groups = 3

accuracies = (0.5174242424, 0.4590909091, 0.8159090909)

fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.15
opacity = 0.8
font_size_large = 16
font_size_small = 13

rects1 = plt.bar(index + bar_width, accuracies, bar_width,
alpha=opacity,
color='orangered')

plt.ylim(0,1.0)
plt.xlabel('Data set', fontsize=font_size_large)
plt.ylabel('Classification Accuracy', fontsize=font_size_large)
plt.title('Perceptron accuracy with different data sets', fontweight='bold', fontsize=font_size_small)
plt.xticks(index + bar_width, ('Differences', 'Ratios', 'Side-by-side'), fontsize=font_size_large)
plt.yticks(fontsize=font_size_small)

plt.tight_layout()
plt.show()


# ###########################
# Buttons that are drawn on render()
#
import logging
import threading
import time
import math
from random import randint
from enum import Enum

from PIL import Image, ImageDraw

from cockpitdecks import ICON_SIZE, DEFAULT_LABEL_FONT
from cockpitdecks.resources.iconfonts import ICON_FONTS

from cockpitdecks.resources.color import convert_color, light_off
from .representation import MultiIcons
from .draw import DrawBase

logger = logging.getLogger(__name__)
# logger.setLevel(logging.DEBUG)

#
# ###############################
# ANIMATED  REPRESENTATION
#
# ###############################
# ICON-BASED ANIMATION
# (very much like a GIF image...)
#
class IconAnimation(MultiIcons):
    """
    To start the animation, set the button's current_value to something different from None or 0.
    To stop the anination, set the button's current_value to 0.
    When not running, an optional icon_off can be supplied, otherwise first icon in multi-icons list will be used.
    """
    def __init__(self, config: dict, button: "Button"):
        MultiIcons.__init__(self, config=config, button=button)

        self.speed = float(config.get("animation-speed", 1))
        self.icon_off = config.get("icon-off")

        if self.icon_off is None and len(self.multi_icons) > 0:
            self.icon_off = self.multi_icons[0]

        # Internal variables
        self.counter = 0
        self.exit = None
        self.thread = None
        self.running = False

    def loop(self):
        self.exit = threading.Event()
        while not self.exit.is_set():
            self.button.render()
            self.counter = self.counter + 1
            self.button.set_current_value(self.counter)  # get_current_value() will fetch self.counter value
            self.exit.wait(self.speed)
        logger.debug(f"exited")

    def should_run(self) -> bool:
        """
        Check conditions to animate the icon.
        """
        value = self.get_current_value()
        return value is not None and value != 0

    def anim_start(self):
        """
        Starts animation
        """
        if not self.running:
            self.running = True
            self.thread = threading.Thread(target=self.loop)
            self.thread.name = f"ButtonAnimate::loop({self.button_name()})"
            self.thread.start()
        else:
            logger.warning(f"button {self.button_name()}: already started")

    def anim_stop(self, render: bool = True):
        """
        Stops animation
        """
        if self.running:
            self.running = False
            self.exit.set()
            self.thread.join(timeout=2*self.speed)
            if self.thread.is_alive():
                logger.warning(f"..thread may hang..")
            if render:
                self.render()
        else:
            logger.debug(f"button {self.button_name()}: already stopped")

    def clean(self):
        """
        Stops animation and remove icon from deck
        """
        logger.debug(f"button {self.button_name()}: cleaning requested")
        self.anim_stop(render=False)
        logger.debug(f"button {self.button_name()}: stopped")
        super().clean()

    def render(self):
        """
        Renders icon_off or current icon in list
        """
        if self.should_run():
            self.icon = self.multi_icons[(self.counter % len(self.multi_icons))]
            if not self.running:
                self.anim_start()
            return super().render()
        if self.running:
            self.anim_stop()
        self.icon = self.icon_off
        return super(MultiIcons, self).render()

    def describe(self):
        """
        Describe what the button does in plain English
        """
        a = [
            f"The representation produces an animation by displaying an icon from a list of {len(self.multi_icons)} icons"
            f"and changing it every {self.speed} seconds."
        ]
        if self.icon_off is not None:
            a.append(f"When the animation is not running, it displays an OFF icon {self.icon_off}.")
        return "\n\r".join(a)

#
# ###############################
# ANIMATED DRAW REPRESENTATION
#
#
class DrawAnimation(DrawBase):
    """
    https://stackoverflow.com/questions/5114292/break-interrupt-a-time-sleep-in-python
    """

    def __init__(self, config: dict, button: "Button"):

        DrawBase.__init__(self, config=config, button=button)

        self._animation = config.get("animation", {})

        # Base definition
        self.speed = float(self._animation.get("speed", 1))

        # Working attributes
        self.tween = 0

        self.running = None  # state unknown
        self.exit = None
        self.thread = None

    def loop(self):
        self.exit = threading.Event()
        while not self.exit.is_set():
            self.animate()
            self.button.render()
            self.exit.wait(self.speed)
        logger.debug(f"exited")

    def should_run(self) -> bool:
        """
        Check conditions to animate the icon.
        """
        return False

    def animate(self):
        """
        Where changes between frames occur

        :returns:   { description_of_the_return_value }
        :rtype:     { return_type_description }
        """
        self.tween = self.tween + 1
        # logger.debug(f"tick")
        return super().render()

    def anim_start(self):
        """
        Starts animation
        """
        if not self.running:
            self.running = True
            self.thread = threading.Thread(target=self.loop)
            self.thread.name = f"ButtonAnimate::loop({self.button.name})"
            self.thread.start()
            logger.debug(f"started")
        else:
            logger.warning(f"button {self.button.name}: already started")

    def anim_stop(self):
        """
        Stops animation
        """
        if self.running:
            self.running = False
            self.exit.set()
            self.thread.join(timeout=2*self.speed)
            if self.thread.is_alive():
                logger.warning(f"button {self.button.name}: animation did not terminate")
            logger.debug(f"stopped")
        else:
            logger.debug(f"button {self.button.name}: already stopped")

    def clean(self):
        """
        Stops animation and remove icon from deck
        """
        logger.debug(f"button {self.button.name}: cleaning requested")
        self.anim_stop()
        logger.debug(f"button {self.button.name}: stopped")
        super().clean()

    def render(self):
        """
        Renders icon_off or current icon in list
        """
        logger.debug(f"button {self.button.name}: enter")
        if self.is_valid():
            logger.debug(f"button {self.button.name}: is valid {self.should_run()}, {self.running}")
            if self.should_run():
                if not self.running:
                    self.anim_start()
                return super().render()
            else:
                if self.running:
                    self.anim_stop()
                return super().render()
        return None

class DrawAnimationFTG(DrawAnimation):

    def __init__(self, config: dict, button: "Button"):

        DrawAnimation.__init__(self, config=config, button=button)

    def should_run(self):
        """
        I.e. only works with onoff activations.
        """
        return hasattr(self.button._activation, "is_on") and self.button._activation.is_on()

    def get_image_for_icon(self):
        """
        Can use self.running to check whether animated or not.
        Can use self.tween to increase iterations.
        Text, color, sizes are all hardcoded here.
        """
        image, draw = self.double_icon(width=ICON_SIZE, height=ICON_SIZE)

        bgrd = self.get_background(width=image.width, height=image.height)
        image.paste(bgrd)
        # Button
        cs = 4  # light size, px
        lum = 5 # num flashing green center lines
        nb = 2 * lum  # num side bleu lights, i.e. twice more blue lights than green ones
        h0 = ICON_SIZE/16  # space from left/right sides
        h1 = ICON_SIZE / 2 - h0  # space from bottom of upper middle part
        s = (ICON_SIZE - (2*h0)) / (nb - 1) # spece between blue lights
        # Taxiway borders, blue lights
        for i in range(nb):
            for h in [h0, h1]:
                w = h0 + i * s
                tl = [w-cs, h-cs]
                br = [w+cs, h+cs]
                draw.ellipse(tl+br, fill="blue")
        # Taxiway center yellow line
        h = ICON_SIZE / 4
        draw.line([(h0, h), (ICON_SIZE - h0, h)], fill="yellow", width=4)

        # Taxiway center lights, lit if animated
        cs = 2 * cs
        for i in range(lum):
            w = h + i * s * 2 - s / 2
            w = ICON_SIZE - w
            tl = [w-cs, h-cs]
            br = [w+cs, h+cs]
            color = "lime" if self.running and (self.tween+i) % lum == 0 else "chocolate"
            draw.ellipse(tl+br, fill=color)

        # Text AVAIL (=off) or framed ON (=on)
        font = self.get_font(DEFAULT_LABEL_FONT, 80)
        inside = ICON_SIZE / 16
        cx = ICON_SIZE / 2
        cy = int( 3 * ICON_SIZE / 4 )
        if self.running:
            draw.multiline_text((cx, cy),
                      text="ON",
                      font=font,
                      anchor="mm",
                      align="center",
                      fill="deepskyblue")
            txtbb = draw.multiline_textbbox((cx, cy),  # min frame, just around the text
                      text="ON",
                      font=font,
                      anchor="mm",
                      align="center")
            text_margin = 2 * inside  # margin "around" text, line will be that far from text
            framebb = ((txtbb[0]-text_margin, txtbb[1]-text_margin/2), (txtbb[2]+text_margin, txtbb[3]+text_margin/2))
            side_margin = 4 * inside  # margin from side of part of annunciator
            framemax = ((cx - ICON_SIZE/2 + side_margin, cy - ICON_SIZE/4 + side_margin), (cx + ICON_SIZE/2 - side_margin, cy + ICON_SIZE/4 - side_margin))
            frame = ((min(framebb[0][0], framemax[0][0]),min(framebb[0][1], framemax[0][1])), (max(framebb[1][0], framemax[1][0]), max(framebb[1][1], framemax[1][1])))
            thick = int(ICON_SIZE / 32)
            # logger.debug(f"button {self.button.name}: part {partname}: {framebb}, {framemax}, {frame}")
            draw.rectangle(frame, outline="deepskyblue", width=thick)
        else:
            font = self.get_font(DEFAULT_LABEL_FONT, 60)
            draw.multiline_text((cx, cy),
                      text="AVAIL",
                      font=font,
                      anchor="mm",
                      align="center",
                      fill="lime")

        return image.convert("RGB")


from typing import Optional
from PyQt6 import QtCore, QtGui, QtWidgets

from lib.utils import get_method_colour, get_status_colour
from ui.qt_models.requests_table_model import RequestsTableModel

class RowStyleDelegate(QtWidgets.QStyledItemDelegate):
    HOVER_COLOUR = "#252526"

    hovered_index: QtCore.QModelIndex
    prev_hovered_index: QtCore.QModelIndex
    hover_background: QtGui.QBrush

    def __init__(self, parent: Optional[QtCore.QObject] = None):
        super(RowStyleDelegate, self).__init__(parent=None)
        self.parent = parent # type:ignore
        self.hovered_index = QtCore.QModelIndex()

    def highlight_index(self, index: QtCore.QModelIndex):
        self.hovered_index = index
        self.parent.viewport().update()

    # https://stackoverflow.com/questions/20565930/qtableview-how-can-i-highlight-the-entire-row-for-mouse-hover
    def initStyleOption(self, options: QtWidgets.QStyleOptionViewItem, index: QtCore.QModelIndex):
        super().initStyleOption(options, index)
        # options.displayAlignment = QtCore.Qt.AlignmentFlag.AlignCenter
        if self.hovered_index.row() == index.row():
            options.backgroundBrush = QtGui.QBrush(QtGui.QColor(self.HOVER_COLOUR))

    def paint(self, painter: QtGui.QPainter, options: QtWidgets.QStyleOptionViewItem, index: QtCore.QModelIndex):
        super().paint(painter, options, index)

        model: RequestsTableModel = index.model()  # type: ignore
        value = model.get_value(index)

        rect = self.parent.viewport().rect()
        x = self.parent.columnViewportPosition(index.column())
        x_next = self.parent.columnViewportPosition(index.column()+1)

        # Method column
        if index.column() == 3:
            color = get_method_colour(str(value))

            label = QtWidgets.QLabel(value)
            label.setAutoFillBackground(True)
            label.setObjectName("mylabel")
            label.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
            label.setMinimumWidth(50)
            label.setStyleSheet(f"color: {color}; background: transparent;")

            # painter.fillRect(options.rect, QtGui.QColor("#C3E88D"))
            x_offest = 5
            y_offset = 0
            painter.drawPixmap(x+x_offest, options.rect.y()+y_offset, label.grab())

        # Response status column
        elif index.column() == 6:
            if value is None:
                return
            bg_color = get_status_colour(int(value)) # type:ignore

            label = QtWidgets.QLabel(str(value))
            label.setAutoFillBackground(True)
            label.setObjectName("responseStatusLabelTable")
            label.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
            label.setMinimumWidth(30)
            label.setStyleSheet(f"background-color: {bg_color};")
            # painter.fillRect(options.rect, QtGui.QColor("#C3E88D"))
            x_offest = 9
            y_offset = 0
            painter.drawPixmap(options.rect.x()+x_offest, options.rect.y()+y_offset, label.grab())


#!/usr/bin/env python3
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.

import sys

from fluent.syntax import parse
from fluent.syntax.ast import Message

def find_error_ids(filename, known_strings):
    with open(filename, "r", encoding="utf-8") as f:
        known_strings += [
            m.id.name for m in parse(f.read()).body if isinstance(m, Message)
        ]

def main(output, *filenames):
    known_strings = []
    for filename in filenames:
        find_error_ids(filename, known_strings)

    output.write("const KNOWN_ERROR_MESSAGE_IDS = new Set([\n")
    for known_string in known_strings:
        output.write('  "{}",\n'.format(known_string))
    output.write("]);\n")

if __name__ == "__main__":
    sys.exit(main(sys.stdout, *sys.argv[1:]))


"""
Group-level analysis from individual clusters
=============================================

In this tutorial, we will learn how to conduct group level analysis
by computing group-level topographies based on individual clusters.
"""

#%%
# .. include:: ../../../../links.inc

#%%
# .. note::
#
#     The lemon datasets used in this tutorial is composed of EEGLAB files. To
#     use the MNE reader :func:`mne.io.read_raw_eeglab`, the ``pymatreader``
#     optional dependency is required. Use the following installation method
#     appropriate for your environment:
#
#     - ``pip install pymatreader``
#     - ``conda install -c conda-forge pymatreader``
#
#     Note that an environment created via the `MNE installers`_ includes
#     ``pymatreader`` by default.

# sphinx_gallery_thumbnail_number = 2

import matplotlib.pyplot as plt
import numpy as np
from mne.io import read_raw_eeglab

from pycrostates.cluster import ModKMeans
from pycrostates.datasets import lemon
from pycrostates.io import ChData
from pycrostates.preprocessing import extract_gfp_peaks

condition = "EO"
subject_ids = ["010020", "010021", "010022", "010023", "010024"]

#%%
# In this example, we start with a subject level analysis by computing
# individual topographies from :term:`Global Field Power` (:term:`GFP`) peaks.
# Then, the individual topographies are concatenated and used in the group
# level analysis to fit a second clustering algorithm.

individual_cluster_centers = list()
for subject_id in subject_ids:
    # load Data
    raw_fname = lemon.data_path(subject_id=subject_id, condition=condition)
    raw = read_raw_eeglab(raw_fname, preload=True)
    raw = lemon.standardize(raw)
    raw.pick("eeg")
    raw.crop(0, 30)  # crop the dataset to speed up computation
    raw.set_eeg_reference("average")
    # extract GFP peaks
    gfp_peaks = extract_gfp_peaks(raw)
    # subject level clustering
    ModK = ModKMeans(n_clusters=5, random_state=42)
    ModK.fit(gfp_peaks, n_jobs=2)
    individual_cluster_centers.append(ModK.cluster_centers_)

group_cluster_centers = np.vstack(individual_cluster_centers).T
group_cluster_centers = ChData(group_cluster_centers, ModK.info)

# group level clustering
ModK = ModKMeans(n_clusters=5, random_state=42)
ModK.fit(group_cluster_centers, n_jobs=2)
ModK.plot()

#%%
# The :term:`cluster centers` can be re-organize to our needs.

ModK.reorder_clusters(order=[4, 2, 0, 1, 3])
ModK.rename_clusters(new_names=["MS1", "MS2", "MS3", "MS4", "MS5"])
ModK.plot()

#%%
# We can now use this fitted clustering algorithm to predict the segmentation
# on each individual. This is also referred to as backfitting the group level
# maps to each individual recording. Finally, we can extract microstate
# parameters from the backfitted segmentations.

ms_data = list()
for subject_id in subject_ids:
    # Load Data
    raw_fname = lemon.data_path(subject_id=subject_id, condition=condition)
    raw = read_raw_eeglab(raw_fname, preload=True)
    raw = lemon.standardize(raw)
    raw.pick("eeg")
    raw.crop(0, 30)  # for sake of time
    raw.set_eeg_reference("average")
    segmentation = ModK.predict(raw, factor=10, half_window_size=8)
    d = segmentation.compute_parameters()
    d["subject_id"] = subject_id
    ms_data.append(d)

#%%
# From this point on, we can visualize our results and do a statistical
# analysis. For example we can plot the :term:`GEV` of each microstate class.

data = [
    [d['MS1_gev'], d['MS2_gev'], d['MS3_gev'], d['MS4_gev'], d['MS5_gev']]
    for d in ms_data
]

plt.violinplot(np.array(data))
plt.title("Global Explained Variance (%)")
plt.xticks(
    ticks=range(1, len(ModK.cluster_names) + 1),
    labels=ModK.cluster_names,
)
plt.show()


valore=False
while valore==False:
    n=input('Inserisci l\'altezza: ')
    try:
        num=int(n)
        if(num>0 and num<9):
            valore=True
        else:
            print(n+' non è compreso tra 0 e 9!')
            valore=False
    except ValueError:
        print(n+' non è un numero intero!')
        valore=False

cont=0
for i in range(1,num+1):
    for j in range(1,num - i+1):
        print(' ',end='')
    cont=1
    for k in range(num-i+1,num+1):
        print(str(cont),end='')
        cont=cont+1
    cont=i-1
    for k in range(num-i+2,num+1):
         print(str(cont),end='')
         cont=cont-1
    print('\n', end='')


""" Forms for subscriber app """
import logging

from django import forms
from django.forms import ValidationError
from django.forms.util import ErrorList

from django.contrib.localflavor.us.forms import USPhoneNumberField

from common.session import parse_curr_session_keys
from common.custom_cleaning import clean_phone_number, trim_fields_in_form
from common.custom_validation import validate_phone_number, validate_zip_postal
from sms_gateway.service import send_carrier_lookup
from subscriber.models import Carrier

LOG = logging.getLogger('ten.%s' % __name__)
LOG.setLevel(logging.ERROR)

class SubscriberRegistrationForm(forms.Form):
    """ Register a subscriber. This is also the Send to Phone form. """
    email = forms.CharField(required=False)
    mobile_phone_number = USPhoneNumberField(widget=forms.TextInput(attrs={
        'class':'fulltext',
        'size': '20',
        'maxlength': '15',
        'tabindex':'1'}
        ), error_messages={
        'required': u' Please enter the 10 digit number of your cell phone',
        'invalid': u' Please enter the 10 digit number of your cell phone'}
        )
    carrier = forms.ModelChoiceField(
        queryset=Carrier.objects.get_or_set_carrier_cache(),
        empty_label = '- select carrier -',
        widget=forms.Select(attrs={'class':'fulltext', 'tabindex':'3'}),
        error_messages={
        'required': u'Select your cell phone service provider',
        'invalid': u'Select a Carrier'}
        )
    subscriber_zip_postal = forms.CharField(widget=forms.TextInput(attrs={
        'size':'10',
        'maxlength':'9',
        'tabindex':'2'}
        ), required=True)

    def clean(self):
        # Only do carrier lookup if the rest of the form is good, since it
        # costs.
        self.cleaned_data = trim_fields_in_form(self)
        LOG.debug('cleaned_data: %s' % self.cleaned_data)
        if self.errors == {} and self.cleaned_data.get('carrier', None):
            carrier = self.cleaned_data.get("carrier")
            if carrier.id == 1:
                try:
                    carrier = send_carrier_lookup(
                        self.cleaned_data['mobile_phone_number'])
                    if carrier:
                        self.cleaned_data['carrier'] = carrier
                except ValidationError:
                    self.errors['mobile_phone_number'] = ErrorList(
                        ["Oops! We tried, but couldn't connect to that phone." +
                        " Please check the number."])
                    # The internationalization code below was erroring out the
                    # subscriber reg form. Would block an ajax json encoded
                    # submit.
                    #self.errors['mobile_phone_number'] = ErrorList(
                    #    [_("""Oops! We tried, but couldn't connect to that
                    #        phone. Please check the number.""")])
        subscriber_zip_postal = self.cleaned_data.get("subscriber_zip_postal")
        validate_zip_postal(self, subscriber_zip_postal,
            'subscriber_zip_postal')
        # Always return cleaned_data back
        return self.cleaned_data

    def clean_mobile_phone_number(self):
        self.cleaned_data['mobile_phone_number'] = clean_phone_number(
            self.cleaned_data.get('mobile_phone_number', None))
        validate_phone_number(self, self.cleaned_data['mobile_phone_number'],
            'mobile_phone_number')
        return self.cleaned_data['mobile_phone_number']

    def clean_subscriber_zip_postal(self):
        self.cleaned_data['subscriber_zip_postal'] = \
            self.cleaned_data.get('subscriber_zip_postal', None).strip()
        return self.cleaned_data['subscriber_zip_postal']

    def get_cleaned_data_for_sms(self):
        """
        Just clean phone and zip without validating entire form. This method
        was created to return the cleaned data fields after another process was
        called which validated and handled resubmits:
            coupon.view.show_sms.send_sms_single_coupon
        At this point the form submission has been accepted.
        """
        if not hasattr(self, 'cleaned_data'):
            self.cleaned_data = {
                'mobile_phone_number': self.data['mobile_phone_number'],
                'subscriber_zip_postal': self.data['subscriber_zip_postal']}
        self.cleaned_data.update({
            'mobile_phone_number': self.clean_mobile_phone_number(),
            'subscriber_zip_postal': self.clean_subscriber_zip_postal()})
        return self.cleaned_data

def get_subscriber_reg_init_data(_session):
    """ Pre-populate the subscriber registration form if possible. """
    initial_data = {}
    try:
        session_dict = parse_curr_session_keys(_session,
                ['carrier_id', 'mobile_phone_number', 'subscriber_zip_postal'])
        initial_data = {
            'mobile_phone_number':session_dict['mobile_phone_number'],
            'subscriber_zip_postal':session_dict['subscriber_zip_postal'],
            'carrier':session_dict['carrier_id']}
    except KeyError:
        try:
            consumer_zip_postal = \
                _session['consumer']['consumer_zip_postal']
            initial_data = {'subscriber_zip_postal':consumer_zip_postal}
        except KeyError:
            pass
    return initial_data


import numpy as np
import cv2
import matplotlib.pyplot as plt
import imutils
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

def displayScreens(feed):
    for image in feed:
        cv2.imshow("Image Output", image)
        cv2.waitKey(0)
    cv2.destroyAllWindows()

source = "sample1.jpeg"

img = cv2.imread(source)

grayscale = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

gray = cv2.bilateralFilter(grayscale, 13, 15, 15)

edged = cv2.Canny(gray, 30, 200)

contours = cv2.findContours(edged.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = imutils.grab_contours(contours)
contours = sorted(contours, key=cv2.contourArea, reverse = True)[:10]
screenCnt = None
d = False
draw = img.copy()

for c in contours:
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.018 * peri, True)
    if len(approx) == 4:
        screenCnt = approx
        d = True
        break

if d == False:
    detected = 0
    print("No detection.")
else:
    detected = 1

if detected == 1:
    cv2.drawContours(draw, [screenCnt], -1, (0, 0, 255), 3)

mask = np.zeros(gray.shape, np.uint8)
new_image = cv2.drawContours(mask, [screenCnt], 0, 255, -1)
new_image = cv2.bitwise_and(draw, draw, mask=mask)

(x, y) = np.where(mask == 255)
(topx, topy) = (np.min(x), np.min(y))
(bottomx, bottomy) = (np.max(x), np.max(y))
cropped = gray[topx:bottomx+1, topy:bottomy+1]
cropped = cv2.resize(cropped, (0, 0), fx=3, fy=3)
offset = 5

text = pytesseract.image_to_string(cropped, config='--psm 10')
#text = pytesseract.image_to_string(cropped)
#draw = cv2.putText(draw, str(text), (topx + offset, topy + offset), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 5)

print("-------------------------------------------------------------------")
print("Registration Plate Recognition:\n")
print("Detection: ", text)
print("-------------------------------------------------------------------")

feed = [img, grayscale, gray, edged, draw, cropped]
displayScreens(feed)

Python Machine Learning/Number Plate Recognition/code/main.py


from collections import defaultdict

class SymbolMap(defaultdict):

    def __init__(self, *args, **kwargs):
        super().__init__(None, *args, **kwargs)

    def __missing__(self, key):
        self[key] = key
        return key

symbols = SymbolMap({
    'j': 'D', 'ñ': '~', 'ng': 'N', 'ts': 'C',
    'aa': ':', 'ii': '1', 'ee': '2', 'uu': '3', 'oo': '4',
    'ie': '5', 'ei': '6', 'uo': '7', 'ou': '8',
    'trailing_consonant': '/',
    'non_trailing_consonant': '=',
    'double_syllable': ':',
    'consonant_stop': '-',
    'double_consonant_stop': ';'})


import cv2
import numpy as np
import time
import window_capture
import keras
from controls import PressKey, ReleaseKey
import getkeys

W = 0x11
A = 0x1E
D = 0x20

def move_straight():
    PressKey(W)
    ReleaseKey(D)
    ReleaseKey(A)

def move_right():
    PressKey(D)
    ReleaseKey(A)
    ReleaseKey(W)

def move_left():
    PressKey(A)
    ReleaseKey(D)
    ReleaseKey(W)

for i in list(range(4))[::-1]:
    print(i+1)
    time.sleep(1)

width = 200
height = 66
model = keras.models.load_model('Final_models/Roblox-drivesimulator-0.0001-nvidia-6-epochs.model')
wincap = window_capture.WindowCapture('Roblox')
loop_time = time.time()
paused = False

while True:
    if not paused:
        keys = getkeys.key_check()
        screenshot = wincap.get_screenshot()
        screenshot = cv2.resize(screenshot, (200, 66))
        prediction = model.predict([screenshot.reshape(-1, width, height, 1)])[0]
        moves = list(np.around(prediction))
        print(moves, prediction)
        print('FPS {}'.format(1 / (time.time() - loop_time)))
        loop_time = time.time()

        if moves == [1, 0, 0] and prediction[0] >= 0.9:
            move_left()
        elif moves == [0, 1, 0]:
            move_straight()
        elif moves == [0, 0, 1] and prediction[2] >= 0.9:
            move_right()

    keys = getkeys.key_check()
    if 'T' in keys:
        if paused:
            paused = False
            print('unpaused!')
            time.sleep(1)
        else:
            print('Pausing!')
            paused = True
            time.sleep(1)


import sys
from PyQt5.QtCore import pyqtSignal, QObject
from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QLabel, QLineEdit, QRadioButton, QFileDialog, QPushButton, QMessageBox, QProgressBar
from analysis import analysis
import operator

class Communicate(QObject):
    bar_on = pyqtSignal()
    bar_off = pyqtSignal()

class MyApp(QWidget):
    def __init__(self):
        super().__init__()

        self.an = analysis()
        self.radio = []
        self.rank = []
        self.c = Communicate()
        self.c.bar_on.connect(self.bar_unlimit_on)
        self.c.bar_off.connect(self.bar_unlimit_off)

        self.initUI()

    def initUI(self):
        grid = QGridLayout()
        self.setLayout(grid)

        # 위젯 생성
        self.setfilename = QPushButton('파일 선택', self)

        self.radio.append(QRadioButton('windows', self))
        self.radio.append(QRadioButton('Mac OS', self))
        self.radio.append(QRadioButton('android', self))
        self.radio.append(QRadioButton('IOS', self))

        self.pbar = QProgressBar()

        self.Fname_Label = QLabel('미선택')
        self.input_name = QLineEdit()
        self.submit = QPushButton('분석 시작', self)

        # 위젯 설정
        self.input_name.setPlaceholderText('미입력시 전체 분석')
        self.setfilename.clicked.connect(self.showDialog)
        self.submit.clicked.connect(self.start_Analysis)

        # 배치
        grid.addWidget(QLabel('대화 파일:'), 0, 0)
        grid.addWidget(QLabel('데이터\n운영체제:'), 1, 0, 4, 1)
        grid.addWidget(QLabel('분석할 이름:'), 5, 0)
        grid.addWidget(QLabel('가장 많이 한 말 top 5'), 7, 0, 1, 3)

        grid.addWidget(self.Fname_Label, 0, 1)
        grid.addWidget(self.setfilename, 0, 2)
        for i in range(len(self.radio)):
            grid.addWidget(self.radio[i], i+1, 1)
        grid.addWidget(self.input_name, 5, 1)
        grid.addWidget(self.submit, 5, 2)

        grid.addWidget(self.pbar, 6, 0, 1, 3)

        for i in range(5):
            self.rank.append(QLabel(str(i+1) + '. '))
            grid.addWidget(self.rank[i], i+8, 0, 1, 4)

        self.setWindowTitle('test')
        # self.setGeometry(300, 300, 300, 250)
        self.show()

    def showDialog(self):
        self.pbar.setValue(0)
        fname = QFileDialog.getOpenFileName(self, 'Open file', './')
        if fname[0]:
            self.filename = fname[0]
            self.Fname_Label.setText(fname[0].split('/')[-1])

    def start_Analysis(self):
        # 입력 에러 검사
        if self.Fname_Label == '미선택':
            QMessageBox.about(self, 'Error', '분석할 파일을 선택하세요.')
            return

        for i in range(len(self.radio)):
            if self.radio[i].isChecked():
                os = i+1
                break
        else:
            QMessageBox.about(self, 'Error', '데이터셋을 추출한 os를 선택하세요.')
            return

        # 분석 시작
        self.c.bar_on.emit()
        state = self.an.fileload(self.filename, os)
        if not state:
            QMessageBox.about(self, 'Error', '파일 로드에 실패했습니다.')
            return

        self.an.analysis(self.input_name.text())

        # 가장 많이 한 말 5위 단어 및 빈도 출력
        for i in self.an.get_rank(5):
            self.rank[i[0]].setText(self.rank[i[0]].text()[:3]+i[1]+': '+str(i[2]))

        self.c.bar_off.emit()
        self.an.write_wordcloud()

    def bar_unlimit_on(self):
        self.pbar.setRange(0, 0)

    def bar_unlimit_off(self):
        self.pbar.setRange(0, 100)
        self.pbar.setValue(100)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())