import sys
import subprocess
import time
import argparse
#import ConfigParser
import os

wlan_IP=[]
conf = {}
i=0
with open('/etc/dhcpcd.conf') as fp:
    for line in fp:
        if line.startswith('#'):
            continue
        if(i==0):
            if 'static ip_address' in line:
                #print(line.lstrip(''))
                #eth_Static_IP = line[18],line[19],line[20],line[21],line[22],line[23],line[24],line[25],line[26],line[27],line[28],line[29],line[30],line[31],line[32]
                #eth_Static_IP = ''.join(eth_Static_IP)
                #print(eth_Static_IP)
                i=1
        elif(i==1):
            if 'static ip_address' in line:
                #print(line.lstrip(''))
                #
                j=18;
                while(True):
                    if(line[j] != '/'):
                        wlan_IP.append(line[j])
                    else:
                        break
                    j=j+1
                wlan_IP=''.join(wlan_IP)
                #print(wlan_IP)
                #
                #wlan_Static_IP = line[18],line[19],line[20],line[21],line[22],line[23],line[24],line[25],line[26],line[27],line[28],line[29],line[30],line[31],line[32]
                #print(wlan_Static_IP)
                #wlan_Static_IP = ''.join(wlan_Static_IP)
                #print(wlan_Static_IP)
                #time.sleep(20)
                i=0

with open('/etc/create_ap.conf') as fp:
    Wifi_Channel = fp.readline()
    Wifi_Channel = Wifi_Channel.rstrip()
    fp.close()

Wifi_Channel = Wifi_Channel[8:]
print(Wifi_Channel)

with open('/etc/create_ap.conf') as fp:
    for line in fp:
        if line.startswith('#'):
            continue
##        if 'CHANNEL' in line:
##            Wifi_Channel = line[8], line[9], line[10], line[11], line[12], line[13], line[14]
##            Wifi_Channel = ''.join(Wifi_Channel)
##            print(Wifi_Channel)

        if 'WPA_VERSION' in line:
            Encryption_Key = line[12]
            Encryption_Key = ''.join(Encryption_Key)
            print(Encryption_Key)

        if 'ISOLATE_CLIENTS' in line:
            Isolate_Client = line[16]
            Isolate_Client = ''.join(Isolate_Client)
            print(Isolate_Client)

        if 'IEEE80211N' in line:
            Wifi_Mode = line[11]
            Wifi_Mode = ''.join(Wifi_Mode)
            print(Wifi_Mode)

        if 'IEEE80211AC' in line:
            Wifi_Mode2 = line[12]
            Wifi_Mode2 = ''.join(Wifi_Mode2)
            print(Wifi_Mode2)

        if 'FREQ_BAND' in line:
            #print(line.lstrip(''))
            Frequency_Band = line[10]
            Frequency_Band = ''.join(Frequency_Band)
            print(Frequency_Band)

Wifi_Conf_File = open("/home/pi/AP-WebApp/Django2.0-Contact-Form-master/django_contact_form/templates/Wifi_Conf1.txt","w+")
Wifi_Conf_File.write(wlan_IP)
Wifi_Conf_File.write('\n')
if(Frequency_Band == '2'):
    Wifi_Conf_File.write("2.4\n")
elif(Frequency_Band == '5'):
    Wifi_Conf_File.write("5\n")

Wifi_Conf_File.close()

Wifi_Conf_File2 = open("/home/pi/AP-WebApp/Django2.0-Contact-Form-master/django_contact_form/templates/Wifi_Conf2.txt","w+")
if(Encryption_Key == '2'):
    Wifi_Conf_File2.write("wpa2\n")
elif(Encryption_Key == '1'):
    Wifi_Conf_File2.write("wpa\n")
if(Wifi_Mode == '1' and Wifi_Mode2 == '0'):
    Wifi_Conf_File2.write("802.11n\n")
elif(Wifi_Mode == '0' and Wifi_Mode2 == '1'):
    Wifi_Conf_File2.write("802.11ac\n")
if(Isolate_Client == '0'):
    Wifi_Conf_File2.write("No\n")
elif(Isolate_Client == '1'):
    Wifi_Conf_File2.write("Yes\n")
Wifi_Conf_File2.write(Wifi_Channel + "\n")

Wifi_Conf_File2.close()


from django.urls import path
from django.contrib.auth import views as auth_views
from .views import *

app_name = 'accounts'

urlpatterns = [
    path('register/', registerPage, name='register'),
    path('login/', loginPage, name='login'),
    path('logout/', logoutUser, name='logout'),

    path('', home, name='home'),
    path('user/', userPage, name='user_page'),

    path('account/', accountSettings, name='account'),

    path('products/', products, name='products'),
    path('customer/<str:pk_test>/', customer, name='customer'),

    path('create_order/<str:pk>/', createOrder, name="create_order"),
    path('update_order/<str:pk>/', updateOrder, name='update_order'),
    path('delete_order/<str:pk>/', deleteOrder, name='delete_order'),

    #path('reset_password/',
    # auth_views.PasswordResetView.as_view(template_name='accounts/password_reset.html'),
    # name='reset_password'),

    #path('reset_password_sent/',
    # auth_views.PasswordResetDoneView.as_view(),
    # name='password_reset_done'),

    #path('reset/<uidb64>/<token>/',
    # auth_views.PasswordResetConfirmView.as_view(),
    # name='password_reset_confirm'),

    #path('reset_password_complete/',
    # auth_views.PasswordResetCompleteView.as_view(),
    # name='password_reset_complete'),
]

# All authentication views
# https://docs.djangoproject.com/en/3.1/topics/auth/default/#all-authentication-views

# 1 - Submit email form                         //PasswordResetView.as_view()
# 2 - Email sent success message                //PasswordResetDoneView.as_view()
# 3 - Link to password Rest form in email       //PasswordResetConfirmView.as_view()
# 4 - Password successfully changed message     //PasswordResetCompleteView.as_view()


# https://onlinejudge.u-aizu.ac.jp/problems/DSL_1_A

n, q = list(map(int, input().split()))
parents = [-1 for _ in range(n)]

def root(i):
    if parents[i] == -1:
        return i
    else:
        parents[i] = root(parents[i])
        return parents[i]

def unite(x, y):
    if same(x, y):
        return

    x = root(x)
    y = root(y)
    parents[y] = x

def same(x, y):
    return root(x) == root(y)

for _ in range(q):
    com, x, y = list(map(int, input().split()))
    if com == 0:
        unite(x, y)
    elif com == 1:
        if same(x, y):
            print(1)
        else:
            print(0)
    else:
        raise Exception


#
# @lc app=leetcode id=523 lang=python3
#
# [523] Continuous Subarray Sum
#

# @lc code=start
class Solution:
    def checkSubarraySum(self, nums: List[int], k: int) -> bool:
        # # Solution 1: Time Limit Exceeded
        # prefix = [0]
        # for num in nums:
        #     cur = prefix[-1] + num
        #     prefix.append(cur)
        #     for pre in prefix[:-2]:
        #         if (cur - pre) % k == 0:
        #             return True
        # return False

        # Solution 2: prefixSum --> prefixRemainder
        # if the current prefixRemainder already exists, return True
        # Time: O(n), Space: O(k)
        prefix = {0: -1}
        remainder = 0
        for i, num in enumerate(nums):
            remainder = (remainder + num) % k
            if remainder in prefix:
                if prefix[remainder] < i - 1:
                    return True
            else:
                prefix[remainder] = i
        return False

# @lc code=end


r'''script_lib -- library of SQL scripts

Scripts are pkg_resources, i.e. design-time constants.

Each script should have a title, taken from the first line::

    >>> Script.cms_patient_mapping.title
    u'map CMS beneficiaries to i2b2 patients'

    >>> fname, text = Script.cms_patient_mapping.value
    >>> lines = text.split('\n')
    >>> print lines[0]
    /** cms_patient_mapping - map CMS beneficiaries to i2b2 patients

TODO: copyright, license blurb enforcement

We can separate the script into statements::

    >>> statements = Script.cms_patient_mapping.statements()
    >>> print next(s for s in statements if 'insert' in s)
    ... #doctest: +ELLIPSIS
    insert /*+ append */
      into "&&I2B2STAR".patient_mapping
    ...

Dependencies between scripts are declared as follows::

    >>> print next(decl for decl in statements if "'dep'" in decl)
    ... #doctest: +ELLIPSIS
    select birth_date from cms_... where 'dep' = 'cms_dem_txform.sql'

    >>> Script.cms_patient_mapping.deps()
    ... #doctest: +ELLIPSIS
    frozenset([<Script(cms_dem_txform)>])

The `.pls` extension indicates a dependency on a package rather than a script::

    >>> Script.cms_dem_txform.deps()
    frozenset([<Script(i2b2_crc_design)>, <Package(cms_keys)>])

We statically detect relevant effects; i.e. tables and views created::

    >>> Script.i2b2_crc_design.created_objects()
    [('view', u'i2b2_status')]

as well as tables inserted into::

    >>> variables={I2B2STAR: 'I2B2DEMODATA',
    ...            CMS_RIF: 'CMS_DEID',
    ...            'cms_source_cd': "'ccwdata.org'", 'fact_view': 'F'}
    >>> Script.cms_facts_load.inserted_tables(variables)
    [u'"I2B2DEMODATA".observation_fact']

To insert in chunks by bene_id, define a view of distinct relevant
bene_ids and use the relevant params in your insert statement:

    >>> ChunkByBene.source_view, ChunkByBene.required_params
    ('bene_id_chunk_source', frozenset(['bene_id_hi', 'bene_id_lo']))

    >>> chunked = Script.cms_encounter_mapping
    >>> from sql_syntax import param_names, created_objects
    >>> [ix for (ix, s) in enumerate(chunked.statements())
    ...  if ('view', ChunkByBene.source_view) in created_objects(s)]
    [3, 7]
    >>> [ix for (ix, s) in enumerate(chunked.statements())
    ... if ChunkByBene.required_params <= set(param_names(s)) ]
    [4, 8]

TODO: indexes.
ISSUE: truncate, delete, update aren't reversible.

The last statement should be a scalar query that returns non-zero to
signal that the script is complete:

    >>> print statements[-1]
    select 1 complete
    from "&&I2B2STAR".patient_mapping
    where rownum = 1

The completion test may depend on a digest of the script and its dependencies:

    >>> design_digest = Script.cms_dem_txform.digest()
    >>> last = Script.cms_dem_txform.statements(variables)[-1].strip()
    >>> print last.replace(str(design_digest), '123...')
    select 1 up_to_date
    from cms_dem_txform where design_digest = 123...

'''

from itertools import groupby
import re

import enum
import pkg_resources as pkg

from sql_syntax import (
    iter_statement, iter_blocks, substitute,
    created_objects, inserted_tables)

I2B2STAR = 'I2B2STAR'  # cf. &&I2B2STAR in sql_scripts
CMS_RIF = 'CMS_RIF'

