__version__ = '$Rev$'

import logging
import re

from datetime import date

from core.constants import TIME_MINUTE
from core.config import Config
from objects.calendar import Event

from components.calendar import InvalidObjectId
from interaction.irc.module import InteractiveModule, InteractiveModuleCommand, InteractiveModuleRequest, InteractiveModuleResponse, ModuleError, Location

#-------------------------------------------------------------------------------
# Constants
#-------------------------------------------------------------------------------
REGEX_DATE = re.compile('^(\d{1,2})\.(\d{1,2})\.(\d{4})$')

#-------------------------------------------------------------------------------
# Exceptions
#-------------------------------------------------------------------------------
class CalendarModuleError(ModuleError): pass
class EventError(CalendarModuleError): pass
class EventNotFound(EventError): pass
class NoEventsFound(EventError): pass
class AmbiguousEventsFound(EventError): pass
class DateError(CalendarModuleError): pass
class DateFormatInvalid(DateError): pass
class DateRangeInvalid(DateError): pass

#-------------------------------------------------------------------------------
# Business Logic
#-------------------------------------------------------------------------------
class Calendar(InteractiveModule):
    """
    This module provides calendaring functions.
    """

    #---------------------------------------------------------------------------
    # Module implementation
    #---------------------------------------------------------------------------
    def initialize(self):
        bot = self.client.bot;

        bot.register_config(CalendarConfig)

        self.logger = logging.getLogger('interaction.irc.calendar')
        self.config = bot.get_config('interaction.irc.calendar')
        self.component = bot.get_subsystem('calendar-component');

        bot.register_timer(
            'interaction.irc.calendar.reminder',
            'daily',
            self.config.get('reminderInterval'),
            self._display_reminder
        )

    # --------------------------------------------------------------------------
    # Lifecycle
    # --------------------------------------------------------------------------
    def start(self):
        self.client.bot.get_timer('interaction.irc.calendar.reminder').start()

    def stop(self):
        self.client.bot.get_timer('interaction.irc.calendar.reminder').stop()

    #---------------------------------------------------------------------------
    # InteractiveModule implementation
    #---------------------------------------------------------------------------
    def module_identifier(self):
        return 'Kalender'

    def init_commands(self):
        return [
            InteractiveModuleCommand(
                 keyword='kalender',
                 callback=self.display_calendar_address,
            ),
            InteractiveModuleCommand(
                 keyword='listtoday',
                 callback=self.display_events_today,
            ),
            InteractiveModuleCommand(
                 keyword='listdeleted',
                 callback=self.display_deleted_objects,
                 pattern=r'^(.*)$',
                 syntaxhint='[kalendar|event|kontakt]'
            ),
            InteractiveModuleCommand(
                 keyword='restore',
                 callback=self.restore_deleted_object,
                 pattern=r'^[\d]+$',
                 syntaxhint='<id>'
            ),

            InteractiveModuleCommand(
                 keyword='addevent',
                 callback=self.insert_event,
                 pattern=r'^(\d{1,2}\.\d{1,2}\.\d{4}|\d{1,2}\.\d{1,2}\.\d{4}-\d{1,2}\.\d{1,2}\.\d{4})\s(.+)$',
                 syntaxhint='<datumvon>[-datumbis] <titel>'
            ),
            InteractiveModuleCommand(
                 keyword='editevent',
                 callback=self.change_event,
                 pattern=r'^([\d]+)\s(.+?)\s(.+)$',
                 syntaxhint='<id> <start|ende|titel|beschreibung|ort> <wert>'
            ),
            InteractiveModuleCommand(
                 keyword='delevent',
                 callback=self.delete_event,
                 pattern=r'^([\d]+|\d{1,2}\.\d{1,2}\.\d{4})$',
                 syntaxhint='<id|datum>'
            ),
            InteractiveModuleCommand(
                 keyword='searchevent',
                 callback=self.search_event,
                 pattern=r'^(.+)$',
                 syntaxhint='<text>'
            ),
            InteractiveModuleCommand(
                 keyword='topicevent',
                 callback=self.topic_event,
                 pattern=r'^[\d]+$',
                 syntaxhint='<id>'
            ),

            InteractiveModuleCommand(
                 keyword='addcontact',
                 callback=self.insert_contact,
                 pattern=r'^(.+)\s(\d{1,2}\.\d{1,2}\.\d{4})$',
                 syntaxhint='<nickname> <geburtsdatum>'
            ),
            InteractiveModuleCommand(
                 keyword='editcontact',
                 callback=self.change_contact,
                 pattern=r'^[\d]+\s(.+)\s(.+)$',
                 syntaxhint='<id> <vorname|nachname|nickname|geburtsdatum> <wert>'
            ),
            InteractiveModuleCommand(
                 keyword='delcontact',
                 callback=self.delete_contact,
                 pattern=r'^([\d]+|(.+))$',
                 syntaxhint='<id>'
            ),
            InteractiveModuleCommand(
                 keyword='searchcontact',
                 callback=self.search_contact,
                 pattern=r'^(.+)$',
                 syntaxhint='<text>'
            )
        ]

    #---------------------------------------------------------------------------
    # Internal module commands
    #---------------------------------------------------------------------------
    def _get_date(self, date_string):
        """
        Check if the input_string contains a valid date.

        The input string is first converted using REGEX_DATE and then
        checked.

        @param date_string: The input string. See REGEX_DATE for the format.

        @return A date object.

        @raise DateFormatInvalid If no properly formatted date was given.
        @raise DateRangeInvalid  If the date values are out of range.
        """

        matchlist = REGEX_DATE.search(date_string)

        if not matchlist:
            raise DateFormatInvalid

        date_tokens = matchlist.group(1, 2, 3)

        try:
            return date(int(date_tokens[2]),int(date_tokens[1]),int(date_tokens[0]))

        except ValueError as e:
            raise DateRangeInvalid(e)

    def _display_reminder(self, date):
        """
        Timer callback function.
        """

        request = InteractiveModuleRequest(
        )

        response = self.display_events_by_date(None, Location.CHANNEL, None, [date])

        for channel in self.usermgmt.chanlist.get_channels().values():
            self.send_response(channel, response)

    #---------------------------------------------------------------------------
    # InteractiveModule commands - display
    #---------------------------------------------------------------------------
    def display_calendar_address(self, request):
        """
        Display the web calendar's address.
        """

        response = InteractiveModuleResponse(self.config.get('calendarUrl'))

        return response

    def display_events_today(self, request):
        """
        Display today's events, if any.
        """

        request.parameter = [date.today()]

        return self.display_events_by_date(request)

    def display_events_by_date(self, request):
        """
        Display events occuring at the given date.
        """

        response = InteractiveModuleResponse()

        date = request.parameter[0]

        try:
            calendar_events = self.component.find_events_by_date(date)

            if len(calendar_events) == 0:
                raise NoEventsFound

            for calendar_event in calendar_events:
                response.add_line("ID {0}: {1}".format(calendar_event.id, calendar_event.title))

        except NoEventsFound:
            response.add_line('Keine Termine gefunden.')

        return response

    def display_deleted_objects(self, event, location, command, parameter):
        """
        """

        return InteractiveModuleResponse('not implemented')

    def restore_deleted_object(self, request):
        """
        """

        return InteractiveModuleResponse('not implemented')

    #---------------------------------------------------------------------------
    # InteractiveModule commands - events
    #---------------------------------------------------------------------------
    def insert_event(self, request):
        """
        Create a new event.

        .addevent <startdate>[-<enddate>] title
        """

        response = InteractiveModuleResponse()

        date = request.parameter[0]
        title = request.parameter[1]

        try:
            if '-' not in date:
                dateFrom = self._get_date(date)
                dateTo = dateFrom

            else:
                dates = date.split('-')

                dateFrom = self._get_date(dates[0])
                dateTo = self._get_date(dates[1])

            calendar = self.component.find_default_calendar()

            event = Event(calendar=calendar, start=dateFrom, end=dateTo, title=title)
            event = self.component.insert_object(event)

            response.add_line("Eintrag erfolgreich eingefügt! ID: {0}".format(event.id))

        except DateFormatInvalid:
            response.add_line("Datum muss im Format [d]d.[m]m.yyyy sein. Bsp: 12.5.2010")

        except DateRangeInvalid as e:
            response.add_line('Ungültiges Datum: {0}.'.format(e))

        return response

    def change_event(self, event, location, command, parameter):
        """
        Change an existing event.
        The event is identified by its ID.

        Syntax: <id> <start|ende|titel|beschreibung|ort> <wert>
        """

        response = InteractiveModuleResponse()

        eventId = parameter[0]
        attribute = parameter[1]
        value = parameter[2]

        try:
            map = {
                'start' : 'start',
                'ende' : 'end',
                'titel' : 'title',
                'beschreibung' : 'description',
                'ort' : 'location'
            }

            if attribute in ['start', 'ende']:
                value = self._get_date(value)

            event = self.component.find_event_by_id(eventId)

            setattr(event, map[attribute], value)

            self.component.update_object(event)

            response.add_line('{0} fuer Eintrag {1} wurde auf {2} gesetzt'.format(
                attribute.capitalize(),
                event.id,
                value
            ))

        except DateFormatInvalid:
            response.add_line("Datum muss im Format [d]d.[m]m.yyyy sein. Bsp: 12.5.2010")

        except EventNotFound:
            response.add_line('Kein Event mit ID {0} gefunden'.format(eventId))

        return response

    def delete_event(self, request):
        """
        .delevent [<id>|<datum>]
        """

        response = InteractiveModuleResponse()

        # when only one parameter is defined a string is returned
        id_or_date = request.parameter[0]

        try:
            try:
                date = self._get_date(id_or_date)

                #---------------------------------------------------------------
                # delete by date
                #---------------------------------------------------------------
                events = self.component.find_events_by_date(date)

                count = len(events)

                if count == 0:
                    raise NoEventsFound

                if count > 1:
                    raise AmbiguousEventsFound(events)

                event = events[0]

            except DateFormatInvalid:
                #---------------------------------------------------------------
                # delete by id
                #---------------------------------------------------------------
                eventId = int(id_or_date)

                event = self.component.find_event_by_id(eventId)

                if not event:
                    raise NoEventsFound

            self.component.delete_object(event)

            response.add_line("Eintrag {0} wurde geloescht.".format(id_or_date))

        except InvalidObjectId:
            response.add_line("Kein Eintrag zu dieser ID gefunden.")

        except NoEventsFound:
            response.add_line("Kein Eintrag zu diesem Datum gefunden.")

        except AmbiguousEventsFound as error:
            response.add_line('Mehrere Einträge gefunden:')
            [response.add_line("(ID={0}) {1}".format(event.id, event.title)) for event in error.message]

        return response

    def search_event(self, request):
        """
        Search for an event

        .searchevent <text>
        """

        response = InteractiveModuleResponse()

        query = request.parameter[0]

        try:
            events = self.component.find_events_by_substring(query)

            [response.add_line("(ID={0}) {1}".format(event.id, event.title)) for event in events]

        except NoEventsFound:
            response.add_line("Keine Einträge mit diesem Inhalt gefunden.")

        return response

    def topic_event(self, request):
        """
        Post the given event to the current topic.
        .topicevent

        TODO: implement
        """

        response = InteractiveModuleResponse()

        eventId = int(request.parameter[0])

        try:
            result = self.component.find_event_by_id(eventId)

            if result is None:
                raise EventNotFound

            response.add_line('currently not implemented');

        except EventNotFound:
            response.add_line('Kein Event mit ID {0} gefunden'.format(eventId))

        return response

    #---------------------------------------------------------------------------
    # InteractiveModule commands - contacts
    #---------------------------------------------------------------------------
    def insert_contact(self, request):
        """
        """

        response = InteractiveModuleResponse("not implemented")

        return response

    def change_contact(self, request):
        """
        """

        response = InteractiveModuleResponse("not implemented")

        return response

    def delete_contact(self, request):
        """
        """

        response = InteractiveModuleResponse("not implemented")

        return response

    def search_contact(self, request):
        """
        """

        response = InteractiveModuleResponse("not implemented")

        return response

