import pickle
import re
import time
from pathlib import Path, PurePath

import ipywidgets as widgets
import numpy as np
import pandas as pd
import requests
from IPython.display import display, clear_output
from rank_bm25 import BM25Okapi
from requests import HTTPError

from cord.core import render_html, show_common, describe_dataframe, is_kaggle, CORD_CHALLENGE_PATH, \
    find_data_dir, SARS_DATE, SARS_COV_2_DATE, listify
from cord.dates import add_date_diff
from cord.jsonpaper import load_json_paper, PDF_JSON, PMC_JSON, \
    get_json_paths
from cord.text import preprocess, shorten, summarize
from cord.vectors import show_2d_chart, similar_papers

_MINIMUM_SEARCH_SCORE = 2

def get(url, timeout=6):
    try:
        r = requests.get(url, timeout=timeout)
        return r.text
    except ConnectionError:
        print(f'Cannot connect to {url}')
        print(f'Remember to turn Internet ON in the Kaggle notebook settings')
    except HTTPError:
        print('Got http error', r.status, r.text)

_DISPLAY_COLS = ['sha', 'title', 'abstract', 'publish_time', 'authors', 'has_text']
_RESEARCH_PAPERS_SAVE_FILE = 'ResearchPapers.pickle'
_COVID = ['sars-cov-2', '2019-ncov', 'covid-19', 'covid-2019', 'wuhan', 'hubei', 'coronavirus']

# Convert the doi to a url
def doi_url(d):
    if not d:
        return '#'
    return f'http://{d}' if d.startswith('doi.org') else f'http://doi.org/{d}'

_abstract_terms_ = '(Publisher|Abstract|Summary|BACKGROUND|INTRODUCTION)'

# Some titles are is short and unrelated to viruses
# This regex keeps some short titles if they seem relevant
_relevant_re_ = '.*vir.*|.*sars.*|.*mers.*|.*corona.*|.*ncov.*|.*immun.*|.*nosocomial.*'
_relevant_re_ = _relevant_re_ + '.*epidem.*|.*emerg.*|.*vacc.*|.*cytokine.*'

def remove_common_terms(abstract):
    return re.sub(_abstract_terms_, '', abstract)

def start(data):
    return data.copy()

def clean_title(data):
    # Set junk titles to NAN
    title_relevant = data.title.fillna('').str.match(_relevant_re_, case=False)
    title_short = data.title.fillna('').apply(len) < 30
    title_junk = title_short & ~title_relevant
    data.loc[title_junk, 'title'] = ''
    return data

def clean_abstract(data):
    # Set unknowns to NAN
    abstract_unknown = data.abstract == 'Unknown'
    data.loc[abstract_unknown, 'abstract'] = np.nan

    # Fill missing abstract with the title
    data.abstract = data.abstract.fillna(data.title)

    # Remove common terms like publisher
    data.abstract = data.abstract.fillna('').apply(remove_common_terms)

    # Remove the abstract if it is too common
    common_abstracts = show_common(data, 'abstract').query('abstract > 2') \
        .reset_index().query('~(index =="")')['index'].tolist()
    data.loc[data.abstract.isin(common_abstracts), 'abstract'] = ''

    return data

def drop_missing(data):
    missing = (data.published.isnull()) & \
              (data.sha.isnull()) & \
              (data.title == '') & \
              (data.abstract == '')
    return data[~missing].reset_index(drop=True)

def fill_nulls(data):
    data.authors = data.authors.fillna('')
    data.doi = data.doi.fillna('')
    data.journal = data.journal.fillna('')
    data.abstract = data.abstract.fillna('')
    return data

def rename_publish_time(data):
    return data.rename(columns={'publish_time': 'published'})

COVID_TERMS = ['covid', 'sars-?n?cov-?2', '2019-ncov', 'novel coronavirus', 'sars coronavirus 2']
COVID_SEARCH = f".*({'|'.join(COVID_TERMS)})"
NOVEL_CORONAVIRUS = '.*novel coronavirus'
WUHAN_OUTBREAK = 'wuhan'

def tag_covid(data):
    """
    Tag all the records that match covid
    :param data:
    :return: data
    """
    abstract = data.abstract.fillna('')
    since_covid = (data.published > SARS_COV_2_DATE) | (data.published.isnull())
    covid_term_match = since_covid & abstract.str.match(COVID_SEARCH, case=False)
    wuhan_outbreak = since_covid & abstract.str.match('.*(wuhan|hubei)', case=False)
    covid_match = covid_term_match | wuhan_outbreak
    data['covid_related'] = False
    data.loc[covid_match, 'covid_related'] = True
    return data

def tag_virus(data):
    VIRUS_SEARCH = f".*(virus|viruses|viral)"
    viral_cond = data.abstract.str.match(VIRUS_SEARCH, case=False)
    data['virus'] = False
    data.loc[viral_cond, 'virus'] = True
    return data

def tag_coronavirus(data):
    corona_cond = data.abstract.str.match(".*corona", case=False)
    data['coronavirus'] = False
    data.loc[corona_cond, 'coronavirus'] = True
    return data

def tag_sars(data):
    sars_cond = data.abstract.str.match(".*sars", case=False)
    sars_not_covid = ~(data.covid_related) & (sars_cond)
    data['sars'] = False
    data.loc[sars_not_covid, 'sars'] = True
    return data

def apply_tags(data):
    print('Applying tags to metadata')
    data = data.pipe(tag_covid) \
        .pipe(tag_virus) \
        .pipe(tag_coronavirus) \
        .pipe(tag_sars)
    return data

def clean_metadata(metadata):
    print('Cleaning metadata')
    return metadata.pipe(start) \
        .pipe(clean_title) \
        .pipe(clean_abstract) \
        .pipe(rename_publish_time) \
        .pipe(add_date_diff) \
        .pipe(drop_missing) \
        .pipe(fill_nulls) \
        .pipe(apply_tags)

def get_json_path(data_path, full_text_file, sha, pmcid):
    if pmcid and isinstance(pmcid, str):
        return Path(data_path) / full_text_file / full_text_file / PMC_JSON / f'{pmcid}.xml.json'
    elif sha and isinstance(sha, str):
        return Path(data_path) / full_text_file / full_text_file / PDF_JSON / f'{sha}.json'

def get_pdf_json_path(data_path, full_text_file, sha):
    """
    :return: The path to the json file if the sha is present
    """
    if sha and isinstance(sha, str):
        return Path(data_path) / full_text_file / full_text_file / PDF_JSON / f'{sha}.json'

def get_pmcid_json_path(data_path, full_text_file, pmcid):
    """
    :return: the path to the json file if the pmcid json is available
    """
    if pmcid and isinstance(pmcid, str):
        return Path(data_path) / full_text_file / full_text_file / PMC_JSON / f'{pmcid}.xml.json'

def _get_bm25Okapi(index_tokens):
    has_tokens = index_tokens.apply(len).sum() > 0
    if not has_tokens:
        index_tokens.loc[0] = ['no', 'tokens']
    return BM25Okapi(index_tokens.tolist())

def _set_index_from_text(metadata, data_path):
    from gensim.corpora import Dictionary
    from cord.jsonpaper import get_json_cache_dir
    print('Creating the BM25 index from the text contents of the papers')
    json_cache_dir = get_json_cache_dir()
    file_paths = [PurePath(p) for p in json_cache_dir.glob(f'jsoncache_*.pq')]
    for cache_path in file_paths:
        print('Loading json cache file', cache_path.stem)
        json_cache = pd.read_parquet(cache_path)
        part_no = cache_path.stem[len('jsoncache_'):]
        dictionary_path = json_cache_dir / f'jsoncache_{part_no}.dict'
        dictionary = Dictionary.load((str(dictionary_path.resolve())))
        json_cache['index_tokens'] \
            = json_cache.token_int.apply(lambda token_int: [dictionary[ti] for ti in token_int])
        json_tokens = json_cache.drop(columns=['token_int']).set_index('cord_uid')
        token_lookup = json_tokens.to_dict()['index_tokens']
        if 'index_tokens' not in metadata:
            metadata['index_tokens'] = metadata['cord_uid'].apply(lambda c: token_lookup.get(c, np.nan))
        else:
            need_tokens = metadata.index_tokens.isnull()
            metadata.loc[need_tokens, 'index_tokens'] = \
                metadata.loc[need_tokens, 'cord_uid'].apply(lambda c: token_lookup.get(c, np.nan))

    # If the index tokens are still null .. use the abstracts
    null_tokens = metadata.index_tokens.isnull()
    print('There are', null_tokens.sum(), 'papers that will be indexed using the abstract instead of the contents')
    metadata.loc[null_tokens, 'index_tokens'] = metadata.loc[null_tokens].abstract.apply(preprocess)
    missing_index_tokens = len(metadata.loc[metadata.index_tokens.isnull()])
    if missing_index_tokens > 0:
        print('There still are', missing_index_tokens, 'index tokens')

    return metadata

def create_annoy_index(document_vectors):
    print('Creating Annoy document index')
    tick = time.time()
    from annoy import AnnoyIndex
    annoy_index = AnnoyIndex(20, 'angular')
    for i in range(len(document_vectors)):
        annoy_index.add_item(i, document_vectors.loc[i])
    annoy_index.build()
    tock = time.time()
    print('Finished creating Annoy document index in', round(tock - tick, 0), 'seconds')
    return annoy_index