class SQLMixin(object):
    def each_statement(self,
                       variables=None):
        _name, text = self.value
        for line, comment, statement in self.parse(text):
            ss = substitute(statement, self._all_vars(variables))
            yield line, comment, ss

    def _all_vars(self, variables):
        '''Add design_digest to variables.
        '''
        if variables is None:
            return None
        return dict(variables, design_digest=self.digest())

    def statements(self,
                   variables=None):
        _name, text = self.value
        return list(stmt for _l, _c, stmt
                    in self.each_statement(variables=variables))

    def created_objects(self):
        return []

    def inserted_tables(self,
                        variables={}):
        return []

    @property
    def title(self):
        _name, text = self.value
        line1 = text.split('\n', 1)[0]
        if not (line1.startswith('/** ') and ' - ' in line1):
            raise ValueError('%s missing title block' % self)
        return line1.split(' - ', 1)[1]

    def deps(self):
        # TODO: takewhile('select' in script)
        return frozenset(child
                         for sql in self.statements()
                         for child in Script._get_deps(sql))

    def dep_closure(self):
        # TODO: takewhile('select' in script)
        return frozenset(
            [self] + [descendant
                      for sql in self.statements()
                      for child in Script._get_deps(sql)
                      for descendant in child.dep_closure()])

    def digest(self):
        '''Hash the text of this script and its dependencies.

        >>> nodeps = Script.i2b2_crc_design
        >>> nodeps.digest() == hash(frozenset([nodeps.value[1]]))
        True

        >>> complex = Script.cms_dem_txform
        >>> complex.digest() != hash(frozenset([complex.value[1]]))
        True
        '''
        return hash(frozenset(text for s in self.dep_closure()
                              for _fn, text in [s.value]))

    @classmethod
    def _get_deps(cls, sql):
        '''
        >>> ds = Script._get_deps(
        ...     "select col from t where 'dep' = 'oops.sql'")
        Traceback (most recent call last):
            ...
        KeyError: 'oops'

        >>> Script._get_deps(
        ...     "select col from t where x = 'name.sql'")
        []
        '''
        m = re.search(r"select \S+ from \S+ where 'dep' = '([^']+)'", sql)
        if not m:
            return []
        name, ext = m.group(1).rsplit('.', 1)
        choices = Script if ext == 'sql' else Package if ext == 'pls' else []
        deps = [s for s in choices if s.name == name]
        if not deps:
            raise KeyError(name)
        return deps

class ScriptMixin(SQLMixin):
    @classmethod
    def parse(cls, text):
        return iter_statement(text)

    def created_objects(self):
        return [obj
                for (_name, text) in [self.value]
                for _l, _comment, stmt in iter_statement(text)
                for obj in created_objects(stmt)]

    def inserted_tables(self,
                        variables={}):
        return [obj
                for (_name, text) in [self.value]
                for _l, _comment, stmt in iter_statement(text)
                for obj in inserted_tables(
                        substitute(stmt, self._all_vars(variables)))]

class Script(ScriptMixin, enum.Enum):
    '''Script is an enum.Enum of (fname, contents) tuples.

    ISSUE: It's tempting to consider separate libraries for NAACCR,
           NTDS, etc., but that doesn't integrate well with the
           generic luigi.EnumParameter() in etl_tasks.SqlScriptTask.

    '''
    [
        # Keep sorted
        cms_dem_dstats,
        cms_dem_txform,
        cms_dx_dstats,
        cms_dx_txform,
        cms_enc_dstats,
        cms_enc_txform,
        cms_encounter_mapping,
        cms_facts_load,
        cms_patient_dimension,
        cms_patient_mapping,
        cms_visit_dimension,
        i2b2_crc_design,
        synpuf_txform,
    ] = [
        (fname, pkg.resource_string(__name__,
                                    'sql_scripts/' + fname).decode('utf-8'))
        for fname in [
                'cms_dem_dstats.sql',
                'cms_dem_txform.sql',
                'cms_dx_dstats.sql',
                'cms_dx_txform.sql',
                'cms_enc_dstats.sql',
                'cms_enc_txform.sql',
                'cms_encounter_mapping.sql',
                'cms_facts_load.sql',
                'cms_patient_dimension.sql',
                'cms_patient_mapping.sql',
                'cms_visit_dimension.sql',
                'i2b2_crc_design.sql',
                'synpuf_txform.sql',
        ]
    ]

    del fname

    def __repr__(self):
        return '<%s(%s)>' % (self.__class__.__name__, self.name)

class PackageMixin(SQLMixin):
    @classmethod
    def parse(cls, txt):
        return iter_blocks(txt)

class Package(PackageMixin, enum.Enum):
    [
        # Keep sorted
        cms_keys,
    ] = [
        (fname, pkg.resource_string(__name__,
                                    'sql_scripts/' + fname).decode('utf-8'))
        for fname in [
                'cms_keys.pls',
        ]
    ]

    def __repr__(self):
        return '<%s(%s)>' % (self.__class__.__name__, self.name)

class ChunkByBene(object):
    source_view = 'bene_id_chunk_source'
    required_params = frozenset(['bene_id_lo', 'bene_id_hi'])

    ntiles_sql = '''
    select chunk_num, count(*) chunk_size
         , min(bene_id) bene_id_lo, max(bene_id) bene_id_hi
    from (
    select bene_id, ntile({ntiles}) over (order by bene_id) as chunk_num
    from {chunk_source_view}
    ) group by chunk_num
    order by bene_id_lo
    '''

    @classmethod
    def chunk_query(cls, ntiles,
                    chunk_source=None):
        return cls.ntiles_sql.format(
            ntiles=ntiles,
            chunk_source_view=chunk_source or cls.source_view)

    @classmethod
    def result_chunks(cls, result, limit):
        chunks = [dict(bene_id_lo=row.bene_id_lo,
                       bene_id_hi=row.bene_id_hi)
                  for row in result[:limit]]
        sizes = [row.chunk_size for row in result[:limit]]
        return chunks, sizes

def _object_to_creators(libs):
    '''Find creator scripts for each object.

    "There can be only one."
    >>> creators = _object_to_creators([Script, Package])
    >>> [obj for obj, scripts in creators
    ...  if len(scripts) > 1]
    [('view', u'bene_id_chunk_source')]
    '''
    item0 = lambda o_s: o_s[0]
    objs = sorted(
        [(obj, s)
         for lib in libs for s in lib
         for obj in s.created_objects()],
        key=item0)
    by_obj = groupby(objs, key=item0)
    return [(obj, list(places)) for obj, places in by_obj]

_redefined_objects = [
    obj for obj, scripts in _object_to_creators([Script, Package])
    if len(scripts) > 1 and
    obj not in [('view', ChunkByBene.source_view)]]
assert _redefined_objects == [], _redefined_objects


from io import TextIOWrapper
from pathlib import Path

from connection import establish_connection
from config.env import ADMIN_ID, TASKS_URL
from .types import T_images, T_response

DEFAULT_LABELS = [
    {
        "name": "car", # label name
        "color": "#fa3253", # color in gui
        "attributes": []
    },
    {
        "name": "plate",
        "color":"#3d3df5",
        "attributes": [
            {
                "name": "plate",
                "mutable": False,
                "input_type": "text", # Select/Radio/Checkbox/Text/Number
                "default_value": "",
                "values": [""]
            }
        ]
    }
]

def generate_task(
    assignee_username: str, # Username исполнителя таска.
    assignee_id: int, # ID исполнителя таска.
    owner_id: int = ADMIN_ID, # ID создателя таска.
    overlap: int = 0, # Честно хз что это, но мне страшно это убирать.
    segment_size: int = 5, # Кол-во картинок на сегмент.
    image_quality: int = 100, # Сжатие.
    labels: list[dict[str, str | list]] = DEFAULT_LABELS, # То, что размечать.
    *,
    times_attempted: int = 1 # Номер попытки
    ) -> T_response:
    """Initial request that POSTs an "empty" task.

    Parameters
    ----------
    assignee_username : str
        Account username to which this task will be assigned.
        Will be used to make a name for a task.
    assignee_id : str
        Account id to which this task will be assigned.
        Mandatory argument to successfully create a task through API.
    owner_id : int
        Admin ID (creator of a task).
        Mandatory argument to successfully create a task through API.
    overlap : int
        TODO: find out if this is a mandatory parameter.
        I actually don't know what it is, and at this point,
        I'm too afraid to ask. But I've set `overlap=0` and it works.
    segment_size : int
        Number of images per job.
        Mandatory argument to successfully create a task through API.
    image_quality : int
        Image quality in percents.
        App will lower the images' resolution if the value is < 100.
        Mandatory (?) argument to successfully create a task through API.
    labels : list[dict[str, str | list]]
        The very things that need to be annotated.
        Can be simply a dict of key-value pairs, if no special
        attributes are needed, or you can some attributes
        as specified on the site.
        Mandatory argument to successfully create a task through API.
    times_attempted : int
        Number of times the candidate has requested a task.
        Will be used to make a name for a task.

    Returns
    -------
    response : requests.Response
        Response from the API. If success, 201.

    See also
    --------
    README, sec. "How Tasks are Created" ("Как создаются таски")
    """
    session = establish_connection()
    data = {
        "name": f"{times_attempted} Test Assignment {assignee_username}",
        "assignee_id": assignee_id,
        "owner_id": owner_id,
        "overlap": overlap,
        "segment_size": segment_size,
        "image_quality": image_quality,
        "labels": labels
    }

    # I've experimented w/ `json=data` and `data=data`
    # and found that `json=data` was correct.
    return session.post(
        TASKS_URL,
        json=data,
    )

def generate_images(number: int = 5, *, times_attempted: int = 1) -> T_images:
    """Generates image payload for a POST request.

    This function only generates the list of required format.
    It doesn't POST the data to the API. The function
    `combine_task_and_images()` does that.

    Parameters
    ----------
    number : int
        Number of images to read and to add in a payload.
    times_attempted : int
        Number of times the candidate has requested a task.
        Will be used to read different images.

    Returns
    -------
    image_payload : list[tuple[str, tuple[str, TextIOWrapper, str]]]
        i.e. (times_attempted=1):
        [
            ("client_files[1]", <IMAGE 1 IN BINARY FORMAT>, "image/png")),
            ("client_files[2]", <IMAGE 2 IN BINARY FORMAT>, "image/png")),
                                        ...
            ("client_files[5]", <IMAGE 5 IN BINARY FORMAT>, "image/png")),
        ]
        i.e. (times_attempted=2):
        [
            ("client_files[1]", <IMAGE 6 IN BINARY FORMAT>, "image/png")),
            ("client_files[2]", <IMAGE 7 IN BINARY FORMAT>, "image/png")),
                                        ...
            ("client_files[5]", <IMAGE 10 IN BINARY FORMAT>, "image/png")),
        ]

    See also
    --------
    `combine_task_and_images()`
    """
    def read_image(path: str | Path) -> TextIOWrapper:
        return open(path, "rb")

    # path_to_original_images: Path = ORIGINAL_IMAGES_DIR.resolve()
    path_to_original_images: Path = Path(Path(__file__).parent.parent / "media" / "images").resolve()

    images = []
    for i in range(number):
        # ("client_files[1]", ("image1.png", read_image(.media/images/1.jpg), "image/png"))
        images.append(
            (
                f"client_files[{i+1}]",
                # f"server_files[{i+1}]",
                (
                    f"image{i+1}.png",
                    (read_image(path_to_original_images / f"{i+1}.jpg")
                        if times_attempted == 1
                        else
                            read_image(path_to_original_images / f"{i+6}.jpg")),
                    "image/png"
                )
            )
        )

    return images