class CalendarConfig(Config):
    identifier = 'interaction.irc.calendar'

    def valid_keys(self):
        return [
            'reminderInterval',
            'calendarUrl'
        ]

    def default_values(self):
        return {
            'reminderInterval' : TIME_MINUTE * 5,
            'calendarUrl'      : ''
        }


import pandas as pd
import requests
import time
import logging

# current template : midcap+ and ipo years >= 10
finviz_url_template = "https://finviz.com/screener.ashx?v=152&f=cap_smallover,fa_pe_u50,geo_usa,ind_stocksonly,ipodate_more10,sh_curvol_o50,sh_price_o2&ft=4&o=-marketcap&r={}&c=0,1,2,3,4,6,7,8,11,16,17,21,39,52,53,54,57,58,62,63,65,67,69,70"

finviz_numeric_cols = ['Market Cap',
                       'P/E',
                       'Fwd P/E',
                       'P/B',
                       'EPS',
                       'EPS this Y',
                       'Sales past 5Y', 'Gross M', 'SMA20', 'SMA50', 'SMA200',
                       '52W High', '52W Low', 'Recom',
                       'Avg Volume',
                       'Price',
                       'Volume',
                       'Target Price', ]

def finviz_features(url_template, start_i=1):
    url = url_template.format(str(start_i))
    header = {
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36",
        "X-Requested-With": "XMLHttpRequest"
    }
    dfs = pd.read_html((requests.get(url, headers=header)).text)
    valid_df_i = 7  # among downloaded dataframes, which dataframe has relevant data
    result = dfs[valid_df_i]
    first_row = result.loc[0, :].values.tolist()
    result.columns = first_row
    result = result[1:]
    return result

