from django.shortcuts import render, get_object_or_404
from . models import Restaurant
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q

def rating(request):
    restaurants = Restaurant.objects.all().order_by('-rating')[:3]
    paginator = Paginator(restaurants, 3)
    page_request_var = 'page'
    page = request.GET.get(page_request_var)
    try:
        paginated_queryset = paginator.page(page)
    except PageNotAnInteger:
        paginated_queryset = paginator.page(1)
    except EmptyPage:
        paginated_queryset = paginator.page(paginator.num_pages)
    context = {
        'restaurants': restaurants,
        'queryset': paginated_queryset,
        'page_request_var': page_request_var,
        # 'rating':rating,
    }
    return render(request, 'by_rating.html', context)

def index(request):
    restaurants = Restaurant.objects.order_by('-created')[:10]
    paginator = Paginator(restaurants, 3)
    page_request_var = 'page'
    page = request.GET.get(page_request_var)
    try:
        paginated_queryset = paginator.page(page)
    except PageNotAnInteger:
        paginated_queryset = paginator.page(1)
    except EmptyPage:
        paginated_queryset = paginator.page(paginator.num_pages)
    context = {
        'restaurants':restaurants,
        'queryset':paginated_queryset,
        'page_request_var':page_request_var,
        # 'rating':rating,
               }
    return render(request, 'index.html', context)

def detail(request):
    post_list = Restaurant.objects.all()
    context = { 'post_list': post_list}
    return render(request, 'details.html', context)

def post(request, id):
    post = get_object_or_404(Restaurant, id=id)
    return render(request, 'post-detail.html',post)

def search(request):
    queryset = Restaurant.objects.all()
    query = request.GET.get('q')
    if query:
        queryset = queryset.filter(
            Q(name__icontains=query) |
            Q(description__icontains=query)
        ).distinct()
    context = {
        'queryset':queryset
    }
    return render(request, 'search_results.html', context)


"""
Starting in the top left corner of a 2x2 grid, there are 6 routes (without
backtracking) to the bottom right corner.

How many routes are there through a 20x20 grid?
"""

import math

def solve_problem():

    rows = 20
    cols = 20

    return math.factorial(rows+cols) / (math.factorial(rows) * math.factorial(cols))

if __name__ == '__main__':
    print(solve_problem())


import json
import os
import sys
import pathlib
from typing import Any, Dict, List, Optional, Generator, Tuple
from context import WorkItem, run

def scrub_directory(directory_path: str) -> Generator[str, None, None]:
    for path in pathlib.Path(directory_path).rglob("*.ipynb"):
        hade_output: bool = False
        with open(path, encoding="UTF8") as file:
            json_obj: Optional[Dict[str, Any]] = json.loads(file.read())
        if json_obj is None:
            continue
        cells: Optional[List[Dict[str, Any]]] = json_obj.get("cells")
        if cells is None:
            continue
        for cell in cells:
            execution_count: Optional[List[dict]] = cell.get("execution_count")
            if execution_count and execution_count != 0:
                cell["execution_count"] = 0
                hade_output = True
            outputs: Optional[List[dict]] = cell.get("outputs")
            if not outputs or len(outputs) == 0:
                continue
            hade_output = True
            cell["outputs"] = []
        if hade_output:
            with open(path, "w", encoding="UTF8") as file:
                file.write(json.dumps(json_obj, indent=1) + "\n")
            yield str(path)[len(directory_path) :]

def verify_directory(directory_path: str) -> Generator[Tuple[str, str], None, None]:
    for path in pathlib.Path(directory_path).rglob("*.ipynb"):
        with open(path, encoding="UTF8") as file:
            json_obj: Optional[Dict[str, Any]] = json.loads(file.read())
        if json_obj is None:
            continue
        cells: Optional[List[Dict[str, Any]]] = json_obj.get("cells")
        if cells is None:
            continue
        for cell in cells:
            execution_count: Optional[List[dict]] = cell.get("execution_count")
            if execution_count and execution_count != 0:
                yield (str(path)[len(directory_path) :], "execution_count")
                continue
            outputs: Optional[List[dict]] = cell.get("outputs")
            if not outputs or len(outputs) == 0:
                continue
            yield (str(path)[len(directory_path) :], json.dumps(outputs, indent=2))

class JupyterVerify(WorkItem):
    async def run(self) -> None:
        directory = os.path.join(os.getcwd(), "examples")
        print("directory " + directory)
        for path, _ in verify_directory(directory):
            self.print('Error "' + path + '" has outputs')
            # self.>print(josn_outputs)
            self.hade_error = True

        if self.hade_error:
            print("run task jupyter scrub to fix")

class JupyterScrub(WorkItem):
    async def run(self) -> None:
        directory = os.path.join(os.getcwd(), "examples")
        print("directory " + directory)
        for path in scrub_directory(directory):
            self.print('"' + path + '" was scrub')

def main() -> None:
    command = sys.argv[1] if len(sys.argv) <= 2 else None

    if command == "--verify":
        run(JupyterVerify)

    if command == "--scrub":
        run(JupyterScrub)

    if command:
        print("bad args " + command)
    else:
        print("no args")

    sys.exit(1)

if __name__ == "__main__":
    main()


'''
Create a solution that accepts five integer inputs. Output the sum of the five inputs three times, converting the inputs to the requested data type prior to finding the sum.
    First output: sum of five inputs maintained as integer values
    Second output: sum of five inputs converted to float values
    Third output: sum of five inputs converted to string values (concatenate)

The solution output should be in the format
    Integer: integer_sum_value
    Float: float_sum_value
    String: string_sum_value

Sample Input/Output:
    If the input is
        1
        3
        6
        2
        7

    then the expected output is
        Integer: 19
        Float: 19.0
        String: 13627

*
Input to program:
1
3
6
2
7
*

'''

#solution accepts five integer inputs
#solution outputs three sums of input values; convert before calculating sum
#first output: sum of five inputs maintained as integer values
#second output: sum of five inputs converted to float values
#third output: sum of five inputs converted to string values (concatenate)

value1 = int(input("Enter value 1: "))
value2 = int(input("Enter value 2: "))
value3 = int(input("Enter value 3: "))
value4 = int(input("Enter value 4: "))
value5 = int(input("Enter value 5: "))

integer_sum_value = value1 + value2 + value3 + value4 + value5
float_sum_value = float(value1) + float(value2) + float(value3) + float(value4) + float(value5)
string_sum_value = str(value1) + str(value2) + str(value3) + str(value4) + str(value5)

print(f"Integer: {integer_sum_value}")
print(f"Float: {float_sum_value}")
print(f"String: {string_sum_value}")

    #OR
#solution accepts five integer inputs
#solution outputs three sums of input values; convert before calculating sum
#first output: sum of five inputs maintained as integer values
#second output: sum of five inputs converted to float values
#third output: sum of five inputs converted to string values (concatenate)

try:
    value_1 = int(input("Enter value 1: "))
    value_2 = int(input("Enter value 2: "))
    value_3 = int(input("Enter value 3: "))
    value_4 = int(input("Enter value 4: "))
    value_5 = int(input("Enter value 5: "))

    integer_sum_value = int(value_1 + value_2 + value_3 + value_4 + value_5)
    float_sum_value = float(value_1) + float(value_2) + float(value_3) + float(value_4) + float(value_5)
    string_sum_value = str(value_1) + str(value_2) + str(value_3) + str(value_4) + str(value_5)

    print(f"Integer: {integer_sum_value}\nFloat: {float_sum_value}\nString: {string_sum_value}")

except ValueError:
    print("Please enter only whole numbers")


import vk_api
from vk_api import VkUpload
from vk_api.longpoll import VkLongPoll, VkEventType
from vk_api.utils import get_random_id

import requests
import json
import socket
import time
import configparser

def conf_read(param):
    config = configparser.ConfigParser()
    config.read('config.ini')
    method = {'group_token': config['KEYS']['group_token'],
              'app_service_key': config['KEYS']['app_service_key']
            }
    return method[param]

def con2serv():
    try:
        sock = socket.socket()
        sock.connect(('localhost', 9090))
        print('Connected!')
        return sock
    except ConnectionRefusedError:
        print('Server not responding.')
        print('Reconnecting...')
        time.sleep(5)
        return con2serv()

def client_exit(request, vk, event):
    if request == "кс" or request == "cs":
        print('Client exit...')
        vk.messages.send(
            user_id=event.user_id,
            random_id=get_random_id(),
            message=f'Клиент отключен.'
        )
        exit()

def server_exit(request, vk, event):
    if request == 'ss' or request == 'сс':
        print(f'Message received: {request}')
        print('Server exit...')
        vk.messages.send(
            user_id=event.user_id,
            random_id=get_random_id(),
            message=f'Сервер отключен.'
        )

def program_exit(request, vk, event):
    if request == "стоп" or request == "stop":
        print('Exit...')
        vk.messages.send(
            user_id=event.user_id,
            random_id=get_random_id(),
            message=f'Выход.'
        )
        exit()

def main():
    print('Client starting...')
    sock = con2serv()

    session = requests.Session()
    vk_session = vk_api.VkApi(token=conf_read('group_token'))
    vk = vk_session.get_api()

    longpoll = VkLongPoll(vk_session)
    for event in longpoll.listen():
        if event.type == VkEventType.MESSAGE_NEW and event.to_me and event.text:
            if event.to_me:
                request = event.text.lower()
                try:
                    server_exit(request, vk, event)
                    data_send = str.encode(request)
                    sock.send(data_send)
                    data = sock.recv(1024)
                    message = data.decode()
                    print(f'Message received: {message}')
                    client_exit(request, vk, event)
                    vk.messages.send(
                        user_id=event.user_id,
                        random_id=get_random_id(),
                        message=f'{message}'
                    )

                except vk_api.exceptions.ApiError:
                    program_exit(request, vk, event)
                    sock = con2serv()

try:
    if __name__ == '__main__':
        main()
        pass
except KeyboardInterrupt:
    print('\nExit...')
    exit()


'''
@File    :   output_layer.py
@Time    :   2022/03/10 15:21:20
@Author  :   ChildEden
@Version :   1.0
@Contact :   chenhao.zhang@uq.edu.au
@Desc    :   None
'''

import torch
import torch.nn as nn
from src.model.temporal_layers import TemporalConvLayer