def combine_task_and_images(task_id: int, images: T_images) -> T_response:
    """POSTs image payload data to a task (can be any task).

    Reads image payload data acquired from `generate_images()`
    and POSTs it through the API to a given task,
    effectively making a task 'complete' and ready to be undertaken.

    Parameters
    ----------
    task_id : int
        ID of an "empty" task that will get the images.
    images : image_payload

    Returns
    -------
    response : requests.Response
        Response from the API. If success, 203.
        NOTE: if the upload failed, task isn't combined with images,
        but the API still returns 203. To check if the request was
        ACTUALLY a success, a JSON with a key "data" must be received.
        This "data" is a numerical value of image directory
        on a server.

    See also
    --------
    `generate_images()`
    """
    session = establish_connection()

    data = {
        "image_quality": 100,
        "use_zip_chunks": False,
        "use_cache": False,
        "sorting_method": "natural",
        "storage": "local",
        "storage_method": "file_system",
    }

    return session.post(
        f"{TASKS_URL}/{task_id}/data",
        headers={"Upload-Start": "true",   # I don't know if these headers are actually needed,
                "Upload-Multiple": "true", # but they were listed in some examples I found online
                "Upload-Finish": "true"},  # and given in the corresponding API end-point through Swagger.
        # Same with `data=data` and `files=images` as in `generate_task()`.
        data=data,
        files=images
    )


def merge_sort(l):
	if len(l)>1:
		mid = len(l)//2
		left_l = l[:mid]
		right_l =l[mid:]

		merge_sort(left_l)
		merge_sort(right_l)

		i=j=k=0
		while i< len(left_l) and j < len(right_l):
			if left_l[i] < right_l[j]:
				l[k] = left_l[i]
				k+=1
				i+=1
			else:
				l[k] = right_l[j]
				k+=1
				j+=1
		while  i < len(left_l):
			l[k] = left_l[i]
			k+=1
			i+=1

		while  j < len(right_l):
			l[k] = right_l[j]
			k+=1
			j+=1

l=[4,3,2,1]
merge_sort(l)
print(l)


#!/usr/bin/env python
# coding: utf-8

# In[22]:

#pip install tk

# # Importing the modules

# In[23]:

import tkinter
from tkinter.filedialog import askopenfilename

# In[24]:

#pip install filetype

# In[25]:

import filetype
import os
import keras

# In[26]:

#from keras.models import Sequential
#from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization

# In[27]:

import livelossplot
plot_losses = livelossplot.PlotLossesKeras()

# In[28]:

from keras.models import Sequential

# In[29]:

from keras.models import Model, load_model

# In[30]:

from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization, Input, ZeroPadding2D, Activation
from PIL import Image
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# In[31]:

plt.style.use('dark_background')
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder

# # OneHotEncoder
#

# In[32]:

encoder = OneHotEncoder()
encoder.fit([[0], [1]])

# # Creating Empty Lists

# In[33]:

data = []
paths = []
result = []

# # Walking through the Dataset via import os

# In[34]:

os.listdir(r'C:\Users\hp\Desktop\Brain Tumor Detection')

# In[35]:

for r, d, f in os.walk(r'C:\Users\hp\Desktop\Brain Tumor Detection\yes'):
    for file in f:
        if '.JPG' in file:
            paths.append(os.path.join(r, file))

# In[36]:

paths

# In[37]:

for path in paths:
    img = Image.open(path)
    img = img.resize((128,128))
    img = np.array(img)
    if(img.shape == (128,128,3)):
        data.append(np.array(img))
        result.append(encoder.transform([[0]]).toarray())

# In[38]:

paths = []
for r, d, f in os.walk(r'C:\Users\hp\Desktop\Brain Tumor Detection\no'):
    for file in f:
        if '.JPG' in file:
            paths.append(os.path.join(r, file))

# In[39]:

paths

# In[40]:

for path in paths:
    img = Image.open(path)
    img = img.resize((128,128))
    img = np.array(img)
    if(img.shape == (128,128,3)):
        data.append(np.array(img))
        result.append(encoder.transform([[1]]).toarray())

# In[41]:

data.shape

# In[42]:

data = np.array(data)
data.shape

# In[43]:

result = np.array(result)
result = result.reshape(74,2)
result.shape

# In[44]:

x_train,x_test,y_train,y_test = train_test_split(data, result, test_size=0.2, shuffle=True, random_state=42)

# # Build Model

# In[45]:

def build_model(input_shape):

    X_input = Input(input_shape)

    X = ZeroPadding2D((2, 2))(X_input)

    X = Conv2D(32, (7, 7), strides = (1, 1), name = 'conv0')(X)
    X = BatchNormalization(axis = 3, name = 'bn0')(X)
    X = Activation('relu')(X)

    X = MaxPooling2D((4, 4), name='max_pool0')(X)

    X = MaxPooling2D((4, 4), name='max_pool1')(X)

    X = Flatten()(X)

    X = Dense(2, activation='sigmoid', name='fc')(X)

    model = Model(inputs = X_input, outputs = X, name='BrainTumourDetectionModel')

    return model

# In[46]:

img_shape = (128,128,3)

# In[47]:

model = build_model(img_shape)

# # Model Summary

# In[48]:

model.summary

# In[49]:

model.compile(loss = "binary_crossentropy", metrics = ['accuracy'] , optimizer='adam')
print(model.summary())

# In[50]:

y_train.shape

# In[51]:

history = model.fit(x_train, y_train, epochs = 10, batch_size = 32, callbacks = [plot_losses], validation_data = (x_test, y_test))
score = model.evaluate(x_test, y_test, verbose = 0)
print("Test losses : ", score[0])
print("Test acc : ", score[1])

# In[53]:

plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model Loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Test Loss', 'Validation Loss'], loc='upper right')
plt.show()

# In[54]:

#pip install Image

# In[92]:

from matplotlib.pyplot import imshow

# In[93]:

root = tkinter.Tk()
path = askopenfilename(initialdir = root, title = "Select an image", filetypes = [("jpg files",".jpg"), ("jpeg files", ".jpeg")])
root.destroy()
if len(path) != 0:
    if not(filetype.is_image(path)):
        print("Selected file is not an image")
        exit()
else:
    print("No file Selected")
    exit()

img = Image.open(path)
x = np.array(img.resize((128,128)))

# In[94]:

x = x.reshape(1,128,128,3)
res = model.predict_on_batch(x)
classification = np.where(res == np.amax(res))[1][0]
imshow(img)
text = (str(res[0][classification]*100) + '\n % Confidence This Is Not A Brain Tumor ' )
from fpdf import FPDF
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial",size= 14)
pdf.cell(180,20,txt="Tumor Report",ln=1,align="C")
pdf.cell(40,10,f'It is not a brain tumor {text}!')
pdf.output('test.pdf')

# In[95]:

from matplotlib.pyplot import imshow

# In[105]:

root = tkinter.Tk()
path = askopenfilename(initialdir = root, title = "Select an image", filetypes = [("jpg files",".jpg"), ("jpeg files", ".jpeg")])
root.destroy()

if len(path) != 0:
    if not(filetype.is_image(path)):
        print("Selected file is not an image")
        exit()
else:
    print("No file Selected")
    exit()

img = Image.open(path)

# In[106]:

x = np.array(img.resize((128,128)))
x = x.reshape(1,128,128,3)
res = model.predict_on_batch(x)
classification = np.where(res == np.amax(res))[1][0]
imshow(img)

text= (str(res[0][classification]*100) + '% Confidence This Is A Tumor''\n' )
from fpdf import FPDF
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial",size= 14)
pdf.cell(180,20,txt="Tumor Report",ln=1,align="C")
pdf.cell(40,10,f' It is a brain tumor {text} !')
pdf.output('add.pdf')

# In[ ]:

# In[ ]:


# Create and use objects in Python
"""
Accessing the object attributes
We use the dot operator . to access the attributes/methods

"""

# usage

class Car:
    def __init__(self, model, year, price):
        self.model = model
        self.year = year
        self.price = price

    number_of_wheels = 4

first_car = Car('Nissan', 2014, 10000)
second_car = Car('BMW', 2009, 20000)

#print(first_car == second_car)  # they are stored in different memory addresses because of keyword self

print(first_car.price)
print(second_car.number_of_wheels)


import pytest
from functions_v2 import chunk_content, read_pdf
#from PyPDF2 import PdfReader
from pypdf import PdfReader

def test_chunk_content():
    """
    Test the chunk_content function.
    """
    # Test content that is shorter than max_words
    content_short = "This is a short content."
    chunks_short = chunk_content(content_short, max_words=1000)
    assert len(chunks_short) == 1 and chunks_short[0] == content_short, "Failed for short content."

    # Test content that is exactly max_words long
    content_exact = " ".join(["word"] * 1000)
    chunks_exact = chunk_content(content_exact, max_words=1000)
    assert len(chunks_exact) == 1 and len(chunks_exact[0].split()) == 1000, "Failed for exact content."

    # Test content that is longer than max_words, which should result in multiple chunks
    content_long = " ".join(["word"] * 2001)
    chunks_long = chunk_content(content_long, max_words=1000)
    assert len(chunks_long) == 3, "Failed for long content."
    assert all(len(chunk.split()) == 1000 for chunk in chunks_long[:-1]), "Failed chunk size for long content."
    assert len(chunks_long[-1].split()) == 1, "Failed last chunk size for long content."

def test_read_pdf(monkeypatch):
    """
    Test the read_pdf function.
    """
    # Mock classes
    class MockPdfReader:
        def __init__(self, file_path):
            self.pages = [MockPdfPage()]

    class MockPdfPage:
        def extract_text(self):
            return "word " * 500  # Simulate 500 words per page

    # Mock the PdfReader to return a mock reader instance
    monkeypatch.setattr('pypdf.PdfReader', MockPdfReader)

    # Call read_pdf and assert the resulting chunks are as expected
    content_chunks = read_pdf("/Users/galampley/Desktop/ChatYourDocs/TheNeedToRead_Graham.pdf")
    assert len(content_chunks) == 1, "Failed to read and chunk PDF content correctly."

# Run the tests
if __name__ == '__main__':
    pytest.main()


import matplotlib.pyplot as plt
import numpy as np

methods = ['SE', 'CR', 'CC', 'GS']

y_lim_start = {'SE': 0, 'CR': 0.8, 'CC': 0.4, 'GS': 0.0}
y_lim_end = {'SE': 3000, 'CR': 1.0, 'CC': 1.0, 'GS': 0.25}

data_types = ['DD', 'LL', 'YY']

default_colors = [[138/256, 158/256, 202/256], [246/256, 140/256, 99/256], [98/256, 194/256, 164/256]]

label_dict = {'DD': 'Duroc', 'LL': 'Landrace', 'YY': 'Yorkshire', 'SE': 'Shanon Entropy', 'CR': 'Concordance Rate', 'CC': 'Correlation Coefficient', 'GS': 'GS Accuracy'}

def read_from_txt(filePath, head=False):
    f = open(filePath)
    line = f.readline()
    data_list = []
    while line:
        num = list(map(float, line.split()))
        data_list.append(num)
        line = f.readline()
    f.close()
    # 去表头
    if head:
        data_list = data_list[1:]
    else:
        pass
    array_data = np.array(data_list)
    return array_data

method = 'GS'
trait = 'AGE'

fig = plt.figure(figsize=(15, 75))