def convert_numeric(download_result, numeric_cols):
    def to_numeric(x):
        if isinstance(x, str):
            if x == "-":
                result = float(-1000)
            else:
                result = float(
                    eval(x.replace("%", "").replace("K", "*1000").replace("M", "*1000000").replace("B", "*1000000000")))
        else:
            result = x
        return result

    for a in numeric_cols:
        download_result[a] = download_result[a].map(lambda x: to_numeric(x))
    return download_result

def build_universe(url_template, num_cols, page_i_max=None) -> pd.DataFrame:
    next_flag = True
    page_i = 1
    result_dfs = []
    while next_flag:
        print("page :{}".format(str(page_i)))
        time.sleep(0.5)
        df = finviz_features(url_template, page_i)
        df = df[df['Industry'].map(lambda x: x != "Shell Companies")]  # excluding shell companies SPAC
        df = df[df['Company'].map(lambda x: "fund" not in x.lower())]  # excluding fund
        df = convert_numeric(df, num_cols)
        if df.shape[0] > 0:
            result_dfs.append(df)
            if df.shape[0] < 20:
                next_flag = False
            page_i = page_i + 20
            if page_i_max is not None:
                if page_i >= page_i_max:
                    next_flag = False
        else:
            next_flag = False
    result = pd.concat(result_dfs, ignore_index=True)
    return result