class ResearchPapers:

    def __init__(self, metadata: pd.DataFrame, bm25_index: BM25Okapi = None, data_dir='data', index='abstract',
                 view='html'):
        self.data_path = Path(data_dir)
        self.num_results = 10
        self.view = view
        self.metadata = metadata

        if bm25_index is None:
            if 'index_tokens' not in metadata:
                print('\nIndexing research papers')
                if any([index == t for t in ['text', 'texts', 'content', 'contents']]):
                    tick = time.time()
                    _set_index_from_text(self.metadata, data_dir)
                    print("Finished indexing in", int(time.time() - tick), 'seconds')
                else:
                    print('Creating the BM25 index from the abstracts of the papers')
                    print('Use index="text" if you want to index the texts of the paper instead')
                    tick = time.time()

                    self.metadata['index_tokens'] = metadata.abstract.apply(preprocess)
                    tock = time.time()
                    print('Finished Indexing in', round(tock - tick, 0), 'seconds')

                if 'antivirals' not in self.metadata:
                    # Add antiviral column
                    self.metadata['antivirals'] = self.metadata.index_tokens \
                        .apply(lambda t:
                               ','.join([token for token in t if token.endswith('vir')]))
            # Create BM25 search index
            self.bm25 = _get_bm25Okapi(self.metadata.index_tokens)
        else:
            self.bm25 = bm25_index

    @staticmethod
    def load_metadata(data_path=None):
        if not data_path:
            data_path = find_data_dir()

        print('Loading metadata from', data_path)
        metadata_path = PurePath(data_path) / 'metadata.csv'
        dtypes = {'Microsoft Academic Paper ID': 'str', 'pubmed_id': str}
        renames = {'source_x': 'source', 'has_full_text': 'has_text'}
        metadata = pd.read_csv(metadata_path, dtype=dtypes, low_memory=False,
                               parse_dates=['publish_time']).rename(columns=renames)
        metadata = clean_metadata(metadata)
        return metadata

    @classmethod
    def load(cls, data_dir=None, index=None):
        if data_dir:
            data_path = Path(data_dir) / CORD_CHALLENGE_PATH
        else:
            data_path = find_data_dir()
        metadata = cls.load_metadata(data_path)
        return cls(metadata, data_dir=data_path, index=index)

    @classmethod
    def restore(cls, storage_path='storage'):
        tick = time.time()
        index_path = Path(storage_path) / 'BM25IndexAbstracts.pq'
        with index_path.open('rb') as f:
            index = pickle.load(f)
        metadata = pd.read_parquet(PurePath('storage') / 'MetadataAbstracts.pq')
        papers = cls(metadata=metadata, bm25_index=index)
        print('Loaded papers in', time.time() - tick, 'seconds')
        return papers

    def show_similar(self, paper_id):
        similar_paper_ids = similar_papers(paper_id)
        self.display(*similar_paper_ids)

    def similar_to(self, paper_id):
        """
        Find and displays papers similar to the paper
        :param paper_id: the cord_uid
        :return: None
        """
        similar_paper_ids = similar_papers(paper_id)
        original_paper = self[paper_id]
        style = 'color: #008B8B; font-weight: bold; font-size: 0.9em;'
        display(widgets.HTML(
            f'
Papers similar to {original_paper.title}
'))
        return self.display(*similar_paper_ids)

    def show(self, *paper_ids):
        return self.display(*paper_ids)

    def display(self, *paper_ids):
        if len(paper_ids) == 1:
            paper_ids = listify(paper_ids[0])

        _recs = []
        for id in paper_ids:
            paper = self[id]
            _recs.append({'published': paper.metadata.published,
                          'title': paper.title,
                          'summary': paper.summary,
                          'when': paper.metadata.when,
                          'cord_uid': paper.cord_uid})
        df = pd.DataFrame(_recs).sort_values(['published'], ascending=False).drop(columns=['published'])

        def highlight_cols(s):
            return 'font-size: 1.1em; color: #008B8B; font-weight: bold'

        return df.style.applymap(highlight_cols, subset=pd.IndexSlice[:, ['title']]).hide_index()

    def create_document_index(self):
        print('Indexing research papers')
        tick = time.time()
        index_tokens = self._create_index_tokens()
        # Add antiviral column
        self.metadata['antivirals'] = index_tokens.apply(lambda t:
                                                         ','.join([token for token in t if token.endswith('vir')]))
        # Does it have any covid term?
        self.bm25 = BM25Okapi(index_tokens.tolist())
        tock = time.time()
        print('Finished Indexing in', round(tock - tick, 0), 'seconds')

    def get_json_paths(self):
        return get_json_paths(self.metadata, self.data_path)

    def describe(self):
        cols = [col for col in self.metadata if not col in ['sha', 'index_tokens']]
        return describe_dataframe(self.metadata, cols)

    def __getitem__(self, item):
        if isinstance(item, int):
            paper = self.metadata.iloc[item]
        else:
            paper = self.metadata[self.metadata.cord_uid == item]

        return Paper(paper, self.data_path)

    def covid_related(self):
        return self.query('covid_related')

    def not_covid_related(self):
        return self.query('~covid_related')

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

    def _make_copy(self, new_data):
        return ResearchPapers(metadata=new_data.copy(),
                              data_dir=self.data_path,
                              view=self.view)

    def query(self, query):
        data = self.metadata.query(query)
        return self._make_copy(data)

    def after(self, date, include_null_dates=False):
        cond = self.metadata.published >= date
        if include_null_dates:
            cond = cond | self.metadata.published.isnull()
        return self._make_copy(self.metadata[cond])

    def before(self, date, include_null_dates=False):
        cond = self.metadata.published < date
        if include_null_dates:
            cond = cond | self.metadata.published.isnull()
        return self._make_copy(self.metadata[cond])

    def get_papers(self, sub_catalog):
        return self.query(f'full_text_file =="{sub_catalog}"')

    def since_sars(self, include_null_dates=False):
        return self.after(SARS_DATE, include_null_dates)

    def before_sars(self, include_null_dates=False):
        return self.before(SARS_DATE, include_null_dates)

    def since_sarscov2(self, include_null_dates=False):
        return self.after(SARS_COV_2_DATE, include_null_dates)

    def before_sarscov2(self, include_null_dates=False):
        return self.before(SARS_COV_2_DATE, include_null_dates)

    def with_text(self):
        return self.query('has_text')

    def contains(self, search_str, column='abstract'):
        cond = self.metadata[column].fillna('').str.contains(search_str)
        return self._make_copy(self.metadata[cond])

    def match(self, search_str, column='abstract'):
        cond = self.metadata[column].fillna('').str.match(search_str)
        return self._make_copy(self.metadata[cond])

    def head(self, n):
        return self._make_copy(self.metadata.head(n))

    def tail(self, n):
        return self._make_copy(self.metadata.tail(n).copy())

    def sample(self, n):
        return self._make_copy(self.metadata.sample(n).copy())

    def abstracts(self):
        return pd.Series([self.__getitem__(i).abstract() for i in range(len(self))])

    def titles(self):
        return pd.Series([self.__getitem__(i).title() for i in range(len(self))])

    def get_summary(self):
        summary_df = pd.DataFrame({'Papers': [len(self.metadata)],
                                   'Oldest': [self.metadata.published.min()],
                                   'Newest': [self.metadata.published.max()],
                                   'SARS-COV-2': [self.metadata.covid_related.sum()],
                                   'SARS': [self.metadata.sars.sum()],
                                   'Coronavirus': [self.metadata.coronavirus.sum()],
                                   'Virus': [self.metadata.virus.sum()],
                                   'Antivirals': [self.metadata.antivirals.apply(lambda a: len(a) > 0).sum()]},
                                  index=[''])
        summary_df.Newest = summary_df.Newest.fillna('')
        summary_df.Oldest = summary_df.Oldest.fillna('')
        return summary_df

    def _repr_html_(self):
        display_cols = ['title', 'abstract', 'journal', 'authors', 'published', 'when']
        return render_html('ResearchPapers', summary=self.get_summary()._repr_html_(),
                           research_papers=self.metadata[display_cols]._repr_html_())

    @staticmethod
    def from_pickle(save_dir='data'):
        save_path = PurePath(save_dir) / _RESEARCH_PAPERS_SAVE_FILE
        with open(save_path, 'rb') as f:
            return pickle.load(f)

    def save(self, save_dir='data'):
        save_path = PurePath(save_dir) / _RESEARCH_PAPERS_SAVE_FILE
        print('Saving to', save_path)
        with open(save_path, 'wb') as f:
            pickle.dump(self, f)

    def _create_index_tokens(self):
        abstract_tokens = self.metadata.abstract.apply(preprocess)
        return abstract_tokens

    def search_2d(self, search_string,
                  num_results=25,
                  covid_related=False,
                  start_date=None,
                  end_date=None):
        search_results = self.search(search_string, num_results, covid_related, start_date, end_date)
        show_2d_chart(search_results.results, query=search_string)

    def search(self, search_string,
               num_results=10,
               covid_related=False,
               start_date=None,
               end_date=None,
               view='html'):
        n_results = num_results or self.num_results
        search_terms = preprocess(search_string)
        doc_scores = self.bm25.get_scores(search_terms)

        # Get the index from the doc scores
        ind = np.argsort(doc_scores)[::-1]
        results = self.metadata.iloc[ind].copy()
        results['Score'] = doc_scores[ind].round(1)
        # paper_ids = find_similar_papers(search_string, num_items=50)
        # results = self.metadata[self.metadata.cord_uid.isin(paper_ids)]

        # Filter covid related
        if covid_related:
            results = results[results.covid_related]

        # Filter by dates
        if start_date:
            results = results[results.published >= start_date]

        if end_date:
            results = results[results.published < end_date]

        # Show only up to n_results
        results = results.head(num_results)

        # Create the final results
        results = results.drop_duplicates(subset=['title'])

        # Return Search Results
        return SearchResults(results, self.data_path, view=view)

    def _search_papers(self, output, SearchTerms: str, num_results=None, view=None,
                       start_date=None, end_date=None, covid_related=False):
        if len(SearchTerms) < 5:
            return
        search_results = self.search(SearchTerms, num_results=num_results, view=view,
                                     start_date=start_date, end_date=end_date, covid_related=covid_related)
        if len(search_results) > 0:
            with output:
                clear_output()
                display(search_results)
        return search_results

    def searchbar(self, initial_search_terms='', num_results=10, view=None):
        text_input = widgets.Text(layout=widgets.Layout(width='400px'), value=initial_search_terms)

        search_button = widgets.Button(description='Search', button_style='primary',
                                       layout=widgets.Layout(width='100px'))
        search_box = widgets.HBox(children=[text_input, search_button])

        # A COVID-related checkbox
        covid_related_CheckBox = widgets.Checkbox(description='Covid-19 related', value=False, disable=False)
        checkboxes = widgets.HBox(children=[covid_related_CheckBox])

        # A date slider to limit research papers to a date range
        search_dates_slider = SearchDatesSlider()

        search_widget = widgets.VBox([search_box, search_dates_slider, checkboxes])

        output = widgets.Output()

        def do_search():
            search_terms = text_input.value.strip()
            if search_terms and len(search_terms) >= 4:
                start_date, end_date = search_dates_slider.value
                self._search_papers(output=output, SearchTerms=search_terms, num_results=num_results, view=view,
                                    start_date=start_date, end_date=end_date,
                                    covid_related=covid_related_CheckBox.value)

        def button_search_handler(btn):
            with output:
                clear_output()
            do_search()

        def text_search_handler(change):
            if len(change['new'].split(' ')) != len(change['old'].split(' ')):
                do_search()

        def date_handler(change):
            do_search()

        def checkbox_handler(change):
            do_search()

        search_button.on_click(button_search_handler)
        text_input.observe(text_search_handler, names='value')
        search_dates_slider.observe(date_handler, names='value')
        covid_related_CheckBox.observe(checkbox_handler, names='value')

        display(search_widget)
        display(output)

        # Show the initial terms
        if initial_search_terms:
            do_search()

def SearchDatesSlider():
    options = [(' 1951 ', '1951-01-01'), (' SARS 2003 ', '2002-11-01'),
               (' H1N1 2009 ', '2009-04-01'), (' COVID 19 ', '2019-11-30'),
               (' 2020 ', '2020-12-31')]
    return widgets.SelectionRangeSlider(
        options=options,
        description='Dates',
        disabled=False,
        value=('2002-11-01', '2020-12-31'),
        layout={'width': '480px'}
    )

class Paper:
    '''
    A single research paper
    '''

    def __init__(self, item, data_path):
        if isinstance(item, pd.DataFrame):
            # convert to a series
            item = item.T.iloc[:, 0]

        self.metadata = item
        self.sha = item.sha
        self.pmcid = item.pmcid
        self.cord_uid = item.cord_uid
        self.data_path = data_path
        self.pmc_json_files = item.pmc_json_files
        self.pdf_json_files = item.pdf_json_files

    def get_json_paper(self):
        if isinstance(self.metadata.pmc_json_files, str):
            return self.get_pmc_json()
        elif isinstance(self.metadata.pdf_json_files, str):
            return self.get_pdf_json()

    def get_pdf_json_path(self):
        if self.metadata.pdf_json_files:
            return self.data_path / self.pdf_json_files.partition(';')[0]

    def get_pdf_json(self):
        path = self.get_pdf_json_path()
        if path and path.exists():
            return load_json_paper(path)

    def get_pmc_json(self):
        path = self.data_path / self.metadata.pmc_json_files
        print(path, path.exists())
        if path and path.exists():
            return load_json_paper(path)

    @property
    def url(self):
        if not isinstance(self.metadata.url, str):
            return None
        for url in self.metadata.url.split(';'):
            if not 'api.elsevier.com' in url:
                return url.strip()

    @property
    def api_url(self):
        if not isinstance(self.metadata.url, str):
            return None
        for url in self.metadata.url.split(';'):
            if 'api.elsevier.com' in url:
                return url.strip()

    @property
    def html(self):
        json_paper = self.get_json_paper()
        if json_paper:
            return json_paper.html

    @property
    def text(self):
        '''
        Load the paper from doi.org and display as text. Requires Internet to be ON
        '''
        json_paper = self.get_json_paper()
        if json_paper:
            return json_paper.text

    @property
    def abstract(self):
        return self.metadata.abstract

    @property
    def summary(self):
        return summarize(self.abstract)

    @property
    def text_summary(self):
        return summarize(self.text, word_count=300)

    @property
    def title(self):
        return self.metadata.title

    def has_text(self):
        return self.paper.has_text

    @property
    def authors(self, split=False):
        json_paper = self.get_json_paper()
        if json_paper:
            return ', '.join(json_paper.authors)
        '''
        Get a list of authors
        '''
        authors = self.metadata.authors
        if not authors:
            return []
        if not split:
            return authors
        if authors.startswith('['):
            authors = authors.lstrip('[').rstrip(']')
            return [a.strip().replace("\'", "") for a in authors.split("\',")]

        # Todo: Handle cases where author names are separated by ","
        return [a.strip() for a in authors.split(';')]

    def _repr_html_(self):
        paper_meta = self.metadata.to_frame().T
        paper_meta = paper_meta[['published', 'authors', 'cord_uid', 'url', ]]
        paper_meta.index = ['']

        return render_html('Paper', paper=self, meta=paper_meta)

class SearchResults:

    def __init__(self, data: pd.DataFrame, data_path, view='html'):
        self.data_path = data_path
        self.results = data.dropna(subset=['title'])
        self.results.authors = self.results.authors.apply(str).replace("'", '').replace('[', '').replace(']', '')
        self.results['url'] = self.results.doi.apply(doi_url)
        self.results['summary'] = self.results.abstract.apply(summarize)
        self.columns = [col for col in ['sha', 'title', 'summary', 'when'] if col in self.results]
        self.view = view

    def __getitem__(self, item):
        return Paper(self.results.loc[item], self.data_path)

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

    def _view_html(self, search_results):
        _results = [{'title': rec['title'],
                     'authors': shorten(rec['authors'], 200),
                     'abstract': shorten(rec['abstract'], 300),
                     'summary': shorten(summarize(rec['abstract']), 500),
                     'when': rec['when'],
                     'url': rec['url'],
                     'cord_uid': rec['cord_uid'],
                     'is_kaggle': is_kaggle()
                     }
                    for rec in search_results.to_dict('records')]
        return render_html('SearchResultsHTML', search_results=_results)

    def get_results_df(self):
        display_cols = [col for col in self.columns if not col == 'sha']
        return self.results[display_cols]

    def _repr_html_(self):
        if self.view == 'html':
            return self._view_html(self.results)
        elif any([self.view == v for v in ['df', 'dataframe', 'table']]):
            return self.get_results_df()._repr_html_()
        else:
            return self._view_html(self.results)


import pyperclip
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import ElementClickInterceptedException
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import TimeoutException

#Open chrome and go to ArcGis Online
driver=webdriver.Chrome()
driver.get("https://www.arcgis.com/index.html")

#Navigate to and open the map
driver.find_element(By.XPATH,"//button[contains(@class, 'esri-header-account-control esri-header-account-control--signin')]").click()
driver.implicitly_wait(200)
driver.find_element(By.XPATH,"//input[@id='user_username']").send_keys("drew@geoservicesinc.net")
driver.find_element(By.XPATH,"//input[@id='user_password']").send_keys("Joseph232323*")
driver.find_element(By.XPATH,"//button[@id='signIn']").click()
driver.find_element(By.XPATH,"//a[@id='esri-header-menus-link-desktop-0-1']").click()
driver.find_element(By.XPATH,"//a[contains(@class, 'card-image-wrap card-last js-default-open')]").click()

#In ArcGIS, Navigate to a project name, Open the table, and take each of the names
#Click out of popup
driver.find_element(By.XPATH,"""//*[@id="dijit_form_Button_2_label"]""").click()
driver.implicitly_wait(700)

################################################INPUTS####################################################
pdftitle= "20122 PDF"#PDF title for sync
driver.find_element(By.XPATH,"""//*[@id="csv_3968_title"]""").click()  #XPATH for Title of specific Project in ARCGIS
driver.find_element(By.XPATH,"""//*[@id="csv_3968_tableTool"]/span""").click() #XPATH for Table Icon For Project
count=driver.find_element(By.XPATH,"""//*[@id="dijit_layout_ContentPane_4"]/div[4]""").text #XPATH for Content ID for project
num=int(count[-15:-14]) #Gets number of elements in the arcgis project 15(one digit) 16(2 digits) 17(three digits)
print(num)
################################################INPUTS####################################################

#proxyClick=str(num-1)
#driver.find_element(By.XPATH,"""//*[@id="dgrid_0-row-"""+proxyClick+""""]/table/tr/td[3]""").click() #click second to last
pdfs=[]
for x in range(int(num)):
        try:
                a=str(x)
                driver.find_element_by_xpath("""//*[@id="dgrid_0-row-"""+a+""""]/table/tr/td[3]/div""").click()
                pdfname=driver.find_element_by_xpath("""//*[@id="dgrid_0-row-"""+a+""""]/table/tr/td[3]/div""").text
                pdfs.append(pdfname)
        except AttributeError as exception:
                print("sheet")

#Open a new tab and navigate to Sync.com login page
driver2=webdriver.Chrome()
driver2.get("https://cp.sync.com/login?return_to=%252Ffiles%252F")
driver2.implicitly_wait(20)
driver2.find_element(By.XPATH,"//input[@id='text-auth-email']").send_keys("drewptak@geoservicesinc.net")
driver2.find_element(By.XPATH,"//input[@id='text-auth-password']").send_keys("Joseph23*")
driver2.find_element(By.XPATH,"//button").click()
driver2.find_element(By.XPATH,"//span[contains(@class, 'filelink showhand tool')]").click()
##driver2.find_element(By.XPATH,"""//li[contains(@class, 'pagination-next')]/a""").click()  #IF ITS ON PAGE 2
driver2.find_element_by_css_selector("[title='"+pdftitle+"']").click()

#Copy the url from a specific PDF
counter=0
switcher=0
for pdf in pdfs:
        index=str(counter)
        print(driver2.title)
        driver2.implicitly_wait(20)
        name=pdf + '.pdf'
        action = ActionChains(driver2)
        try:
                anchor = driver2.find_element_by_css_selector("[title='"+name+"']")
                driver2.implicitly_wait(20)
                action.move_to_element(anchor).perform()
                action.move_to_element_with_offset(anchor, 760, 10)
                action.click()
                action.perform()
                action.move_to_element_with_offset(anchor, 750, 62)
                action.click()
                action.perform()
                driver2.implicitly_wait(4000)
                driver2.find_element(By.XPATH,"/html/body/ngb-modal-window/div/div/sync-dialog-link/sync-link-manage/div[2]/div[1]/div/div/button[1]").click()
                driver2.find_element(By.XPATH,"//button[contains(@class, 'close')]/span").click()
                driver2.implicitly_wait(4000)

                #Navigate out of Sync and back to ArcGIS online to paste the link
                print(driver.title)
                print(index)
                print(name)
                driver.implicitly_wait(2000)
                bubble=driver.find_element_by_xpath("""//*[@id="dgrid_0-row-"""+index+""""]/table/tr/td[6]""")
                newaction=ActionChains(driver)
                newaction.double_click(bubble)
                newaction.perform()
                linktext=text = pyperclip.paste()
                driver.find_element(By.XPATH,"""//input[@id='dijit_form_ValidationTextBox_"""+index+"""']""").send_keys(linktext)
                driver.find_element_by_xpath("""//*[@id="dgrid_0-row-"""+index+""""]/table/tr/td[5]""").click()
                switch=str(switcher)
                if (switcher%100)>3:
                        dropper=str(((switcher%100)-4)*73)
                        driver2.execute_script("window.scrollTo(0,"+dropper+")")
                if ((switcher+1)%100)==0 and (switcher>0):
                        driver.implicitly_wait(30000)
                counter=counter+1
                switcher=switcher+1
        except NoSuchElementException as exception:
                print(driver.title)
                print("exception")
                driver.implicitly_wait(2000)
                bubble=driver.find_element_by_xpath("""//*[@id="dgrid_0-row-"""+index+""""]/table/tr/td[6]""")
                newaction=ActionChains(driver)

                newaction.double_click(bubble)
                newaction.perform()
                driver.find_element(By.XPATH,"""//input[@id='dijit_form_ValidationTextBox_"""+index+"""']""").send_keys("Log Not Found")
                driver.find_element_by_xpath("""//*[@id="dgrid_0-row-"""+index+""""]/table/tr/td[4]""").click()
                counter=counter+1

print("done")


import errno
import os
from functools import wraps

from .loggingutils import logged

@logged
def make_dirs(fname):
    if not os.path.exists(os.path.dirname(fname)):
        try:
            os.makedirs(os.path.dirname(fname))
        except OSError as exc:  # Guard against race condition
            if exc.errno != errno.EEXIST:
                raise

def one_kwarg(func):
    @wraps(func)
    def onekwarg_wrapper(self, **kwarg):
        if len(kwarg) != 1:
            raise ValueError("Please push one variable at the time.")
        func(self, **kwarg)

    return onekwarg_wrapper


import numpy as np
import getpass
from qiskit import QuantumCircuit
import random

from qiskit import Aer
from qiskit_ionq_provider import IonQProvider
key = str(np.genfromtxt('ionQkey.txt',dtype='str'))
provider = IonQProvider(token=key)

def get_players():
    N = 0
    while N < 2:
        N = int(input('How many players are there?\n Enter Number: '))

        if N < 2:
            delay_print('Please have at least two players')
    return N

def get_rounds():
    N = 0
    while N < 1:
        N = int(input('How many rounds would you like?\n Enter Number: '))

        if N < 1:
            delay_print('Please have at 1 round')
    return N

def get_init_state(N):
    qc = QuantumCircuit(N)
    init_string = ''
    for i in np.arange(N):
        state_valid = False
        while not state_valid:
            delay_print("Player %d, select your initial state:" % i)
            delay_print(' 0: |0>')
            delay_print(' 1: |1>')
            delay_print(' 2: (|0> + |1>)/sqrt(2)')
            state = getpass.getpass('')
            print('')

            if (state != '0') and (state != '1') and (state != '2'):
                delay_print('Please input a valid state')
            else:
                state_valid=True

        init_string += state

    for i, s in enumerate(init_string):
        if s=='1':
            qc.x(i)
        if s=='2':
            qc.h(i)
    return qc

def get_gate_and_target(N):

    # Get gate to add
    delay_print("  What gate would you like to add?")
    delay_print("    0:X      (1-qubit)", dt=0.01)
    delay_print("    1:Y      (1-qubit)", dt=0.01)
    delay_print("    2:Z      (1-qubit)", dt=0.01)
    delay_print("    3:H      (1-qubit)", dt=0.01)
    delay_print("    4:RX/4   (1-qubit)", dt=0.01)
    delay_print("    5:CNOT   (2-qubit)", dt=0.01)
    delay_print("    6:CPHASE (2-qubit)", dt=0.01)
    delay_print("    7:Swap   (2-qubit)", dt=0.01)

    while True:
        try:
            gate = int(input('    Input: '))
        except ValueError:
            delay_print(    "Sorry, didn't understand that.")
            continue
        else:
            if gate<8:
                break
            print("    Sorry, choose a gate between 0 and 7.")

    # Get target(s) to add gate to
    delay_print("  Where would you like to add this gate?  (e.g. 0 or 1,2)")
    for i in range(N):
        delay_print("    %d: qubit %d" % (i,i), dt=0.01)

    while True:
        try:
            target = list(map(int, input("    Input: ").split(',')))
            target = [t for t in target]
        except ValueError:
            delay_print(    "Sorry, didn't understand that!")
            continue
        else:

            # Ask for another input if bad qubit index
            if max(target)+1 > N or min(target)+1<1:
                delay_print("    Sorry, use a qubit index between 0 and %d!" % (N-1))
                continue

            # Use this input if we have right number of targets
            if (gate<5 and len(target)==2) or (gate>4 and len(target)==1) or len(target)>2 or len(target)==0:
                delay_print("    Sorry, use the right number of qubits!")
                continue

            break

    return gate, target

def davids_gameplay_loop(N_players, qc_init, N_rounds=1, backend_name='ionq_simulator'):

    qc = QuantumCircuit(N_players)
    qmeas = QuantumCircuit(N_players)
    qmeas.measure_all()

    for i in range(N_rounds):

        delay_print("-"*30 + "Round %d!"%(i+1) + "-"*30)

        for j in range (N_players):

            delay_print("Hello player %d...\n" % j)

            gate, target = get_gate_and_target(N_players)

            if gate == 0:
                qc.x(target[0])
            elif gate == 1:
                qc.y(target[0])
            elif gate == 2:
                qc.z(target[0])
            elif gate == 3:
                qc.h(target[0])
            elif gate == 4:
                qc.rx(np.pi/4, target[0])
            elif gate == 5:
                qc.cx(target[0],target[1])
            elif gate == 6:
                qc.cz(target[0],target[1])
            elif gate == 7:
                qc.swap(target[0],target[1])

            print(qc)

            delay_print('\n'+"-"*50)

        if i+1 < N_rounds:
            delay_print("Preparing a measurement...")
            print(qc+qmeas)
            backend = provider.get_backend(backend_name)
            job = backend.run(qc_init+qc+qmeas, shots=2)
            result = job.result()
            # Since we only have 2 shots, take a random bitstr for the meas.
            meas = random.choice(list(result.data()['counts'].keys()))
            print("Result: %s" % meas[::-1])
            delay_print("The measurement operators will now be removed!\n")

    delay_print("Time for the final results...")
    delay_print("-"*50)

    return qc

def game_end(N, qc_init, qc_game, shots=1000, backend_name='ionq_simulator'):
    qc = qc_init + qc_game
    qc.measure_all()

    f = open("./text_art/final_circuit.txt", "r", encoding="utf8")
    delay_print(f.read(), dt=0.009)
    print(qc)
    delay_print('')

    delay_print('Calculating...')

    backend = provider.get_backend(backend_name)
    job = backend.run(qc, shots=shots)
    result = job.result()
    counts_dict = result.data()['counts']

    player_counts = np.zeros(N)
    for key in counts_dict:
        for i, s, in enumerate(key[::-1]):
            player_counts[i] += int(s) * counts_dict[key]
    player_p1 = player_counts / shots

    return player_p1, np.argmax(player_p1)

import sys
import time
def delay_print(s, dt=0.04):
    for c in s:
        sys.stdout.write(c)
        sys.stdout.flush()
        time.sleep(dt)
    sys.stdout.write('\n')
    sys.stdout.flush()


# for i in range(100):
#     print("Love You Jyoti")
# 1>:-----------

# a = {1, 2, 3}
# b = {4, 5, 6}

# print(a | b)

# a |= b

# print(a)
# 2>:-----------

# def func(x):
#     return x[::-1].title()

# x = 'Oediv eht ekil esaelp'
# print(func(x))
# 3>:----------

# user = 'Jyoti'

# if user is not None:
#     print(user)

# if None is not user:
#     print(user)

# if not user is None:
#     print(user)

# def max_value_3(a,b,c):
#     if a > b:
#         return a
#     elif b > c :
#         return b
#     else :
#         return c
# c = max_value_3(50,70,30)
# print(c)

# a = "Jyoti"
# last_char = a[-1]
# print('last charecter:',last_char)

# x = lambda a : a +10
# print(x(5))

# add = lambda x , y: x+y
# mul = lambda x,y: x*y
# print(mul(10,20))

# N = int(input(""))
# for i in range(N):
    # reversed = input()
    # print(int(reversed[::-1]))

# side = int(input())
# area = side * side
# print('Area of the sqaure ='+str(area))

# side = int(input())
# print("Square star pattern")
# for i in range(side):
#     for i in range(side):
#         print("*", end = ' ')
#     print()

a=[23,78,[12,98]]
sum=0
for i in a[2]:
    sum=sum+i
    print(sum)


# -*- coding: utf-8 -*-
import time, functools

def metric(fn):
    start=time.time()
    def decorator(*args, **kw):
        stop=time.time()
        print('%s executed in %s ms' % (fn.__name__, stop-start))
        return fn(*args, **kw)
    return decorator

# 测试
@metric
def fast(x, y):
    time.sleep(0.0012)
    return x + y;

@metric
def slow(x, y, z):
    time.sleep(0.1234)
    return x * y * z;

f = fast(11, 22)
s = slow(11, 22, 33)
if f != 33:
    print('测试失败!')
elif s != 7986:
    print('测试失败!')


"""
Merge sort:

- Divide the unsorted list "a" into n sublists, each containing 1 element
- Repeatedly merge sublists to produce new sorted sublists until there is only 1
  sublist remaining. This list is sorted
"""

def mergesort(a):
    if len(a) <= 1:
        return a

    left = a[:len(a) / 2]
    right = a[len(a) / 2:]

    left = mergesort(left)
    right = mergesort(right)

    return merge(left, right)

def merge(left, right):
    result = []

    while left and right:
        if left[0] <= right[0]:
            result.append(left[0])
            left = left[1:]
        else:
            result.append(right[0])
            right = right[1:]

    if left:
        result.extend(left)
    if right:
        result.extend(right)

    return result


import math
import random

from Klass import Klass, is_inside
from Point import Point

def accuracy(solved: dict, klasses):
    hit = 0
    for p in solved.keys():
        if is_inside(p, solved[p]):
            hit += 1
    return hit

def generate_klasses(x1_borders: list, x2_borders: list):
    klasses = list()
    x1_borders.sort()
    x2_borders.sort()
    for i in range(len(x1_borders) - 1):
        x1_1 = x1_borders[i]
        x1_2 = x1_borders[i + 1]
        for j in range(len(x2_borders) - 1):
            x2_1 = x2_borders[j]
            x2_2 = x2_borders[j + 1]
            klasses.append(Klass("class_" + str((i + 1) * (j + 1)), x1_1, x1_2, x2_1, x2_2))
    return klasses

def generate_all_points(number, x1_min, x1_max, x2_min, x2_max):
    points = list()
    for i in range(number):
        points.append(Point(random.uniform(x1_min, x1_max), random.uniform(x2_min, x2_max)))
    return points

def divide_points(points):
    learn_n = math.floor(len(points) / 3)
    return [points[: learn_n + 1], points[learn_n:]]

def set_learn_data(points: list, klasses: list):
    learn_data = dict()
    for p in points:
        for klass in klasses:
            if is_inside(p, klass):
                learn_data[p] = klass
                break
    return learn_data


cnp = []
ok = False

def dict_get_value(s, cnp_0):
    for keys, value in s.items():
        if cnp_0 in keys:
            return value
    return None

def birth_year(cnp):
    saa = {('1', '2', '7', '8', '9'): 1900, ('3', '4'): 1800, ('5', '6'): 2000}
    days_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

    year = dict_get_value(saa, cnp[0]) + int(cnp[1:3])
    month = int(cnp[3:5])
    day = int(cnp[5:7])

    if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
        days_month[2] = 29
    return 1 <= month <= 12 and 1 <= day <= days_month[month]

def control(cnp):
    num = '279146358279'
    sum = 0

    ### SUM & MODULO ###
    for i in range(0, 12):
        sum = sum + int(cnp[i]) * int(num[i])
    c = sum % 11
    if c == 10:
        c = 1
    ### OUTPUT ###

    if c == int(cnp[12]):
        return True
    else:
        return False

while not ok:
    ok = True
    cnp = input("Te rugam sa introduci condul numeric personal:")
    if cnp[0] == 0 or len(cnp) != 13 or not cnp.isdigit():
        print("Cod numeric personal invalid.")
        ok = False

    elif not birth_year(cnp):
        ok = False
    elif int(cnp[7:9]) not in range(1, 53):
        ok = False
    elif cnp[9:12] == '000':
        ok = False
    elif not control(cnp):
        ok = False
    elif not ok:
        print("CNP gresit")

print("Ai introdus un CNP Valid.")


# -*- coding: utf-8 -*-
# @Time    : 2017/8/8 11:57
# @Author  : play4fun
# @File    : 预测手写数字1.py
# @Software: PyCharm

"""
预测手写数字1.py:

验证码
https://login.bthhotels.com/
"""

import numpy as np
import cv2
from matplotlib import pyplot as plt

with np.load('knn_data_num.npz') as data:
    print(data.files)  # ['train', 'train_labels', 'test', 'test_labels']
    train = data['train']
    train_labels = data['train_labels']
    test = data['test']
    test_labels = data['test_labels']

print('加载KNN,数据')
knn = cv2.ml.KNearest_create()
knn.train(train, cv2.ml.ROW_SAMPLE, train_labels)

# 加载相片
print('加载相片')
img2 = cv2.imread('2.png', 0)
gray2 = cv2.resize(img2, (20, 20))
# gray2=gray2.reshape((400,))
gray21 = gray2.reshape((-1, 400)).astype(np.float32)

img6 = cv2.imread('6.png', 0)
gray6 = cv2.resize(img6, (20, 20))
# gray2=gray2.reshape((400,))
gray61 = gray6.reshape((-1, 400)).astype(np.float32)

g2 = np.append(gray21, gray61)
g3 = g2.reshape((2, 400))

# 预测
retval, results = knn.predict(g3)
print(retval, results)  # 不准确
# (0.0, array([[ 0.],
#         [ 5.]], dtype=float32))

ch46-机器学习-K近邻/预测手写数字1.py


from mpi4py import MPI
import h5py

comm = MPI.COMM_WORLD
rank = comm.rank

f = h5py.File('collective_test.h5', 'w', driver='mpio', comm=comm)

dset = f.create_dataset('x', (100,), 'i')
dset.attrs['title'] = "Hello"

if rank == 0:
    dset[0] = 42

if rank == 1:
    dset[1] = 44

f.close()


import re

class PhoneListBr:
    def __init__(self, number):
        self.phone_list = []
        if self.phone_search(number):
            self.phone_list.append(self.phone_search(number))
        else:
            raise ValueError("No valid phone number!")

    def __str__(self):
        for phone in self.phone_list:
            return self.format_phone_number(str(phone))

    @staticmethod
    def phone_search(number):
        pattern = "(\d{2,3})?(\d{2})(\d{4,5})(\d{4})"
        search = re.search(pattern, number)
        return search

    @staticmethod
    def format_phone_number(number):
        search = PhoneListBr.phone_search(number)
        if search.group(1):
            answer = "+{}({})9{}-{}".format(
                search.group(1), search.group(2), search.group(3), search.group(4)
            )
        else:
            answer = "({})9{}-{}".format(
                search.group(2), search.group(3), search.group(4)
            )
        return answer


import cv2
import numpy as np

img = cv2.imread('00000019.jpg')

ret, mask = cv2.threshold(img[:, :,2], 200, 255, cv2.THRESH_BINARY)

mask3 = np.zeros_like(img)
mask3[:, :, 0] = mask
mask3[:, :, 1] = mask
mask3[:, :, 2] = mask

# extracting `orange` region using `biteise_and`
orange = cv2.bitwise_and(img, mask3)

cv2.imwrite('orange.png', orange)


# -*- coding: utf-8 -*-
'''
@author: subhash g
'''

# -*- coding: utf-8 -*-
'''
@author: subhash g
'''

import numpy as np
import pickle
import pandas as pd
#from flasgger import Swagger
import streamlit as st
from abalone_predictions import RandomForestClassifier
from PIL import Image

#app=Flask(__name__)
#Swagger(app)

pickle_in = open("RFC.pkl","rb")
classifier=pickle.load(pickle_in)

#@app.route('/')
def welcome():
    return "Welcome All"

#@app.route('/predict',methods=["Get"])
def predict_note_authentication(Length,Height,Whole_weight,Viscera_weight,Shell_weight,Sex_I,Sex_M):

    """Let's Authenticate the Banks Note
    This is using docstrings for specifications.
    ---
    parameters:
      - name: variance
        in: query
        type: number
        required: true
      - name: skewness
        in: query
        type: number
        required: true
      - name: curtosis
        in: query
        type: number
        required: true
      - name: entropy
        in: query
        type: number
        required: true
    responses:
        200:
            description: The output values

    """
    x=[[Length,Height,Whole_weight,Viscera_weight,Shell_weight,Sex_I,Sex_M]]
    prediction=classifier.predict(x)
    print(prediction)
    return prediction

def main():
    st.title(" Abalone_predictions")
    html_temp = """

Streamlit Abalone_predictions ML App

    """
    st.markdown(html_temp,unsafe_allow_html=True)
    Length = st.text_input("Length","Type Here")

    Height = st.text_input("Height","Type Here")

    Whole_weight = st.text_input("Whole_weight","Type Here")

    Viscera_weight = st.text_input("Viscera_weight","Type Here")

    Shell_weight = st.text_input("Shell_weight","Type Here")

    Sex_I = st.text_input("Sex_I","Type Here")

    Sex_M = st.text_input("Sex_M","Type Here")

    result=""
    if st.button("Predict"):
        Length=float(Length)
        Height=float(Height)
        Whole_weight=float(Whole_weight)
        Viscera_weight=float(Viscera_weight)
        Shell_weight=float(Shell_weight)
        Sex_I=float(Sex_I)
        Sex_M=float(Sex_M)

        result=predict_note_authentication(Length,Height,Whole_weight,Viscera_weight,Shell_weight,Sex_I,Sex_M)
    st.success('THE Abalone Age IS  {}'.format(result))
    if st.button("About"):
        st.text("Lets LEarn")
        st.text("Built with Streamlit")

if __name__=='__main__':
    main()


seconds=int(input("Enter number of seconds: "))
product = 0
difference=0
new_seconds = 0
minutes = int(seconds/60)
hours =int(seconds/3600)
days = int(seconds/86400)

if  seconds < 60 :
    print(str(seconds) + " Seconds")
elif 60<= seconds < 3600:
    product= minutes*60
    difference = seconds - product
    print(str(minutes) + " mins " + str(difference) + " seconds." )
elif (seconds>60) and (seconds >= 3600) and (seconds < 86400):
  product = hours * 3600
  new_seconds = seconds - product
  minutes = int(new_seconds/60)
  product = minutes*60
  difference = new_seconds - product
  print(str(hours)+" hours " + str(minutes) + " minutes " + str(difference) + " seconds.")
elif  (seconds >= 86400):
    product = days*86400
    new_seconds = seconds - product
    hours = int(new_seconds/3600)
    product = hours * 3600
    difference = new_seconds - product
    minutes = int(difference/60)
    product = minutes*60
    new_seconds = difference - product
    print(str(days) + " days " + str(hours)+" hours " + str(minutes) + " minutes " + str(new_seconds) + " seconds.")


'''
  Contest: 1095
  Problem A : Repeating Cipher
  Author : Rakesh Kumar
  Date: 22/06/2020
'''

def cipher():
    d = []
    for n in range(11):
        d.append((n * (n + 1)) >> 1)
    n = int(input())
    line = str(input())
    for i in range(len(d)):
        if d[i] < len(line):
            print(line[d[i]], end='')
    print()

if __name__ == "__main__":
    cipher()


# Reference : https://ietresearch.onlinelibrary.wiley.com/doi/10.1049/iet-ipr.2019.1471

import numpy as np
import cv2

class GuidedFilter:
    def __init__(self, img, r, eps):

        # Changing data type of image to float
        if img.dtype != np.float32:
            img = (1.0 / 255.0) * np.float32(img)

        self.img = img
        self.r = 2*r + 1
        self.eps = eps
        self.begin()

    # Computing mean of input image over box of size (r,r)
    def mean(self, img):
        r = self.r
        return cv2.blur(img, (r,r))

    def begin(self):
        img = self.img
        eps = self.eps

        img_r = img[:,:,0]
        img_g = img[:,:,1]
        img_b = img[:,:,2]

        # Calculating mean of R,G,B over box of size (r,r)
        img_r_mean = self.mean(img_r)
        img_g_mean = self.mean(img_g)
        img_b_mean = self.mean(img_b)

        # Calculating variance
        # var = mean(img * img) - (img_mean * img_mean)
        img_rr_var = self.mean(img_r * img_r) - (img_r_mean * img_r_mean) + eps
        img_rg_var = self.mean(img_r * img_g) - (img_r_mean * img_g_mean)
        img_rb_var = self.mean(img_r * img_b) - (img_r_mean * img_b_mean)
        img_gg_var = self.mean(img_g * img_g) - (img_g_mean * img_g_mean) + eps
        img_gb_var = self.mean(img_g * img_b) - (img_g_mean * img_b_mean)
        img_bb_var = self.mean(img_b * img_b) - (img_b_mean * img_b_mean) + eps

        img_rr_inv = (img_gg_var * img_bb_var) - (img_gb_var)**2
        img_rg_inv = (img_gb_var * img_rb_var) - (img_rg_var * img_bb_var)
        img_rb_inv = (img_rg_var * img_gb_var) - (img_gg_var * img_rb_var)
        img_gg_inv = (img_rr_var * img_bb_var) - (img_rb_var)**2
        img_gb_inv = (img_rb_var * img_rg_var) - (img_rr_var * img_gb_var)
        img_bb_inv = (img_rr_var * img_gg_var) - (img_rg_var)**2

        img_cov = (img_rr_inv * img_rr_var) + (img_rg_inv * img_rg_var) + (img_rb_inv * img_rb_var)

        img_rr_inv = img_rr_inv / img_cov
        img_rg_inv = img_rg_inv / img_cov
        img_rb_inv = img_rb_inv / img_cov
        img_gg_inv = img_gg_inv / img_cov
        img_gb_inv = img_gb_inv / img_cov
        img_bb_inv = img_bb_inv / img_cov

        self.img_r_mean = img_r_mean
        self.img_g_mean = img_g_mean
        self.img_b_mean = img_b_mean

        self.img_rr_inv = img_rr_inv
        self.img_rg_inv = img_rg_inv
        self.img_rb_inv = img_rb_inv
        self.img_gg_inv = img_gg_inv
        self.img_gb_inv = img_gb_inv
        self.img_bb_inv = img_bb_inv

    def getCoefficients(self, p):
        img = self.img
        r = self.r

        img_r = img[:,:,0]
        img_g = img[:,:,1]
        img_b = img[:,:,2]

        img_r_mean = self.img_r_mean
        img_g_mean = self.img_g_mean
        img_b_mean = self.img_b_mean

        # Calculating mean
        p_mean = self.mean(p)

        # Calculating mean of I_i * p_i
        img_pr_mean = self.mean(img_r * p)
        img_pg_mean = self.mean(img_g * p)
        img_pb_mean = self.mean(img_b * p)

        # Calculating numerator = (I_i * p_i) - (u_k * p'_k)
        img_pr_cov = img_pr_mean - img_r_mean * p_mean
        img_pg_cov = img_pg_mean - img_g_mean * p_mean
        img_pb_cov = img_pb_mean - img_b_mean * p_mean

        # Calculating coefficient a_k = (1/w) ((I_i * p_i) - (u_k * p'_k)) / (sigma**2 + eps)
        a_r = (self.img_rr_inv * img_pr_cov) + (self.img_rg_inv * img_pg_cov) + (self.img_rb_inv * img_pb_cov)
        a_g = (self.img_rg_inv * img_pr_cov) + (self.img_gg_inv * img_pg_cov) + (self.img_gb_inv * img_pb_cov)
        a_b = (self.img_rb_inv * img_pr_cov) + (self.img_gb_inv * img_pg_cov) + (self.img_bb_inv * img_pb_cov)

        # Calculating coefficient b_k = (p'_k - a_k * u_k)
        b = p_mean - (a_r * img_r_mean + a_g * img_g_mean + a_b * img_b_mean)

        # Calculating mean of coefficients
        a_r_mean = self.mean(a_r)
        a_g_mean = self.mean(a_g)
        a_b_mean = self.mean(a_b)
        b_mean = self.mean(b)

        return a_r_mean, a_g_mean, a_b_mean, b_mean

    def filter(self, p):
        # Converting image to float
        # if p.dtype != np.float32:
        #     p = np.float32(p)

        img = self.img

        # Computing coefficients a_k & b_k
        a_r_mean, a_g_mean, a_b_mean, b_mean = self.getCoefficients(p)

        # print("Coefficients : ", a_r_mean, a_g_mean, a_b_mean, b_mean)

        img_r, img_g, img_b = img[:,:,0], img[:,:,1], img[:,:,2]

        # Finding ouput image q = a_k * I_i + b_k
        out_img = (a_r_mean * img_r) + (a_g_mean * img_g) + (a_b_mean * img_b) + b_mean

        return out_img


import sys
sys.stdin = open('input.txt')
input = sys.stdin.readline

N = int(input())
num = list(map(int, input().split()))
cal = list(map(int, input().split())) # +,-,*,//
visited = [0]*4
ans_max = -int(1e9)
ans_min = int(1e9)

def sol(x, tmp):
    global ans_max, ans_min

    if x == N:
        ans_max = max(ans_max, tmp)
        ans_min = min(ans_min, tmp)
        return

    for k in range(4):
        if cal[k] > visited[k]:
            visited[k] += 1
            if k == 0:
                sol(x + 1, tmp+num[x])
            elif k == 1:
                sol(x+1, tmp-num[x])
            elif k == 2:
                sol(x+1, tmp*num[x])
            else:
                sol(x+1, int(tmp/num[x]))

            visited[k] -= 1

sol(1, num[0])
print(ans_max)
print(ans_min)


"""
Caitlin Locke
Code in Place
Final Project
5.25.2020
"""

"""
File: triptych.py
----------------
Take an original image. Crop it into three parts. Create a new
image that is 20 pixels wider than the original image. Place
cropped images into new image as a triptych.
"""

# The lines below import SimpleImage and Image
from simpleimage import SimpleImage
from PIL import Image

#Create image constrants, so the original image can be easily changed
USER_DIRECTORY = 'images/'
#The image must be a JPEG for this code to work
IMAGE = 'images/quad.jpg'
IMAGE_NAME = 'quad'

def main():
    """
    This program creates a triptych from an original image. Constants
    allow the user to pick an image of their choice and turn it into a
    triptych.
    """
    original = SimpleImage(IMAGE)
    original.show()
    image_crop(IMAGE)
    triptych = make_triptych(IMAGE)
    triptych.show()

#Creates triptych from original image
def make_triptych(filename):
    image = SimpleImage(filename)
    width = image.width
    height = image.height
    #Creates new image to contain triptych
    triptych = SimpleImage.blank(width + 20, height)
    #Creates panel one of triptych
    image = SimpleImage(USER_DIRECTORY + IMAGE_NAME + '_1.JPG')
    width1 = image.width
    height1 = image.height
    for y in range(height1):
        for x in range(width1):
            pixel = image.get_pixel(x,y)
            triptych.set_pixel(x,y,pixel)
    #Creates panel two of triptych
    image = SimpleImage(USER_DIRECTORY + IMAGE_NAME + '_2.JPG')
    width2 = image.width
    height2 = image.height
    for y in range(height2):
        for x in range(width2):
            pixel = image.get_pixel(x, y)
            triptych.set_pixel(x + ((width/4) + 10), y, pixel)
    #Creates panel three of triptych
    image = SimpleImage(USER_DIRECTORY + IMAGE_NAME + '_3.JPG')
    width3 = image.width
    height3 = image.height
    for y in range(height3):
        for x in range(width3):
            pixel = image.get_pixel(x, y)
            triptych.set_pixel(x + (((width/4)*3) + 20), y, pixel)
    return triptych

#Crops original image into three parts for triptych
def image_crop(filename):
    im_name = IMAGE_NAME
    im = Image.open(filename)
    width = im.width
    height = im.height
    #crops first panel
    im1 = im.crop((0, 0, width/4, height))
    im1.save(USER_DIRECTORY + IMAGE_NAME + '_1.JPG')
    #crops second/middle panel
    im2 = im.crop((width/4, 0, (width/4) * 3, height))
    im2.save(USER_DIRECTORY + IMAGE_NAME + '_2.JPG')
    #crops third panel
    im3 = im.crop(((width/4) * 3, 0, width, height))
    im3.save(USER_DIRECTORY + IMAGE_NAME + '_3.JPG')

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
"""
Created on Thu Oct 28 14:33:48 2021

@author: CHENG
"""
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import Fuma_functions as Ff

learning_rate = 1e-4

err = 1e-6

n = 100

epochs = 10000

data = Ff.read_excel("rc.xls")

D = data[:,1]

L = data[:,6] #* 3.828e26

R_eff = data[:,8]

R_d = data[:,10]

R_H = data[:,13]

R = R_H #* 3.085677581491367e19

v = data[:,14] #* 1000

state = np.random.get_state()
np.random.shuffle(R)

np.random.set_state(state)
np.random.shuffle(L)

np.random.set_state(state)
np.random.shuffle(v)

weights = {
    'w_1':tf.Variable(tf.truncated_normal([2,64],stddev=0.1)),
    'w_2':tf.Variable(tf.truncated_normal([64,64],stddev=0.1)),
    'w_3':tf.Variable(tf.truncated_normal([64,64],stddev=0.1)),
    'w_4':tf.Variable(tf.truncated_normal([64,64],stddev=0.1)),
    'w_5':tf.Variable(tf.truncated_normal([64,64],stddev=0.1)),
    'w_6':tf.Variable(tf.truncated_normal([64,1],stddev=0.1))
    }

biases = {
    'b_1':tf.Variable(tf.ones([64])),
    'b_2':tf.Variable(tf.ones([64])),
    'b_3':tf.Variable(tf.ones([64])),
    'b_4':tf.Variable(tf.ones([64])),
    'b_5':tf.Variable(tf.ones([64])),
    'b_6':tf.Variable(tf.ones([1]))
    }

L_R_D_layer = tf.placeholder(tf.float32,[None,2])
v_layer = tf.placeholder(tf.float32,[None,1])

layer_1 = tf.nn.relu(tf.matmul(L_R_D_layer,weights['w_1'])+biases['b_1'])

layer_2 = tf.nn.relu(tf.matmul(layer_1,weights['w_2'])+biases['b_2'])

#layer_3 = tf.nn.relu(tf.matmul(layer_2,weights['w_3'])+biases['b_3'])

#layer_4 = tf.nn.relu(tf.matmul(layer_3,weights['w_4'])+biases['b_4'])

#layer_5 = tf.nn.relu(tf.matmul(layer_4,weights['w_5'])+biases['b_5'])

pre = tf.nn.relu(tf.matmul(layer_2,weights['w_6'])+biases['b_6'])

loss = tf.reduce_mean(tf.abs(v_layer - pre)/(v_layer))

train = tf.train.AdamOptimizer(learning_rate).minimize(loss)

accuracy = tf.reduce_mean(tf.abs(v_layer - pre)/(v_layer))

LR_losslist = []
LR_acclist = []
LR_test_acc_list = []

train_L_R = np.concatenate((L[:n].reshape([-1,1]),
                            R[:n].reshape([-1,1])),
                           axis = 1)

train_L_v = np.concatenate((L[:n].reshape([-1,1]),
                            v[:n].reshape([-1,1])),
                           axis = 1)
train_R_v = np.concatenate((R[:n].reshape([-1,1]),
                            v[:n].reshape([-1,1])),
                           axis = 1)

train_v = v[:n].reshape([-1,1])

train_L = L[:n].reshape([-1,1])

train_R = R[:n].reshape([-1,1])
#-----------------------------------------------------------------------------
test_L_R = np.concatenate((L[n:].reshape([-1,1]),
                            R[n:].reshape([-1,1])),
                           axis = 1)

test_L_v = np.concatenate((L[n:].reshape([-1,1]),
                            v[n:].reshape([-1,1])),
                           axis = 1)
test_R_v = np.concatenate((R[n:].reshape([-1,1]),
                            v[n:].reshape([-1,1])),
                           axis = 1)

test_v = v[n:].reshape([-1,1])

test_L = L[n:].reshape([-1,1])

test_R = R[n:].reshape([-1,1])
##############################################################################

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for epoch in range(epochs):

        #batch_m_a = train_m_a[epoch*150:(epoch+1)*150-1]
        #batch_F = train_F[epoch*150:(epoch+1)*150-1]

        #test_batch_m_a = test_m_a[epoch*150:(epoch+1)*150-1]
        #test_batch_F = test_F[epoch*150:(epoch+1)*150-1]

        _,lossval,accval = sess.run([train,loss,accuracy],
                                    feed_dict={L_R_D_layer:train_R_v,
                                               v_layer:train_L})

        LR_losslist.append(lossval)
        LR_acclist.append(accval)

        test_acc_val = sess.run(accuracy,feed_dict={L_R_D_layer:test_R_v,
                                                    v_layer:test_L})
        LR_test_acc_list.append(test_acc_val)

    plt.figure(0);plt.plot(LR_losslist[:])
    plt.figure(1);plt.plot(LR_acclist[:])
    plt.figure(2);plt.plot(LR_test_acc_list[-100:])


import telebot
import requests
from privateapi import get_key
from privateapi import get_token
import csv
import json

apiKey = get_key()
token = get_token()

movie=telebot.TeleBot(token)
@movie.message_handler(commands=['movie'])

def getMovie(message):
    movie.reply_to(message, 'Getting movie information for you.')
    movie_name = message.text.split(' ',1)[1]
    api_url = "https://www.omdbapi.com/?apikey="+apiKey+"&t=" + movie_name
    response = requests.get(api_url)

    if response.status_code == 200:                                                         #Here 200 is the Success Code
        movie.reply_to(message, response.text)

        movie_data=json.loads(response.text)

        csv_file='./store.csv'
        with open(csv_file, mode='a',newline='\r\n') as file:
            writer = csv.writer(file)

            writer.writerow(response.text)
    else:
        movie.reply_to(message, 'Sorry, unable to get the movie you are looking for.')

movie.infinity_polling()


import pygame
from pygame.locals import *
pygame.init()

# canvas setup
x = 800
y = 600
concrete_color = (100,100,100)

# object setup
car = pygame.image.load('./img/yellow-car-01.png')
car_width = 85
car_height = 170
speed = 10
obj_x = x/2 - car_width/2
obj_y = y/2 - car_height/2
#obj_radious = 10
#obj_color = (255, 255, 0)

# grass setup
grass_x = x/4
grass_color = (0,100,0)

# border setup
border_width = 20
border_color = (0,0,150)

# line setup
line_width = 8
line_color = (200, 255, 0)

window = pygame.display.set_mode((x,y))
pygame.display.set_caption('Game 01')

open_window = True

while open_window:
    pygame.time.delay(50)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            open_window = False

    commands = pygame.key.get_pressed()
#    if commands[pygame.K_UP] and obj_y > 0:
#        obj_y -= speed
#    if commands[pygame.K_DOWN] and obj_y < y - car_height:
#        obj_y += speed
    if commands[pygame.K_LEFT] and obj_x > grass_x + border_width:
        obj_x -= speed
    if commands[pygame.K_RIGHT] and obj_x < x - grass_x - border_width - car_width:
        obj_x += speed

    # CONCRETE
    window.fill(concrete_color)
    # LEFT GRASS
    pygame.draw.rect(window, grass_color, (0, 0, grass_x, y))
    # RIGHT GRASS
    pygame.draw.rect(window, grass_color, (x-grass_x, 0, grass_x, y))
    # LEFT BORDER
    pygame.draw.rect(window, border_color, (grass_x, 0, border_width, y))
    # RIGHT BORDER
    pygame.draw.rect(window, border_color, (x - grass_x - border_width, 0, border_width, y))
    # LEFT LINE
    pygame.draw.rect(window, line_color, (x/2 - line_width * 2, 0, line_width, y))
    # RIGHT LINE
    pygame.draw.rect(window, line_color, (x/2 + line_width * 2, 0, line_width, y))
    # CAR
    window.blit(car, (obj_x, obj_y))
    #pygame.draw.circle(window, obj_color, (obj_x, obj_y), obj_radious*2)
    pygame.display.update()

pygame.quit()


class Solution:
    def pathSum(self, root: TreeNode, sum_: int) -> List[List[int]]:
        def helper(root, tmp, sum_):
            if not root:
                return
            if not root.left and not root.right and sum_ - root.val == 0:
                tmp += [root.val]
                res.append(tmp)
            helper(root.left, tmp + [root.val], sum_ - root.val)
            helper(root.right, tmp + [root.val], sum_ - root.val)
        res = []
        helper(root, [], sum_)
        return res


import datetime
import itertools

import numpy
from astropy.time import Time, TimeDelta
import astropy.units as u
from astropy.coordinates import SkyCoord, AltAz, get_sun, get_moon
from astroplan import Observer
from astroplan import TargetNeverUpWarning

from kronos import observatory

def wrapHA(ha):
    """Force ha into range -180 to 180. Just to be sure.
    """
    if -180 < ha <= 180:
        return ha
    while ha > 180:
        ha = ha - 360.
    while ha <= -180:
        ha = ha + 360.
    assert -180 < ha <= 180, "ha = {:.2f}".format(ha)
    return ha

class Site(object):
    # lat = 32.789278

    if observatory == "APO":
        site = Observer.at_site("APO", timezone="US/Mountain")
    else:
        site = Observer.at_site("LCO", timezone="America/Santiago")

    lat = site.location.lat.deg

    @classmethod
    def zenithAngleHA(cls, dec, zenithAngle):
        """Return hour angle (degrees) at which a given declination (dec, degrees) will fall within zenithAngle (degrees from zenith at APO)
        """
        # don't bother doing any work if dec never comes within zenithAngle of zenith at apo
        if numpy.abs(dec - cls.lat) > zenithAngle:
            # spherical trig is tricky, check that this is valid?
            return 0
        # numpy routines use radians:
        zenithAngleRad = numpy.radians(zenithAngle)
        decRad = numpy.radians(90. - dec)
        siteLatRad = numpy.radians(90. - cls.lat) # spherical coords, polar angle is zero at [0 0 1]
        # use the fact that cos(angle) = A dot B.  A and B are unit vectors in cartesian coords.
        # solve for HA which is hidden in B via (A dot B) = cos(zenithAngle)
        # strategy: convert zenith vector at APO into unit cartesian coord, call it A:
        # A = [sin(apoLatitude) 0 cos(apoLatitude)]
        # create unit cartesian vector B containing HA an unknown to solve for, at fixed declination dec.
        # B = [cos(HA)*sin(dec) sin(HA)*sin(dec) cos(dec)]
        # dot them together: cos(zenithAngle) = A dot B
        # cos(zenithAngle) = sin(apoLatitude)*cos(HA)*sin(dec) + cos(apoLatitude)*cos(dec)
        # isolate HA
        HA = numpy.arccos((numpy.cos(zenithAngleRad) - numpy.cos(siteLatRad)*numpy.cos(decRad)) / (numpy.sin(siteLatRad)*numpy.sin(decRad)))
        # and we want degrees
        return numpy.degrees(HA)

    @classmethod
    def targetHa2UTC(cls, ha, **kwargs):
        t_time = cls.transitTime(**kwargs).datetime
        ha_hours = ha / 15.
        delta = datetime.timedelta(hours=ha_hours)
        return (t_time - delta, t_time + delta)

    @classmethod
    def transitTime(cls, target=None, ra=None, dec=None, mjd=None, time=None):
        """calculate transit time for an object using astroplan.observer

           target : astropy.SkyCoord
           ra, dec: degrees, if no target is given
           time : an astropy time
           mjd : if no time is given, if neither now is used
        """

        if time is None:
            if mjd is not None:
                time = Time(mjd, format="mjd")
            else:
                time = Time.now()

        if target is None:
            assert ra is not None, "must specify coords if targ not given"
            assert dec is not None, "must specify coords if targ not given"
            target = SkyCoord(ra*u.deg, dec*u.deg)

        # which means relative to sunrise, "nearest" seems to work best
        t_time = cls.site.target_meridian_transit_time(time, target, which="nearest")

        t_time.format = "mjd"
        time.format = "mjd"

        check = t_time - time
        if check > 0.5:
            days = numpy.floor(check.value)
            t_time = t_time - datetime.timedelta(days=days)
        if check < - 0.5:
            days = numpy.abs(numpy.floor(check.value))
            t_time = t_time + datetime.timedelta(days=days)

        return t_time

    @classmethod
    def mjd2lst(cls, MJD):
        """return lst in decimal hours
        """
        return cls.site.localSiderialTime(2400000 + MJD)

    # @classmethod
    # def lstMidnight(cls, datetimeObj=None, returntype="datetime"):
    #     if not datetimeObj:
    #         datetimeObj = datetime.datetime.now()
    #     dateObj = datetimeObj.date()
    #     return cls.site.localSiderialTime(dateObj, returntype=returntype)
    #     # else:
    #     #     return cls.site.localSiderialTime(returntype="datetime")

    # @classmethod
    # def raDec2AltAz(cls, ra, dec):
    #     """Convert from RA, DEC to Alt Az
    #     @return tuple (alt, az) in degrees.
    #     """
    #     platecoo = pycoo.ICRSCoordinates(ra, dec)
    #     coords = cls.site.apparentCoordinates(platecoo)
    #     return (coords.alt.d, coords.az.d)

    @classmethod
    def moonRiseSet(cls, mjd_evening_twilight):
        """calculate moon rise and set appropriately after mjd_evening_twilight
        """
        time = Time(mjd_evening_twilight, format="mjd")
        moon_pos = cls.site.moon_altaz(time)
        bak_delta = TimeDelta(1, format="jd")
        if moon_pos.alt.value > 0:
            moon_set = cls.site.moon_set_time(time, which="next")
            moon_rise = cls.site.moon_rise_time(time, which="previous")
        else:
            moon_set = cls.site.moon_set_time(time, which="next")
            if moon_set.mask:
                moon_set = cls.site.moon_set_time(time+bak_delta, which="next")
            moon_rise = cls.site.moon_rise_time(time, which="next")
            if moon_rise.mask:
                moon_rise = cls.site.moon_set_time(time+bak_delta, which="next")
        return moon_rise.datetime, moon_set.datetime


# 문자열 밀기
# def solution(A, B):
#     answer = 0
#     while A!=B:
#         A = A[-1]+A[:-1]
#         answer += 1
#         if answer>=len(A):
#             return -1
#     return answer

solution=lambda a,b:(b*2).find(a)

# 종이 자르기
def solution(M, N):
    return M*N-1

# 연속된 수의 합
# def solution(num, total):
#     if num%2==0:
#         answer = list(range(int(total/num)-int(num/2)+1,int(total/num)+int(num/2)+1))
#     else:
#         answer = list(range(int(total/num)-int(num/2),int(total/num)+int(num/2)+1))
#     return answer

def solution(num, total):
    answer = []
    var = sum(range(num+1))
    diff = total - var
    start_num = diff//num
    answer = [i+1+start_num for i in range(num)]
    return answer

# 다음에 올 숫자
def solution(common):
    answer = 0
    if common[1]-common[0]==common[2]-common[1]:
        answer = common[-1]+common[1]-common[0]
    else:
        answer = common[-1]*(common[1]/common[0])
    return answer


""""
Conway's Game Of Life

20221125 (Last update: 20231123)

Version: 1.0
"""

import json

import numpy as np

class GameOfLife:
    """Conway's Game Of Life"""

    def __init__(
        self,
        board_width: int,
        board_height: int,
        in_box: bool = True,
        initiate_randomly: bool = False,
    ) -> None:
        """Conway's Game Of Life

        Args:
            board_width (int): Game board width.
            board_height (int): Game board height.
            in_box (bool, optional): Bounded by board boundaries. Defaults to True.
            initiate_randomly (bool, optional): Initiate populations randomly. Defaults to False.
        """
        self._board_width = board_width
        self._board_height = board_height
        self._in_box = in_box
        self._initiate_randomly = initiate_randomly
        self._board = self._create_board()
        self._mask_life = np.zeros(
            (self._board_height, self._board_width),
            dtype=np.int64,
        )
        self._mask_dead = np.zeros(
            (self._board_height, self._board_width),
            dtype=np.int64,
        )

    def __str__(self) -> str:
        return str(self._board)

    @classmethod
    def from_json(cls, filepath: str):
        """Create Conway's Game Of Life based on a json file

        Args:
            filepath (str): Json file path.

        Returns:
            GameOfLife: Conway's Game Of Life
        """
        with open(filepath, encoding="utf-8") as f:
            data = json.load(f)
        new_game = cls(
            data["board_width"],
            data["board_height"],
            data["in_box"],
            initiate_randomly=False,
        )
        new_game._board = np.frombuffer(
            bytes(data["board"], "utf-8"), dtype=np.int64
        ).reshape((data["board_height"], data["board_width"]))
        new_game._mask_life = np.frombuffer(
            bytes(data["mask_life"], "utf-8"), dtype=np.int64
        ).reshape((data["board_height"], data["board_width"]))
        new_game._mask_dead = np.frombuffer(
            bytes(data["mask_dead"], "utf-8"), dtype=np.int64
        ).reshape((data["board_height"], data["board_width"]))
        return new_game

    @classmethod
    def from_np(cls, array: np.ndarray, in_box=True):
        """Create Conway's Game Of Life based on a np.ndarray

        Args:
            array (np.ndarray): Board
            in_box (bool, optional): Bounded by board boundaries. Defaults to True.

        Returns:
            GameOfLife: Conway's Game Of Life
        """
        board_height, board_width = array.shape
        new_game = cls(
            board_width, board_height, in_box=in_box, initiate_randomly=False
        )
        new_game._board = array
        return new_game

    @classmethod
    def from_cells_file(cls, filepath: str, padding: int = 10):
        """Create Conway's Game Of Life based on a cells file

        Args:
            filepath (str): cells file path.
            padding (int): Board padding.

        Returns:
            GameOfLife: Conway's Game Of Life
        """

        temp_board = []
        max_len = 0
        with open(filepath, encoding="utf-8") as f:
            for line in f:
                if line.startswith('!'):
                    continue
                max_len = len(line)-1 if len(line)-1 > max_len else max_len
                temp_board.append([0 if i=='.' else 1 for i in list(line)[:-1]])
        temp_board = [i + [0]*(max_len-len(i)) for i in temp_board]
        temp_board = np.array(temp_board, dtype=np.int64)
        temp_board = np.pad(temp_board, ((padding, padding), (padding, padding)), constant_values=0)
        board_height, board_width = temp_board.shape
        new_game = cls(
            board_width,
            board_height,
            in_box = False,
            initiate_randomly=False,
        )
        new_game._board = temp_board
        return new_game

    @property
    def board(self) -> np.ndarray:
        """Game board

        Returns:
            np.ndarray: Game board
        """
        return self._board

    @board.setter
    def board(self, value: np.ndarray):
        self._board = value

    @property
    def mask_life(self) -> np.ndarray:
        """Life mask

        Returns:
            np.ndarray: Life mask
        """
        return self._mask_life

    @mask_life.setter
    def mask_life(self, value: np.ndarray):
        self._mask_life = value
        self._apply_masks()

    @property
    def mask_dead(self) -> np.ndarray:
        """Dead mask

        Returns:
            np.ndarray: Dead mask
        """
        return self._mask_dead

    @mask_dead.setter
    def mask_dead(self, value: np.ndarray):
        self._mask_dead = value
        self._apply_masks()

    def _create_board(self) -> np.ndarray:
        if self._initiate_randomly:
            return np.random.randint(
                0,
                2,
                size=(self._board_height, self._board_width),
                dtype=np.int64,
            )
        return np.zeros(
            (self._board_height, self._board_width),
            dtype=np.int64,
        )

    def _apply_masks(self):
        temp_board = self._board
        temp_board = (temp_board == 1) | (self._mask_life == 1)
        temp_board = (temp_board == 1) & (self._mask_dead == 0)
        self._board = temp_board.astype(np.int64)

    def update_board(self) -> None:
        """Update the board to the next generation."""
        temp_board = self._board
        if self._in_box:
            temp_board = np.pad(temp_board, ((1, 1), (1, 1)), constant_values=0)

        neighbor = np.zeros(temp_board.shape, dtype=np.int64)
        neighbor += np.roll(temp_board, 1, axis=0)
        neighbor += np.roll(temp_board, -1, axis=0)
        neighbor += np.roll(temp_board, 1, axis=1)
        neighbor += np.roll(temp_board, -1, axis=1)
        neighbor += np.roll(temp_board, (1, 1), axis=(0, 1))
        neighbor += np.roll(temp_board, (-1, -1), axis=(0, 1))
        neighbor += np.roll(temp_board, (-1, 1), axis=(0, 1))
        neighbor += np.roll(temp_board, (1, -1), axis=(0, 1))

        temp_board = ((neighbor == 3) & (temp_board == 0)) | (
            ((neighbor == 2) | (neighbor == 3)) & (temp_board == 1)
        )
        temp_board = temp_board.astype(np.int64)

        if self._in_box:
            temp_board = temp_board[1:-1, 1:-1]

        self._board = temp_board
        self._apply_masks()

    def export_game(self, filepath: str) -> None:
        """Export the board to a json file

        Args:
            filepath (str): Json file path.
        """
        data = {
            "board_width": self._board_width,
            "board_height": self._board_height,
            "in_box": self._in_box,
            "board": self._board.tobytes().decode("utf-8"),
            "mask_life": self._mask_life.tobytes().decode("utf-8"),
            "mask_dead": self._mask_dead.tobytes().decode("utf-8"),
        }
        with open(filepath, "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=4)


# coding: utf-8

__version__ = '1.0.0'

__main_author_name__ = 'Pablo Figue'
__main_author_email__ = 'pfigue posteo de'
__authors__ = (
    '%s <%s>' % (__main_author_name__, __main_author_email__),
)
__license__ = 'MIT'
__program_name__ = 'notizen'
__short_description__ = 'Indexing and searching of personal notes.'
__url__ = 'https://bitbucket.org/pfigue/notizen'

def get_platform_id() -> str:
    '''Returns a string with the description of the platform.

E.g.:
    Linux-3.8.1-1-mainline; x86_64-64bit; CPython-3.4.3'''

    import platform
    msg = '{platform}; {arch}; {python_implementation}-{python_version}'
    msg = msg.format(
        platform=platform.system() + '-' + platform.release(),
        arch=platform.machine() + '-' + platform.architecture()[0],
        python_implementation=platform.python_implementation(),
        python_version=platform.python_version(),
    )
    del(platform)
    return msg


# -*- coding: utf-8 -*-
"""
Created on Tue Nov 22 14:35:56 2022

@author: harpreet.singh
"""

import serial
import struct
import os
import sys
import glob

#BL Commands
COMMAND_BL_GET_VER                                  =0x51
COMMAND_BL_GET_HELP                                 =0x52
COMMAND_BL_GET_CID                                  =0x53
COMMAND_BL_GET_RDP_STATUS                           =0x54
COMMAND_BL_GO_TO_ADDR                               =0x55
COMMAND_BL_FLASH_ERASE                              =0x56
COMMAND_BL_MEM_WRITE                                =0x57
COMMAND_BL_EN_R_W_PROTECT                           =0x58
COMMAND_BL_MEM_READ                                 =0x59
COMMAND_BL_READ_SECTOR_P_STATUS                     =0x5A
COMMAND_BL_OTP_READ                                 =0x5B
COMMAND_BL_DIS_R_W_PROTECT                          =0x5C
COMMAND_BL_MY_NEW_COMMAND                           =0x5D

#len details of the command
COMMAND_BL_GET_VER_LEN                              =6
COMMAND_BL_GET_HELP_LEN                             =6
COMMAND_BL_GET_TORQUE_LEN_LEN                       =6
COMMAND_BL_GET_RPM_LEN_LEN                          =6
COMMAND_BL_GO_FORCE_LEN                             =6
COMMAND_BL_MY_NEW_COMMAND_LEN                       =6

verbose_mode = 1
mem_write_active =0

#----------------------------- utilities----------------------------------------

def word_to_byte(addr, index , lowerfirst):
    value = (addr >> ( 8 * ( index -1)) & 0x000000FF )
    return value

def get_crc(buff, length):
    Crc = 0xFFFFFFFF
    #print(length)
    for data in buff[0:length]:
        Crc = Crc ^ data
        for i in range(32):
            if(Crc & 0x80000000):
                Crc = (Crc << 1) ^ 0x04C11DB7
            else:
                Crc = (Crc << 1)
    return Crc

#----------------------------- Serial Port ----------------------------------------
def serial_ports():
    """ Lists serial port names

        :raises EnvironmentError:
            On unsupported or unknown platforms
        :returns:
            A list of the serial ports available on the system
    """
    if sys.platform.startswith('win'):
        ports = ['COM%s' % (i + 1) for i in range(256)]
    elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
        # this excludes your current terminal "/dev/tty"
        ports = glob.glob('/dev/tty[A-Za-z]*')
    elif sys.platform.startswith('darwin'):
        ports = glob.glob('/dev/tty.*')
    else:
        raise EnvironmentError('Unsupported platform')

    result = []
    for port in ports:
        try:
            s = serial.Serial(port)
            s.close()
            result.append(port)
        except (OSError, serial.SerialException):
            pass
    return result

def Serial_Port_Configuration(port):
    global ser
    try:
        ser = serial.Serial(port,115200,timeout=2)
    except:
        print("\n   Oops! That was not a valid port")

        port = serial_ports()
        if(not port):
            print("\n   No ports Detected")
        else:
            print("\n   Here are some available ports on your PC. Try Again!")
            print("\n   ",port)
        return -1
    if ser.is_open:
        print("\n   Port Open Success")
    else:
        print("\n   Port Open Failed")
    return 0

def read_serial_port(length):
    read_value = ser.read(length)
    return read_value

def Close_serial_port():
    pass
def purge_serial_port():
    ser.reset_input_buffer()

def Write_to_serial_port(value, *length):
        data = struct.pack('>B', value)
        if (verbose_mode):
            value = bytearray(data)
            #print("   "+hex(value[0]), end='')
            print("   "+"0x{:02x}".format(value[0]),end=' ')
        if(mem_write_active and (not verbose_mode)):
                print("#",end=' ')
        ser.write(data)

#----------------------------- command processing----------------------------------------

def process_COMMAND_BL_MY_NEW_COMMAND(length):
    pass

def process_COMMAND_BL_GET_VER(length):
    ver=read_serial_port(1)
    value = bytearray(ver)
    print("\n   Bootloader Ver. : ",hex(value[0]))

def process_COMMAND_BL_GET_HELP(length):
    #print("reading:", length)
    value = read_serial_port(length)
    reply = bytearray(value)
    print("\n   Supported Commands :",end=' ')
    for x in reply:
        print(hex(x),end=' ')
    print()

#------------------------------COmmand decode-------------------------------------------------

def decode_menu_command_code(command):
    ret_value = 0
    data_buf = []
    for i in range(255):
        data_buf.append(0)

    if(command  == 0 ):
        print("\n   Exiting...!")
        raise SystemExit
    elif(command == 1):
        print("\n   Command == > BL_GET_VER")
        COMMAND_BL_GET_VER_LEN              = 6
        data_buf[0] = COMMAND_BL_GET_VER_LEN-1
        data_buf[1] = COMMAND_BL_GET_VER
        crc32       = get_crc(data_buf,COMMAND_BL_GET_VER_LEN-4)
        crc32 = crc32 & 0xffffffff
        data_buf[2] = word_to_byte(crc32,1,1)
        data_buf[3] = word_to_byte(crc32,2,1)
        data_buf[4] = word_to_byte(crc32,3,1)
        data_buf[5] = word_to_byte(crc32,4,1)

        Write_to_serial_port(data_buf[0],1)
        for i in data_buf[1:COMMAND_BL_GET_VER_LEN]:
            Write_to_serial_port(i,COMMAND_BL_GET_VER_LEN-1)

        ret_value = read_bootloader_reply(data_buf[1])

#----------------------------- Ask Menu implementation----------------------------------------

name = input("Enter the Port Name of your device(Ex: COM3):")
ret = 0
ret=Serial_Port_Configuration(name)
if(ret < 0):
    decode_menu_command_code(0)

while True:
    print("\n +==========================================+")
    print(" |                  Menu                      |")
    print(" |         STM32F4 Command Center v1        |")
    print(" +==========================================+")

    print("\n   Which BL command do you want to send ??\n")
    print("   BL_GET_VER                            --> 1")
    print("   BL_GET_HLP                            --> 2")
    print("   BL_GET_TORUQE                         --> 3")
    print("   BL_GET_RPM                            --> 4")
    print("   BL_GO_FORCE                           --> 5")
    print("   MENU_EXIT                             --> 0")

    #command_code = int(input("\n   Type the command code here :") )

    command_code = input("\n   Type the command code here :")

    if(not command_code.isdigit()):
        print("\n   Please Input valid code shown above")
    else:
        decode_menu_command_code(int(command_code))

    input("\n   Press any key to continue  :")
    purge_serial_port()

def check_flash_status():
    pass

def protection_type():
    pass


import discord
import pickle
import os
from discord.ext import commands
from discord import Spotify

from collections.abc import Sequence

# Client Keys
CLIENT_ID = os.environ['CLIENT_ID']
CLIENT_SECRET = os.environ['CLIENT_SECRET']

# Spotify API URLs
SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token"
SPOTIFY_API_BASE_URL = "https://api.spotify.com"
API_VERSION = "v1"
SPOTIFY_API_URL = "{}/{}".format(SPOTIFY_API_BASE_URL, API_VERSION)

class SpotifyUtilityCommands(commands.Cog, name='Spotify Commands'):
    def __init__(self, bot):
        self.bot = bot

    async def cog_check(self, ctx):
        infile = open('storage/blacklist', 'rb')
        self.banned = pickle.load(infile)
        infile.close()
        for id in self.banned:
            if int(format(ctx.author.id)) == id:
                return False
        return True

    def make_sequence(self, seq):
        if seq is None:
            return ()
        if isinstance(seq, Sequence) and not isinstance(seq, str):
            return seq
        else:
            return (seq, )

    def reaction_check(self, message=None, emoji=None, author=None, ignore_bot=True):
        message = self.make_sequence(message)
        message = tuple(m.id for m in message)
        emoji = self.make_sequence(emoji)
        author = self.make_sequence(author)

        def check(reaction, user):
            if ignore_bot and user.bot:
                return False
            if message and reaction.message.id not in message:
                return False
            if emoji and reaction.emoji not in emoji:
                return False
            if author and user not in author:
                return False
            return True

        return check

def setup(bot):
    bot.add_cog(SpotifyUtilityCommands(bot))


# coding: utf-8

import uiautomator2 as u2
from time import sleep
import logging
import random

#config logging
logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
sleep(5)

d=u2.connect()
sleep(5)

def playMusic():
    #Enter all apps
    d.xpath('//*[@resource-id="com.android.systemui:id/grid_nav"]/android.widget.LinearLayout[1]/android.widget.ImageButton[1]').click()
    sleep(2)
    #start_Local Media Player
    d(scrollable=True).scroll.to(text="Local Media Player")
    sleep(1)
    d(resourceId="com.android.car.carlauncher:id/app_name", text="Local Media Player").click()
    sleep(5)
    #enter music file_start
    d(resourceId="com.android.car.media:id/title", text="Music").click()
    sleep(2)
    d(resourceId='com.android.car.media:id/thumbnail').click()
    sleep(1)
    for j in range(1,3):
        for i in range(50):
            #play_pause_stop
            d(resourceId='com.android.car.media:id/play_pause_stop').click()
            sleep(0.5)
        for i in range(50):
            #skip_prev
            d(resourceId='com.android.car.media:id/skip_prev').click()
            sleep(0.5)
        for i in range(50):
            #skip_next
            d(resourceId='com.android.car.media:id/skip_next').click()
            sleep(0.5)
    d.press("back")

def adjustVolme():
    d.app_start("com.android.car.settings", stop=True)
    d(text="Settings").wait(timeout=10)
    d(text="More").click()
    d(scrollable=True).scroll.to(text="Sound")
    d(text="Sound").click()

    volume0 = d.xpath(
        '//*[@resource-id="com.android.car.settings:id/nested_recycler_view_layout"]/androidx.recyclerview.widget.RecyclerView[1]/android.widget.LinearLayout[1]/android.widget.RelativeLayout[1]/android.widget.LinearLayout[1]'
        ).rect
    volume1 = d.xpath(
        '//*[@resource-id="com.android.car.settings:id/nested_recycler_view_layout"]/androidx.recyclerview.widget.RecyclerView[1]/android.widget.LinearLayout[2]/android.widget.RelativeLayout[1]/android.widget.LinearLayout[1]'
        ).rect

    #adjut media volume0 and volume1
    for j in range(1,100):
        for i in range(30):
            # 随机点
            d.click(random.randint(volume0[0], volume0[0]+volume0[2]), volume0[1]+volume0[3]/2)
            sleep(10)
        for i in range(30):
            # 随机点
            d.click(random.randint(volume1[0], volume1[0]+volume1[2]), volume1[1]+volume1[3]/2)
            sleep(10)

if __name__=='__main__':
    while True:
    #for i in range(1,3):
        playMusic()
        sleep(5)
        adjustVolme()
        sleep(5)


'''
Program :- Given n as input, print table of n in following format

Author : AmRiyaz

Last Modified : April 2021
'''

n = 9
table = n
st = ""
for i in range(1,11):
    table = n*i
    st = str(n)+" X "+str(i)+" = "+str(table)
    print(st)

'''
Output:-
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
'''

Conditions in python with loop/challenge1A3CO.py


import re

from scan.fetchers.cli.cli_fetcher import CliFetcher

# Fetch Interface details from output of 'ip address show' ('ip a show')

class CliFetchInterfaceDetails(CliFetcher):
    def __init__(self):
        super().__init__()
        self.ethtool_attr = re.compile('^\s+([^:]+):\s(.*)$')
        self.regexps = [
            {'name': 'mac_address', 're': '^.*\slink/ether\s(\S+)\s',
             'description': 'MAC address'},
            {'name': 'IP Address', 're': '^\s*inet ([0-9.]+)/',
             'description': 'IP Address v4'},
            {'name': 'IPv6 Address', 're': '^\s*inet6 (\S+) .* global ',
             'description': 'IPv6 Address'}
        ]

    def get_interface_details(self, host_id, interface_name, ip_lines, ethtool_lines) -> dict:
        interface = None
        status_up = None
        for line in [l1 for l1 in ip_lines if l1 != '']:
            tokens = None
            if interface is None:
                tokens = line.split()
                line_remainder = line.split(":")[2].strip()
                interface = {
                    "host": host_id,
                    "index": line[:line.index(":")],
                    "name": interface_name,
                    "local_name": interface_name,
                    "lines": []
                }
                self.handle_line(interface, line_remainder)
                if '<UP,' in line or ',UP,' in line:
                    status_up = True
            if status_up is None:
                if tokens is None:
                    tokens = line.split()
                if 'BROADCAST' in tokens:
                    status_up = 'UP' in tokens
            if interface:
                self.handle_line(interface, line)
        self.set_interface_data(interface, ethtool_lines)
        interface['state'] = 'UP' if status_up else 'DOWN'
        if 'id' not in interface:
            interface['id'] = interface_name + '-unknown_mac'
        return interface

    def handle_line(self, interface, line):
        self.find_matching_regexps(interface, line, self.regexps)
        if 'mac_address' in interface:
            interface["id"] = interface["name"] + "-" + interface["mac_address"]
        interface["lines"].append(line.strip())

    def set_interface_data(self, interface, ethtool_lines):
        # Ethtool output shorter than 2 lines doesn't contain useful data
        if not interface or len(ethtool_lines) <= 2:
            return
        interface["data"] = "\n".join(interface["lines"])
        interface.pop("lines", None)
        attr = None
        for line in ethtool_lines[1:]:
            matches = self.ethtool_attr.match(line)
            if matches:
                # add this attribute to the interface
                attr = matches.group(1)
                value = matches.group(2)
                interface[attr] = value.strip()
            else:
                # add more values to the current attribute as an array
                if isinstance(interface[attr], str):
                    interface[attr] = [interface[attr], line.strip()]
                else:
                    interface[attr].append(line.strip())


from matplotlib import pyplot as plt
import pandas as pd
corona=pd.read_csv("full_data.csv")
corona=pd.DataFrame(corona)
x=corona["total_cases"]
y=corona["weekly_cases"]
plt.plot(corona["total_cases"], corona["weekly_cases"])

plt.scatter(x,y)
plt.show()

import numpy as np
import matplotlib.pyplot as plt
corona=pd.read_csv("full_data.csv")
corona.plot.scatter(x="total_cases", y="weekly_cases")
plt.show()