for i in range(len(data_types)):
    data = read_from_txt('data/data_' + method + '_' + data_types[i] + '_' + trait +  '.txt')

    x = ['300', '500', '800', '1k', '1.5k', '2k', '3k']

    plt.subplot(1, 3, i+1)
    plt.rcParams['font.sans-serif'] = ['Times New Roman']
    plt.rcParams['xtick.direction'] = 'in'  # 将x周的刻度线方向设置向内
    plt.rcParams['ytick.direction'] = 'in'  # 将y轴的刻度方向设置向内
    l1 = plt.plot(x, data[:, 0], 'r-', label='Method 1', marker='s', color=default_colors[i])
    l2 = plt.plot(x, data[:, 1], 'g--', label='Method 2', marker='o', color=default_colors[i])
    l3 = plt.plot(x, data[:, 2], 'b-.', label='Method 3', marker='^', color=default_colors[i])

    if i == 0:
        plt.ylabel(label_dict[method], fontsize=15)
    plt.xlabel('Number of SNPs in LD panel', fontsize=15)
    plt.title(label_dict[data_types[i]], fontsize=15)
    plt.grid(alpha=0.3)
    plt.legend(fontsize=15, loc=4)
    plt.ylim(y_lim_start[method], y_lim_end[method])
# plt.suptitle('Correlation Coefficient (AGE) of GEBV using raw and imputed LD-chip', y=0.94, fontsize=20)
plt.show()

# 文章中需要用到矢量图
fig.savefig('images/baipiao_' + method + '_' + trait + '.svg', dpi=600, format='svg', bbox_inches='tight')
# 普通图片
fig.savefig('images/baipiao_' + method + '_' + trait + '.png', bbox_inches='tight')


from konlpy.tag import Komoran

#userdic=고유명사 추가
komoran = Komoran(userdic='./user_dic.tsv')#user_dic.tsv파일=([단어]Tab[품사])형식으로 저장
text = "자연어처리는 엔엘피라고 하지." #엔엘피=명시되지 않는 명사
text2 = "나 저번주에 스즈메의 문단속을 봤어."#스즈메의 문단속=명시되지 않는 명사(하지만 공백이 있어서 지정X)
pos = komoran.pos(text)
pos2 = komoran.pos(text2)
print(pos)
print(pos2)


import os
import sys
import shutil
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))

from pytest import raises

import unidbm.backends.sqlite
import unidbm.backends.kyotocabinet
import unidbm.backends.semidbm

BACKENDS = [('sqlite', 'test.sqlite'),
            ('kyotocabinet', 'test.kch'),
            ('semidbm', u'test.semidbm')]

def test():
    for backend_name, path in BACKENDS:
        # print(backend_name)
        path = os.path.join(os.path.dirname(__file__), path)
        remove_db_files(path)
        db = getattr(unidbm.backends, backend_name).Backend(path)

        assert len(db) == 0

        # setitem
        k, v = encode('foo', 'bar')
        db[k] = v
        k, v = encode('baz', 'spam')
        db[k] = v

        # len
        assert len(db) == 2

        # getitem
        assert db[k] == v
        with raises(KeyError):
            db['not found']

        # iter
        assert set([x for x in db]) == set(encode('foo', 'baz'))

        # delete
        del db[k]
        assert len(db) == 1

def remove_db_files(path):
    if os.path.isfile(path):
        os.unlink(path)
    elif os.path.isdir(path):
        shutil.rmtree(path)

def encode(*seq):
    return [item.encode('utf-8') for item in seq]

if __name__ == '__main__':
    test()


#!/usr/bin/env python

from setuptools import setup

# extract version from __init__.py
with open('s2sphere/__init__.py', 'r') as f:
    version_line = [l for l in f if l.startswith('__version__')][0]
    VERSION = version_line.split('=')[1].strip()[1:-1]

setup(
    name='s2sphere',
    version=VERSION,
    description='Python implementation of the S2 Geometry Library',
    long_description=open('README.rst').read(),
    author='Jonathan Gillham and contributors',
    author_email='sven@sidewalklabs.com',
    url='http://s2sphere.readthedocs.io',
    packages=['s2sphere'],
    install_requires=[
        'future>=0.15',
    ],
    extras_require={
        'tests': [
            'flake8>=2.5.4',
            'hacking>=0.11.0',
            'nose>=1.3.4',
            'numpy>=1.11.0',
        ],
        'docs': [
            'Sphinx>=1.6.5',
            'sphinx-rtd-theme>=0.1.9',
        ]
    },
    license='MIT',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Intended Audience :: Science/Research',
        'Natural Language :: English',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
    ],
)


import os
from dotdrop.exceptions import YamlException

# local imports
from dotdrop.linktypes import LinkTypes
from dotdrop.dictparser import DictParser
from dotdrop.utils import is_bin_in_path

ENV_WORKDIR = 'DOTDROP_WORKDIR'

class Settings(DictParser):
    """Settings block in config"""
    # key in yaml file
    key_yaml = 'config'

    # settings item keys
    key_backup = 'backup'
    key_banner = 'banner'
    key_create = 'create'
    key_default_actions = 'default_actions'
    key_dotpath = 'dotpath'
    key_ignoreempty = 'ignoreempty'
    key_keepdot = 'keepdot'
    key_longkey = 'longkey'
    key_link_dotfile_default = 'link_dotfile_default'
    key_link_on_import = 'link_on_import'
    key_showdiff = 'showdiff'
    key_upignore = 'upignore'
    key_impignore = 'impignore'
    key_cmpignore = 'cmpignore'
    key_instignore = 'instignore'
    key_workdir = 'workdir'
    key_minversion = 'minversion'
    key_func_file = 'func_file'
    key_filter_file = 'filter_file'
    key_diff_command = 'diff_command'
    key_force_chmod = 'force_chmod'
    key_template_dotfile_default = 'template_dotfile_default'
    key_ignore_missing_in_dotdrop = 'ignore_missing_in_dotdrop'
    key_chmod_on_import = 'chmod_on_import'
    key_check_version = 'check_version'
    key_clear_workdir = 'clear_workdir'
    key_compare_workdir = 'compare_workdir'
    key_key_prefix = 'key_prefix'
    key_key_separator = 'key_separator'

    # import keys
    key_import_actions = 'import_actions'
    key_import_configs = 'import_configs'
    key_import_variables = 'import_variables'

    # defaults
    default_diff_cmd = 'diff -r -u {0} {1}'

    def __init__(self, backup=True, banner=True,
                 create=True, default_actions=None, dotpath='dotfiles',
                 ignoreempty=False, import_actions=None, import_configs=None,
                 import_variables=None, keepdot=False,
                 link_dotfile_default=LinkTypes.NOLINK,
                 link_on_import=LinkTypes.NOLINK, longkey=False,
                 upignore=None, cmpignore=None, instignore=None,
                 impignore=None, workdir='~/.config/dotdrop',
                 showdiff=False, minversion=None,
                 func_file=None, filter_file=None,
                 diff_command=default_diff_cmd,
                 template_dotfile_default=True,
                 ignore_missing_in_dotdrop=False,
                 force_chmod=False, chmod_on_import=False,
                 check_version=False, clear_workdir=False,
                 compare_workdir=False, key_prefix=True,
                 key_separator='_'):
        self.backup = backup
        self.banner = banner
        self.create = create
        self.default_actions = default_actions or []
        self.dotpath = dotpath
        self.ignoreempty = ignoreempty
        self.import_actions = import_actions or []
        self.import_configs = import_configs or []
        self.import_variables = import_variables or []
        self.keepdot = keepdot
        self.longkey = longkey
        self.showdiff = showdiff
        self.upignore = upignore or []
        self.cmpignore = cmpignore or []
        self.instignore = instignore or []
        self.impignore = impignore or []
        self.workdir = workdir
        if ENV_WORKDIR in os.environ:
            self.workdir = os.environ[ENV_WORKDIR]
        self.link_dotfile_default = LinkTypes.get(link_dotfile_default)
        self.link_on_import = LinkTypes.get(link_on_import)
        self.minversion = minversion
        self.func_file = func_file or []
        self.filter_file = filter_file or []
        self.diff_command = diff_command
        self.template_dotfile_default = template_dotfile_default
        self.ignore_missing_in_dotdrop = ignore_missing_in_dotdrop
        self.force_chmod = force_chmod
        self.chmod_on_import = chmod_on_import
        self.check_version = check_version
        self.clear_workdir = clear_workdir
        self.compare_workdir = compare_workdir
        self.key_prefix = key_prefix
        self.key_separator = key_separator

        # check diff command
        if not is_bin_in_path(self.diff_command):
            err = f'bad diff_command: {diff_command}'
            raise YamlException(err)

    def _serialize_seq(self, name, dic):
        """serialize attribute 'name' into 'dic'"""
        seq = getattr(self, name)
        dic[name] = seq

    def serialize(self):
        """Return key-value pair representation of the settings"""
        dic = {
            self.key_backup: self.backup,
            self.key_banner: self.banner,
            self.key_create: self.create,
            self.key_dotpath: self.dotpath,
            self.key_ignoreempty: self.ignoreempty,
            self.key_keepdot: self.keepdot,
            self.key_link_dotfile_default: str(self.link_dotfile_default),
            self.key_link_on_import: str(self.link_on_import),
            self.key_longkey: self.longkey,
            self.key_showdiff: self.showdiff,
            self.key_workdir: self.workdir,
            self.key_minversion: self.minversion,
            self.key_diff_command: self.diff_command,
            self.key_template_dotfile_default: self.template_dotfile_default,
            self.key_ignore_missing_in_dotdrop: self.ignore_missing_in_dotdrop,
            self.key_force_chmod: self.force_chmod,
            self.key_chmod_on_import: self.chmod_on_import,
            self.key_check_version: self.check_version,
            self.key_clear_workdir: self.clear_workdir,
            self.key_compare_workdir: self.compare_workdir,
            self.key_key_prefix: self.key_prefix,
            self.key_key_separator: self.key_separator,
        }
        self._serialize_seq(self.key_default_actions, dic)
        self._serialize_seq(self.key_import_actions, dic)
        self._serialize_seq(self.key_import_configs, dic)
        self._serialize_seq(self.key_import_variables, dic)
        self._serialize_seq(self.key_cmpignore, dic)
        self._serialize_seq(self.key_upignore, dic)
        self._serialize_seq(self.key_instignore, dic)
        self._serialize_seq(self.key_impignore, dic)
        self._serialize_seq(self.key_func_file, dic)
        self._serialize_seq(self.key_filter_file, dic)

        return {self.key_yaml: dic}


from enum import Enum
from pandas import DataFrame

class NodeAttribute(Enum):

    """
    This class enumerates the keys to the node properties that need to be mapped for standardized analytics functions
    """

    ID = "id"
    NAME = "name"
    LABEL = "label"
    TYPE = "type"
# END NodeAttributes

class EdgeAttribute(Enum):

    """
    This class enumerates the keys to the node properties that need to be mapped for standardized analytics functions
    """

    ID = "id"
    NAME = "name"
    LABEL = "label"
    SOURCE = "source"
    TARGET = "target"
    TYPE = "type"
# END EdgeAttributes