def test_finviz_features():
    actual = finviz_features(finviz_url_template)
    logging.info(actual.dtypes)
    actual_numeric = convert_numeric(actual, finviz_numeric_cols)
    logging.info(actual_numeric.dtypes)
    multiple_pages = build_universe(finviz_url_template, finviz_numeric_cols, 60)
    logging.info(multiple_pages.dtypes)
    logging.info(multiple_pages.head(5).to_dict("records"))
    logging.info(multiple_pages.shape)
    logging.info(multiple_pages.Company.unique())


import sys
sys.setrecursionlimit(10000)
def find_largest(alist):
    if len(alist) == 1:
        return alist[0]
    else:
        if alist[-1]<alist[0]:
            return find_largest(alist[:-1])
        else:
            return find_largest(alist[1:])
integer = int(input("Please enter an integer for the length of the array\n"))
list = []
for i in range(1, integer+1):
    list.append(int(input("Please enter an integer for item {0}\n".format(i))))
print(find_largest(list))


#!/usr/bin/env python3
"""
Provides utility methods (i.e. methods not directly related to ``nevis``).
"""
import timeit

import nevis

class Timer(object):
    """
    Provides accurate timing.

    Example
    -------
    ::

        timer = nevis.Timer()
        print(timer.format(timer.time()))

    """

    def __init__(self, output=None):
        self._start = timeit.default_timer()
        self._methods = {}

    def format(self, time=None):
        """
        Formats a (non-integer) number of seconds, returns a string like
        "5 weeks, 3 days, 1 hour, 4 minutes, 9 seconds", or "0.0019 seconds".
        """
        if time is None:
            time = self.time()
        if time < 1e-2:
            return str(time) + ' seconds'
        elif time < 60:
            return str(round(time, 2)) + ' seconds'
        output = []
        time = int(round(time))
        units = [
            (604800, 'week'),
            (86400, 'day'),
            (3600, 'hour'),
            (60, 'minute'),
        ]
        for k, name in units:
            f = time // k
            if f > 0 or output:
                output.append(str(f) + ' ' + (name if f == 1 else name + 's'))
            time -= f * k
        output.append('1 second' if time == 1 else str(time) + ' seconds')
        return ', '.join(output)

    def reset(self):
        """
        Resets this timer's start time.
        """
        self._start = timeit.default_timer()

    def time(self):
        """
        Returns the time (in seconds) since this timer was created, or since
        meth:`reset()` was last called.
        """
        return timeit.default_timer() - self._start

#
# Version-related methods
#
def howdy(name='version'):
    """ Say hi the old fashioned way. """
    print('')
    print('                |>          ')
    print(' Starting Ben   |   Nevis   ')
    print('               / \    ' + name)
    print('            /\/---\     ' + nevis.__version__)
    print('           /---    \/\      ')
    print('        /\/   /\   /  \     ')
    print('     /\/  \  /  \_/    \    ')
    print('    /      \/           \   ')

def print_result(x, y, z):
    """
    Print information about an optimisation result.

    Arguments:

    ``x``
        The x-coordinate of the result.
    ``y``
        The y-coordinate of the result.
    ``z``
        The z-coordinate of the result.
    """

    coords = nevis.Coords(gridx=x, gridy=y)
    hill, distance = nevis.Hill.nearest(coords)
    print('Congratulations!' if distance < 100 else (
        'Good job!' if distance < 1000 else 'Interesting!'))
    print(f'You landed at an altitude of {round(z)}m.')
    print(f'  {coords.opentopomap}')
    dm = (
        f'{round(distance)}m' if distance < 1000
        else f'{round(distance / 1000, 1)}km'
    )
    print(f'You are {dm} from the nearest named hill top, "{hill.name}",')
    print(f'  ranked the {hill.ranked} heighest in GB.')
    photo = hill.photo()
    if photo:
        print('  ' + photo)