class OutputBlock(nn.Module):
    def __init__(
            self,
            ko,
            last_block_channel,
            channels,
            end_channel,
            n_vertex,
            gated_act_func,
            drop_rate
    ):
        super(OutputBlock, self).__init__()
        self.ko = ko
        self.last_block_channel = last_block_channel
        self.channels = channels
        self.end_channel = end_channel
        self.n_vertex = n_vertex
        self.gated_act_func = gated_act_func
        self.enable_gated_act_func = True
        self.drop_rate = drop_rate
        self.tmp_conv1 = TemporalConvLayer(ko, last_block_channel, channels[0], n_vertex, gated_act_func,
                                           self.enable_gated_act_func)
        self.fc1 = nn.Linear(channels[0], channels[1])
        self.fc2 = nn.Linear(channels[1], end_channel)
        self.tc1_ln = nn.LayerNorm([n_vertex, channels[0]])
        self.act_func = 'sigmoid'
        self.sigmoid = nn.Sigmoid()
        self.tanh = nn.Tanh()
        self.relu = nn.ReLU()
        self.leaky_relu = nn.LeakyReLU()
        self.elu = nn.ELU()
        self.do = nn.Dropout(p=self.drop_rate)

    def forward(self, x):
        x_tc1 = self.tmp_conv1(x)
        x_tc1_ln = self.tc1_ln(x_tc1.permute(0, 2, 3, 1))
        x_fc1 = self.fc1(x_tc1_ln)
        if self.act_func == 'sigmoid':
            x_act_func = self.sigmoid(x_fc1)
        elif self.act_func == 'tanh':
            x_act_func = self.tanh(x_fc1)
        elif self.act_func == 'relu':
            x_act_func = self.relu(x_fc1)
        elif self.act_func == 'leaky_relu':
            x_act_func = self.leaky_relu(x_fc1)
        elif self.act_func == 'elu':
            x_act_func = self.elu(x_fc1)
        else:
            raise ValueError(
                f'ERROR: The {self.act_func} activate function is not supported currently.')
        x_fc2 = self.fc2(x_act_func).permute(0, 3, 1, 2)
        x_out = x_fc2

        return x_out


# Demos the use of drag_track in a couple of different `tkinter` widgets
#
# Things you can change:
#  - If you don't set the `scrollregion` in the `CanvasTracker` constructor
#    then you can drag the canvas indefinitely!

import os, sys
sys.path.insert(0, os.path.abspath(os.path.join("..")))

import tilewindow.util.util as util
from tilewindow.util.drag_track import DragTrack

import tkinter as tk
import tkinter.ttk as ttk

root = tk.Tk()
util.centre_window_percentage(root, 50, 50)

label_frame = ttk.LabelFrame(root, text="Label Frame", width=200, height=200)
label_frame.grid_propagate(False)
label_frame.grid(row=0, column=0)
lf_dt = DragTrack(label_frame)
label = ttk.Label(label_frame)
label.grid()

def lf_callback(dx, dy, new=False):
    label["text"] = "dx={}, dy={}, new={}".format(dx, dy, new)

def lf_release():
    label["text"] = "click here!"

lf_dt.callback = lf_callback
lf_dt.release_callback = lf_release
lf_release()

lf = ttk.LabelFrame(root, text="Canvas object")
lf.grid(row=0, column=1)
canvas = tk.Canvas(lf, borderwidth=0, highlightthickness=0)
canvas.grid(sticky=tk.NSEW)
canvas["width"] = 300
canvas["height"] = 200

class CanvasTracker(DragTrack):
    def __init__(self, canvas):
        super().__init__(canvas)
        self.canvas = canvas
        self.text_id = canvas.create_text(20, 20, anchor=tk.NW)
        self.released()
        self.rect_id = canvas.create_rectangle(20, 50, 120, 100, width=2, fill="green")
        self.move_rect_id = canvas.create_rectangle(150, 70, 170, 90, width=1, fill="red")
        self._grabbed = None
        canvas.config(scrollregion=(-50,-50, 350,250))

    def _in_rect(self, event, rect_id):
        x, y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
        minx, miny, maxx, maxy = self.canvas.bbox(rect_id)
        return ( minx <= x and x <= maxx and miny <= y and y <= maxy )

    def notify(self, event, what):
        if what == "down":
            if self._in_rect(event, self.rect_id):
                return True
            if self._in_rect(event, self.move_rect_id):
                self._grabbed = event.x - self.canvas.canvasx(event.x), event.y - self.canvas.canvasy(event.y)
        if what == "up":
            self._grabbed = None
        return False

    def moved(self, dx, dy, new=False):
        self.canvas.itemconfigure(self.text_id,
                text = "dx={}, dy={}, new={}".format(dx, dy, new))
        if self._grabbed is not None:
            # Slightly complex.  Call `canvas.xview_moveto(p)` where `p` is the
            # fraction of the entire width of the `scrollregion`.  For us, this
            # is 400.  But the canvas "window" is 300 wide, so we can only
            # actually scroll between 0 and 100 or, as fractions, 0.0 and 0.25
            #x = -self._grabbed[0] - dx
            #y = -self._grabbed[1] - dy
            #canvas.xview_moveto((x+50) / 100 * 0.25)
            #canvas.yview_moveto((y+50) / 100 * (300-200)/300)

            # Alternative, somewhat nicer method!
            x = dx + self._grabbed[0]
            y = dy + self._grabbed[1]
            canvas.scan_dragto(int(x), int(y), gain=1)

    def released(self):
        self.canvas.itemconfigure(self.text_id, text = "click here!")

CanvasTracker(canvas)

ttk.Label(root, text="Notice that you can click anywhere inside the 'canvas' object\n"
          + "and the tracking works.  But if you click inside the 'label frame'\n"
          + "object but on top of the text, it doesn't work.  The text is a new widget\n"
          + "which doesn't have mouse capture enabled.\n"
          + "We manually intercept clicks in the green rectangle and ignore them.\n"
          + "Click and drag the red rectangle to drag the whole canvas about."
          ).grid(row=1, column=0, columnspan=2)

root.mainloop()


# 1. 코딩 테스트 단어에 나오는 모음의 순서를 바꾸는 함수를 코딩해보세요.
# ex) hello -> holle
# naver webtoon => novor webtean

def main(str):
    strSet = set(['a','e','i','o','u','y','A','E', 'I', 'O', 'U', 'Y'])
    tempArray = []
    chaArray = []

    for cha in str:
        chaArray.append(cha)
        if cha in strSet:
            tempArray.append(cha)

    for index in range(len(chaArray)):
        if chaArray[index] in strSet:
            chaArray[index] = tempArray.pop()

    return chaArray;

result = main("nAvEr wEbtOOn")
print(''.join(result))


from collections import OrderedDict
from typing import Callable, Optional

import tensorflow as tf
from tensorflow.keras import layers

from modules.modeling.common.utils import make_divisible
from .base_ops import HSigmoid

class QConvNormActivation(tf.keras.Model):

    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        kernel_size: int = 3,
        stride: int = 1,
        padding: Optional[int] = None,
        groups: int = 1,
        norm_layer: Optional[Callable[..., layers.Layer]] = layers.BatchNormalization,
        activation_layer: Optional[Callable[..., layers.Layer]] = layers.ReLU,
        dilation: int = 1,
        inplace: bool = True,
    ) -> None:
        super().__init__()
        self.conv = layers.Conv2D(filters=out_channels, kernel_size=int(kernel_size), strides=stride, padding='same', use_bias=False)
        if norm_layer is not None:
            self.bn = norm_layer()
        else:
            self.bn = None
        if activation_layer is not None:
            self.activation = activation_layer()
        else:
            self.activation = None
        self.out_channels = out_channels

    def call(self, x):
        x = self.conv(x)
        if self.bn is not None:
            x = self.bn(x)
        if self.activation is not None:
            x = self.activation(x)
        return x

class DWConvK3(tf.keras.Sequential):

    def __init__(self, kernel_size, strides, padding='same', use_bias=True):
        _layers = []
        stacks = {3: 1, 5: 2, 7: 3}[kernel_size]
        for i in range(stacks):
            s = strides if i == 0 else 1
            _layers.append(layers.DepthwiseConv2D(kernel_size=3, strides=s, padding=padding, use_bias=use_bias))
        super().__init__(layers=_layers)

class _QDWConvNormActivation(tf.keras.Model):

    def __init__(
        self,
        channels: int,
        kernel_size: int = 3,
        stride: int = 1,
        padding: Optional[int] = None,
        norm_layer: Optional[Callable[..., layers.Layer]] = layers.BatchNormalization,
        activation_layer: Optional[Callable[..., layers.Layer]] = layers.ReLU,
        dilation: int = 1,
        inplace: bool = True,
        DWConv = layers.DepthwiseConv2D
    ) -> None:
        super().__init__()
        self.dwconv = DWConv(kernel_size=int(kernel_size), strides=stride, padding='same', use_bias=False)
        self.bn = norm_layer()
        self.activation = activation_layer()
        self.out_channels = channels

    def call(self, x):
        x = self.dwconv(x)
        x = self.bn(x)
        x = self.activation(x)
        return x

class QDWConvNormActivation(_QDWConvNormActivation):

    def __init__(self, channels: int, kernel_size: int = 3, stride: int = 1, padding: Optional[int] = None, norm_layer: Optional[Callable[..., layers.Layer]] = layers.BatchNormalization, activation_layer: Optional[Callable[..., layers.Layer]] = layers.ReLU, dilation: int = 1, inplace: bool = True) -> None:
        super().__init__(channels, kernel_size, stride, padding, norm_layer, activation_layer, dilation, inplace, DWConv=layers.DepthwiseConv2D)

class QDWConvK3NormActivation(_QDWConvNormActivation):

    def __init__(self, channels: int, kernel_size: int = 3, stride: int = 1, padding: Optional[int] = None, norm_layer: Optional[Callable[..., layers.Layer]] = layers.BatchNormalization, activation_layer: Optional[Callable[..., layers.Layer]] = layers.ReLU, dilation: int = 1, inplace: bool = True) -> None:
        super().__init__(channels, kernel_size, stride, padding, norm_layer, activation_layer, dilation, inplace, DWConv=DWConvK3)

class HSwish(tf.keras.Model):

    def __init__(self):
        super().__init__()
        self.relu6 = layers.ReLU(6)

    def call(self, x):
        return x * self.relu6(x + 3.) * (1. / 6.)

class Relu6(tf.keras.Model):

    def __init__(self):
        super().__init__()
        self.relu6 = layers.ReLU(6)

    def call(self, x):
        return self.relu6(x)