class Graph(object):

    """
    This class represents a generic graph that can be used in various standardized analytics functions. The sets of nodes and edges are represented as Pandas DataFrames. To use your custom dataframes with standardized analytics functions, please map your columns to the attributes as specified in the respective enums.
    """

    def __init__(self, id, nodes=DataFrame(columns=['id', 'name', 'type', 'label']), edges=DataFrame(columns=['id', 'name', 'type', 'label', 'source', 'target']), data=DataFrame(), defaultAttributeMapping=False):

        """
        Create a new Graph instance.

        :returns: a new Graph instance
        :rtype: Graph

        :param str id: The id of your graph.
        :param pandas.DataFrame nodes: *Optional*. A dataframe representing the nodes in your graph. Defaults to an empty dataframe with the columns: id x type x name x label
        :param pandas.DataFrame edges: *Optional*. A dataframe representing the edges in your graph. Defaults to an empty dataframe with the columns: id x type x source x target x name x label
        :param pandas.DataFrame data: *Optional*. A dataframe representing the properties of the elements of your graph. Preferred representation is a row per concept, keyed by ID, containing a properties object with key-value pairs.
        :param bool defaultAttributeMapping: *Optional*. Whether or not you want to map the columns of your dataframes to the graph attributes based on a predefined template for this type of graph.

        :exception TypeError: Thrown when defaultAttributeMapping is True, but there is no template specified for this type of graph.
        """

        self.id = id
        self.nodes = nodes
        if len(list(nodes))==0:
            self.nodes=DataFrame(columns=['id', 'name', 'type', 'label'])
        self.edges = edges
        if len(list(edges))==0:
            self.edges= DataFrame(columns=['id', 'name', 'type', 'label', 'source', 'target'])
        self.data = data
        self._nodeAttributeMapping = {}
        self._edgeAttributeMapping = {}

        if type(self) == Graph and defaultAttributeMapping:
            self.applyDefaultAttributeMapping()

    # END __init__

    def hasValidAttributeMapping(self):

        """
        Checks whether the mapping of attributes for nodes and edges is complete, and fits with the current DataFrame columns.

        :returns: Whether or not the current attribute mapping is valid.
        :rtype: bool
        """

        return self.hasValidNodeAttributeMapping() and self.hasValidEdgeAttributeMapping()

    def putNodeAttributeMapping(self, key, ref):

        """
        Add a new node property mapping or override an existing one.

        :param str key: The lookup name of the property
        :param str ref: The name of the DataFrame column that contains the property value

        :exception TypeError: Thrown when there is no nodes DataFrame associated with this graph
        :exception ValueError: Thrown when the column name reference does not exist in the DataFrame
        """

        if isinstance(key, NodeAttribute):
            key = key.value

        if self.nodes is None:
            raise TypeError('There are no nodes associated with this graph! Please assign a dataframe to the nodes property first, before attempting to map property names.')

        elif not any(filter(lambda attr: attr == ref, list(self.nodes))):
            raise ValueError('The property you are attempting to map does not exist!')

        self._nodeAttributeMapping[key] = ref
    # END putNodeAttributeMapping

    def getNodeAttributeMapping(self, key):

        """
        Retrieve the name of the DataFrame column that contains a particular node property. If the property has not been mapped, this returns None.

        :returns: the name of the DataFrame column that contains a particular node property.
        :rtype: str

        :param str key: The lookup name of the property
        """

        if isinstance(key, NodeAttribute):
            key = key.value

        return self._nodeAttributeMapping.get(key)
    # END getNodeAttributeMapping

    def hasValidNodeAttributeMapping(self):

        """
        Checks whether the mapping of attributes for nodes is complete, and fits with the current DataFrame columns.

        :returns: Whether or not the current attribute mapping is valid.
        :rtype: bool
        """

        df_cols = list(self.nodes)
        mapping_keys = list(self._nodeAttributeMapping.keys())
        attrs = [a.value for a in NodeAttribute]

        return (isinstance(self.nodes, DataFrame)
                and not any(filter(lambda a: a not in mapping_keys, attrs))
                and not any(filter(lambda n: n not in df_cols, list(self._nodeAttributeMapping.values()))))
    # END hasValidNodeAttributeMapping

    def putEdgeAttributeMapping(self, key, ref):

        """
        Add a new edge property mapping or override an existing one.

        :param str key: The lookup name of the property
        :param str ref: The name of the DataFrame column that contains the property value

        :exception TypeError: Thrown when there is no edge DataFrame associated with this graph
        :exception ValueError: Thrown when the column name reference does not exist in the DataFrame
        """

        if isinstance(key, EdgeAttribute):
            key = key.value

        if self.edges is None:
            raise TypeError('There are no edges associated with this graph! Please assign a dataframe to the edges property first, before attempting to map property names.')

        elif not any(filter(lambda attr: attr == ref, list(self.edges))):
            raise ValueError('The property you are attempting to map does not exist!')

        self._edgeAttributeMapping[key] = ref
    # END putEdgeAttributeMapping

    def getEdgeAttributeMapping(self, key):

        """
        Retrieve the name of the DataFrame column that contains a particular edge property. If the property has not been mapped, this returns None.

        :returns: the name of the DataFrame column that contains a particular edge property.
        :rtype: str

        :param str key: The lookup name of the property
        """

        if isinstance(key, EdgeAttribute):
            key = key.value

        return self._edgeAttributeMapping.get(key)
    # END getEdgeAttributeMapping

    def hasValidEdgeAttributeMapping(self):

        """
        Checks whether the mapping of attributes for edges is complete, and fits with the current DataFrame columns.

        :returns: Whether or not the current attribute mapping is valid.
        :rtype: bool
        """

        df_cols = list(self.edges)
        mapping_keys = list(self._edgeAttributeMapping.keys())
        attrs = [a.value for a in EdgeAttribute]

        return (isinstance(self.edges, DataFrame)
                and not any(filter(lambda a: a not in mapping_keys, attrs))
                and not any(filter(lambda e: e not in df_cols, list(self._edgeAttributeMapping.values()))))
    # END hasValidEdgeAttributeMapping

    def getNodeById(self, nodeid):

        """
        Returns the node with the given ID.

        :returns: The node with the given ID, or None if no such node exists. If multiple nodes with the same ID exist, only the first encountered is returned.
        :rtype: dict

        :param str nodeid: The id of the node you're looking for.
        """

        result = [node for node in self.nodes.to_dict(orient='records') if node[self.getNodeAttributeMapping(NodeAttribute.ID)] == nodeid]
        return result[0] if result else None
    # END getNodeById

    def getEdgeById(self, edgeid):

        """
        Returns the edge with the given ID.

        :returns: The edge with the given ID, or None if no such edge exists. If multiple edges with the same ID exist, only the first encountered is returned.
        :rtype: dict

        :param str nodeid: The id of the edge you're looking for.
        """

        result = [edge for edge in self.edges.to_dict(orient='records') if edge[self.getEdgeAttributeMapping(EdgeAttribute.ID)] == edgeid]
        return result[0] if result else None
    # END getNodeById

    def getEdgeByEndpoints(self, source, target):

        """
        Find the edge with the given source and target in the given graph.

        :returns: The id of the edge with the given source and target in the given graph. If there is more than one match, returns the first occurrence.
        :rtype: str

        :param str source: The id of the source node.
        :param str target: the id of the target node.
        """

        source_key = self.getEdgeAttributeMapping(EdgeAttribute.SOURCE)
        target_key = self.getEdgeAttributeMapping(EdgeAttribute.TARGET)

        edges = [e for e in self.edges.to_dict(orient='records') if e[source_key] == source and e[target_key] == target]
        return edges[0][self.getEdgeAttributeMapping(EdgeAttribute.ID)] if edges else None
    # END findEdge

    def applyDefaultAttributeMapping(self):

        """
        If this type of graph will often be instantiated with a specific set of columns, define this function to automatically map the graph attributes to these columns. The columns can be automatically mapped by setting the defaultAttributeMapping parameter of the constructor to True.
        """

        self.putNodeAttributeMapping(NodeAttribute.ID, "id")
        self.putNodeAttributeMapping(NodeAttribute.TYPE, "type")
        self.putNodeAttributeMapping(NodeAttribute.NAME, "name")
        self.putNodeAttributeMapping(NodeAttribute.LABEL, "label")

        self.putEdgeAttributeMapping(EdgeAttribute.ID, "id")
        self.putEdgeAttributeMapping(EdgeAttribute.TYPE, "type")
        self.putEdgeAttributeMapping(EdgeAttribute.NAME, "name")
        self.putEdgeAttributeMapping(EdgeAttribute.LABEL, "label")
        self.putEdgeAttributeMapping(EdgeAttribute.SOURCE, "source")
        self.putEdgeAttributeMapping(EdgeAttribute.TARGET, "target")
    # END applyDefaultAttributeMapping
# END Graph


"""
Running script for the portfolio allocation.
"""
from datetime import timedelta, datetime
from portfolio_allocation import StockSelection
from modern_portfolio_theory import Portfolio

import pandas as pd

if __name__ == "__main__":
    # Adding file path for the stock data
    path = r"~/dissertation/datasets/required_stocks.csv"
    END_TIME = datetime.now()
    START_TIME = END_TIME - timedelta(365 * 10)  # We take data of 10 years
    data = pd.read_csv(path)
    stocks = data["indices"][1:].tolist()
    portfolio = StockSelection(tickers=stocks, start_date=START_TIME, end_date=END_TIME)
    top_stocks = portfolio.return_top_stocks()
    print(top_stocks)
    portfolio.plot_returns()
    markowitz_model = Portfolio(stocks=stocks, start=START_TIME, end=END_TIME)
    print("generating mean-variance optimisation weights")
    markowitz_model.display_and_print_portfolio()


import streamlit as st
from thirdweb import ThirdwebSDK
from thirdweb.types.nft import NFTMetadataInput
from dotenv import load_dotenv
import os
from functions import mint_nft

#Names for the different tabs of the streamlit application
tab1,tab2,tab3,tab4 = st.tabs(["Welcome","Mint","Browse","Trade"])
#In the Welcome tab:
with tab1:
    st.title("NFT Marketplace")#Title
    st.header("Mint NFTs from your original artwork, and buy and sell them on the Ethereum Blockchain")#Explanation of the application
    st.write("First, input the contract address below. Then, head over to the Mint tab to upload your work, or the Trade screen to buy and sell NFTs")#How to use the application
    contract_address=st.sidebar.text_input("NFT collection contract address")

#In the Mint tab:
with tab2:
    st.warning("By using this service you agree that the work you are uploading is your own, original artwork.",icon="⛔")#Displays a warning message to the user
    artwork=st.file_uploader("Upload your artwork here for minting") #Allows users to upload a file
    if st.button("Display Artwork"): #A button that displays the uploaded image
        st.image(artwork)
    address=st.text_input("Address to which the NFT will be minted") #The address that will own the NFT
    nft_name=st.text_input("Give a name to your NFT")
    nft_description=st.text_input("Price your NFT in MATIC")
    if st.button("Mint NFT"):
        load_dotenv()
        private_key=os.getenv("mumbai_private_key")
        sdk= ThirdwebSDK.from_private_key(private_key,"mumbai")
        contract = sdk.get_nft_collection(str(contract_address))
        receipt,token_id,nft=mint_nft(contract_object=contract,name=nft_name,description=nft_description,image=artwork,address=address)
        st.write("Receipt",receipt)
        st.write("Token ID",token_id)
        st.write("NFT",nft)
#contract.call("function_name", "arg1", "arg2") #Pseudocode for functions
#contract.call("mintto",artwork) #Pseudocode for minting