def generate_kml(path, labels=None, trajectory=None, points=None,):
    """
    Generate a KML (Keyhole Markup Language, used to display geographic data
    in an Earth browser such as Google Earth) file from given data.

    For a description of the KML format, see
    https://developers.google.com/kml/documentation/kml_tut

    Arguments:

    ``path``
        The path of the file to write to.
    ``labels``
        An optional dictionary mapping string labels to points (tuples in
        meters or Coords objects) that will be marked on the map. The points
        will be shown as green pinpoints with text labels beside them.
    ``trajectory``
        An optional array of shape ``(n_points, 2)`` indicating the trajectory
        to be plotted (points specified in meters). All the points along the
        trajectory will be shown as small orange pinpoints with labels of
        their index prefixed with "T" (e.g. "T3"). The trajectory itself will
        be shown as a red curve extended down to the ground connecting
        adjacent points.
    ``points``
        An optional array of shape ``(n_points, 2)`` indicating points on the
        map (points specified in meters). All the points will be shown as small
        blue pinpoints with labels of their index prefixed with "P" (e.g.
        "P3").

    ``lables``, ``trajectory``, and ``points`` can be used simultaneously.
    """
    from pykml.factory import KML_ElementMaker as KML
    from lxml import etree

    def make_coords(x, y):
        """
        Convert a pair of coordinates (in meters) to a KML coordinates string.
        """
        lat, lon = nevis.Coords(x, y).latlong
        return f'{lon},{lat}'

    marks = []
    if labels is not None:
        for label, p in labels.items():
            if isinstance(p, nevis.Coords):
                p = p.grid
            x, y = p

            marks.append(
                KML.Placemark(
                    KML.name(label),
                    KML.Point(
                        KML.coordinates(make_coords(x, y))
                    ),
                    KML.styleUrl('#label_icon_style'),
                )
            )

    if points is not None:
        for i, (x, y) in enumerate(points):
            marks.append(
                KML.Placemark(
                    KML.name(f'P{i}'),
                    KML.Point(
                        KML.coordinates(make_coords(x, y))
                    ),
                    KML.styleUrl('#points_icon_style'),
                )
            )

    if trajectory is not None:
        for i, (x, y) in enumerate(trajectory):
            marks.append(
                KML.Placemark(
                    KML.name(f'T{i}'),
                    KML.Point(
                        KML.coordinates(make_coords(x, y))
                    ),
                    KML.styleUrl('#trajectory_icon_style'),
                )
            )

        marks.append(
            KML.Placemark(
                KML.name('Trajectory'),
                KML.styleUrl('#line_style'),
                KML.LineString(
                    KML.coordinates(
                        ' '.join([make_coords(x, y) for x, y in trajectory])
                    ),
                    KML.extrude(1),
                    KML.tessellate(1),
                )
            )
        )

    icon_url = 'http://maps.google.com/mapfiles/kml/paddle/wht-blank.png'

    doc = KML.kml(
        KML.Document(
            KML.name('Nevis Project'),
            KML.Style(
                KML.LineStyle(
                    KML.color('ff1400FF'),
                    KML.width(3),
                ),
                id="line_style"
            ),
            KML.Style(
                KML.IconStyle(
                    KML.Icon(
                        KML.href(icon_url),
                    ),
                    KML.color('ff00FF14'),
                ),
                id="label_icon_style"
            ),
            KML.Style(
                KML.IconStyle(
                    KML.Icon(
                        KML.href(icon_url),
                    ),
                    KML.scale(0.5),
                    KML.color('ffFF7800'),
                ),
                KML.LabelStyle(
                    KML.scale(0.5),
                ),
                id="points_icon_style"
            ),
            KML.Style(
                KML.IconStyle(
                    KML.Icon(
                        KML.href(icon_url),
                    ),
                    KML.scale(0.5),
                    KML.color('ff1e90ff'),
                ),
                KML.LabelStyle(
                    KML.scale(0.5),
                ),
                id="trajectory_icon_style"
            ),
            *marks,
        )
    )

    with open(path, 'w') as fobj:
        fobj.write(
            etree.tostring(doc, pretty_print=True).decode('utf-8'))


from uuid import UUID

class JobCancelledError(Exception):
    def __init__(self, job: UUID) -> None:
        self.job = job
        super().__init__(f'The job "{job}" was canceled while it was being processed')

class JobDoesNotExist(Exception):
    def __init__(self, job: UUID) -> None:
        self.job = job
        super().__init__(f'The job "{job}" does not exist')

class QueueDoesNotExist(Exception):
    def __init__(self, queue_name: str) -> None:
        self.queue_name = queue_name
        super().__init__(f'The queue "{queue_name}" does not exist')

class ReceiptHandleExpired(Exception):
    def __init__(self, receipt_handle: int) -> None:
        self.receipt_handle = receipt_handle
        msg = (
            f'The receipt handle "{receipt_handle}" expired.'
            " This likely means this client is failing to send back heartbeats for in-flight jobs"
        )
        super().__init__(msg)


from inputStream import InputStream
typeList = ['op', 'punc', 'identity', 'number', 'keyword', 'string', 'bool']

# class Token():
#     def __init__(self, type_, value_):
#         self.type = type_
#         self.value = value_
#     def __repr__(self):
#         return str({
#             'type': self.type,
#             'value': self.value
#         })