class QSE(tf.keras.Model):

    REDUCTION = 4

    def __init__(self, channel, reduction=None):
        super().__init__()
        self.channel = channel
        self.reduction = QSE.REDUCTION if reduction is None else reduction

        self.pool = layers.GlobalAveragePooling2D(keepdims=True)
        self.squeeze = layers.Conv2D(filters=make_divisible(self.channel // self.reduction), kernel_size=1, padding='same')
        self.relu = layers.ReLU()
        self.excite = layers.Conv2D(filters=self.channel, kernel_size=1, padding='same')
        self.hsigmoid = HSigmoid()

    def call(self, x):
        x0 = x
        x = self.pool(x)
        x = self.squeeze(x)
        x = self.relu(x)
        x = self.excite(x)
        x = self.hsigmoid(x)
        return x * x0

class QSE4Resnet(tf.keras.Model):

    '''se ratio in regnet is defined with respect to the input width of this block instead of hidden width'''
    REDUCTION = 4

    def __init__(self, in_channels, mid_channels) -> None:
        super().__init__()
        self.in_channels = in_channels
        self.mid_channels = mid_channels

        self.pool = layers.GlobalAveragePooling2D(keepdims=True)
        self.squeeze = layers.Conv2D(filters=self.mid_channels, kernel_size=1, padding='same')
        self.relu = layers.ReLU()
        self.excite = layers.Conv2D(filters=self.in_channels, kernel_size=1, padding='same')
        self.hsigmoid = HSigmoid()

    def call(self, x):
        x0 = x
        x = self.pool(x)
        x = self.squeeze(x)
        x = self.relu(x)
        x = self.excite(x)
        x = self.hsigmoid(x)
        return x * x0

    @staticmethod
    def get_mid_channels(cin: int) -> int:
        return make_divisible(cin // QSE4Resnet.REDUCTION)


from airflow.hooks.postgres_hook import PostgresHook
from airflow.contrib.hooks.aws_hook import AwsHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults

class StageToRedshiftOperator(BaseOperator):
    ui_color = '#358140'

    @apply_defaults
    def __init__(self,
                 conn_id,
                 aws_credentials_id,
                 table,
                 s3_bucket,
                 s3_key,
                 json_path,
                 *args, **kwargs):

        super(StageToRedshiftOperator, self).__init__(*args, **kwargs)
        self.conn_id = conn_id
        self.table = table
        self.s3_bucket = s3_bucket
        self.s3_key = s3_key
        self.aws_credentials_id = aws_credentials_id
        self.json_path = json_path

    def execute(self, context):
        aws_hook = AwsHook(self.aws_credentials_id)
        credentials = aws_hook.get_credentials()
        redshift = PostgresHook(postgres_conn_id=self.conn_id)
        redshift.run(f"DELETE FROM {self.table}")
        self.log.info(f"Deleted any existing data from {self.table}")
        self.s3_key = self.s3_key.format(**context)
        s3_path = f"s3://{self.s3_bucket}/{self.s3_key}"
        query = f"COPY {self.table} FROM '{s3_path}' " \
                f"ACCESS_KEY_ID '{credentials.access_key}' " \
                f"SECRET_ACCESS_KEY '{credentials.secret_key}' " \
                f"REGION 'us-west-2' "
        query += f"FORMAT AS JSON '{self.json_path}'" if self.json_path else " JSON 'auto'"
        redshift.run(query)
        self.log.info(f"Copied data from S3 to {self.table}")

Automate ETL Pipeline using Apache Airflow/plugins/operators/stage_redshift.py


from django.shortcuts import render, HttpResponse, redirect
from .models import *

def books(request):
    context = {
        "all_books": Book.objects.all(),
        "all_authors": Author.objects.all(),
    }

    return render(request, "index.html", context)

def add_books(request):
    title = request.POST['title']
    description = request.POST['description']
    Book.objects.create(title= title , desc= description)
    return redirect("/")

def display_books(request, id):
    # id = request.session['book.id']
    one_book = Book.objects.get(id=id)
    context = {
        "book_one": one_book ,
        "all_authors_book_one" : one_book.authors.all(),
        "all_books": Book.objects.all(),
        "all_authors": Author.objects.all(),
    }

    return render(request, "bookscontent.html", context)

def add_book_base_author(request):
    pass
    author_id = request.POST['author']
    one_author = Author.objects.get(id=author_id)
    Book.objects.create(title=one_book.title , one_author=authors)
    context = {
        "author_one": one_author.books.all() ,
    }

def authors(request):
    context = {
        "all_books": Book.objects.all(),
        "all_authors": Author.objects.all(),
    }

    return render(request, "author.html", context)

def add_authors(request):
    fname = request.POST['fname']
    lname = request.POST['lname']
    author_note = request.POST['note']
    Author.objects.create(first_name= fname , last_name = lname, notes= author_note)
    return redirect("/authors")

def display_authors(request, id):
    one_author = Author.objects.get(id=id)
    context = {
        "author_one": one_author,
        "all_books_author_one" : one_author.books.all(),
        "all_books": Book.objects.all(),
        "all_authors": Author.objects.all(),
    }

    return render(request, "author_content.html", context)

def add_author_base_book(request):
    pass
    book_id = request.POST['book']
    one_book = Book.objects.get(id=book_id)
    context = {
        "book_one": one_book.authors.all() ,
    }
    return redirect("books/{{author_id}}", context)  #wrong


import json
import cv2
import numpy as np

images = []
masks = []

def get_points(raw_data):
    point = []
    points = []
    count = 1
    for i in raw_data:
        point.append(i)
        if count % 2 == 0:
            points.append(point)
            point = []
        count += 1
    return np.array(points, dtype = np.int32)

with open('dataset.json', 'r') as json_file:
    json_data = [json.loads(line) for line in json_file]
    for data in json_data:

        image_path = data['image_path']
        image_path = image_path[:6] + '/annotated_images' + image_path[6:]

        image = cv2.imread(image_path)
        image = np.mean(image, axis = 2).astype(np.uint8)
        mask = np.zeros_like(image)

        line = data['lines']
        line = get_points(line)
        # mask olustumak icin
        mask = cv2.fillPoly(mask, [line], (255, 255, 255))

        print(mask.shape)
        print(image.shape)

        # image ve maskı istediğiniz şekile kullanabilirsiniz.


from fastapi import APIRouter, Request, Depends, responses

from application.models import User
from application import config

router = APIRouter(prefix="/auth", tags=["auth"])

@router.get("/logout")
async def logout(request: Request):
    response = responses.RedirectResponse(url=f"{router.prefix}/login", status_code=302)
    response.delete_cookie("Authorization")

    return response

@router.get("/{method}")
async def auth(request: Request, method: str, user: User = Depends(User.dependency)):
    if method not in ["login", "register"]:
        return responses.RedirectResponse(url=f"{router.prefix}/login", status_code=302)

    if user:
        return responses.RedirectResponse(url=request.url_for("index"), status_code=302)

    response = config.templates.TemplateResponse(
        "auth.html",
        {"request": request, "method": method}
    )

    response.delete_cookie("Authorization")

    return response


from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options

# Constants
WIKI_URL = 'https://en.wikipedia.org/wiki/Main_Page'
FORM_URL = 'https://web.archive.org/web/20220120120408/https://secure-retreat-92358.herokuapp.com/'

# Instantiating Selenium Stuff
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=chrome_options)

# WIKI PROJECT
# driver.get(WIKI_URL)

# # Getting article count link
# article_count = driver.find_element(By.CSS_SELECTOR, '#articlecount a')
#
# # Clicking on it
# article_count.click()
#
# # Finding a clickable link by using the text itself in the tag
# view_source = driver.find_element(By.LINK_TEXT, "View source")
#
# # Clicking on it
# view_source.click()

# Finding search bar
# search = driver.find_element(By.NAME, 'search')
# search.send_keys("Python")
# search.send_keys(Keys.ENTER)

# FORM PROJECT
driver.get(FORM_URL)

# Get form info/fetch elements
first_name = driver.find_element(By.NAME, 'fName')
last_name = driver.find_element(By.NAME, 'lName')
email = driver.find_element(By.NAME, 'email')

# Input data for the form and hit 'Enter' to submit
first_name.send_keys("James")
last_name.send_keys("Wright")
email.send_keys("not-a-real-email@not-a-real-domain.com")
email.send_keys(Keys.ENTER)

# Quit selenium
# driver.quit()


"""
--- Day 2: 1202 Program Alarm ---

On the way to your gravity assist around the Moon, your ship computer beeps
angrily about a "1202 program alarm". On the radio, an Elf is already
explaining how to handle the situation: "Don't worry, that's perfectly
norma--" The ship computer bursts into flames.

You notify the Elves that the computer's magic smoke seems to have escaped.
"That computer ran Intcode programs like the gravity assist program it was
working on; surely there are enough spare parts up there to build a new
Intcode computer!"

An Intcode program is a list of integers separated by commas (like 1,0,0,3,
99). To run one, start by looking at the first integer (called position 0).
Here, you will find an opcode - either 1, 2, or 99. The opcode indicates
what to do; for example, 99 means that the program is finished and should
immediately halt. Encountering an unknown opcode means something went wrong.

Opcode 1 adds together numbers read from two positions and stores the result
in a third position. The three integers immediately after the opcode tell
you these three positions - the first two indicate the positions from which
you should read the input values, and the third indicates the position at
which the output should be stored.

For example, if your Intcode computer encounters 1,10,20,30, it should read
the values at positions 10 and 20, add those values, and then overwrite the
value at position 30 with their sum.

Opcode 2 works exactly like opcode 1, except it multiplies the two inputs
instead of adding them. Again, the three integers after the opcode indicate
where the inputs and outputs are, not their values.

Once you're done processing an opcode, move to the next one by stepping
forward 4 positions.

For example, suppose you have the following program:

1,9,10,3,2,3,11,0,99,30,40,50

For the purposes of illustration, here is the same program split into
multiple lines:

1,9,10,3,
2,3,11,0,
99,
30,40,50

The first four integers, 1,9,10,3, are at positions 0, 1, 2, and 3.
Together, they represent the first opcode (1, addition), the positions of
the two inputs (9 and 10), and the position of the output (3). To handle
this opcode, you first need to get the values at the input positions:
position 9 contains 30, and position 10 contains 40. Add these numbers
together to get 70. Then, store this value at the output position; here,
the output position (3) is at position 3, so it overwrites itself.
Afterward, the program looks like this:

1,9,10,70,
2,3,11,0,
99,
30,40,50

Step forward 4 positions to reach the next opcode, 2. This opcode works just
like the previous, but it multiplies instead of adding. The inputs are at
positions 3 and 11; these positions contain 70 and 50 respectively.
Multiplying these produces 3500; this is stored at position 0:

3500,9,10,70,
2,3,11,0,
99,
30,40,50

Stepping forward 4 more positions arrives at opcode 99, halting the program.

Here are the initial and final states of a few more small programs:

    1,0,0,0,99 becomes 2,0,0,0,99 (1 + 1 = 2).
    2,3,0,3,99 becomes 2,3,0,6,99 (3 * 2 = 6).
    2,4,4,5,99,0 becomes 2,4,4,5,99,9801 (99 * 99 = 9801).
    1,1,1,4,99,5,6,0,99 becomes 30,1,1,4,2,5,6,0,99.

Once you have a working computer, the first step is to restore the gravity
assist program (your puzzle input) to the "1202 program alarm" state it had
just before the last computer caught fire. To do this, before running the
program, replace position 1 with the value 12 and replace position 2 with
the value 2. What value is left at position 0 after the program halts?
"""
import sys

# Define machine characteristics
OP_ADD = 1
OP_MULTIPLY = 2
OP_HALT = 99

class HaltException (Exception):
    pass

# Implement the instruction operations

def add(params):
    return params[0] + params[1]

def multiply(params):
    return params[0] * params[1]

def halt(params):
    # We're done.  Blow through the instruction decoder and catch this
    # in the main execute() loop.
    raise HaltException

def decode_inst(pc, memory):
    """
    decode a single instruction
    :param pc: the current program counter (location in memory)
    :param memory: the machine's memory
    :return: (param_list, op_function, result_loc, instruction_width)
    """
    #
    # Describe each operation a dict keyed by opcode, of dicts:
    #   {opcode: {
    #       p_locs: [],
    #       result_loc:,
    #       op_function:,
    #       instruction_width:,
    #       },
    #   }
    #
    op_defs = {
        OP_ADD: {
            'p_locs': [1, 2],
            'result_loc': 3,
            'op_function': add,
            'instruction_width': 4,
        },
        OP_MULTIPLY: {
            'p_locs': [1, 2],
            'result_loc': 3,
            'op_function': multiply,
            'instruction_width': 4,
        },
        OP_HALT: {
            'p_locs': [],
            # Lie about the halt instruction's result location. It has no
            # result, so it would seem that putting None here would be better.
            # But that would require special case code below when we make
            # the result location be relative to the pc because you can't add
            # the pc to None.  The halt operation raises an exception, so
            # the result location is never used.
            'result_loc': 0,
            'op_function': halt,
            'instruction_width': 1,
        }
    }

    opcode = memory[pc]

    # Silence PyCharm warning use before def
    op_def = None

    try:
        op_def = op_defs[opcode]
    except KeyError:
        # Oops! an invalid opcode. Report the error and halt.
        print("Invalid opcode: {}".format(opcode), file=sys.stderr)
        halt([])

    # Get the actual parameters (NB, sneak peek: This section will need
    # to be changed in day 5's exercise.
    params = []
    for relative_parameter_loc in op_def['p_locs']:
        absolute_parameter_loc = memory[relative_parameter_loc + pc]
        params.append(memory[absolute_parameter_loc])

    result_loc = memory[op_def['result_loc'] + pc]

    return (params,
            op_def['op_function'],
            result_loc,
            op_def['instruction_width'],
            )

def execute(memory):
    """
    Loop over the instructions until we get a halt.
    :param memory: The memory of our machine implemented as a list.
    :return: None
    """
    pc = 0

    while True:
        try:
            params, op_function, result_loc, inst_width = \
                decode_inst(pc, memory)

            # We know everything we need to execute the instruction.
            result = op_function(params)
            memory[result_loc] = result
            #  memory[result_loc] = op_function(params)
        except HaltException:
            return

        # Advance the PC
        pc += inst_width

def main():
    with open('2-1 sample input.txt') as f:
        memory = list(map(int, f.readline().split(',')))
    execute(memory)
    print(memory)

if __name__ == '__main__':
    main()


"""
Author: Chaofan Wu
Student ID: 02285924
Email: cw522@ic.ac.uk
Project Name: Predicting flood risk in Ghana
Supervisors:
    Sesinam Dagadu(MEng)
    Yves Plancherel(PhD)
Company: SnooCODE
Date: 08/2023
"""
from get_flood_sampling_data import combine_duration_maxDuration_dates
from get_precipitation_data import download_daily_precip_dic, combine_precip
from common_fucs import compare_float_lists, discard_duplicates
import pandas as pd

def auto_get_flood_data_for_application(input_df,
                                        historical_info_path,
                                        daily_precip_pickle_file_path,
                                        geo_data_path,
                                        download_daily_precip=False,
                                        save_path=None):
    """
    Automatically retrieve and process flood data for application purposes.

    This function processes input flood data, optionally downloads daily precipitation data,
    and merges it with geographic data for the same samples. The function is designed for
    application use cases where data needs to be fetched, processed, and returned in a structured format.

    Parameters:
    -----------
    :param input_df: Input DataFrame containing flood sample data.
    :type input_df: pd.DataFrame
    :param historical_info_path: Path to the historical flood information.
    :type historical_info_path: str
    :param daily_precip_pickle_file_path: Path to the pickle file where daily rainfall data is saved.
    :type daily_precip_pickle_file_path: str
    :param geo_data_path: Path to the flood samples geographic data.
    :type geo_data_path: str
    :param download_daily_precip: Whether to download daily precipitation data, default is False.
    :type download_daily_precip: bool, default False
    :param save_path: Where to save the resulting DataFrame as a CSV file, if provided.
    :type save_path: str or None, default None
    :return: A DataFrame containing the processed flood data for application.
    :rtype: pd.DataFrame

    Example of usage:
    ----------------
        # >>> df = auto_get_flood_data_for_application(input_df=pd.DataFrame(...),
        #                                         historical_info_path='path/to/historical_info.csv',
        #                                         daily_precip_pickle_file_path='path/to/rainfall_data.pkl',
        #                                         geo_data_path='path/to/geo_data.csv',
        #                                         download_daily_precip=True)
    """

    flood_samples_ls = []
    flood_samples = input_df.copy()

    # If specified, download daily precipitation data for each flood ID group
    if download_daily_precip:
        for flood_id, group in flood_samples.groupby('Flood_ID'):
            print(f"Processing {flood_id}:")
            data = combine_duration_maxDuration_dates(group, historical_info_path)
            _ = download_daily_precip_dic(data, save_path=daily_precip_pickle_file_path+str(flood_id)+str(".pickle"))
            print()
            print()

    # Process each flood ID group to combine precipitation related columns
    for flood_id, group in flood_samples.groupby('Flood_ID'):
        print(f"Processing {flood_id}:")
        data = combine_precip(group, daily_precip_pickle_file_path+str(flood_id)+str(".pickle"))
        flood_samples_ls.append(data)

    flood_samples = pd.concat(flood_samples_ls)
    geo_data = pd.read_csv(geo_data_path)

    # Compare and merge dataframes based on coordinates and flood state
    flood_samples_Lon = flood_samples['Lon'].tolist()
    flood_samples_geo_data_Lon = geo_data['Lon'].tolist()
    flood_samples_Lat = flood_samples['Lat'].tolist()
    flood_samples_geo_data_Lat = geo_data['Lat'].tolist()
    flood_samples_Flooded = flood_samples['Flooded'].tolist()
    flood_samples_geo_data_label = geo_data['label'].tolist()

    # Drop repeated columns if the values match:
    if compare_float_lists(flood_samples_Lon, flood_samples_geo_data_Lon):
        geo_data.drop(columns=['Lon'], inplace=True)

    if compare_float_lists(flood_samples_Lat, flood_samples_geo_data_Lat):
        geo_data.drop(columns=['Lat'], inplace=True)

    if compare_float_lists(flood_samples_Flooded, flood_samples_geo_data_label):
        flood_samples.reset_index(drop=True, inplace=True)
        geo_data.reset_index(drop=True, inplace=True)
        flood_samples = pd.concat([flood_samples, geo_data], axis=1)
        flood_samples.drop(columns=['Flooded'], inplace=True)

    # Remove duplicates
    flood_samples_for_application = discard_duplicates(flood_samples, print_info=True)

    # Save the processed DataFrame if a save path is provided
    if save_path:
        flood_samples_for_application.to_csv(save_path, index=False)
        print(f"your file has been saved to {save_path} ")

    return flood_samples_for_application


import torch
import torch.nn as nn
import torch.nn.functional as F
from utils import NucleusSampler

class DilatedCausalConv1d(nn.Module):
    def __init__(
            self,
            kernel_size,
            dilate,
            input_dim,
            output_dim,
            skip_dim,
            embed_dim=None,  # usu. one-hot encoding of speaker ids
            condition="none",
            padding_mode="constant"
    ):
        super(DilatedCausalConv1d, self).__init__()
        self.kernel_size = kernel_size
        self.dilate = dilate
        self.input_dim = input_dim
        self.output_dim = output_dim
        self.left_padding = (kernel_size - 1) * dilate

        # combined two gates: content gate and output gate
        self.conv1 = nn.Conv1d(input_dim, 2 * output_dim, kernel_size, dilation=dilate)
        self.conv2 = nn.Conv1d(output_dim, output_dim, 1, 1, 0)  # depthwise convolution

        # check whether the input_dim matches the output_dim
        self.in_eq_out = input_dim == output_dim

        # residual connection to the end of **this layer**
        self.residual_connection = None
        if not self.in_eq_out:
            self.residual_connection = nn.Conv1d(input_dim, output_dim, 1, 1, 0)

        # global|local|non conditioning
        self.condition = condition
        if condition == "global":
            self.conv3 = nn.Linear(embed_dim, 2 * output_dim, bias=False)

        elif condition == "local":
            # assume the other supplementary low-frequency time series (linguistic features such as text sequences)
            # has already been upsampled to the same resolution as the input audio
            self.conv3 = nn.Conv1d(embed_dim, 2 * output_dim, kernel_size, dilation=dilate, bias=False)
        self.padding_mode = padding_mode

        # learnable padding
        if padding_mode == "learnable":
            self.padding_vector = nn.Parameter(torch.empty(output_dim, 1))
            nn.init.kaiming_normal_(self.padding_vector)  # parameter initialization

        # skip connection to the end of **all the stacked dilated layers**
        # an additional parameterized shortcut
        # learnable regardless of dimensional expansion or contraction
        self.skip_connection = nn.Conv1d(output_dim, skip_dim, 1, 1, 0)

    def forward(self, x, y=None, automatic_padding=True):

        identity = x.clone()
        if self.residual_connection is not None:
            identity = self.residual_connection(identity)

        if automatic_padding:
            if self.padding_mode == "constant":
                if isinstance(automatic_padding, bool):
                    padded = F.pad(x, (self.left_padding, 0))  # notice: the padding starts from the last dim
                elif isinstance(automatic_padding, int):
                    padded = F.pad(x, (automatic_padding, 0))
                else:
                    raise ValueError("Unexpected type of automatic padding!")
            else:
                if isinstance(automatic_padding, bool):
                    padded = torch.cat([
                        self.padding_vector[None, :, :].repeat((x.size(0), 1, self.left_padding)),
                        x], dim=-1)
                elif isinstance(automatic_padding, int):
                    padded = torch.cat([
                        self.padding_vector[None, :, :].repeat((x.size(0), 1, automatic_padding)),
                        x], dim=-1)
                else:
                    raise ValueError("Unexpected type of automatic padding!")

        else:
            padded = x

        content, output = self.conv1(padded).chunk(2, dim=1)
        if self.condition != "none":
            content_cond, output_cond = self.conv3(y).chunk(2, dim=1)

            if self.condition == "global":
                # broadcast over time
                content_cond = content_cond.unsqueeze(2)
                output_cond = output_cond.unsqueeze(2)
            content = content + content_cond
            output = output + output_cond

        content = torch.tanh(content)  # tanh activation
        output = torch.sigmoid(output)  # sigmoid activation
        hidden_repr = content * output

        residual = self.conv2(hidden_repr)
        skip = self.skip_connection(hidden_repr)

        out = residual + identity[:, :, -residual.size(2):]  # residual connection
        return out, skip[:, :, -out.size(2):]

class WaveNet(nn.Module):
    def __init__(
            self,
            input_dim=256,
            hidden_dim=16,
            embed_dim=None,  # for conditioning only
            skip_dim=32,
            output_dim=256,
            layers_per_block=10,
            num_blocks=2,
            kernel_size=2,
            condition="none",
            quantization=True,
            padding_mode="constant",
            sampler=NucleusSampler()
    ):
        super(WaveNet, self).__init__()
        self.input_dim = input_dim
        self.hidden_dim = hidden_dim
        self.embed_dim = embed_dim
        self.skip_dim = skip_dim
        self.output_dim = output_dim
        self.layers_per_block = layers_per_block
        self.num_blocks = num_blocks
        self.kernel_size = kernel_size
        self.condition = condition
        self.padding_mode = padding_mode

        if quantization:
            # take input values (integer) as coding indices
            self.feature = nn.Embedding(input_dim+1, hidden_dim, padding_idx=0)
        else:
            self.feature = nn.Conv1d(input_dim, hidden_dim, 1, 1, 0)
        self.quantization = quantization

        for i in range(num_blocks):
            self.add_module(f"block_{i}", self._make_block())

        self.classifier = nn.Sequential(
            nn.ReLU(),
            nn.Conv1d(skip_dim, output_dim, 1, 1, 0),
            nn.ReLU(),
            nn.Conv1d(output_dim, output_dim, 1, 1, 0)
        )

        if condition != "none":
            self.use_label = None  # indicator attribute

        self.sampler = sampler

    def _make_block(self):

        class Block(nn.Module):

            def __init__(
                    self,
                    num_layers,
                    kernel_size,
                    hidden_dim,
                    embed_dim,
                    skip_dim,
                    condition
            ):
                super(Block, self).__init__()
                """
                take kernel size 2 as example,
                the ultimate receptive region of 10 stacked layers is 1024 pixel wide
                """
                for i in range(num_layers):
                    self.add_module(
                        f"dilated_causal_layer_{i}",
                        DilatedCausalConv1d(
                            kernel_size, kernel_size ** i, input_dim=hidden_dim, output_dim=hidden_dim,
                            skip_dim=skip_dim, embed_dim=embed_dim, condition=condition)
                    )
                self.num_layers = num_layers

            def forward(self, x, y=None):
                # culmulative skip connection
                skip_sum = 0
                for i in range(self.num_layers):
                    layer = getattr(self, f"dilated_causal_layer_{i}")
                    x, skip = layer(x, y)
                    skip_sum += skip
                return x, skip_sum

        return Block(self.layers_per_block, self.kernel_size,
                     self.hidden_dim, self.embed_dim, self.skip_dim, condition=self.condition)

    def generate(self, x, y=None, generate_length=0):
        layers = []
        n_samples, input_length = x.shape
        full_length = input_length + generate_length
        if y is not None:
            y = y.float()
        for block in [getattr(self, f"block_{i}") for i in range(self.num_blocks)]:
            layers.extend([getattr(block, f"dilated_causal_layer_{j}") for j in range(self.layers_per_block)])
        out = torch.zeros(n_samples, full_length).to(x)
        hidden_repr = torch.zeros(n_samples, len(layers) + 1, self.hidden_dim, full_length).to(x.device)
        skip_sum = torch.zeros(n_samples, self.skip_dim, full_length).to(x.device)
        with torch.no_grad():
            out[:, :input_length] = x
            if self.quantization:
                hidden_repr[:, 0, :, :input_length] = self.feature(x + 1).swapdims(1, 2)
            else:
                hidden_repr[:, 0, :, :input_length] = self.feature(x.unsqueeze(1))
            for i, layer in enumerate(layers):
                hidden_repr[:, 1 + i, :, :input_length], skip = layer(hidden_repr[:, i, :, :input_length], y)
                skip_sum[:, :, :input_length] += skip
            if input_length < full_length:
                logits = self.classifier(skip_sum[:, :, [input_length - 1]]).squeeze(-1)
                out[:, input_length] = self.sampler.sample(logits=logits)
                if not self.quantization:
                    out[:, input_length] = out[:, input_length] / (self.output_dim // 2) - 1
                for i in range(input_length, full_length):
                    if self.quantization:
                        hidden_repr[:, 0, :, i] = self.feature(out[:, i] + 1)
                    else:
                        hidden_repr[:, 0, :, i] = self.feature(out[:, None, [i]]).squeeze(-1)
                    for j, layer in enumerate(layers):
                        hidden_repr[:, 1 + j, :, [i]], skip = layer(
                            hidden_repr[:, j, :, max(0, i - layer.left_padding):(i + 1)],
                            y, automatic_padding=max(0, layer.left_padding - i))
                        skip_sum[:, :, [i]] += skip
                    if not i == (full_length - 1):
                        logits = self.classifier(skip_sum[:, :, [i]]).squeeze(-1)
                        out[:, i + 1] = self.sampler.sample(logits=logits)
                        if not self.quantization:
                            out[:, i + 1] = out[:, i + 1] / (self.output_dim // 2) - 1
                if not self.quantization:
                    out = torch.round((out + 1) * (self.output_dim // 2)).int()
            else:
                out = self.classifier(skip_sum[:, :, :]).max(dim=1)[1]
        return out

    def forward(self, x, y=None):
        if self.quantization:
            # reserve index 0 for padding token
            x = x + 1
        else:
            # expand additional representation dim
            x = x.unsqueeze(1)
        if y is not None:
            y = y.float()
        feat = self.feature(x)
        if self.quantization:
            feat = feat.swapdims(1, 2)
        skip_sum = 0
        for i in range(self.num_blocks):
            block = getattr(self, f"block_{i}")
            if i == 0:
                hidden_repr, skip = block(feat, y)
            else:
                hidden_repr, skip = block(hidden_repr, y)
            skip_sum += skip
        # feed the cumulative skip connection to the classifier
        out = self.classifier(skip_sum)
        return out


import csv
from django.core.paginator import Paginator
from django.shortcuts import render, redirect
from django.urls import reverse
from django.conf import settings

def index(request):
    return redirect(reverse('bus_stations'))

def bus_stations(request):
    bus_station = []
    with open(settings.BUS_STATION_CSV, encoding='utf-8') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            bus_station.append(row)

    page_number = int(request.GET.get("page", 1))
    paginator = Paginator(bus_station, 10)
    page = paginator.get_page(page_number)

    context = {
        'bus_stations': page.object_list,
        'page': page
    }

    return render(request, 'stations/index.html', context)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct  6 18:33:07 2018

@author: jimmy
"""
import numpy as np
import pandas as pd

def reduce_mem_usage(data, verbose = True):
    """
    Reduce the memory usage of data.

    Parameters
    ----------
    data : DataFrame
        The data which memory usage will be reduced.
    verbose : bool, default True
        if True, the reduced memory usage information will be printed.

    Returns
    -------
    The mem-usage-reduced data.

    Examples
    --------
    >>> data = pandas.DataFrame({'x':['a','b']*3000,
        'y':[1.4,1.3,4.5]*2000,'z':[True,False]*3000})
    >>> data.head()
       x         y      z
    0  a  1.400391   True
    1  b  1.299805  False
    2  a  4.500000   True
    3  b  1.400391  False
    4  a  1.299805   True

    >>> new_data = reduce_mem_usage(data)
    Memory usage of dataframe: 0.10 MB
    Memory usage after optimization: 0.06 MB
    Decreased by 35.3%

    >>> new_data.head()
       x         y      z
    0  a  1.400391   True
    1  b  1.299805  False
    2  a  4.500000   True
    3  b  1.400391  False
    4  a  1.299805   True

    """
    start_mem = data.memory_usage().sum() / 1024**2
    if verbose:
        print('Memory usage of dataframe: {:.2f} MB'.format(start_mem))
    types = [np.int,np.int8,np.int16,np.int32,np.int64]
    types.extend([np.float,np.float16,np.float32,np.float64])
    for col in data.columns:
        col_type = data[col].dtype

        if col_type in types:
            c_min = data[col].min()
            c_max = data[col].max()
            if str(col_type)[:3] == 'int':
                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:
                    data[col] = data[col].astype(np.int8)
                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:
                    data[col] = data[col].astype(np.int16)
                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:
                    data[col] = data[col].astype(np.int32)
                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:
                    data[col] = data[col].astype(np.int64)
            else:
                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:
                    data[col] = data[col].astype(np.float16)
                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:
                    data[col] = data[col].astype(np.float32)
                else:
                    data[col] = data[col].astype(np.float64)

    end_mem = data.memory_usage().sum() / 1024**2
    if verbose:
        print('Memory usage after optimization: {:.2f} MB'.format(end_mem))
        print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))

    return data


"""geo.py

Contains the following function:
* get_distance: Return a float regarding the distance between two coordinates. use:
    import geo
    geo.get_distance(coor1 = (LATITUDE, LONGITUDE), coor2 = (LATITUDE, LONGITUDE))

* get_coordinates: Return a tuple with the coordinates of the input postcode. use:
    import geo
    geo.get_coordinates(post_code = 'YOUR POSTCODE)

"""

import pandas as pd
from geopy.distance import geodesic
from geopy.geocoders import Nominatim
from shapely.geometry import Point, Polygon

bca_coords = [(51.525843, -2.683383),
(51.523520, -2.677107),
(51.523520, -2.677107),
(51.516857, -2.682418),
(51.521277, -2.689488),
(51.525843, -2.683383)]

bca = Polygon(bca_coords)

def get_distance(coor1:tuple[float, float], coor2:tuple[float, float])->float:
    """Function to calculate the distance between two coordinates

    Args:
        coor1 (tuple[float, float]): coordinate #1 (latitude, longitude)
        coor2 (tuple[float, float]): coordinate #2 (latitude, longitude)

    Returns:
        float: distance between the two coordinates. Number.
    """
    distance = geodesic(coor1, coor2).miles
    return distance

def get_coordinates(post_code:str)->tuple[float, float]:
    """Function to get the coordinates (latitude and longitude) from a postcode

    Args:
        post_code (str): postcode to be transform to coordinate

    Returns:
        tuple[float, float]: coordinate (latitude, longitude)
    """
    geolocator = Nominatim(user_agent="geoapiExercises")
    location = geolocator.geocode(post_code)
    if location:
        return location.latitude, location.longitude
    else:
        return None

def into_bca(coor:tuple)->bool:
    return Point(coor).within(bca)


import random
import string

#functions
def printWord(word):
    for letter in word:
        print(letter, " ", end="")
    print()

def changeWord(letter):
    for i, value in enumerate(word):
        if (letter == word[i]):
            maskedWord[i] = letter

f = open("hangman_words.txt", mode="r")
contents = f.read()

#variables
words = contents.split()
selectedWord = words[random.randint(0, len(words)-1)]
word = list(selectedWord)
maskedWord = ["_"] * len(word)
availableLetters = list(string.ascii_lowercase)
wrongGuessCounter = 0
correctGuessCounter = len(set(word))

#game logic
print("Welcome to play Hangman!")
print("Try to guess following word:")
while (True):
    printWord(maskedWord)

    print("Available letters:")
    printWord(availableLetters)
    print("Wrong guesses left:", (10 - wrongGuessCounter))
    print("Pick a letter or type exit to close the game: ")
    guess = input()
    if(guess == 'exit'):
        print("See you later!")
        break
    #valid guess
    elif (guess in availableLetters):
        availableLetters.remove(guess)
        if (guess in word):
            print("Correct!")
            correctGuessCounter = correctGuessCounter - 1
            changeWord(guess)
        else:
            print("Wrong letter!")
            wrongGuessCounter = wrongGuessCounter + 1
    #invalid guess
    elif (len(guess) > 1 or not guess.isalpha()):
        print("Pick one available letter.")
    #already used letter
    else:
        print("You already guessed that letter. Pick a different one!")

    #check win & lose conditions
    if(wrongGuessCounter == 10):
        print("You lost!")
        print("Word was:")
        printWord(word)
        break
    elif (correctGuessCounter == 0):
        printWord(word)
        print("You won!")
        break


import copy
import logging
import re
from typing import List

import numpy as np
from nltk.translate.bleu_score import sentence_bleu

from dataset1 import DB, DSV

from values1 import ALLOWED_DOMAINS

RE_ART = re.compile(r'\b(a|an|the)\b')
RE_PUNC = re.compile(r'[!"#$%&()*+,-./:;<=>?@\[\]\\^`{|}~_\']')

logger = logging.getLogger(__name__)

def MakeFractionalString(numerator: int, denominator: int) -> str:
    if (numerator == 0 and denominator == 0):
        fraction = np.nan
    else:
        fraction = numerator / denominator
    text = str(fraction) + " (" + str(numerator) + \
        " / " + str(denominator) + ")"
    return fraction, text

def NormalizeText(text: str):
    result = text.lower()
    result = RE_PUNC.sub(' ', result)
    result = RE_ART.sub(' ', result)
    result = ' '.join(result.split())
    return result

def Bleu(ref_tokens: List[str], hyp_tokens: List[str], n: int = 4):
    if (len(hyp_tokens) == 0):
        return 0

    weights = [1 / n] * n
    score = sentence_bleu([ref_tokens], hyp_tokens, weights)

    return score

def ComputePRF(tps: int, fps: int, fns: int):
    micro_recall, micro_recall_text = MakeFractionalString(tps, tps + fns)
    micro_precision, micro_precision_text = MakeFractionalString(
        tps, tps + fps)
    micro_f1 = 2 * micro_precision * micro_recall / \
        (micro_precision + micro_recall + 1e-10)

    return {
        "precision": micro_precision_text,
        "recall": micro_recall_text,
        "f1": micro_f1
    }

def ComputePRFFromDict(tp: dict, fp: dict, fn: dict):
    result = {}
    for domain in tp:
        result[domain] = ComputePRF(
            tp[domain],
            fp[domain],
            fn[domain]
        )
    return result

def ComputeHallucinationRecallFromDict(hallucination: dict,
                                       tp: dict,
                                       fn: dict):
    result = {}
    for domain in tp:
        _, result[domain] = MakeFractionalString(
            hallucination[domain], tp[domain] + fn[domain])
    return result

def ConvertDSVtoSV(dsv_list: List[DSV]) -> List[DSV]:
    l = []
    for dsv in dsv_list:
        x = DSV(None, dsv.slot, dsv.value)
        l.append(x)
    l = list(set(l))
    l.sort(key=lambda x: (x.slot, x.value))
    return l

def GetTP_FP_FN_Hallucination(gt_values: List[DSV],
                              ge_values: List[DSV],
                              used_domain: str,
                              used_entity_name: str,
                              db_raw: DB,
                              domain: str) -> dict:
    if (domain != "global"):
        gt_values_ = []
        for dsv in gt_values:
            d = dsv.domain
            if (d == domain):
                gt_values_.append(dsv)

        ge_values_ = []
        for dsv in ge_values:
            d = dsv.domain
            if (d == domain):
                ge_values_.append(dsv)
    else:
        gt_values_ = ConvertDSVtoSV(gt_values)
        ge_values_ = ConvertDSVtoSV(ge_values)

    gt_values_ = set(gt_values_)
    ge_values_ = set(ge_values_)

    if (not gt_values_):
        None

    hallucination_numerator = 0
    if (used_domain != None and used_entity_name != None):
        for dsv in ge_values_:
            slot = dsv.slot
            value = dsv.value
            # print("BRUH")
            # print(dsv)
            # print(db_raw.GetEntity(used_domain, used_entity_name).HasSlot(slot))
            # if (db_raw.GetEntity(used_domain, used_entity_name).HasSlot(slot)):
            #     print(db_raw.GetEntity(used_domain, used_entity_name).GetSlotValue(slot).GetValue())
            if (dsv in gt_values_
                    and db_raw.GetEntity(used_domain, used_entity_name).HasSlot(slot)
                    and db_raw.GetEntity(used_domain, used_entity_name).GetSlotValue(slot).GetValue() == value):
                hallucination_numerator += 1

    return {
        "hallucination_numerator": hallucination_numerator,
        "tp": len(gt_values_.intersection(ge_values_)),
        "fp": len(ge_values_.difference(gt_values_)),
        "fn": len(gt_values_.difference(ge_values_))
    }

class Metrics():
    def __init__(self) -> None:
        self.bleu = {
            "bleu1": 0,
            "bleu2": 0,
            "bleu3": 0,
            "bleu4": 0,
            "num_examples": 0
        }

        self.tp = {
            "global": 0
        }
        allowed_domains = list(ALLOWED_DOMAINS)
        allowed_domains.sort()
        for domain in allowed_domains:
            self.tp[domain] = 0

        self.fp = copy.deepcopy(self.tp)
        self.fn = copy.deepcopy(self.tp)
        self.copy = {
            "num_slot_matches": 0,
            "num_slot_mismatches": 0,
            "num_examples": 0
        }
        self.hallucination_numerator = copy.deepcopy(self.tp)

    def UpdateBleu(self, ref_text: str, hyp_text: str):
        ref_tokens = NormalizeText(ref_text).split()
        hyp_tokens = NormalizeText(hyp_text).split()
        for n in range(1, 5):
            self.bleu["bleu" + str(n)] += Bleu(ref_tokens, hyp_tokens, n=n)

        self.bleu["num_examples"] += 1

    def UpdateTP_FP_FN_Hallucination(self,
                                     gt_values: List[DSV],
                                     ge_values: List[DSV],
                                     used_domain: str,
                                     used_entity_name: str,
                                     db_raw: DB):
        for domain in self.tp:
            numbers = GetTP_FP_FN_Hallucination(
                gt_values,
                ge_values,
                used_domain,
                used_entity_name,
                db_raw,
                domain
            )
            self.tp[domain] += numbers["tp"]
            self.fp[domain] += numbers["fp"]
            self.fn[domain] += numbers["fn"]
            self.hallucination_numerator[domain] += numbers["hallucination_numerator"]

    def UpdateCopyScores(self,
                         ge_values: List[DSV],
                         used_domain: str,
                         used_entity_name: str,
                         db_raw: DB):
        if (used_domain != None):
            for dsv in ge_values:
                if (db_raw.GetEntity(used_domain, used_entity_name).HasSlot(dsv.slot)
                        and db_raw.GetEntity(used_domain, used_entity_name).GetSlotValue(dsv.slot).GetValue() == dsv.value):
                    self.copy["num_slot_matches"] += 1
                else:
                    self.copy["num_slot_mismatches"] += 1
            self.copy["num_examples"] += 1

    def Scores(self):
        results = {}

        # bleu
        if (self.bleu["num_examples"] > 0):
            for n in range(1, 5):
                self.bleu["bleu" + str(n)] /= self.bleu["num_examples"]
            results["bleu"] = self.bleu

        # prf
        results["prf"] = ComputePRFFromDict(
            self.tp,
            self.fp,
            self.fn
        )

        # hallucination
        results["hallucination_recall"] = ComputeHallucinationRecallFromDict(
            self.hallucination_numerator,
            self.tp,
            self.fn
        )

        # copy
        _, self.copy["precision"] = MakeFractionalString(
            self.copy["num_slot_matches"],
            self.copy["num_slot_matches"] + self.copy["num_slot_mismatches"]
        )
        _, self.copy["avg_slot_matches"] = MakeFractionalString(
            self.copy["num_slot_matches"],
            self.copy["num_examples"]
        )
        _, self.copy["avg_slot_mismatches"] = MakeFractionalString(
            self.copy["num_slot_mismatches"],
            self.copy["num_examples"]
        )
        results["copy"] = self.copy

        return results


# -*- coding: utf-8 -*-
"""
Created on Thu Aug 15 16:23:11 2019

@author: yllzxzyq
"""
N,M=map(int,input().split(" "))
L=[]
reN=[]
for i in range(N):
    line=list(map(int,input().split(" ")))
    reN.append(max(line))
    L.append(line)

reM=[]
for j in range(M):
    m=0
    for i in range(N):
        if m<=L[i][j]:
            m=L[i][j]
    reM.append(m)
print((sum(reM)+sum(reN)+N*M)*2)

算法题/360笔试第一题错解.py

360笔试第一题错解.py


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

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def hasPathSum(self, root, target):
        # write code here
        if not root: return False
        if not root.left and not root.right and root.val == target:
            return True
        flag1 = self.hasPathSum(root.left, target - root.val)
        flag2 = self.hasPathSum(root.right, target - root.val)
        # 即2个子树有一个为真则是满足要求的
        return flag1 or flag2


# coding: utf-8

from __future__ import unicode_literals

import json

from .base_object import BaseObject

class Item(BaseObject):
    """Box API endpoint for interacting with files and folders."""

    def update_info(self, data, etag=None):
        """Baseclass override.

        :param etag:
            If specified, instruct the Box API to perform the update only if
            the current version's etag matches.
        :type etag:
            `unicode` or None
        :return:
            The updated object.
            Return a new object of the same type, without modifying the original object passed as self.
            Construct the new object with all the default attributes that are returned from the endpoint.
        :rtype:
            :class:`BaseObject`
        """
        # pylint:disable=arguments-differ
        headers = {'If-Match': etag} if etag is not None else None
        return super(Item, self).update_info(data, headers=headers)

    def rename(self, name):
        """
        Rename the item to a new name.

        :param name:
            The new name, you want the item to be renamed to.
        :type name:
            `unicode`
        """
        data = {
            'name': name,
        }
        return self.update_info(data)

    def get(self, fields=None, etag=None):
        """Base class override.

        :param etag:
            If specified, instruct the Box API to get the info only if the current version's etag doesn't match.
        :type etag:
            `unicode` or None
        :returns:
            Information about the file or folder.
        :rtype:
            `dict`
        :raises: :class:`BoxAPIException` if the specified etag matches the latest version of the item.
        """
        # pylint:disable=arguments-differ
        headers = {'If-None-Match': etag} if etag is not None else None
        return super(Item, self).get(fields=fields, headers=headers)

    def copy(self, parent_folder):
        """Copy the item to the given folder.

        :param parent_folder:
            The folder to which the item should be copied.
        :type parent_folder:
            :class:`Folder`
        """
        url = self.get_url('copy')
        data = {
            'parent': {'id': parent_folder.object_id}
        }
        box_response = self._session.post(url, data=json.dumps(data))
        response = box_response.json()
        return self.__class__(
            session=self._session,
            object_id=response['id'],
            response_object=response,
        )

    def move(self, parent_folder):
        """
        Move the item to the given folder.

        :param parent_folder:
            The parent `Folder` object, where the item will be moved to.
        :type parent_folder:
            `Folder`
        """
        data = {
            'parent': {'id': parent_folder.object_id}
        }
        return self.update_info(data)

    def get_shared_link(self, access=None, etag=None):
        """Get a shared link for the item with the given access permissions.

        :param access:
            Determines who can access the shared link. May be open, company, or collaborators. If no access is
            specified, the default access will be used.
        :type access:
            `unicode` or None
        :param etag:
            If specified, instruct the Box API to create the link only if the current version's etag matches.
        :type etag:
            `unicode` or None
        :returns:
            The URL of the shared link.
        :rtype:
            `unicode`
        :raises: :class:`BoxAPIException` if the specified etag doesn't match the latest version of the item.
        """
        data = {
            'shared_link': {} if not access else {
                'access': access
            }
        }
        item = self.update_info(data, etag=etag)
        return item.shared_link['url']

    def remove_shared_link(self, etag=None):
        """Delete the shared link for the item.

        :param etag:
            If specified, instruct the Box API to delete the link only if the current version's etag matches.
        :type etag:
            `unicode` or None
        :returns:
            Whether or not the update was successful.
        :rtype:
            `bool`
        :raises: :class:`BoxAPIException` if the specified etag doesn't match the latest version of the item.
        """
        data = {'shared_link': None}
        item = self.update_info(data, etag=etag)
        return item.shared_link['url']

    def delete(self, params=None, etag=None):
        """Delete the item.

        :param params:
            Additional parameters to send with the request.
        :type params:
            `dict`
        :param etag:
            If specified, instruct the Box API to delete the item only if the current version's etag matches.
        :type etag:
            `unicode` or None
        :returns:
            Whether or not the delete was successful.
        :rtype:
            `bool`
        :raises: :class:`BoxAPIException` if the specified etag doesn't match the latest version of the item.
        """
        headers = {'If-Match': etag} if etag is not None else None
        return super(Item, self).delete(params, headers)


from flask import Flask, request, redirect, render_template, abort, make_response, jsonify, url_for
from flask.wrappers import Response
from werkzeug.exceptions import HTTPException
from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, SelectField
from wtforms.validators import DataRequired
from nltk import word_tokenize, FreqDist, RegexpTokenizer
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import sqlite3
import string
from wiki import *

DB = 'app.db'

app = Flask(__name__)
app.config.from_pyfile('config.py')

# Forms
class searchForm(FlaskForm):
    searchText = StringField('Search')
    actionUrl = '/search_results'

class reviewForm(FlaskForm):
    name = StringField('Name', validators=[DataRequired()])
    city = SelectField('City', validators=[DataRequired()], validate_choice=False)
    state = SelectField('State', validate_choice=False)
    country = SelectField('Country', validators=[DataRequired()])
    review = TextAreaField('Review', validators=[DataRequired()])

class serviceForm(FlaskForm):
    inputText = TextAreaField('Input Text', validators=[DataRequired()])

# Featured locations for home page
class FeaturedLoc:
    def __init__(self, city, state, country):
        self.city = city
        self.state = state
        self.country = country
        self.img = '/static/placeholder.jpg'
        self.page = '/location?city=' + city.replace(' ', '%20') + '&state=' \
            + state.replace(' ', '%20') + '&country=' + country.replace(' ', '%20')

# Get sentiment of text
def getSentiment(compound):
    if not isinstance(compound, float):
        return 0
    if compound <= -0.05:
        return 'negative'
    elif compound < 0.05:
        return 'neutral'
    else:
        return 'positive'

# Get word count of text
def getWordCount(text):
    wordList = text.split(' ')
    count = 0
    for word in wordList:
        if word != '':
            count = count + 1
    return count

# Get Top x most frequent words in the text
def getMostFrequent(text, count):
    tokenizer = RegexpTokenizer(r'[A-Za-z]+')
    tokens = tokenizer.tokenize(text)
    frequency = FreqDist(tokens)
    return frequency.most_common(count)

# Execute SELECT Query
def execSelectQuery(dbName, query, qParams):
    conn = sqlite3.connect(dbName)
    cur = conn.cursor()
    if qParams != None:
        result = cur.execute(query, qParams).fetchall()
    else:
        result = cur.execute(query).fetchall()
    conn.close()
    return result

# Execute INSERT Query
def execInsertQuery(dbName, query, qParams):
    conn = sqlite3.connect(dbName)
    cur = conn.cursor()
    cur.execute(query, qParams)
    conn.commit()
    conn.close()

# Get search term for a given location
def getWikiSearchTerm(id):
    return execSelectQuery(DB, 'SELECT searchTerm FROM locations WHERE id = (?)', id)

# Navigation Bar - Label : Route
nav = {
    'Home': '/',
    'Browse Locations': '/browse',
    'Submit a Review': '/review'
}

serviceUrl = '/service'
searchResultsUrl = '/search_results'

# Home Page
@app.route('/')
def home():
    searchBox = searchForm()
    pics = [('find.png', '/browse'), ('share.png', '/review')]

    # TODO: Make function to choose random featured locations and retrieve their data
    #       from DB.
    # Each location needs city, state, country, img link, page link
    featuredLocs = [
        FeaturedLoc('Corvallis', 'OR', 'United States'), \
        FeaturedLoc('Redmond', 'WA', 'United States'), \
        FeaturedLoc('Grays Point', 'NSW', 'Australia')
        ]

    for loc in featuredLocs:
        locationId = execSelectQuery(DB, 'SELECT id FROM locations WHERE city = (?)', (loc.city,))[0]
        print('locationId is ' + str(locationId), flush=True)
        searchTerm = getWikiSearchTerm(locationId)
        loc.img = getImgUrl(searchTerm)

    return render_template(
        'home.html',
        nav=nav,
        searchBox=searchBox,
        serviceUrl=serviceUrl,
        featuredLocs=featuredLocs,
        pics=pics
    )

# Initialize dropdown choices
def initializeDropdown(field):
    choices = []
    queryResults = execSelectQuery(DB, 'SELECT DISTINCT ' + field + ' FROM locations', None)
    for loc in queryResults:
        choices.append((loc[0], loc[0]))
    choices.sort()
    choices.insert(0, ('', ''))             # Insert blank at top of menu
    return choices

# Submit a Review Page
@app.route('/review')
def review():
    form = reviewForm()
    form.city.choices = initializeDropdown('city')
    form.state.choices = initializeDropdown('state')
    form.country.choices = initializeDropdown('country')
    return render_template(
        'review.html',
        nav=nav,
        serviceUrl=serviceUrl,
        form=form
    )

# This routing handles submission of user reviews
@app.route('/process_submission', methods=['POST'])
def process():
    form = reviewForm()

    # Retrieve id of location that the user specified
    city = form.city.data
    state = form.state.data
    country = form.country.data
    locationId = execSelectQuery(DB, 'SELECT id FROM locations WHERE city = (?) AND state = (?) \
        AND country = (?)', (city, state, country))

    # Check for location validity
    if locationId == []:
        print('ERROR: Location with this city/state/country combination not found')
        abort(404)

    # Add review to database and close connection
    executeInsertQuery("INSERT INTO reviews (locationId, name, review) VALUES (?, ?, ?)", \
        (locationId[0][0], form.name.data, form.review.data))

    redirectUrl = '/location?city=' + city.replace(' ', '%20') + '&state=' \
            + state.replace(' ', '%20') + '&country=' + country.replace(' ', '%20')

    return redirect(redirectUrl, code=303)

# Search Results Page
@app.route('/search_results', methods=['GET', 'POST'])
def search():
    form = searchForm()

    # Initialize search text
    searchText = form.searchText.data
    searchText = '%' + searchText + '%'

    # Perform search of cities, states and countries columns
    # TODO: Make this work with full state name. Currently works only with state abbr.
    # ie, 'OR' returns a match, whereas 'Oregon' does not
    queries = (
        'SELECT * FROM locations WHERE city LIKE (?)',
        'SELECT * FROM locations WHERE state LIKE (?)',
        'SELECT * FROM locations WHERE country LIKE (?)'
    )
    cities = execSelectQuery(DB, queries[0], (searchText,))
    states = execSelectQuery(DB, queries[1], (searchText,))
    countries = execSelectQuery(DB, queries[2], (searchText,))

    # Build results list
    rawResults = cities + states + countries
    resultsWithLink = []
    for locationId, city, state, country, searchTerm in rawResults:
        url = '/location?city=' + city.replace(' ', '%20') + '&state=' \
            + state.replace(' ', '%20') + '&country=' + country.replace(' ', '%20')
        imgUrl = getImgUrl(searchTerm)
        resultsWithLink.append((locationId, city, state, country, url, imgUrl))

    # TODO: Remove duplicates from list (eg, New York City, New York would appear twice if
    # searching for 'New York'. This is unwanted behavior.)

    return render_template(
        'search_results.html',
        results=resultsWithLink,
        nav=nav,
        serviceUrl=serviceUrl,
    )

# Browse Page
@app.route('/browse')
def browse():
    locations = execSelectQuery(DB, 'SELECT * FROM locations', None)

    # Add link to locations
    locationsWithLink = []
    for locationId, city, state, country, searchTerm in locations:
        url = '/location?city=' + city.replace(' ', '%20') + '&state=' \
            + state.replace(' ', '%20') + '&country=' + country.replace(' ', '%20')
        imgUrl = getImgUrl(searchTerm)
        locationsWithLink.append((locationId, city, state, country, url, imgUrl))

    return render_template(
        'browse.html',
        nav=nav,
        serviceUrl=serviceUrl,
        locations=locationsWithLink)

# Location Page
@app.route('/location', methods=['GET', 'POST'])
def location():
    submitURL = nav.get('Submit a Review')
    city = request.args.get('city')
    state = request.args.get('state')
    country = request.args.get('country')

    # Get locationId based on URL query string parameters
    query = 'SELECT id FROM locations WHERE city = (?)'
    locationId = execSelectQuery(DB, query, (city,))[0]

    # Get all reviews for this location and analyze their sentiment scores
    query = 'SELECT review, name, id FROM reviews WHERE locationId = (?)'
    reviews = execSelectQuery(DB, query, locationId)

    concatReviews = ''
    for review in reviews:
        concatReviews = concatReviews + review[0] + ' '
    scores = SentimentIntensityAnalyzer().polarity_scores(concatReviews)
    sentiment = getSentiment(scores['compound'])
    reviewCount = len(reviews)

    # TODO: Fix this
    reviews.reverse()

    # TODO: Create function to display location name properly

    # Get information from Wikipedia scraper services
    searchTerm = getWikiSearchTerm(locationId)
    locationText = getLocationText(searchTerm)
    imgUrl = getImgUrl(searchTerm)

    return render_template(
        'location.html',
        nav=nav,
        serviceUrl=serviceUrl,
        city=city,
        locationText=locationText,
        submitURL=submitURL,
        scores=scores,
        sentiment=sentiment,
        reviewCount=reviewCount,
        reviews=reviews,
        imgUrl=imgUrl
    )

# Delete a review
@app.route('/deleteReview', methods=['POST'])
def deleteReview():
    # TODO: Validate id
    id = request.json['id']
    conn = sqlite3.connect('app.db')
    cur = conn.cursor()
    success = cur.execute('DELETE FROM reviews WHERE id = (?)', (id,))
    conn.commit()
    conn.close()
    return make_response({'success':True, 'id':id}, 200)

# Update a review
@app.route('/update_review', methods=['POST'])
def updateReview():
    # TODO: Validate id
    id = request.json['id']
    newReview = request.json['newReview']
    conn = sqlite3.connect('app.db')
    cur = conn.cursor()
    success = cur.execute('UPDATE reviews SET review = (?) WHERE id = (?)', (newReview, id))
    conn.commit()
    conn.close()
    return make_response({'success':True, 'id':id, 'newReview':newReview}, 200)

# Sentiment/Text Analysis GUI
# See https://github.com/cjhutto/vaderSentiment for more information on how the
# VADER tool (included in nltk library) calculates sentiment analysis scores
@app.route('/service', methods=['GET', 'POST'])
def service():
    form = serviceForm()

    descriptions = {
        'neg': 'Proportion of the text that has negative sentiment',
        'neu': 'Proportion of the text that is neutral',
        'pos': 'Proportion of the text that has positive sentiment',
        'compound': 'A normalized, weighted composite score for the text overall. Ranges \
                    between -1 (most negative) to 1 (most positive)',
        'sentiment': 'Overall sentiment, based on compound score. Below -0.05 is negative',
        'word_count': 'Word Count',
        'most_frequent': 'Most frequently used words and number of appearances in the text'
    }
    displayResults = False
    txtInput = ''
    scores = {
        'neg': '-',
        'neu': '-',
        'pos': '-',
        'compound': '-'
    }
    sentiment = '-'
    wordCount = '-'
    mostFrequent = '-'

    if request.method == 'POST':
        displayResults = True
        txtInput = form.inputText.data
        scores = SentimentIntensityAnalyzer().polarity_scores(txtInput)
        sentiment = getSentiment(scores.get('compound'))
        if sentiment == 0:
            sentiment = 'ERROR'
        wordCount = getWordCount(txtInput)
        mostFrequent = getMostFrequent(txtInput, 5)

    return render_template(
        'service.html',
        nav=nav,
        serviceUrl=serviceUrl,
        form=form,
        displayResults=displayResults,
        txtInput=txtInput,
        scores=scores,
        sentiment=sentiment,
        wordCount=wordCount,
        mostFrequent=mostFrequent,
        descriptions=descriptions
    )

# Error handler for GUI
@app.errorhandler(404)
def pageNotFound(e):
    return render_template('404.html')

# API implementation
@app.route('/api', methods=['GET', 'POST'])
def api():
    # Check for request type, content type
    if request.method == 'GET':
        return make_response({'error': 'Method Not Allowed'}, 405)
    if request.content_type != 'application/json':
        return make_response({'error': 'Unsupported Media Type'}, 415)

    else:
        # Check for request body in correct format
        try:
            txtInput = request.json['text']
        except:
            return make_response({'error': 'Bad Request'}, 400)

        # Create API response
        scores = SentimentIntensityAnalyzer().polarity_scores(txtInput)
        sentiment = getSentiment(scores.get('compound'))
        if sentiment == 0:
            sentiment = 'ERROR'
        wordCount = getWordCount(txtInput)
        mostFrequent = getMostFrequent(txtInput, 5)
        return jsonify(sentiment=sentiment,
                        compound=scores.get('compound'),
                        pos=scores.get('pos'),
                        neu=scores.get('neu'),
                        neg=scores.get('neg'),
                        wordCount=wordCount,
                        mostFrequent=mostFrequent,
                        )


inverted_index = dict()

AND_OPERATOR = 'AND'
OR_OPERATOR = 'OR'
NOT_OPERATOR = 'NOT'

def or_operation(query_words):
    result = []
    for token in query_words:
        if inverted_index[token]:
            result.extend(inverted_index[token])
    return set(result)

def and_operator(query_words):
    pages = []
    for token in query_words:
        if token in inverted_index:
            if inverted_index[token]:
                pages.append(set(inverted_index[token]))
    if len(pages) != 0:
        result = pages[0]
        for page in pages:
            result &= page
        return result
    else:
        return 0

def not_operator(query_words):
    pp = []
    notpp = []
    pp = inverted_index[query_words[0]]
    query_words.pop(0)
    for token in query_words:
        if inverted_index[token]:
            notpp = inverted_index[token]
    for el in notpp:
        if el in pp:
            pp.remove(el)
    return pp

def search(operator, query_words):
    if operator == OR_OPERATOR:
        query_words.remove('or')
        return or_operation(query_words)
    elif operator == AND_OPERATOR:
        query_words.remove('and')
        return and_operator(query_words)
    elif operator == NOT_OPERATOR:
        query_words.remove('not')
        return not_operator(query_words)

with open('inverted_index.txt', encoding='utf-8') as input_file:
    lines = input_file.readlines()
    for line in lines:
        key = line.rstrip().split(' ')[0]
        values = line.rstrip().split(' ')[1:]
        inverted_index[key] = values

if __name__ == '__main__':
    query = input('Введите запрос:\n')
    args = query.split(' ')
    if len(args) > 1:
        operator = args[0].upper()
    else:
        operator = OR_OPERATOR

    print(search(operator, args[0:]))


import urllib.request, json

if __name__ == '__main__':
    url = "http://192.168.1.140:8001"
    method = "POST"
    headers = {"Content-Type" : "application/json"}

    # PythonオブジェクトをJSONに変換する
    obj = {'0':{"x" : 0.0, 'y':0.0, 'theta':0.0}, 'stop_flg': 0, 'photo_flg':1, 'dest_x':0.0, 'dest_y':0.0}
    json_data = json.dumps(obj).encode("utf-8")

    # httpリクエストを準備してPOST
    request = urllib.request.Request(url, data=json_data, method=method, headers=headers)
    with urllib.request.urlopen(request) as response:
        response_body = response.read().decode("utf-8")


import cv2
import numpy as np

circle_filename = "white-circle-filled.png"
ring_filename = "white-ring.png"
circle = cv2.cvtColor(cv2.imread(circle_filename), cv2.COLOR_RGB2GRAY)
ring = cv2.cvtColor(cv2.imread(ring_filename), cv2.COLOR_RGB2GRAY)

start_scale = 1.0
end_scale = 0.05
scale_step = 0.005

num_steps = int( (start_scale - end_scale)/scale_step )
print(num_steps)

step_count = 0
out = np.zeros_like(circle, dtype=np.uint8)
fr_r = 0
to_r = 0
orig_w = circle.shape[0]
scl_w = 0
s = start_scale
for step_count in range(num_steps):
#for s in range(start_scale, end_scale - scale_step, -scale_step):
    scl_w = int(orig_w*s)
    fr_r = int( (orig_w - scl_w)/2. )
    to_r = fr_r + scl_w
    scaled = cv2.resize(circle, (scl_w, scl_w))
    out[:] = 0
    out[fr_r:to_r, fr_r:to_r] = scaled
    cv2.imwrite("circle_images/scaled-%010d-%s"%\
                (num_steps - step_count, circle_filename),
                out)
    scaled = cv2.resize(ring, (scl_w, scl_w))
    out[:] = 0
    out[fr_r:to_r, fr_r:to_r] = scaled
    cv2.imwrite("ring_images/scaled-%010d-%s"%\
                (num_steps - step_count, ring_filename),
                out)
    s -= scale_step


from src.lambda_handler import LambdaHandler
from src.powerball_response import PowerballResponse

def test_handle_event(monkeypatch):

    handler = LambdaHandler()
    monkeypatch.setattr(handler, "powerball_service", MockPowerballService)

    response = handler.handle_event({}, {})
    assert response["statusCode"] == 200
    assert response["headers"]["Content-Type"] == "application/json"
    assert response["body"] == '{"numbers": [1, 2, 3, 4, 5, 6], "powerball": 7}'

class MockPowerballService:
    def generate_random_powerball():
        return PowerballResponse([1, 2, 3, 4, 5, 6], 7)


from heapq import heappush, heappop, heapify

class Solution(object):

    def leastInterval(self, tasks, n):
        hashmap = dict()
        heap = []
        heapify(heap)
        count = 0
        for t in tasks:
            while (len(heap) > 0 and heap[0][0] < count - n):
                hashmap.pop(heappop(heap)[1])
            count = max(count+1, hashmap.get(t, float("-inf")) + n + 1)
            hashmap[t] = count
            heappush(heap, (hashmap[t], t))
        return count


from datetime import datetime
import json
from math import sqrt

def convert_time_format(time_str):
    time_str = time_str[-12:-4]
    time_obj = datetime.strptime(time_str, '%H:%M:%S')
    hour_val = time_obj.hour + time_obj.minute / 60.0
    return hour_val

def time_duration(time1, time2):
    if time2 >= time1:
        return time2 - time1
    else:
        return 24 - time1 + time2

with open('acndata_sessions_jpl_dec2020_may2023.json', 'r') as f:
    data = json.load(f)

mapping = {
    'Mon': [],
    'Tue': [],
    'Wed': [],
    'Thu': [],
    'Fri': [],
    'Sat': [],
    'Sun': []
}

for item in data['_items']:
    weekday = item['connectionTime'][0:3];
    # print(weekday)
    arrival_hour = convert_time_format(item['connectionTime'])
    unplug_hour = convert_time_format(item['disconnectTime'])
    connection_time = time_duration(arrival_hour, unplug_hour)
    kwh = item['kWhDelivered']
    feature = [arrival_hour, connection_time, kwh]
    mapping[weekday].append(feature)

# for weekday,sessions in mapping.items():
#     print(weekday)
#     if(weekday == 'Mon'):print(sessions)
# print(mapping)
# print(data)

with open('Mon.json', 'w') as M:
    json.dump(mapping['Mon'], M)

with open('Tue.json', 'w') as T:
    data = json.dump(mapping['Tue'], T)

with open('Wed.json', 'w') as W:
    data = json.dump(mapping['Wed'], W)

with open('Thu.json', 'w') as Th:
    data = json.dump(mapping['Thu'], Th)

with open('Fri.json', 'w') as f:
    data = json.dump(mapping['Fri'], f)

with open('Sat.json', 'w') as S:
    data = json.dump(mapping['Sat'], S)

with open('Sun.json', 'w') as Su:
    data = json.dump(mapping['Sun'], Su)


class Solution:
    def maxProfit(self, prices):
        '''
        可以交易多次，没有冷冻期
        :param prices:
        :return:
        '''
        res = 0
        N = len(prices)
        if N <= 1:
            return 0
        for i in range(1,N):
            if prices[i-1] < prices[i]:
                res += prices[i] - prices[i-1]
        return res


import sys
import requests
import pandas as pd
import pymysql
import collections
from pymongo import MongoClient
con = pymysql.connect(host='localhost', unix_socket='/tmp/mysql.sock',user='root', passwd="", db='NBA')
mysql = con.cursor(pymysql.cursors.DictCursor)
client = MongoClient()
db = client.sportsvu # MongoDB database: sportsvu, collection: requests
# Added command line parameter for cutoff game_id so that I can run multiple scripts in parallel without game_id overlap
mysql.execute("""select game_id from SportsVuGameIdsUnique where not exists (select * from SportsVuGameIdsStoredInMongo where SportsVuGameIdsStoredInMongo.game_id = SportsVuGameIdsUnique.game_id) and game_id > "{game_id}" order by game_id asc """.format(game_id=sys.argv[1]))
for row in mysql.fetchall():
    game_id=row['game_id']
    for event_id in range(1,1000):
        url = "http://stats.nba.com/stats/locations_getmoments/?eventid={event_id}&gameid={game_id}".format(event_id=event_id,game_id=game_id)
        response = requests.get(url)
        if response.status_code == 200:
            composite_key = collections.OrderedDict()
            composite_key['game_id']=game_id
            composite_key['event_id']=event_id
            json = response.json()
            json['_id']=composite_key
            db.requests.insert_one(json)
    mysql.execute("""insert into SportsVuGameIdsStoredInMongo(game_id) values("{game_id}")""".format(game_id=game_id))
    con.commit()
    print(game_id)
con.close()


from xml.sax.saxutils import quoteattr
import requests
template = '<build><buildType id={id}/></build>'

url = "http://localhost:9090/httpAuth/app/rest/buildQueue/"
headers = {'Content-Type': 'application/xml'}
build_id = 'MyDeal_Mydealbuild1'
data = template.format(id=quoteattr(build_id))

r = requests.post(url, headers=headers, data=data, auth=("xxx", "123@xxx"), timeout=10)
print(r)