#In the Browse tab:
with tab3:
    if st.button("Load my Balance"):
        load_dotenv()
        private_key=os.getenv("mumbai_private_key")
        sdk= ThirdwebSDK.from_private_key(private_key,"mumbai")
        contract=sdk.get_nft_collection(str(contract_address))
        st.write(contract.balance())
    st.write("Show another address' balance")
    view_balance_address=st.text_input("Wallet address to view NFT balance")
    if st.button("Load wallet's balance"):
        load_dotenv()
        private_key=os.getenv("mumbai_private_key")
        sdk= ThirdwebSDK.from_private_key(private_key,"mumbai")
        contract=sdk.get_nft_collection(str(contract_address))
        st.write(contract.balance_of(view_balance_address))
    token_id=st.text_input("NFT ID to view") #User input of the artwork address
    if st.button("View NFT"):#Allow users view artwork given the token ID
        load_dotenv()
        private_key=os.getenv("mumbai_private_key")
        sdk=ThirdwebSDK.from_private_key(private_key,"mumbai")
        contract=sdk.get_nft_collection(str(contract_address))
        output=contract.get(token_id)
        st.write("Name:",output.metadata.name)
        st.image(output.metadata.image)
        st.write("Price in MATIC:",output.metadata.description)
        st.write("Owner:",output.owner)

#In the Trade tab:
with tab4:
    receiver_address=st.text_input("Wallet address to receive an NFT")
    token_id=st.text_input("Token ID")
    if st.button("Preview NFT"):
        load_dotenv()
        private_key=os.getenv("mumbai_private_key")
        sdk=ThirdwebSDK.from_private_key(private_key,"mumbai")
        contract=sdk.get_nft_collection(str(contract_address))
        output=contract.get(token_id)
        st.write("Name:",output.metadata.name)
        st.image(output.metadata.image)
        st.write("Price in MATIC:",output.metadata.description)
        st.write("Current owner",output.owner)
    st.write("Transfer an NFT after you have received sufficient MATIC")
    if st.button("Transfer NFT"):
        load_dotenv()
        private_key=os.getenv("mumbai_private_key")
        sdk=ThirdwebSDK.from_private_key(private_key,"mumbai")
        contract=sdk.get_nft_collection(contract_address)
        st.write(contract.transfer(receiver_address,token_id))

    #listing_number=st.text_input("Listing ID")
    #receiver=st.text_input("Receiver for the NFT")
    #if st.button("Buy NFT"):
    #    load_dotenv()
    #    private_key=os.getenv("mumbai_private_key")
    #    sdk=ThirdwebSDK.from_private_key(private_key,"mumbai")
    #    contract=sdk.get_marketplace(marketplace_contract_address)
    #    st.write(contract.buyout_listing(listing_id=listing_number,quantity_desired=1,receiver=receiver))
    #recipient_address=st.text_input("Recipient Address") #The address of the recipient of the transaction
    #sender_address=st.text_input("Your Address") #Transaction sender
    #nft_address=st.text_input("NFT Address") #NFT to transact
    #st.write("Buy")


# coding=utf-8
import csv
import logging
import os
import xml.etree.ElementTree as ET

import constants
import globals
import codecs
from parserr.parser_enums import TOSRegion, TOSLanguage
from utils.stringutil import is_ascii

TRANSLATION_PREFIX = '@dicID_^*$'
TRANSLATION_SUFFIX = '$*^'
REGION=None
LANGUAGE=None
def parse(region,language):
    global REGION,LANGUAGE
    REGION=region
    LANGUAGE=language
    translations = None

    if TOSLanguage.ko!=language:
        translations=parse_translations(TOSLanguage.to_full_string(language))
        #translations = parse_translations('English') if region == TOSRegion.iTOS else translations
        #translations = parse_translations('Japanese') if region == TOSRegion.jTOS else translations
        #translations = parse_translations('Taiwanese') if region == TOSRegion.twTOS else translations

    if translations:
        parse_dictionary(translations)
    parse_clmsg()

def parse_dictionary(translations):
    logging.debug('Parsing translations dictionary...')
    dictionary_path = os.path.join(constants.PATH_INPUT_DATA, 'language.ipf', 'wholedicid.xml')
    dictionary = ET.parse(dictionary_path).getroot()

    # example: <file name="xml\item_Equip.xml">
    for file in dictionary:
        # <data original="없음_helmet" dicid="@dicID_^*$ITEM_20150317_000001$*^"/>
        for data in file:
            key = data.get('original').replace('"', '')
            value = data.get('dicid')
            value_translated = '%s' % data.get('dicid')

            for dicid in value.split(TRANSLATION_SUFFIX):  # Sometimes there are multiple ids in a single entry (as translations are re-used)
                if TRANSLATION_PREFIX in dicid:
                    dicid = dicid[dicid.index(TRANSLATION_PREFIX) + len(TRANSLATION_PREFIX):]
                    if dicid not in translations:
                        logging.warn('Missing translation for dicid: (%s)', dicid)

                    translation = translations[dicid] if dicid in translations else dicid
                    value_translated = value_translated.replace(TRANSLATION_PREFIX + dicid + TRANSLATION_SUFFIX, translation)

            globals.translations[key] = value_translated

def parse_translations(language):
    logging.debug('Parsing translations for %s...', language)
    result = {}

    translation_folder = os.path.join(constants.PATH_INPUT_RELEASE, 'languageData', language)

    for translation in os.listdir(translation_folder):
        translation_path = os.path.join(translation_folder, translation)

        if '.tsv' not in translation:
            continue

        with codecs.open(translation_path, 'r','utf-8',errors="replace") as translation_file:
            for row in csv.reader(translation_file, delimiter='\t', quoting=csv.QUOTE_NONE):
                if len(row) > 1:
                    result[row[0]] = str(row[1])

    return result

def parse_clmsg():
    global globals
    logging.debug('Parsing clmsgs ...')
    result = {}

    dictionary_path = os.path.join(constants.PATH_INPUT_DATA, 'xml_lang.ipf', 'clientmessage.xml')
    dictionary = ET.parse(dictionary_path).getroot()

    # example: <file name="xml\item_Equip.xml">
    for category in dictionary:
        for data in category:
            key = data.get('ClassName')
            value = data.get('Data')
            if key is not None and value is not None:
                globals.clmsgs[key] = translate(value)

def translate(key,secondtouch=False):

    try:
        key = str(key.replace('"', ''), 'utf-8')
    except TypeError:
        pass

    # In case the key is already in english, there's no need to translate
    #if not secondtouch  and is_ascii(key) and REGION==TOSRegion.iTOS:
    #    return key
    if not globals.translations:
        return key

    if (key == '' or key not in globals.translations):
        if  key not in globals.clmsgs:
           # if key != '':
               # logging.warn('Missing translation for key: %s', key)
            return key
        else:
            if key!=globals.clmsgs[key]:
                return translate(globals.clmsgs[key],True)
            else:
                return key
    return globals.translations[key]


import string

import pandas as pd

paths = ["train", "dev", "test"]
df_dict = {}

""" Combine the data and answers files into one file. (subtask A) """

for path in paths:
    taska_data_df = pd.read_csv(f"./OriginalDataset/{path}/subtaskA_data.csv")
    taska_answers_df = pd.read_csv(f"./OriginalDataset/{path}/subtaskA_answers.csv")
    # join the two files on id
    merged_df = taska_data_df.join(taska_answers_df.set_index("id"), on="id", how="inner")
    df_dict[path] = merged_df

# merge the dev data with the train data
taska_merged_train_df = df_dict.get("train").append(df_dict.get("dev"), ignore_index=True)
# save the processed data into csv files
taska_merged_train_df.to_csv("./ProcessedDataset/train/subtaskA.csv", index=False)
df_dict.get("test").to_csv("./ProcessedDataset/test/subtaskA.csv", index=False)

""" Combine the data and answers files into one file. (subtask B) """

for path in paths:
    taskb_data_df = pd.read_csv(f"./OriginalDataset/{path}/subtaskB_data.csv")
    taskb_answers_df = pd.read_csv(f"./OriginalDataset/{path}/subtaskB_answers.csv")
    # join the two files on id
    merged_df = taskb_data_df.join(taskb_answers_df.set_index("id"), on="id", how="inner")
    df_dict[path] = merged_df

# merge the dev data with the train data
df_dict["train"] = df_dict.get("train").append(df_dict.get("dev"), ignore_index=True)

""" Additional preprocessing for subtask B """

paths = ["train", "test"]

for path in paths:
    taskb_df = df_dict.get(path)
    taska_df = pd.read_csv(f"./ProcessedDataset/{path}/subtaskA.csv")
    # fetch the correct sentences from subtaskA data and include in subtaskB data
    dictionary = {0:"sent1", 1:"sent0"}
    correct_sents = [taska_df[dictionary.get(label)][index] for index, label in enumerate(taska_df["label"])]
    taskb_df["correct_sent"] = correct_sents
    # update the labels from alphabets to numbers
    mapping = {"A":0, "B":1, "C":2}
    taskb_df["label"] = [mapping.get(x) for x in taskb_df["label"]]
    # update the column names
    taskb_df.columns = ["id", "false_sent", "explanation0", "explanation1", "explanation2", "label", "correct_sent"]
    # reorder the columns
    taskb_df = taskb_df[["id", "false_sent", "correct_sent", "explanation0", "explanation1", "explanation2", "label"]]
    # save the processed data into csv file
    taskb_df.to_csv(f"./ProcessedDataset/{path}/subtaskB.csv", index=False)


import os

os.system("clear")

def is_pandigital(number:str) -> bool:
    used_numbers = { 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0 }

    for i in number:
        i = int(i)
        if i > 0 and i <= 9:
            used_numbers[i] += 1

    for i in range(1, 9 + 1):
        if used_numbers[i] != 1:
            return False
    return True

sum_of_pandigital_nums = 0

for num in range(1234, 9876+1): # the product has to be a four digit value
    for multiplicand in range(1, int(num/2) + 1):
        if num % multiplicand == 0: # if num is divideable
            multiplier = int(num / multiplicand)
            whole_number = str(multiplier) + str(multiplicand) + str(num)
            if len(whole_number) > 9:
                continue
            if is_pandigital(whole_number):
                print(multiplier, '*', multiplicand, '=', num , '->', whole_number)
                sum_of_pandigital_nums += num
                break

print(sum_of_pandigital_nums)


import os

import pandas as pd
import numpy as np
import ProcessPicture,updateDatabase # this are the functions that will get geodata from pictures and add it to the database

import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine
from flask import Flask, jsonify, render_template,make_response,url_for
from flask_sqlalchemy import SQLAlchemy
from werkzeug.utils import secure_filename
from flask import request, redirect
import sqlite3
from boto.s3.connection import S3Connection
import boto3
import psycopg2
from botocore.client import Config
from config import S3_KEY, S3_SECRET, S3_BUCKET, API_KEY,DATABASE_URL
app = Flask(__name__, static_url_path='/static')

# the keys are saved under an enviromental variable in both heroku and my local computer.
# https://devcenter.heroku.com/articles/config-vars

# app.config["SECRET_KEY"]= os.environ['AWS_SECRET_ACCESS_KEY']
# app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///db/Oldports.sqlite"

# Get config values
app.config.from_object("config")

# look at configfile
#print(app.config)