class Tokenizer():
    def __init__(self, ipstr):
        assert(type(ipstr) == InputStream)
        self.ipstr = ipstr
        self.__current = None

    def peek(self):
        if self.__current is not None:
            return self.__current
        self.__current = self.__next()
        return self.__current

    def next(self):
        if self.__current is not None:
            ret = self.__current
            self.__current = None
            return ret
        return self.__next()

    def eof(self):
        return self.peek() is None

    def error(self, msg):
        return self.ipstr.error(msg)

    def __next(self):
        if self.ipstr.eof():
            return None
        while Tokenizer.is_white_char(self.ipstr.peek()):
            self.ipstr.next()

        ch = self.ipstr.peek()
        if (ch == '#'):
            self.__skip_comment()
            return self.next()
        if (ch == '"'):
            return self.__read_string()
        if (Tokenizer.is_digit(ch)):
            return self.__read_number()
        if (Tokenizer.is_identity_begin(ch)):
            return self.__read_identity()
        if (Tokenizer.is_punc(ch)):
            return {
                'type': 'punc',
                'value': self.ipstr.next()
            }
        if (Tokenizer.is_op(ch)):
            return self.__read_op()
        self.ipstr.error('Can not handle charactor: {}'.format(ch))
    def __read_op(self):
        return {
            'type': 'op',
            'value': self.__read_while(Tokenizer.is_op)
        }
    def __read_until(self, predicate):
        ret = ''
        while not self.ipstr.eof() and not predicate(self.ipstr.peek()):
            ret += self.ipstr.next()
        ret += self.ipstr.next()
        return ret

    def __read_while(self, predicate):
        ret = ''
        while not self.ipstr.eof() and predicate(self.ipstr.peek()):
            ret += self.ipstr.next()
        return ret

    def __read_identity(self):
        idf = self.__read_while(Tokenizer.is_identity)
        if idf in Tokenizer.keywords():
            return {
                'type': 'keyword',
                'value': idf
            }
        else:
            return {
                'type': 'identity',
                'value': idf
            }

    def __read_number(self):
        num = self.__read_while(Tokenizer.is_digit)
        return {
            'type': 'number',
            'value': num
        }

    def __skip_comment(self):
        self.__read_until(Tokenizer.is_newline)

    def __read_string(self):
        assert(self.ipstr.peek() == '"')
        self.ipstr.next()
        ret = self.__read_until(Tokenizer.is_double_quote)
        # return Token('string', ret[:-1])
        return {
            'type': 'string',
            'value': ret[:-1]
        }

    @staticmethod
    def is_newline(ch):
        Tokenizer.check_is_char(ch)
        return ch == '\n'
    @staticmethod
    def is_double_quote(ch):
        Tokenizer.check_is_char(ch)
        return ch == '"'
    @staticmethod
    def is_digit(ch):
        Tokenizer.check_is_char(ch)
        return ch in list('0123456789')

    @staticmethod
    def is_identity_begin(ch):
        Tokenizer.check_is_char(ch)
        return (ord(ch) >= ord('a')
            and ord(ch) <= ord('z')) or (ord(ch) >= ord('A')
            and ord(ch) <= ord('Z')) or ch == '_'
    @staticmethod
    def is_identity(ch):
        Tokenizer.check_is_char(ch)
        return Tokenizer.is_identity_begin(ch) or ch in list('0123456789')

    @staticmethod
    def is_punc(ch):
        Tokenizer.check_is_char(ch)
        return ch in list(r',()[]{};')

    @staticmethod
    def is_op(ch):
        Tokenizer.check_is_char(ch)
        return ch in list('+-*/=<>%&|!')

    @staticmethod
    def check_is_char(ch):
        assert(type(ch) == str)
        assert(len(ch) == 1)

    @staticmethod
    def is_white_char(ch):
        Tokenizer.check_is_char(ch)
        return ch in list(' \t\n')

    @staticmethod
    def keywords():
        return ['if', 'else', 'function', 'then', 'true', 'false']

if __name__ == '__main__':
    f = open('input', 'r')
    s = f.read()
    tokenizer = Tokenizer(InputStream(s))
    while not tokenizer.eof():
        print(tokenizer.next())


#!/usr/bin/env python3

i = [x.strip() for x in open("../inputs/day03.txt", "r").readlines()]

gamma = ""
ep = ""

for ct in range(len(i[0])):
    val = 0

    for x in i:
        val += int(x[ct])

    gamma += "1" if (int(val>len(i)-val)) else "0"
    ep += "0" if (int(val>len(i)-val)) else "1"

print(int(gamma,2), int(ep,2))
print(int(gamma,2)*int(ep,2))

#2981
#1114


match_url = "https://kr.api.riotgames.com/lol/match/v4/matchlists/by-account/" + r.json()['accountId'] +'?api_key=' + api_key
match = requests.get(match_url)
match_data = match.json()

history = match_data["matches"] # 나의 게임기록
first = history[0]  #기록 중에  첫번째
gameID = first['gameId']  #그 게임의 gameId

match_data = "https://kr.api.riotgames.com/lol/match/v4/matches/" + str(gameID) + "?api_key=" + api_key #gameId로 검색
match_data1 = requests.get(match_data)
match_data2 = match_data1.json()
match_data3 = match_data2['participantIdentities']
participants = match_data2['participants']

for summoner in match_data3:
    if summoner['player']['summonerName'] == nick_name:
        break;
participantId = summoner['participantId'] #닉네임으로 게임 참가번호 검색

for my_history in participants:
    if my_history['participantId'] == participantId: # 참가번호로 그 게임내 데이터 출력
        print(my_history)
        break;

championId = my_history['championId'] # 원하는 JSON값을 변수에 저장
spell1Id = my_history['spell1Id']
spell2Id = my_history['spell2Id']
stats = my_history['stats']
result_game = stats['win']
if result_game == True:   #win값이 True면 win 아니면 loose
    result = "Win!"
else:
    result = "Lose"

kill = stats['kills']
death = stats['deaths']
assist = stats['assists']

champion = (dd.getChampion(championId).name)
champ_img = "C:\\Users\\GIGABYTE\\Desktop\\img\\champ_img\\" + champion + ".gif" #turtle에 챔피언이미지 등록
screen.addshape(champ_img)
t1.left(180)
t1.forward(300)
t1.shape(champ_img)  #turtle의 모양을 champion이미지로 변경
t1.stamp()   #움직이고 찍기

t1.left(90)
t1.forward(600)
t1.write("Result: " + result + " Kill: "+ str(kill) + ", Death: " + str(death) +", Assist: " + str(assist), False, "right", ("",20))

item = ["item1", "item2", "item3", "item4", "item5", "item6"]
k = 1
for i in item:
    t1. forward(80)
    if stats.get (i):
        i = "items" + str(k)
        i = stats['item'+str(k)]
        item_img = "C:\\Users\\GIGABYTE\\Desktop\\img\\item_img\\" + str(i) + ".gif"
        screen.addshape(item_img)
        t1.shape(item_img)
        t1.stamp()
    else:
        break


palavrasecreta = 'algoritmo'
tentativas = 0
letras_acertadas = ''

while True:
    letra = input('Digite uma letra: ')
    tentativas += 1
    if(len(letra) > 1):
        print('Digite apenas uma letra.')
        continue

    if letra in palavrasecreta:
        letras_acertadas += letra

    palavraformatada = ''

    for letra_secreta in palavrasecreta:
        if letra_secreta in letras_acertadas:
            palavraformatada += letra_secreta
        else:
            palavraformatada += '*'

    print(f'Palavra formatada: {palavraformatada}')

    if(palavraformatada == palavrasecreta):
        break

print("Você adivinhou a palavra secreta!!!")
print('Plavara secreta: ', palavrasecreta)
print(f'Tentativas: {tentativas}')


# -*- coding: utf-8 -*-
"""
Created on Wed Jul  8 23:55:31 2020

@author: Bhageerath
"""

import csv
import re
from nltk.corpus import stopwords
from string import punctuation
import nltk
import pandas as pd
nltk.download('stopwords')
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import train_test_split
from scipy.sparse import csr_matrix
import numpy as np
from sklearn.model_selection import cross_val_score
from wordcloud import WordCloud
import matplotlib.pyplot as plt

def buildTrainingData(twitterDataFile):
    training_data = []
    with open(twitterDataFile, "rt") as f:
        lineReader = csv.reader(f,delimiter=',', quotechar="\"")
        for row in lineReader:
            training_data.append({"company":row[0], "label":row[1], "text":row[2]})
    return training_data

def buildTestingData(testcsvDataFile):
    testing_data = []
    with open(testcsvDataFile, "rt", encoding="utf-8") as f:
        lineReader = csv.reader(f,delimiter=',', quotechar="\"")
        for row in lineReader:
            if row != []:
                testing_data.append({"text":row[0], "label":"dummy"})
    return testing_data

class PreProcessTweets:
    def __init__(self):
        self._stopwords = set(stopwords.words('english') + list(punctuation) + ['AT_USER','URL'])

    def processTweets(self, list_of_tweets):
        processedTweets=[]
        for tweet in list_of_tweets:
            processedTweets.append((self._processTweet(tweet["text"]),tweet["label"]))
            text, label = tuple(zip(*processedTweets))
        return pd.DataFrame({'text': text, 'label': label})

    def _processTweet(self, tweet):
        tweet = tweet.lower() # convert text to lower-case
        tweet = re.sub('((www\.[^\s]+)|(https?://[^\s]+))', 'URL', tweet) # remove URLs
        tweet = re.sub('@[^\s]+', 'AT_USER', tweet) # remove usernames
        tweet = re.sub(r'#([^\s]+)', r'\1', tweet) # remove the # in #hashtag
        #tweet = word_tokenize(tweet) # remove repeated characters (helloooooooo into hello)
        return tweet

def toUnigramTfDf(train_data, test_data):
    unigram_vectorizer = CountVectorizer(ngram_range=(1, 1))
    unigram_vectorizer.fit(train_data)
    X_train_unigram = unigram_vectorizer.transform(train_data)
    Y_train_unigram = unigram_vectorizer.transform(test_data)
    unigram_tf_idf_transformer = TfidfTransformer()
    unigram_tf_idf_transformer.fit(X_train_unigram)
    X_train_tf_idf = unigram_tf_idf_transformer.transform(X_train_unigram)
    Y_train_tf_idf = unigram_tf_idf_transformer.transform(Y_train_unigram)
    return (X_train_tf_idf, Y_train_tf_idf)