# define directory for intermediate file upload
UploadDir="static/Images/uploads/"

#################################################
# Database Setup

# postgre

app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URL
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # silence the deprecation warning

db = SQLAlchemy(app)

db = SQLAlchemy(app)
# reflect an existing database into a new model
Base = automap_base()
# reflect the tables
Base.prepare(db.engine, reflect=True)

conn = db.engine.connect()
PictureData = pd.read_sql('SELECT * from "GeoTagData"', conn) #import pandas

app = Flask(__name__, static_url_path='/static')

# route 1

@app.route("/")
def index():
    """Return the homepage."""
    return render_template("index.html", key= API_KEY)

# data route
@app.route("/Geodata")
def data():
    # to refresh the database every time we go to the index page

    #################################################
    # Database Setup
    #################################################

    app.config["SQLALCHEMY_DATABASE_URI"] = DATABASE_URL
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # silence the deprecation warning
    db = SQLAlchemy(app)

    # reflect an existing database into a new model
    Base = automap_base()
    # reflect the tables
    Base.prepare(db.engine, reflect=True)

    conn = db.engine.connect()
    PictureData = pd.read_sql('SELECT * from "GeoTagData"', conn) #import pandas

# end of refresh get data into a variable that can be jsonified

    df=PictureData
    i = 0
    data=[]

    while i < len(df):
        geodatavar = {

                'FileAddress':list(df['FileAddress'])[i],
                'ImageTimeStamp':list(df['ImageTimeStamp'])[i],
                'city':list(df['city'])[i],
                'country':list(df['country'])[i],
                'landmark':list(df['landmark'])[i],
                'latitude':list(df['latitude'])[i],
                'longitude':list(df['longitude'])[i],
                'state':list(df['state'])[i],
                'zipcode':list(df['zipcode'])[i],
                'index':list(df['index'])[i]
           }
        data.append(geodatavar)
        i+=1
    return jsonify(data)

# individual picture route
@app.route("/latestUpload")
def imageFunct():

# to refresh the database every time we go to the index page

    #################################################
    # Database Setup
    #################################################

    app.config["SQLALCHEMY_DATABASE_URI"] = DATABASE_URL
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # silence the deprecation warning
    db = SQLAlchemy(app)

    # reflect an existing database into a new model
    Base = automap_base()
    # reflect the tables
    Base.prepare(db.engine, reflect=True)

    conn = db.engine.connect()
    PictureData = pd.read_sql('SELECT * from "GeoTagData"', conn) #import pandas

# end of refresh get data into a variable that can be jsonified

    MaxIndex=PictureData["index"].max()
    data=[]
    df=PictureData.loc[(PictureData["index"] == MaxIndex) ]

    i = 0
    data=[]

    while i < len(df):
        geodatavar = {

            'FileAddress':list(df['FileAddress'])[i],
            'ImageTimeStamp':list(df['ImageTimeStamp'])[i],
            'city':list(df['city'])[i],
            'country':list(df['country'])[i],
            'landmark':list(df['landmark'])[i],
            'latitude':list(df['latitude'])[i],
            'longitude':list(df['longitude'])[i],
            'state':list(df['state'])[i],
            'zipcode':list(df['zipcode'])[i],
            'index':list(df['index'])[i]
                          }
        data.append(geodatavar)
        i+=1
    return jsonify(data)

# image upload route
@app.route("/upload-image", methods=["GET", "POST"])
def upload_image():
    # upload picture procedure: https://pythonise.com/feed/flask/flask-uploading-files
    app.config["IMAGE_UPLOADS"] = UploadDir

    if request.method == "POST":
        if request.files:
            image = request.files["image"]
            image.save(os.path.join(app.config["IMAGE_UPLOADS"], image.filename))

            # use function to get geotag data for the picture

            Picname=image.filename
            picAddress=UploadDir +image.filename
            print (picAddress)
            # execute function saved into the updateDatabase.py file(whuch was added at the begining of this app)
            updateDatabase.UpdateDB(picAddress,Picname,DATABASE_URL)

            print(image.filename)
            #the above steps will save the pictures into an ephemeral file system, so we have to send it to amazon web services for a permanent location

            ACCESS_KEY_ID = S3_KEY
            ACCESS_SECRET_KEY = S3_SECRET
            BUCKET_NAME = S3_BUCKET

            data = open(picAddress, 'rb')

            s3 = boto3.resource(
                's3',
                aws_access_key_id=ACCESS_KEY_ID,
                aws_secret_access_key=ACCESS_SECRET_KEY,
                config=Config(signature_version='s3v4')
            )
            s3.Bucket(BUCKET_NAME).put_object(Key=Picname, Body=data,ACL='public-read')

            return redirect(request.url)
    return render_template("public/upload_image.html")

@app.route("/carrusel")
def carrusel():

# to refresh the database every time we go to the index page

    #################################################
    # Database Setup
    #################################################

    app.config["SQLALCHEMY_DATABASE_URI"] = DATABASE_URL
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # silence the deprecation warning
    db = SQLAlchemy(app)

    # reflect an existing database into a new model
    Base = automap_base()
    # reflect the tables
    Base.prepare(db.engine, reflect=True)

    conn = db.engine.connect()
    PictureData = pd.read_sql('SELECT * from "GeoTagData"', conn) #import pandas

# end of refresh get data into a variable that can be jsonified

    MaxIndex=PictureData["index"].max()
    data=[]
    df=PictureData.loc[(PictureData["index"] > MaxIndex-20) ]

    i = 0
    data=[]

    while i < len(df):
        geodatavar = {

            'FileAddress':list(df['FileAddress'])[i],
            'ImageTimeStamp':list(df['ImageTimeStamp'])[i],
            'city':list(df['city'])[i],
            'country':list(df['country'])[i],
            'landmark':list(df['landmark'])[i],
            'latitude':list(df['latitude'])[i],
            'longitude':list(df['longitude'])[i],
            'state':list(df['state'])[i],
            'zipcode':list(df['zipcode'])[i],
            'index':list(df['index'])[i]
                          }
        data.append(geodatavar)
        i+=1
    return jsonify(data)

if __name__ == "__main__":
    app.run()


# 개선된 다익스트라
# - 힙 자료구조를 이용
# 기본 원리는 동일하다.
# 현재 가장 가까운 노드를 저장하기 위해 힙 자료구조를 이용
# 현재 최단 거리가 가장 짧은 노드를 선택해야 하므로 최소 힙 사용
# ElogV

import heapq

INF = int(1e9)  # 무한

# 노드의 개수, 간선의 개수
n, m = map(int, input().split())
# 시작 노드 번호
start = int(input())
# 각 노드에 연결되어 있는 노드에 대한 정보
graph = [[] for i in range(n + 1)]
# 최단 거리 테이블
distance = [INF] * (n + 1)

# 간선의 정보 입력 받기
for _ in range(m):
    a, b, c = map(int, input().split())
    graph[a].append((b, c))  # a -> b 의 비용이 c

def dijkstra(start):
    q = []
    # 시작 노드로 가기위한 최단 경로는 0으로 설정
    heapq.heappush(q, (0, start))
    distance[start] = 0

    while q:
        # 가장 최단 거리가 짧은 노드 꺼내기
        dist, now = heapq.heappop(q);
        # 현재 노드가 이미 처리된 적 있는 노드면 무시 (방문 처리와 동일)
        if distance[now] < dist:
            continue
        # 현재 노드와 연결된 다른 인접 노드 확인
        for i in graph[now]:
            cost = dist + i[1]
            # 현재 노드를 거쳐서 다른 노드로 이동하는 거리가 더 짧은 경우 갱신
            if cost < distance[i[0]]:
                distance[i[0]] = cost
                heapq.heappush(q, (cost, i[0])) # 우선순위 큐에 인접 노드 저장

dijkstra(start)

# 모든 노드로 가기 위한 최단 거리 출력
for i in range(1, n + 1):
    if distance[i] == INF: # 도달할 수 없는 경우
        print("INF")
    else:
        print(distance[i])


def uniqueValues(aDict):
    '''
    aDict: a dictionary
    '''
    v=[]
    d={}
    l=[]
    for key,value in aDict.iteritems():
        if value not in d.values():
            d[key]=value
        else:
            v.append(value)
    for key1,value1 in sorted(d.iteritems()):
        if value1 not in v:
            l.append(key1)
    return l


from db import db_utils

db_utils.criar_tabela("Estudantes")

estudantes = [
    ('Ana Silva' , 'Computação', 2019),
    ('Pedro Mendes', 'Física', 2021),
    ('Carla Souza', 'Computação', 2020),
    ('João Alves', 'Matemática', 2018),
    ('Maria Oliveira', 'Química', 2022)
]

db_utils.inserir_estudante("Estudantes", estudantes)

db_utils.atualiza_registro("Estudantes", 2021, "João Alves")

db_utils.deleta_registro("Estudantes", 1)

db_utils.update_ano_curso("Estudantes", 2018, "Computação")

db_utils.select_estudantes("Estudantes", "Computação", 2019)

db_utils.select_ano("Estudantes", 2019)

db_utils.mostra_registros("Estudantes")

db_utils.close()


import os
import HydroCNHS
prj_path, this_filename = os.path.split(__file__)

#%% ===========================================================================
# Step 1: Create a model configuration file
# =============================================================================
### Initialize a model builder object.
wd = prj_path
mb = HydroCNHS.ModelBuilder(wd)

### Setup a water system simulation information
mb.set_water_system(start_date="1981/1/1", end_date="2013/12/31")

### Setup land surface model (rainfall-runoff model)
# Here we have seven subbasins and we select GWLF as the rainfall-runoff model.
outlet_list = ['Hagg', 'DLLO', 'TRGC', 'DAIRY', 'RCTV', 'WSLO']
area_list = [10034.2408, 22568.2404, 24044.6363, 59822.7546, 19682.6046,
             47646.8477]
lat_list = [45.469, 45.475, 45.502, 45.520, 45.502, 45.350]
mb.set_rainfall_runoff(outlet_list=outlet_list,area_list=area_list,
                       lat_list=lat_list, runoff_model="GWLF")

### Setup routing
flow_length_list = [101469.139, 91813.075, 80064.864, 70988.164, 60398.680, 0]
mb.set_routing_outlet(routing_outlet="WSLO",
                      upstream_outlet_list=outlet_list,
                      flow_length_list=flow_length_list)

### Print the model in the console
mb.print_model()

### Output initial model configuration file (.yaml)
mb.write_model_to_yaml(filename="HydroModel.yaml")

#%% ===========================================================================
# Step 2: Populate a model configuration file
# =============================================================================

# Nothing need to be manually modified in this example.

#%% ===========================================================================
# Step 3: Run a calibration
# =============================================================================
import matplotlib.pyplot as plt
import pandas as pd
import HydroCNHS.calibration as cali
from copy import deepcopy

# Load climate data
temp = pd.read_csv(os.path.join(wd,"Data","Temp_degC.csv"),
                   index_col=["Date"]).to_dict(orient="list")
prec = pd.read_csv(os.path.join(wd,"Data","Prec_cm.csv"),
                   index_col=["Date"]).to_dict(orient="list")
pet = pd.read_csv(os.path.join(wd,"Data","Pet_cm.csv"),
                   index_col=["Date"]).to_dict(orient="list")