def train_and_show_scores(X: csr_matrix, y: np.array, title: str):
    X_train, X_valid, y_train, y_valid = train_test_split(
        X, y, train_size=0.95, stratify=y
    )
    clf = SGDClassifier()
    clf.fit(X_train, y_train)
    train_score = clf.score(X_train, y_train)
    valid_score = clf.score(X_valid, y_valid)
    print(f'{title}\nTrain score: {round(train_score, 2)} ; Validation score: {round(valid_score, 2)}\n')
    return clf

training_data_raw = buildTrainingData("C:/Users/bvulu/Documents/AIT-664/full-corpus.csv")
training_data_raw = training_data_raw[1:-1]
tweetProcessor = PreProcessTweets()
training_data = tweetProcessor.processTweets(training_data_raw)
#training_features = toUnigramTfDf(training_data['text'].values)
training_labels = training_data['label'].values
testing_data_raw = buildTestingData("C:/Users/bvulu/Documents/AIT-664/test123457.csv")
testing_data = tweetProcessor.processTweets(testing_data_raw)
training_features,testing_features = toUnigramTfDf(training_data['text'].values,testing_data['text'].values)

clf = train_and_show_scores(training_features, training_labels, 'Unigram Counts')
scores = cross_val_score(clf, training_features, training_labels, cv=5)
scores1 = clf.predict(testing_features)

testing_data_str = " ".join(str(e) for e in testing_data['text'].values)
wordcloud = WordCloud().generate(testing_data_str)
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")

k = pd.DataFrame(scores1)
print(k[0].value_counts())
print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
print(scores)


from django.conf import settings
from django.conf.urls.defaults import patterns, include, url

# Uncomment the next two lines to enable the admin:
from django.contrib import admin

admin.autodiscover( )

urlpatterns = patterns( '',
    # Serve static
    url( r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT, 'show_indexes': True} ),

    url( r'^', include( 'limited.core.urls' ) ),

    url( r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'limited/login.html'}, name='login' ),
    url( r'^logout/$', 'django.contrib.auth.views.logout_then_login', name='logout' ),

    # Uncomment the next line to enable the admin:
    url( r'^admin/doc/', include( 'django.contrib.admindocs.urls' ) ),
    url( r'^admin/', include( admin.site.urls ) ),
)


import math

def hoursForSeconds(hour, minutes, seconds):
    return hour * 3600 + minutes * 60 + seconds

def secondsForHours(seconds):
    hours = seconds // 3600
    seconds -= hours * 3600
    minutes = seconds // 60
    seconds -= minutes * 60
    return '{}:{}:{}'.format(hours, minutes, seconds)

hourIn = input('Digite a hora de entrada (hh:mm:ss): ')
segIn = hoursForSeconds(int(hourIn[0:2]), int(hourIn[3:5]), int(hourIn[6:8]))

hourOut = input('Digite a hora de entrada (hh:mm:ss): ')
segOut = hoursForSeconds(int(hourOut[0:2]), int(hourOut[3:5]), int(hourOut[6:8]))

onSeconds = segOut - segIn
print('O tempo em que o usuário ficou online corresponde a {} horas'.format(secondsForHours(onSeconds)))


"""
Collect pieces for compiling scheduled_stop_times
shape_geometry and stop_geometry.

Done in `rt_segment_speeds/A4_calculate_stop_delay`
"""
import dask.dataframe as dd
import dask_geopandas as dg
import geopandas as gpd
import pandas as pd

from segment_speed_utils import helpers, gtfs_schedule_wrangling
from segment_speed_utils.project_vars import (analysis_date,
                                              PREDICTIONS_GCS)

def stop_times_with_shape_and_stop_geometry(
    analysis_date: str
) -> dg.GeoDataFrame:
    trips_with_geom = gtfs_schedule_wrangling.get_trips_with_geom(
        analysis_date,
        trip_cols = ["feed_key", "name", "trip_id",
                     "shape_id", "shape_array_key"]
    )

    stop_times = helpers.import_scheduled_stop_times(
        analysis_date,
        columns = [
            "feed_key", "trip_id",
            "stop_id", "stop_sequence",
        ]
    )

    scheduled_stop_times = gtfs_schedule_wrangling.merge_shapes_to_stop_times(
        trips_with_geom, stop_times)

    stops = helpers.import_scheduled_stops(
            analysis_date,
            columns = ["feed_key", "stop_id", "stop_name", "geometry"],
        )

    stop_times_with_geom = gtfs_schedule_wrangling.attach_stop_geometry(
        scheduled_stop_times,
        stops,
    )

    stop_times_with_geom = stop_times_with_geom.rename(
        columns = {"geometry_x": "shape_geometry",
                   "geometry_y": "stop_geometry"
                  }).set_geometry("stop_geometry")

    stop_times_with_geom = stop_times_with_geom.repartition(
        partition_size="75MB")

    return stop_times_with_geom

if __name__ == "__main__":

    gdf = stop_times_with_shape_and_stop_geometry(analysis_date)
    gdf.to_parquet(
        f"{PREDICTIONS_GCS}scheduled_stop_times_with_geom_{analysis_date}")