# Load flow gauge monthly data at WSLO
obv_flow_WSLO = pd.read_csv(os.path.join(wd,"Data","WSLO_M_cms.csv"),
                            index_col=["Date"], parse_dates=["Date"])

# Load model
model_dict = HydroCNHS.load_model(os.path.join(wd, "HydroModel.yaml"))

# Generate default parameter bounds
df_list, df_name = HydroCNHS.write_model_to_df(model_dict)
par_bound_df_list, df_name = HydroCNHS.gen_default_bounds(model_dict)

# Create convertor for calibration
converter = cali.Convertor()
cali_inputs = converter.gen_cali_inputs(wd, df_list, par_bound_df_list)
formatter = converter.formatter

# Code evaluation function for GA algorthm
def evaluation(individual, info):
    cali_wd, current_generation, ith_individual, formatter, _ = info
    name = "{}-{}".format(current_generation, ith_individual)

    ##### individual -> model
    # Convert 1D array to a list of dataframes.
    df_list = cali.Convertor.to_df_list(individual, formatter)
    # Feed dataframes in df_list to model dictionary.
    model = deepcopy(model_dict)
    for i, df in enumerate(df_list):
        s = df_name[i].split("_")[0]
        model = HydroCNHS.load_df_to_model_dict(model, df, s, "Pars")

    ##### Run simuluation
    model = HydroCNHS.Model(model, name)
    Q = model.run(temp, prec, pet)

    ##### Get simulation data
    # Streamflow of routing outlets.
    cali_target = ["WSLO"]
    cali_period = ("1981-1-1", "2005-12-31")
    sim_Q_D = pd.DataFrame(Q, index=model.pd_date_index)[cali_target]
    # Resample the daily simulation output to monthly outputs.
    sim_Q_M = sim_Q_D[cali_target].resample("MS").mean()

    KGE = HydroCNHS.Indicator().KGE(
        x_obv=obv_flow_WSLO[cali_period[0]:cali_period[1]][cali_target],
        y_sim=sim_Q_M[cali_period[0]:cali_period[1]][cali_target])

    fitness = KGE
    return (fitness,)

config = {'min_or_max': 'max',
         'pop_size': 100,
         'num_ellite': 1,
         'prob_cross': 0.5,
         'prob_mut': 0.15,
         'stochastic': False,
         'max_gen': 100,
         'sampling_method': 'LHC',
         'drop_record': False,
         'paral_cores': -1,
         'paral_verbose': 1,
         'auto_save': True,
         'print_level': 1,
         'plot': True}

seed = 5
rn_gen = HydroCNHS.create_rn_gen(seed)
ga = cali.GA_DEAP(evaluation, rn_gen)
ga.set(cali_inputs, config, formatter, name="Cali_HydroModel_gwlf_KGE")
ga.run()
summary = ga.summary
individual = ga.solution

##### Output the calibrated model.
df_list = cali.Convertor.to_df_list(individual, formatter)
model_best = deepcopy(model_dict)
for i, df in enumerate(df_list):
    s = df_name[i].split("_")[0]
    model = HydroCNHS.load_df_to_model_dict(model_best, df, s, "Pars")
HydroCNHS.write_model(model_best, os.path.join(ga.cali_wd, "Best_HydroModel_gwlf_KGE.yaml"))

#%% ===========================================================================
# Step 3: Run a simulation
# =============================================================================
### Run a simulation.
model = HydroCNHS.Model(os.path.join(wd, "Cali_HydroModel_gwlf_KGE",
                                     "Best_HydroModel_gwlf_KGE.yaml"))
Q = model.run(temp, prec, pet)
result = pd.DataFrame(Q, index=model.pd_date_index).resample("MS").mean()

### Plot
fig, ax = plt.subplots()
ax.plot(obv_flow_WSLO.index, obv_flow_WSLO.loc[:, "WSLO"], label="Obv")
ax.plot(obv_flow_WSLO.index, result["WSLO"], ls="--", label="Sim")
ax.legend()


import math

def parse_asteroids(lines):

    asteroids = []

    for y in range(len(lines)):

        line = lines[y]

        for x in range(len(line)):
            if lines[y][x] == '#':
                asteroids.append({'x': x, 'y': y})

    return asteroids

def solve_ratio(x, y):
    numbers = [x, y]
    gcd = math.gcd(x, y)
    solved = [int(i/gcd) for i in numbers]
    return solved

def find_ratios_for_asteroid(baseAsteroid, asteroids):

    ratios = {}
    for targetAsteroid in asteroids:
        dx = baseAsteroid['x'] - targetAsteroid['x']
        dy = baseAsteroid['y'] - targetAsteroid['y']

        if dx == 0 and dy == 0:
            continue;

        ratio = str(solve_ratio(dx, dy))

        if ratio not in ratios:
            ratios[ratio] = 1
        else:
            ratios[ratio] = ratios[ratio] + 1

    return ratios

def find_asteroid_max_visible(asteroids):
    maxVisible = 0;
    maxAsteroid = {}

    for asteroid in asteroids:
        ratios = find_ratios_for_asteroid(asteroid, asteroids)
        if len(ratios) > maxVisible:
            maxVisible = len(ratios)
            maxAsteroid = { 'asteroid' : asteroid, 'visible': len(ratios) }

    return maxAsteroid

_fileName = "input10.txt"

infile = open(_fileName, 'r')
lines = [line for line in infile.readlines()]

asteroids = parse_asteroids(lines)
bestAsteroid  = find_asteroid_max_visible(asteroids)

print ('Best Asteroid: ', bestAsteroid)


import pandas as pd

def Read_data(file):
 dt=pd.read_excel('201404070532-20230716-213836(1).xlsx')
 dt.columns=['time']
 data=dt
 pd.set_option('display.max_rows', None)
 pd.set_option('display.max_columns', None)
 pd.set_option('display.width', None)
 pd.set_option('display.unicode.ambiguous_as_wide', True)
 pd.set_option('display.unicode.east_asian_width', True)
 print(data.head())
 return data
def data_clean(data):
 print('存在'if any(data.duplicated()) else'不存在',data.drop_duplicates())
 print(data.isnull())
 print(data.isnull().sum())
 print(data.isnull().T.sum())
 print('不存在'if any(data.isnull())else'cunzai','缺失值')
 data.dropna()
 data.fillna(method='ffill')
 data.fillna(method='bfill')
 data.fillna(value=2)
 data.fillna(value={'':data[''].mean()})
 data1=data['']
 xmean=data1.mean()
 xstd=data1.std()
 print('cunzai'if any(data1>xmean+2*xstd)else'不存在','上限异常值')
 print('cunzai' if any(data1 > xmean + 2 * xstd) else '不存在', '下限异常值')
 q1=data1.quantile(0.25)
 q3=data1.quantile(0.75)
 up=q3+1.5*(q3-q1)
 dw= q1 - 1.5 * (q3 - q1)
 print('存在'if any(data1>up)else'不存在','上限异常值')
 print('存在'if any(data1<dw)else'不存在','下限异常值')
 data1[data1>up]=data1[data1<up].max()
 data1[data1<dw]=data1[data1>dw].min()
 print(data1)


import sys
import csv
import numpy as np
import matplotlib.pyplot as plt

graph = sys.argv[1]

degList = np.loadtxt(f'{graph}/{graph}.deg', dtype = np.uint32, delimiter = ',')
deg = degList[:, 1]

val, count = np.unique(deg, return_counts = True)
plt.scatter(val, count, alpha = 0.5)
plt.xlabel('degree')
plt.ylabel('frequency')
plt.title(f'degree distribution')
plt.xscale('log')
plt.yscale('log')
plt.savefig(f'{graph}_deg.png')


from pprint import pprint

#### DEBUG CONSTANTS ####

VERBOSE = False     # enable logs
PLOT = True         # enable plot

#### ANNEALING CONSTANTS ####

INITIAL_TEMP = 20
FINAL_TEMP = 1      # stop condition
T_FACTOR = 0.95      # decreasing temperature by (1 - T_FACTOR)
N_FACTOR = 0.9      # neighborhood ratio factor

#### LOCAL SEARCH CONSTANTS ####

LOOP_LIMIT = 500
RANDOM_START = 20

#### MODULE FUNCTIONS ####

def print_constants():
  const = {
    "INITIAL_TEMP": INITIAL_TEMP,
    "FINAL_TEMP": FINAL_TEMP,
    "T_FACTOR": T_FACTOR,
    "N_FACTOR": N_FACTOR
  }
  print("Constants:")
  pprint(const)
  print("\n")

if __name__ == "__main__":
  print_constants()


import os
import numpy as np
import datefinder
from transformers import pipeline
from transformers import AutoTokenizer, AutoModelForTokenClassification

STARTER_ENTITIES = ['I-ORG', 'I-LOC', 'I-PER', "I-MISC", "O", "B-MISC"]
ENTITIES = {'B-ORG': 'Company', 'B-LOC': 'Location', 'B-PER': 'Person'}
LABELS = ['Sports', 'Technology', 'Medicine', "Politics", "Arts"]
TOKENIZER = AutoTokenizer.from_pretrained("dslim/bert-base-NER")
MODEL = AutoModelForTokenClassification.from_pretrained("dslim/bert-base-NER")
NLP = pipeline("ner", model=MODEL, tokenizer=TOKENIZER)
CLASSIFIER = pipeline("zero-shot-classification",
                      model="facebook/bart-large-mnli")
SUMMARIZER = pipeline("summarization", model="philschmid/distilbart-cnn-12-6-samsum")

def get_comment(text):
    return SUMMARIZER(text)

def categorize_text(text):
    res =  CLASSIFIER(text, LABELS, multi_label=True)
    return res['labels'][np.argmax(res['scores'])]

def get_named_entities(text):
    res = NLP(text)
    temp = []
    for elem in res:
        if elem['entity'] not in STARTER_ENTITIES:
            temp.append({ENTITIES[elem['entity']]: elem['word']})
    dates = datefinder.find_dates(text)
    for date in dates:
        temp.append({"Date": str(date.date())})
    return temp

def generate_comment(post):
    named_entities = get_named_entities(post)
    category = categorize_text(post)
    comment = get_comment(post)
    if comment:
        comment = comment[0]['summary_text']
    else:
        comment = ''
    result = {"category": category,
              "named_entities": named_entities,
              "comment": comment}
    return result


import requests
import json
from typing import Dict

if __name__ == '__main__':
    response = requests.get('https://www.breakingbadapi.com/api/episodes?series=Breaking+Bad')
    response_deaths = requests.get('https://www.breakingbadapi.com/api/deaths')

    def info_for_serial_deaths(data_serial: list) -> Dict:
        result = max(data_serial, key=lambda x: x['number_of_deaths'])
        result = {'episode_id': None, 'season': result['season'], 'episode': result['episode'],
                  'number_of_deaths': result['number_of_deaths'], 'death': result['death']}

        return result

    def info_for_serial(data_serial: list, result={}) -> Dict:

        for i, v in enumerate(data_serial):
            episode = result['episode']
            season = result['season']
            if int(v['season']) == season and int(v['episode']) == episode:
                result['episode_id'] = data_serial[i]['episode_id']

        return result

    info_depths = info_for_serial_deaths(response_deaths.json())
    info_serial = info_for_serial(response.json(), info_depths)
    print(json.dumps(info_serial, indent=4))

    with open('death_dict.json', 'w') as file:
        json.dump(info_serial, file, indent=4)

# зачёт!