from ..alarm_item import AlarmItem, AlarmSeverity
from ..alarm_table_view import AlarmTableType, AlarmTableViewWidget
from qtpy.QtCore import QEvent, QItemSelectionModel, QModelIndex
import pytest

@pytest.fixture(scope="function")
def active_alarm_table_view(tree_model, mock_kafka_producer):
    """Return an empty alarm table view for testing"""
    return AlarmTableViewWidget(tree_model, mock_kafka_producer, "TEST_TOPIC", AlarmTableType.ACTIVE, lambda x: x)

@pytest.fixture(scope="function")
def acknowledged_alarm_table_view(tree_model, mock_kafka_producer):
    """Return an empty alarm table view for testing"""
    return AlarmTableViewWidget(tree_model, mock_kafka_producer, "TEST_TOPIC", AlarmTableType.ACKNOWLEDGED, lambda x: x)

def test_create_and_show(qtbot, active_alarm_table_view):
    """A simple check that the alarm table view will init and show without any errors"""
    qtbot.addWidget(active_alarm_table_view)
    with qtbot.waitExposed(active_alarm_table_view):
        active_alarm_table_view.show()

def test_update_counter_label(alarm_item, active_alarm_table_view, acknowledged_alarm_table_view):
    """Verify alarm item counts are updated accurately"""
    # Add one active alarm and update the counts. Should be 1 for active and 0 for acknowledged
    active_alarm_table_view.alarmModel.append(alarm_item)
    active_alarm_table_view.update_counter_label()
    assert active_alarm_table_view.alarm_count_label.text() == "Active Alarms: 1"

    # Now add an acknowledged alarm. Counts should now be 1 for both
    acknowledged_alarm_table_view.alarmModel.append(alarm_item)
    assert acknowledged_alarm_table_view.alarm_count_label.text() == "Acknowledged Alarms: 1"

def test_context_menu_create_and_show(qtbot, active_alarm_table_view):
    """Quick check to confirm that both context menus on this view init and show without any errors"""
    qtbot.addWidget(active_alarm_table_view)
    active_alarm_table_view.alarm_context_menu_event(ev=QEvent(QEvent.Type.ContextMenu))
    with qtbot.waitExposed(active_alarm_table_view.alarm_context_menu):
        active_alarm_table_view.alarm_context_menu.show()

def test_send_acknowledgement(qtbot, monkeypatch, active_alarm_table_view, mock_kafka_producer):
    """Test that when a user acknowledges an alarm, the message send to kafka is as expected"""
    qtbot.addWidget(active_alarm_table_view)
    # Create an alarm with a severity of major
    alarm_item = AlarmItem("TEST:PV", path="/path/to/TEST:PV", alarm_severity=AlarmSeverity.MAJOR)
    active_alarm_table_view.alarmModel.append(alarm_item)
    active_alarm_table_view.tree_model.added_paths["TEST:PV"] = ["/path/to/TEST:PV"]

    # Monkeypatch some qt methods to return our alarm as the selected index
    model_index = QModelIndex()
    indices = [model_index]
    monkeypatch.setattr(QItemSelectionModel, "selectedRows", lambda x: indices)
    monkeypatch.setattr(model_index, "row", lambda: 0)

    # Send the acknowledgement, and verify the message we are sending to kafka looks the way we want it to
    active_alarm_table_view.send_acknowledge_action(True)
    # Setting the correct topic, path, and acknowledgement command is all we need to acknowledge an alarm
    assert mock_kafka_producer.topic == "TEST_TOPICCommand"
    assert mock_kafka_producer.key == "command:/path/to/TEST:PV"
    assert "command" in mock_kafka_producer.values
    assert mock_kafka_producer.values["command"] == "acknowledge"

def test_send_unacknowledgement(qtbot, monkeypatch, acknowledged_alarm_table_view, mock_kafka_producer):
    """Similar to the send acknowledgment test, except we now deal with the unacknowledge action and table"""
    qtbot.addWidget(acknowledged_alarm_table_view)
    # Create an alarm that has been acknowledged
    alarm_item = AlarmItem("TEST:PV", path="/path/to/TEST:PV", alarm_severity=AlarmSeverity.MAJOR_ACK)
    acknowledged_alarm_table_view.alarmModel.append(alarm_item)
    acknowledged_alarm_table_view.tree_model.added_paths["TEST:PV"] = ["/path/to/TEST:PV"]

    # Monkeypatch some qt methods to return our alarm as the selected index
    model_index = QModelIndex()
    indices = [model_index]
    monkeypatch.setattr(QItemSelectionModel, "selectedRows", lambda x: indices)
    monkeypatch.setattr(model_index, "row", lambda: 0)

    # Send the unacknowledgement, and verify the message we are sending to kafka looks the way we want it to
    acknowledged_alarm_table_view.send_acknowledge_action(False)
    # Setting the correct topic, path, and acknoledgement command is all we need to acknowledge an alarm
    assert mock_kafka_producer.topic == "TEST_TOPICCommand"
    assert mock_kafka_producer.key == "command:/path/to/TEST:PV"
    assert "command" in mock_kafka_producer.values
    assert mock_kafka_producer.values["command"] == "unacknowledge"


from fastapi import APIRouter, Request

router = APIRouter()

@router.get("/")
async def home(req: Request):
    return "fastapi"

# @router.get("/items/{item_id}")
# def read_item(item_id: int, q: str | None):
#     return {"item_id": item_id, "q": q}


import pygame, sys
from button import Button
import random
pygame.init()

SCREEN = pygame.display.set_mode((1280, 720))
pygame.display.set_caption("Menu")

#variables
BG = pygame.image.load("Background.png")
blue = pygame.image.load("BlueSprite.png")
cyan = pygame.image.load("CyanSprite.png")
green = pygame.image.load("GreenSprite.png")
orange = pygame.image.load("OrangeSprite.png")
pink = pygame.image.load("PinkSprite.png")
red = pygame.image.load("RedSprite.png")
yellow = pygame.image.load("YellowSprite.png")
direction = 1
clock = pygame.time.Clock()
player_rect_blue = blue.get_rect(midbottom = (80,100))
player_rect_cyan = cyan.get_rect(midbottom = (80,200))
player_rect_green = green.get_rect(midbottom = (80,300))
player_rect_orange = orange.get_rect(midbottom = (80,400))
player_rect_pink = pink.get_rect(midbottom = (80,500))
player_rect_red = red.get_rect(midbottom = (80,600))
player_rect_yellow = yellow.get_rect(midbottom = (80,700))

#definition for the font
def get_font(size): # Returns Press-Start-2P in the desired size
    return pygame.font.Font("font.ttf", size)

#play screen
def play():
    while True:
        PLAY_MOUSE_POS = pygame.mouse.get_pos()
        keys = pygame.key.get_pressed()
        SCREEN.fill("black")
        speed_x = 1
        if keys[pygame.K_SPACE]:
            print('jump')

        PLAY_TEXT = get_font(45).render("This is the PLAY screen.", True, "White")
        PLAY_RECT = PLAY_TEXT.get_rect(center=(640, 260))

        SCREEN.blit(PLAY_TEXT, PLAY_RECT)
        SCREEN.blit(blue, player_rect_blue)
        SCREEN.blit(cyan, player_rect_cyan)
        SCREEN.blit(green, player_rect_green)
        SCREEN.blit(orange, player_rect_orange)
        SCREEN.blit(pink, player_rect_pink)
        SCREEN.blit(red, player_rect_red)
        SCREEN.blit(yellow, player_rect_yellow)
        direction = 1
        direction *=-1
        #if player_rect_blue.right >=80 or player_rect_blue.right >=1280:
            #player_rect_blue.x = random.randint(0,8) * direction
            #player_rect_blue.y = random.randint(0.8) * direction
                #if player_rect_blue.bottom >=720:
                    #player_rect_blue.x +=1
                    #player_rect_blue.y = 0

        PLAY_BACK = Button(image=None, pos=(640, 460),
                            text_input="BACK", font=get_font(75), base_color="White", hovering_color="Green")

        PLAY_BACK.changeColor(PLAY_MOUSE_POS)

        PLAY_BACK.update(SCREEN)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                if PLAY_BACK.checkForInput(PLAY_MOUSE_POS):
                    return
            if event.type == pygame.KEYDOWN:
                print('key down')
            if event.type == pygame.KEYUP:
                print("key up")

        pygame.display.update()

#option screen
def options():
    while True:
        OPTIONS_MOUSE_POS = pygame.mouse.get_pos()

        SCREEN.fill("white")

        OPTIONS_TEXT = get_font(45).render("This is the OPTIONS screen.", True, "Black")
        OPTIONS_RECT = OPTIONS_TEXT.get_rect(center=(640, 260))
        SCREEN.blit(OPTIONS_TEXT, OPTIONS_RECT)

        OPTIONS_BACK = Button(image=None, pos=(640, 460),
                            text_input="BACK", font=get_font(75), base_color="Black", hovering_color="Green")

        OPTIONS_BACK.changeColor(OPTIONS_MOUSE_POS)
        OPTIONS_BACK.update(SCREEN)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                if OPTIONS_BACK.checkForInput(OPTIONS_MOUSE_POS):
                    return

        pygame.display.update()

#main menu screen
while True:
    SCREEN.blit(BG, (0, 0))

    MENU_MOUSE_POS = pygame.mouse.get_pos()

    MENU_TEXT = get_font(100).render("TEAM ORANGE", True, "#b68f40")
    MENU_RECT = MENU_TEXT.get_rect(center=(640, 100))

    PLAY_BUTTON = Button(image=pygame.image.load("Play Rect.png"), pos=(640, 250),
                            text_input="PLAY", font=get_font(75), base_color="#d7fcd4", hovering_color="Black")
    OPTIONS_BUTTON = Button(image=pygame.image.load("Options Rect.png"), pos=(640, 400),
                            text_input="OPTIONS", font=get_font(75), base_color="#d7fcd4", hovering_color="Black")
    QUIT_BUTTON = Button(image=pygame.image.load("Quit Rect.png"), pos=(640, 550),
                            text_input="QUIT", font=get_font(75), base_color="#d7fcd4", hovering_color="Black")

    SCREEN.blit(MENU_TEXT, MENU_RECT)

    for button in [PLAY_BUTTON, OPTIONS_BUTTON, QUIT_BUTTON]:
        button.changeColor(MENU_MOUSE_POS)
        button.update(SCREEN)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            if PLAY_BUTTON.checkForInput(MENU_MOUSE_POS):
                play()
            if OPTIONS_BUTTON.checkForInput(MENU_MOUSE_POS):
                    options()
            if QUIT_BUTTON.checkForInput(MENU_MOUSE_POS):
                pygame.quit()
                sys.exit()

    pygame.display.update()


from dash.dependencies import Input, Output
import plotly.graph_objs as go

import datetime
import time
from app import app
import pandas as pd
import joblib

df_dim = pd.read_csv('data/Dimension.csv', encoding='latin-1')
model = joblib.load("RF_model.pkl")

@app.callback(Output('output', component_property='children'),
              [Input('date1', 'date'),
               Input('Time', component_property='value'),
               Input('predict-dropdown', component_property='value'),
               Input('button', 'n_clicks')])
def update_data(date, tim, state, n_clicks):
    # date = date.strftime('%Y/%m/%d')
    if n_clicks is not None:
        Lat = df_dim.loc[df_dim['State'] == state, 'Latitude'].values[0]
        Long = df_dim.loc[df_dim['State'] == state, 'Longitude'].values[0]
        ts = datetime.datetime.strptime(date+' '+tim, '%Y-%m-%d %H:%M:%S')
        ts = int(time.mktime(ts.timetuple()))
        d = {'c1': [ts], 'c2': [Lat], 'c3': [Long]}
        x = pd.DataFrame(data=d)

        # model = joblib.load("model.pkl")
        answer = model.predict(x)[0]
        return "As per the calculations of our model, there is a probability of an earthquake occurring of magnitude {} and depth {} km".format(answer[0], answer[1])

# ############################### -------  EARTHQUAKE CALLBACKS  ------- ######################################## #

df_EQ = pd.read_csv('data/Consolidated_EQ.csv', encoding='latin-1')
df_EQ['Date'] = pd.to_datetime(df_EQ['Date'], errors='coerce')

# callback for Earthquake data table changing as per data picker
@app.callback(Output('datatable-Earthquake', 'data'),
              [Input('date-picker-earthquake', 'start_date'),
               Input('date-picker-earthquake', 'end_date')])
def update_data_1(start_date, end_date):
    df2 = df_EQ[(df_EQ['Date'] > start_date) & (df_EQ['Date'] < end_date)]
    df2 = df2.to_dict("rows")
    return df2

# callback for Earthquake Graph as per data table
@app.callback(Output('EarthquakeGraph', 'figure'),
              [Input('date-picker-earthquake', 'start_date'),
               Input('date-picker-earthquake', 'end_date')])

def update_graph_1(start_date, end_date):
    df2 = df_EQ[(df_EQ['Date'] > start_date) & (df_EQ['Date'] < end_date)]
    return {
        'data': [go.Scatter(
            x=df2['Date'],
            y=df2['Magnitude'],
            mode='markers'
        )],
        'layout': {
            'height': 225,
            'margin': {'l': 20, 'b': 30, 'r': 30, 't': 10},
            'xaxis':{
                'title': 'Date'
                },
            'yaxis': {
                'title': 'Magnitude',
                'side': 'right'
            }
        }
    }

# ############################### -------  HEALTH STATISTICS CALLBACKS  ------- ###################################### #

df_health = pd.read_csv('data/Delhi Health WP data 2017.csv', encoding='latin-1')

df_health['Reported Date'] = pd.to_datetime(df_health['Reported Date'], errors='coerce')

# callback for Health data table changing as per data picker
@app.callback(Output('datatable-Health', 'data'),
              [Input('date-picker-health', 'start_date'),
               Input('date-picker-health', 'end_date')])
def update_data_2(start_date, end_date):
    df3 = df_health[(df_health['Reported Date'] > start_date) & (df_health['Reported Date'] < end_date)]
    df3 = df3.to_dict("rows")
    return df3

# callback for Health Graph as per data table
@app.callback(Output('HealthGraph', 'figure'),
              [Input('date-picker-health', 'start_date'),
               Input('date-picker-health', 'end_date')])

def update_graph_2(start_date, end_date):
    df4 = df_health[(df_health['Reported Date'] > start_date) & (df_health['Reported Date'] < end_date)]
    grp = df4.groupby('Month')['Occurrence'].sum().sort_values()
    return {
        'data': [go.Bar(
                    x=grp.index,
                    y=grp,
                    marker=dict(
                        color=['#35af8a', '#00846e', '#4d6e81', '#00d2da', '#008695', '#35af8a', '#00846e', '#4d6e81',
                               '#00d2da', '#008695', '#35af8a', '#00846e', '#4d6e81'
                        ]),
                    )
                ],
        'layout': {
            'height': 225,
            'margin': {'l': 20, 'b': 30, 'r': 50, 't': 10},
            'xaxis':{
                'title': 'Month'
                },
            'yaxis': {
                'side': 'right'
            }
        }
    }

# callback for Health Graph as per data table
@app.callback(Output('HealthScatter', 'figure'),
              [Input('date-picker-health', 'start_date'),
               Input('date-picker-health', 'end_date')])

def update_graph_3(start_date, end_date):
    df5 = df_health[(df_health['Reported Date'] > start_date) & (df_health['Reported Date'] < end_date)]
    grp = df5.groupby('Disease')['Occurrence'].sum().sort_values()
    return {
        'data': [go.Bar(
                    y=grp.index,
                    x=grp,
                    orientation='h',
                    )
                ],
        'layout': {
            'height': 1500,
            'margin': {'l': 120, 'b': 30, 'r': 10, 't': 10},
            'xaxis':{
                'title': 'Reported Disease Count'
                }
            }
        }

# callback for Health Graph grouped by Month
@app.callback(Output('MonthGraph', 'figure'),
              [Input('health-dropdown', 'value')])

def update_graph_4(value):
    grp = df_health.groupby('Month')
    grp1 = grp.get_group(value)
    grp2 = grp1.groupby('Disease')['Occurrence'].sum().nlargest(5)
    grp2 = grp2.sort_values()
    return {
        'data': [go.Bar(
                    y=grp2.index,
                    x=grp2,
                    orientation='h',
                    marker=dict(
                        color=['#35af8a', '#00846e', '#4d6e81', '#00d2da', '#008695']),
                    )
                ],
        'layout': {
            'height': 300,
            'margin': {'l': 20, 'b': 30, 'r': 280, 't': 10},
            'xaxis': {
                'title': 'Reported Disease Count',
                },
            'yaxis': {
                # 'tickangle':315,
                'side': 'right'
            }
            }
        }

# callback for Health Graph grouped by Region
@app.callback(Output('RegionGraph', 'figure'),
              [Input('region-dropdown', 'value')])

def update_graph_5(value):
    grp = df_health.groupby('Final Zone')
    grp1 = grp.get_group(value)
    grp2 = grp1.groupby('Disease')['Occurrence'].sum().nlargest(5)
    grp2 = grp2.sort_values()
    return {
        'data': [go.Bar(
                    y=grp2.index,
                    x=grp2,
                    orientation='h',
                    marker=dict(
                        color=['#35af8a', '#4d6e81', '#008695', '#00846e', '#00d2da']),
                    )
                ],
        'layout': {
            'height': 300,
            'margin': {'l': 20, 'b': 30, 'r': 280, 't': 10},
            'xaxis': {
                'title': 'Reported Disease Count',
                },
            'yaxis': {
                # 'tickangle':315,
                'side': 'right'
            }
            }
        }


from src import *
from data.data_loading import CocoStyleDataGenerator
from data.references import DATASETS

from keras.models import Sequential
from keras.layers import Conv2D, Flatten, Activation, Dense, Reshape
from keras.optimizers import SGD
from keras.losses import MSE
from keras.metrics import Accuracy

# libcudart.so.10.0
# libcublas.so.10.0
# libcufft.so.10.0
# libcurand.so.10.0
# libcusolver.so.10.0
# libcusparse.so.10.0
# libcudnn.so.7

if __name__ == "__main__":
    train_generator = CocoStyleDataGenerator(
        images_dir=DATASETS['coco']['train']['images'],
        labels_dir=DATASETS['coco']['train']['labels'],
        names_path=DATASETS['coco']['names']
    )
    test_generator = CocoStyleDataGenerator(
        images_dir=DATASETS['coco']['test']['images'],
        labels_dir=DATASETS['coco']['test']['labels'],
        names_path=DATASETS['coco']['names']
    )

    model = Sequential()
    model.add(Conv2D(
        filters=1024,
        kernel_size=(3, 3),
        activation='relu'
    ))
    model.add(Dense(4096))
    model.add(Dense(100 * 84))
    model.add(Reshape(target_shape=(100, 84)))
    model.add(Activation('softmax'))

    model.compile(
        optimizer=SGD(),
        loss=MSE,
        metrics=[Accuracy(), ]
    )

    model.fit_generator(
        generator=train_generator,
        validation_data=test_generator
    )


'''
작성일 : 23/5/23
작성자 : 김민채
목적 : 13주차 수업내 코딩 연습
'''

from tkinter import *
from PIL import ImageTk, Image
root = Tk()
root.title('Show Image')

def showing1(event):
    label.configure(text='')
    img = Image.open('cat.gif')
    canvas.image = ImageTk.PhotoImage(img)
    canvas.create_image(0,0, image=canvas.image, anchot='nw')

def showing2(event):
    label.configure(text='')
    img = Image.open('dog.gif')
    canvas.image = ImageTk.PhotoImage(img)
    canvas.create_image(0,0, image=canvas.image, anchot='nw')

def resetCanvas(event):
    canvas.delete('all')
    label.configure(text='Disappear')
7
button1 = Button(root, text = 'Show cat')
button1.pack()

button2 = Button(root, text = 'Show dog')
button2.pack()

canvas = Canvas(root, width=500, height=400)
canvas.pack()

label = Label(root)
label.pack()

button1.bind('<Button-1>', showing1)
button1.bind('<Double-1>', resetCanvas)
button2.bind('<Button-1>', showing1)
button2.bind('<Double-1>', resetCanvas)

root.mainloop()


from django.conf.urls.defaults import *
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.auth.decorators import login_required
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.decorators.cache import cache_page
from django.views.generic.base import TemplateView
from fanju.apis import v1_api, mobile_user_login, mobile_user_logout, mobile_user_register, weibo_user_login, checkemail
from fanju.decorators import restaurant_login_required, cache_page_for_anonymous
from fanju.views import upload_app
from fanju.views_common import list_tags, add_tag, add_like
from fanju.views import *
from django.conf import settings

import fanju.views_restaurant as rest

admin.autodiscover()
urlpatterns = patterns('',
    (r'^admin/', include(admin.site.urls)),
    url(r'^admin_tool/', include('admin_tools.urls')),
    #  (r'^grappelli/', include('grappelli.urls')),
    #    ('^get_restaurant_list_by_geo/$', get_restaurant_list_by_geo),
    #    ('^restaurant/(\d+)/$', get_restaurant),
    #    ('^restaurant/(\d+)/dish/recommendation/$', get_recommended_dishes),
    #    ('^restaurant/(\d+)/rating/$', restaurant_rating),
    #    ('^restaurant_tag/$', get_restaurant_tags),
    #    ('^restaurant_tag/(\d+)/restaurant/$', get_restaurants_with_tag),
    #    ('^region/$', get_regions),
    #    ('^region/(\d+)/restaurant/$', get_restaurants_in_region),
    #    ('^search_restaurant_list/$', restaurantList),
    ('^api/v1/login/$', mobile_user_login),
    ('^api/v1/logout/$', mobile_user_logout),
    ('^api/v1/weibo_user_login/$', weibo_user_login),
    ('^api/v1/checkemail/$', checkemail),
    ('^api/v1/register/$', mobile_user_register),
    #    ('^order/$', get_orders),
    #    ('^profile/$', get_user_profile),
    #    ('^profile/favorite/restaurant/(\d+)/$', favorite_restaurant),
    #    ('^profile/favorite/restaurant/$', favorite_restaurants),
    #    ('^search/restaurant/$', query_restaurant_from_google),

    #social
    #    ('^user/(\d+)/following/$', get_following),
    #    ('^user/(\d+)/following/remove/$', remove_following),
    #    ('^user/(\d+)/followers/$', followers),
    #    ('^user/(\d+)/following/recommendations/$', get_recommended_following),
    #    ('^user/(\d+)/messages/$', messages),
    #    ('^meal/(\d+)/participants/$', meal_participants),
    #    ('^user/(\d+)/invitation/$', view_or_send_meal_invitations),
    #    ('^user/(\d+)/invitation/(\d+)/$', accept_or_reject_meal_invitations),

    ######################below is used for website urls
    # meal
    url(r'^$', cache_page_for_anonymous(MealListView.as_view()), name="index"),
    url(r'^meal/$', cache_page_for_anonymous(MealListView.as_view()), name="meal_list"),
    url(r'^meal/(?P<meal_id>\d+)/$', MealDetailView.as_view(), name='meal_detail'),
    url(r'^order/cancel/(?P<order_id>\d+)/$', cancel_order, name='cancel_order'),
    url(r'^meal/add/$', login_required(MealCreateView.as_view()), name='create_meal'),

    url(r'^user/(?P<user_id>\d+)/meals/$', login_required(UserMealListView.as_view()), name="user_meal_list"),

    #menu
    url(r'^menu/$', login_required(MenuListView.as_view()), name="menu_list"),
    url(r'^menu/(?P<pk>\d+)/$', login_required(MenuDetailView.as_view()), name="menu_detail"),

    #ajax get menus
    #    url(r'^menu/$',login_required(get_menu), name='get_menu'),

    #comment

    #group
    #    url(r'^group/$', GroupListView.as_view(), name="group_list"),
    #    url(r'^group/(?P<pk>\d+)/$', GroupDetailView.as_view(), name='group_detail'),
    #    url(r'^group/add/$',login_required(GroupCreateView.as_view()), name='create_group'),
    #    url(r'^group/edit/(?P<pk>\d+)/$',login_required(GroupUpdateView.as_view()), name='edit_group'),
    #    url(r'^group/logo/edit/(?P<pk>\d+)/$',login_required(GroupLogoUpdateView.as_view()), name='edit_group_logo'),
    #    url(r'^group/(?P<pk>\d+)/join/$',login_required(join_group), name='join_group'),
    #    url(r'^group/(?P<pk>\d+)/leave/$',login_required(leave_group), name='leave_group'),
    #    url(r'^group/comment/add/$',login_required(create_group_comment), name='create_group_comment'),
    #    url(r'^group/comment/(?P<pk>\d+)/del/$',login_required(del_group_comment), name='del_group_comment'),
    #    url(r'^group/(?P<group_id>\d+)/comment/p/(?P<page>[0-9]+)/$', GroupCommentListView.as_view(),
    #        name='group_comment_list'),
    #    url(r'^group/(?P<group_id>\d+)/member/$', GroupMemberListView.as_view(), name='group_member_list'),
    #    url(r'^group/(?P<group_id>\d +)/member/p/(?P<page>[0-9]+)/$', GroupMemberListView.as_view(template_name="group/member_container.html"), name='more_group_member_list'),

    # order
    #    url(r'^meal/(?P<meal_id>\d+)/order/$',login_required(OrderCreateView.as_view()), name='create_order'),
    url(r'^meal/(?P<meal_id>\d+)/order/(?P<pk>\d+)/$', login_required(OrderDetailView.as_view()),
        name='order_detail'),
    url(r'^order/paying/(?P<order_id>\d+)/$', login_required(pay_order),
        name='pay_order'),
    url(r'^meal/(?P<meal_id>\d+)/order/status/', login_required(check_order_status), name="check_order_status"),

    url(r'^login/weibo/$', weibo_login, name='weibo_login'),
#    url(r'^bind/$', login_required(BindProfileView.as_view()), name='bind'),
    url(r'^login/$', 'django.contrib.auth.views.login', name='login'),
    url(r'^logout/$', 'django.contrib.auth.views.logout_then_login', kwargs={'login_url': "/"}, name="logout"),

    #account
    #    url(r'^user/register/$', RegisterView.as_view(), name='register'),
    url(r'^user/$', cache_page_for_anonymous(UserListView.as_view()), name="user_list"),
    url(r'^user/p/(?P<page>[0-9]+)/$', cache_page_for_anonymous(UserListView.as_view(template_name="profile/user_container.html")),
        name="more_user"),
    url(r'^profile/edit/$', login_required(ProfileUpdateView.as_view()), name='edit_basic_profile'),
    url(r'^user/(?P<pk>\d+)/$', login_required(ProfileDetailView.as_view()), name='user_detail'),
    url(r'profile/upload_avatar/$', login_required(UploadAvatarView.as_view()), name='upload_avatar'),
    url(r'user/info/$', login_required(get_user_info), name='get_user_info'),

    url(r'^follow/(?P<user_id>\d+)/$', login_required(follow), name='follow'),
    url(r'^unfollow/(?P<user_id>\d+)/$', login_required(un_follow), name='un_follow'),
    url(r'^follows/(?P<user_id>\d+)/$', login_required(FollowsView.as_view()), name='following_list'),

    #photo
    url(r'^photo/u/(?P<user_id>\d+)/$', login_required(PhotoListView.as_view()), name='photo_list'),
    url(r'^photo/upload/$', login_required(PhotoCreateView.as_view()), name='upload_photo'),
    url(r'^photo/(?P<pk>\d+)/$', login_required(PhotoDetailView.as_view()), name='photo_detail'),
    url(r'^photo/del/(?P<pk>\d+)/$', login_required(del_photo), name='del_photo'),
    url(r'^photo/request/(?P<host_id>\d+)/$', login_required(photo_request), name='photo_request'),

    url(r'^tag/$', login_required(list_tags), name='tag_list'),
    url(r'^tag/add/$', login_required(add_tag), name='add_tag'),

    url(r'^comment/(?P<comment_type>\w+)/(?P<target_id>\d+)/$', cache_page_for_anonymous()(CommentListView.as_view()), name='comment_list'),
    url(r'^comment/(?P<comment_type>\w+)/(?P<target_id>\d+)/add/$', login_required(add_comment), name='add_comment'),
    url(r'^comment/(?P<comment_type>\w+)/(?P<comment_id>\d+)/del/$', login_required(del_comment), name='del_comment'),

    url(r'^like/(?P<target_type>\w+)/(?P<target_id>\d+)/add/$', login_required(add_like), name='add_like'),

    #restaurant admin
    url(r'^restaurant/$', restaurant_login_required(rest.OrderCheckInView.as_view()), name="restaurant_admin"),

    url(r'^restaurant/chekin/$', restaurant_login_required(rest.OrderCheckInView.as_view()),
        name="restaurant_checkin"),
    url(r'^restaurant/order/use/$', restaurant_login_required(rest.use_order), name="restaurant_use_order"),

    url(r'^restaurant/order/today/$', restaurant_login_required(rest.TodayMealListView.as_view()), name="restaurant_today_meals"),

    url(r'^restaurant/dish/$', restaurant_login_required(rest.DishListView.as_view()), name="restaurant_dish_list"),
    url(r'^restaurant/dish/add/$', restaurant_login_required(rest.DishCreateView.as_view()),
        name="restaurant_dish_add"),
    url(r'^restaurant/dish/edit/(?P<pk>\d+)/$', restaurant_login_required(rest.DishUpdateView.as_view()),
        name="restaurant_dish_edit"),
    url(r'^restaurant/dish/del/(?P<dish_id>\d+)/$', restaurant_login_required(rest.del_dish),
        name="restaurant_dish_del"),
    url(r'^restaurant/dish_category/add/$', restaurant_login_required(rest.add_dish_category),
        name="add_dish_category"),

    url(r'^restaurant/order/$',
        restaurant_login_required(TemplateView.as_view(template_name="restaurant/order_history.html")),
        name="restaurant_order"),

    url(r'^restaurant/menu/$', restaurant_login_required(rest.MenuListView.as_view()), name="restaurant_menu_list"),
    url(r'^restaurant/menu/add/$', restaurant_login_required(rest.add_menu), name="add_menu"),
    url(r'^restaurant/menu/del/(?P<pk>\d+)/$', restaurant_login_required(rest.del_menu), name="del_menu"),
    url(r'^restaurant/menu/edit/(?P<pk>\d+)/$', restaurant_login_required(rest.edit_menu), name="edit_menu"),
    url(r'^restaurant/menu/copy/(?P<pk>\d+)/$', restaurant_login_required(rest.copy_menu), name="copy_menu"),
    url(r'^restaurant/menu/cover/edit/(?P<pk>\d+)/$', restaurant_login_required(rest.EditMenuCoverView.as_view()),
        name="edit_menu_cover"),

    #support
    url(r'^support/$', TemplateView.as_view(template_name="support/support.html"), name="support"),
    url(r'^faq/$', TemplateView.as_view(template_name="support/faq.html"), name="faq"),
    url(r'^faq/mobile/$', TemplateView.as_view(template_name="support/faq_mobile.html"), name="faq"),
    (r'^test/$', TemplateView.as_view(template_name="test.html")),

    # developer interfaces...
    ('^upload_app/$', upload_app),

    #pay
    url(r'^pay/alipay/direct/back/sync/$', handle_alipay_direct_sync_back, name="alipay_direct_sync_back"),
    url(r'^pay/alipay/direct/back/async/$', handle_alipay_direct_aysnc_back, name="alipay_direct_async_back"),
    url(r'^pay/alipay/app/back/sync/$', handle_alipay_app_sync_back, name="alipay_app_sync_back"),
    url(r'^pay/alipay/app/back/async/$', handle_alipay_app_async_back, name="alipay_app_async_back"),
    url(r'^pay/alipay/wap/back/sync/$', handle_alipay_wap_sync_back, name="alipay_wap_sync_back"),
    url(r'^pay/alipay/wap/back/async/$', handle_alipay_wap_async_back, name="alipay_wap_async_back"),

    url(r'^error/$', TemplateView.as_view(template_name='500.html'), name='error')
)

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()

# Standard bits...
urlpatterns += patterns('',
                        (r'^api/', include(v1_api.urls)),
)


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

original_image = cv2.imread('test/noise/right/081.png')

img = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)

vectorized = img.reshape((-1,3))
vectorized = np.float32(vectorized)

criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 7
attempts=10
ret,label,center=cv2.kmeans(vectorized,K,None,criteria,attempts,cv2.KMEANS_PP_CENTERS)

center = np.uint8(center)

res = center[label.flatten()]
result_image = res.reshape((img.shape))

cv2.imwrite('result.jpg',result_image)


import torch
from torch.optim.lr_scheduler import MultiStepLR, CosineAnnealingLR, ExponentialLR, OneCycleLR

def fetch_optimizer(model, cfg):
    """ Create the optimizer and learning rate scheduler """
    # optimizer = optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.wdecay, eps=args.epsilon)

    # scheduler = optim.lr_scheduler.OneCycleLR(optimizer, args.lr, args.num_steps+100,
    #     pct_start=0.05, cycle_momentum=False, anneal_strategy='linear')
    optimizer = build_optimizer(model, cfg)
    scheduler = build_scheduler(cfg, optimizer)

    return optimizer, scheduler

def build_optimizer(model, config):
    name = config.optimizer
    lr = config.canonical_lr

    if name == "adam":
        return torch.optim.Adam(model.parameters(), lr=lr, weight_decay=config.adam_decay, eps=config.epsilon)
    elif name == "adamw":
        if hasattr(config, 'twins_lr_factor'):
            factor = config.twins_lr_factor
            print("[Decrease lr of pre-trained model by factor {}]".format(factor))
            param_dicts = [
                {"params": [p for n, p in model.named_parameters() if "feat_encoder" not in n and 'context_encoder' not in n and p.requires_grad]},
                {
                    "params": [p for n, p in model.named_parameters() if ("feat_encoder" in n or 'context_encoder' in n) and p.requires_grad],
                    "lr": lr*factor,
                },
            ]
            full = [n for n, _ in model.named_parameters()]
            return torch.optim.AdamW(param_dicts, lr=lr, weight_decay=config.adamw_decay, eps=config.epsilon)
        else:
            return torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=config.adamw_decay, eps=config.epsilon)
    else:
        raise ValueError(f"TRAINER.OPTIMIZER = {name} is not a valid optimizer!")

def build_scheduler(config, optimizer):
    """
    Returns:
        scheduler (dict):{
            'scheduler': lr_scheduler,
            'interval': 'step',  # or 'epoch'
        }
    """
    # scheduler = {'interval': config.TRAINER.SCHEDULER_INTERVAL}
    name = config.scheduler
    lr = config.canonical_lr

    if name == 'OneCycleLR':
        # scheduler = OneCycleLR(optimizer, )
        if hasattr(config, 'twins_lr_factor'):
            factor = config.twins_lr_factor
            scheduler = OneCycleLR(optimizer, [lr, lr*factor], config.num_steps+100,
                pct_start=0.05, cycle_momentum=False, anneal_strategy=config.anneal_strategy)
        else:
            scheduler = OneCycleLR(optimizer, lr, config.num_steps+100,
                pct_start=0.05, cycle_momentum=False, anneal_strategy=config.anneal_strategy)
    # elif name == 'MultiStepLR':
    #     scheduler.update(
    #         {'scheduler': MultiStepLR(optimizer, config.TRAINER.MSLR_MILESTONES, gamma=config.TRAINER.MSLR_GAMMA)})
    #elif name == 'CosineAnnealing':
    #    scheduler = CosineAnnealingLR(optimizer, config.num_steps+100)
    #     scheduler.update(
    #         {'scheduler': CosineAnnealingLR(optimizer, config.TRAINER.COSA_TMAX)})
    # elif name == 'ExponentialLR':
    #     scheduler.update(
    #         {'scheduler': ExponentialLR(optimizer, config.TRAINER.ELR_GAMMA)})
    else:
        raise NotImplementedError()

    return scheduler


# HC

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# imporing Mall_Customers with pandas
dataset = pd.read_csv('Mall_Customers.csv')

# selct our column of insterest (annual, spending score)
X = dataset.iloc[:, [3,4]].values

# using the dendrogram to find the optimal number of clusters
import scipy.cluster.hierarchy as sch
dendrogram = sch.dendrogram(sch.linkage(X, method='ward'))

plt.title('Dendrogram')
plt.xlabel('Customers')
plt.ylabel('Euclidean Distance')
plt.show()

# next step is to fit the K-Means algorithm to our data X.
from sklearn.cluster import AgglomerativeClustering
hc = AgglomerativeClustering(n_clusters=5, affinity='euclidean', linkage='ward')
y_hc = hc.fit_predict(X)

# visualizing the cluster
plt.scatter(X[y_hc == 0, 0], X[y_hc == 0, 1], s = 100, c = 'red', label = 'Careful')
plt.scatter(X[y_hc == 1, 0], X[y_hc == 1, 1], s = 100, c = 'blue', label = 'Standard')
plt.scatter(X[y_hc == 2, 0], X[y_hc == 2, 1], s = 100, c = 'green', label = 'Target')
plt.scatter(X[y_hc == 3, 0], X[y_hc == 3, 1], s = 100, c = 'cyan', label = 'Careless')
plt.scatter(X[y_hc == 4, 0], X[y_hc == 4, 1], s = 100, c = 'magenta', label = 'Sensible')
plt.title('Clusters of customers')
plt.xlabel('Annual Income (k$)')
plt.ylabel('Spending Score (1-100)')
plt.legend()
plt.show()

Part 4 - Clustering/Section 22 - Hierarchical Clustering/hc.py


#pip install geocoder
import geocoder
#Modify this to your own lookup folder
lookups = 'D:/Documents/IPython/Datathon/MelbDatathon2017/lookups/'
df_patients=pd.read_csv('{}patients.txt'.format(lookups), sep = '\t')
pc=df_patients.postcode.unique()

df_pc=pd.DataFrame(columns=['postcode'])
df_pc.postcode=pc

gc=Nominatim(view_box=(112.467,-55.050,168.000,-9.133),country_bias='Australia')

def get_cor(postcode):
    s_t=clock()
    loc=None
    while loc is None:
        try:
            loc=geocoder.google('{}, Australia'.format(postcode))
        except:
            print ("error")

    e_t=clock()
    time.append(e_t-s_t)
    print('{}:{}'.format(len(time),time[-1]),end=' , ')
    print ('{}'.format(postcode),end=',')
    print('{},{}'.format(loc.lng,loc.lat))
    return '{}#{}#{}'.format(loc.address,loc.lng,loc.lat)

df_pc=df_pc[:]
time=[]

df_pc['address,lon,lat']=df_pc['postcode'].apply(lambda x: get_cor(x))

df_pc['address'],df_pc['lon'],df_pc['lat']=df_pc['address,lon,lat'].str.split('#').str
df_pc=df_pc.drop('address,lon,lat',1)

# df_pc.lon=df_pc.lon.astype(float)
# df_pc.lat=df_pc.lat.astype(float)
df_pc


#!/usr/bin/python3

from typing import List
from typing import Dict

from datasets.aDataset import ADataset #class
from datasets.datasetML import DatasetML #class
from pandas.core.series import Series #class

from datasets.ml.ratings import Ratings #class

from portfolioDescription.aPortfolioDescription import APortfolioDescription #class

from portfolio.aPortfolio import APortfolio #class

from simulation.aSequentialSimulation import ASequentialSimulation #class

import pandas as pd
import numpy as np

from recommender.aRecommender import ARecommender #class

from pandas.core.frame import DataFrame #class

from history.aHistory import AHistory #class
from evaluationTool.aEvalTool import AEvalTool #class

from datasets.ml.behavioursML import BehavioursML #class

from simulation.tools.modelOfIndexes import ModelOfIndexes #class

class SimulationML(ASequentialSimulation):

    _ratingClass = Ratings
    _behaviourClass = BehavioursML

    @staticmethod
    def divideDataset(dataset:ADataset, behaviourDF:DataFrame,
                      divisionDatasetPercentualSize:int, testDatasetPercentualSize:int,
                      recomRepetitionCount:int):

        ratingsDF:DataFrame = dataset.ratingsDF
        usersDF:DataFrame = dataset.usersDF
        itemsDF:DataFrame = dataset.itemsDF

        # create train Dataset
        ratingsSortedDF:DataFrame = ratingsDF.sort_values(by=Ratings.COL_TIMESTAMP)
        numberOfRatings:int = ratingsSortedDF.shape[0]

        trainSize:int = (int)(numberOfRatings * divisionDatasetPercentualSize / 100)
        #print("trainSize: " + str(trainSize))
        trainRatingsDF:DataFrame = ratingsSortedDF[0:trainSize]

        datasetID:str = "ml1m" + "Div" + str(divisionDatasetPercentualSize)
        trainDataset:ADataset = DatasetML(datasetID, trainRatingsDF, usersDF, itemsDF)

        # create test Rating DataFrame
        testSize:int = (int)(numberOfRatings * testDatasetPercentualSize / 100)
        #print("testSize: " + str(testSize))
        testRatingsDF:DataFrame = ratingsSortedDF[trainSize:(trainSize + testSize)]

        # create test relevant Rating DataFrame
        testRelevantRatingsDF:DataFrame = testRatingsDF.loc[testRatingsDF[Ratings.COL_RATING] >= 4]

        # create behaviour dictionary of DataFrame indexed by recomRepetition
        recomRepetitionCountInDataset:int = behaviourDF[BehavioursML.COL_REPETITION].max() + 1

        testRepeatedBehaviourDict:dict = {}
        bIndexes:List[int] = list([recomRepetitionCountInDataset*i for i in testRatingsDF.index])
        for repetitionI in range(recomRepetitionCount):
            # indexes of behaviour
            indexes:List[int] = [vI+repetitionI for vI in bIndexes]
            behaviourDFI:DataFrame = DataFrame(behaviourDF.take(indexes).values.tolist(),
                        index=testRatingsDF.index, columns=behaviourDF.keys())
            testRepeatedBehaviourDict[repetitionI] = behaviourDFI

        return (trainDataset, testRelevantRatingsDF, testRelevantRatingsDF, testRepeatedBehaviourDict)

    @staticmethod
    def initEvaluationModel(dataset:ADataset):
        usersDF:DataFrame = dataset.usersDF

        # model with clicked ItemIDs for users
        clickedItems:dict[List[int]] = {}
        for indexI, rowI in usersDF.iterrows():
            clickedItems[rowI[Ratings.COL_USERID]] = []
        return clickedItems

    def iterateOverDataset(self, portfolios:List[APortfolio], portfolioDescs:List[APortfolioDescription],
                             portFolioModels:List[pd.DataFrame], evaluatonTools:List[AEvalTool],
                             histories:List[AHistory], testRatingsDF:DataFrame, testRelevantRatingsDF:DataFrame,
                             testBehaviourDict:Dict[int, DataFrame]):

        model:ModelOfIndexes = ModelOfIndexes(testRatingsDF, list(testRelevantRatingsDF.index), Ratings)

        portIds:List[str] = [portDescI.getPortfolioID() for portDescI in portfolioDescs]

        evaluations:List[dict] = [{} for i in range(len(portfolios))]

        counterI:int = 0

        currentDFIndexI:int
        nextIndexDFI:int
        for currentDFIndexI in list(testRatingsDF.index):

            counterI += 1
            if counterI  % 100 == 0:
                print("RatingI: " + str(counterI) + " / " + str(testRatingsDF.shape[0]))
                print("PortfolioIds: " + str(portIds))
                print("Evaluations: " + str(evaluations))

                self.computationFile.write("RatingI: " + str(counterI) + " / " + str(testRatingsDF.shape[0]) + "\n")
                self.computationFile.write("PortfolioIds: " + str(portIds) + "\n")
                self.computationFile.write("Evaluations: " + str(evaluations) + "\n")
                self.computationFile.flush()

            currentItemIdI:int = testRatingsDF.loc[currentDFIndexI][Ratings.COL_MOVIEID]
            currentRatingI:int = testRatingsDF.loc[currentDFIndexI][Ratings.COL_RATING]
            currentUserIdI:int = testRatingsDF.loc[currentDFIndexI][Ratings.COL_USERID]
            currentSessionIdI:int = None
            currentPageTypeI:object = None

            portfolioI:APortfolio
            for portfolioI in portfolios:

                dfI:DataFrame = DataFrame([testRatingsDF.loc[currentDFIndexI]], columns=testRatingsDF.keys())
                portfolioI.update(dfI, {})

            windowOfItemIDsI:int = model.getNextRelevantItemIDsExceptItemIDs(currentDFIndexI,
                                            self._clickedItems[currentUserIdI], self._windowSize)

            repetitionI:int
            for repetitionI in range(self._recomRepetitionCount):
                self.simulateRecommendations(portfolios, portfolioDescs, portFolioModels, evaluatonTools,
                                             histories, evaluations, currentDFIndexI, counterI, testRatingsDF.shape[0],
                                             currentUserIdI, currentSessionIdI, repetitionI,
                                             testRatingsDF, testBehaviourDict, windowOfItemIDsI, currentPageTypeI)

        return evaluations


#!/usr/bin/env python3

import quine
from collections import Counter
from itertools import product

import math

# Brute force attempt to find good constants

def get_frequencies():
    pre = quine.prefixsection.generate()
    code = quine.codesection.generate(pre)
    from collections import Counter
    return Counter(code)

def find_representations(fixed_constants, weights):
    rep = dict((ord(c), (float("inf"), None)) for c in weights)
    # Assume cost of 4 for all fixed constants
    constants = dict((c, (4, "constant_%s" % c)) for c in fixed_constants)
    # Assume length of 5 for all adjectives and length 4 for the noun
    # used to generate powers of two. (add one to each adjective for spaces)
    for k in range(10):
        if 2**k not in constants:
            constants[2**k] = (6*k+4, "power_of_two_%s" % 2**k)
        if -2**k not in constants:
            constants[-2**k] = (6*k+4, "negative_power_of_two_%s" % 2**k)
    # constants
    rep.update(constants)

    uncovered_numbers = set(ord(c) for c in weights if ord(c) not in constants)
    while uncovered_numbers or changes:
        def add_number(x, cost, r):
            if x < 10000 and (x not in rep or rep[x][0] > cost):
                rep[x] = (cost, r)
                changes = True
        changes = False
        known_numbers = [(x, (cost, r)) for x, (cost, r) in rep.items()
                                          if cost < float("inf")]
        for x, (cost, r) in known_numbers:
            # twice x
            add_number(2*x, cost + 6, "twice " + r)
            # the cube of x
            add_number(x**3, cost + 12, "the cube of " + r)
            # the square of x
            add_number(x**2, cost + 14, "the square of " + r)
            if x > 0:
                # the factorial of x
                add_number(math.factorial(x), cost + 17, "the factorial of " + r)
                # the square root of x
                add_number(int(x**0.5), cost + 19, "the square root of " + r)

        for x1, (cost1, r1) in known_numbers:
            for x2, (cost2, r2) in known_numbers:
                # the sum of x and y
                add_number(x1 + x2, cost1 + cost2 + 16, "the sum of %s and %s" % (r1, r2))
                # the product of x and y
                add_number(x1 * x2, cost1 + cost2 + 20, "the product of %s and %s" % (r1, r2))
                # the difference between x and y
                add_number(x1 - x2, cost1 + cost2 + 28, "the difference between %s and %s" % (r1, r2))

        uncovered_numbers -= set(x for x, (cost, _) in rep.items()
                                       if cost < float("inf"))
    return rep

def main():
    frequencies = get_frequencies()
    frequencies.update("QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890")
    constants = [ord(c) for c, _ in frequencies.most_common(3)]
    best = None
    best_cost = float("inf")
    ints_to_cover = [ord(c) for c in frequencies]

    for c1 in range(1, 150):
        for c2 in range(c1 + 1, 150):
            print(c1,c2)
            representations = find_representations(constants + [c1, c2], frequencies)
            cost = sum(c * frequencies[chr(k)] for k, (c, _) in representations.items()
                                                    if k in ints_to_cover)
            if cost < best_cost:
                best_cost = cost
                best = representations

    for char, (cost, rep) in best.items():
        if char in ints_to_cover:
            print("    %s: \"%s\",%d" % (char, rep, cost))

if __name__ == "__main__":
    main()


import hashlib

from fastapi.testclient import TestClient
import pytest

from test.conftest import set_preferred_colourmap, unset_preferred_colourmap

class TestGetImage:
    @pytest.mark.parametrize(
        "record_id, channel_name, original_image, use_preferred_colourmap,"
        "lower_level, upper_level, colourmap_name, expected_image_md5sum",
        [
            pytest.param(
                "20220408164136",
                "N_COMP_FF_IMAGE",
                True,
                False,
                None,
                None,
                None,
                "9d2fc96084349c5bff10206ef4dfdf3e",
                id="Original image",
            ),
            pytest.param(
                "20220408002114",
                "N_LEG1_GREEN_NF_IMAGE",
                False,
                False,
                None,
                None,
                None,
                "97a854f18ef539f443a39c091c88df29",
                id="Image with default false colour settings",
            ),
            # repeat the above test but with the user's preferred colour map set to
            # check that the preference is used when no specific map is chosen
            pytest.param(
                "20220408002114",
                "N_LEG1_GREEN_NF_IMAGE",
                False,
                True,
                None,
                None,
                None,
                "002431ebfe4232121856ae88c15ad939",
                id="Image using user's preferred colourmap",
            ),
            pytest.param(
                "20220408002114",
                "N_LEG1_GREEN_NF_IMAGE",
                None,
                False,
                50,
                200,
                "jet_r",
                "707c50d0784e305f0f6d20fe39c93162",
                id="Image with all false colour params specified",
            ),
            # repeat the test above but with the user's preferred colour map set to
            # ensure that it is ignored and the specified colour map used
            pytest.param(
                "20220408002114",
                "N_LEG1_GREEN_NF_IMAGE",
                None,
                True,
                50,
                200,
                "jet_r",
                "707c50d0784e305f0f6d20fe39c93162",
                id="Image with all false colour params specified (ignoring "
                "user's pref)",
            ),
        ],
    )
    def test_valid_get_image(
        self,
        test_app: TestClient,
        login_and_get_token,
        record_id,
        channel_name,
        original_image,
        use_preferred_colourmap,
        lower_level,
        upper_level,
        colourmap_name,
        expected_image_md5sum,
    ):
        set_preferred_colourmap(test_app, login_and_get_token, use_preferred_colourmap)

        query_string = ""
        query_params_array = []

        if original_image is not None:
            # allow setting of "original_image=False"
            query_params_array.append(f"original_image={original_image}")
        if lower_level:
            query_params_array.append(f"lower_level={lower_level}")
        if upper_level:
            query_params_array.append(f"upper_level={upper_level}")
        if colourmap_name:
            query_params_array.append(f"colourmap_name={colourmap_name}")

        if len(query_params_array) > 0:
            query_string = "?" + "&".join(query_params_array)

        test_response = test_app.get(
            f"/images/{record_id}/{channel_name}{query_string}",
            headers={"Authorization": f"Bearer {login_and_get_token}"},
        )

        unset_preferred_colourmap(
            test_app,
            login_and_get_token,
            use_preferred_colourmap,
        )

        assert test_response.status_code == 200

        bytes_image = test_response.content

        image_checksum = hashlib.md5(bytes_image).hexdigest()
        assert expected_image_md5sum == image_checksum


import scipy.io
import numpy as np
import common
import time
import os
import matplotlib.pyplot as plt
import FieldTrip2
import subprocess

output_directory = common.set_output_directory('prepare_cursor_gaze\\')

start = time.time()

mat = scipy.io.loadmat('..\\visual_input\\movie_cursor_eye\\test.mat')

cursor_xy = mat['CURSOR_XY2'][0, 0]
#np.save(file=output_directory + 'test.npy', arr=cursor_xy)
# #np.savetxt(fname=output_directory + 'test.npy', X=cursor_xy)
# del cursor_xy
# array = np.load(file=output_directory + 'test.npy', allow_pickle=True)
dimensions = cursor_xy.shape

class Number:
    axes = 2
    frames = 360
    trials = 480
    cursors = 3

Number.axes = dimensions[0]
Number.frames = dimensions[1]
Number.trials = dimensions[2]
Number.cursors = dimensions[3]
#
# cursor_xy = np.empty((Number.axes, Number.frames, Number.trials, Number.cursors))
# cursor_xy[:] = np.NaN
#
# for axis in range(0, Number.axes):
#     for frame in range(0, Number.frames):
#         for trial in range(0, Number.trials):
#             for cursor in range(0, Number.cursors):
#                 #print(array[axis, frame, trial, cursor])
#                 cursor_xy[axis, frame, trial, cursor] = array[axis, frame, trial, cursor]
#
# stop = time.time()
# print(stop-start)
# print('done!')

TRIAL = 1
CURSOR = 1

trajectory = np.transpose(cursor_xy[:, :, TRIAL, CURSOR])

plt.close('all')
plt.plot(trajectory[:, 0], trajectory[:, 1])
plt.xlim([-540, +540])
plt.ylim([-540, +540])

##

def close_buffers():
    try:
        subprocess.call("taskkill /F /IM buffer.exe /T")  # kill buffer
    except:
        print("buffer not running...")

    try:
        subprocess.call("taskkill /F /IM cmd.exe /T")  # kill cmd
    except:
        print("cmd not running...")

def buffer_trial(port, array):

    path_buffer_executable = "D:\\Network.Buffer.DRP.19.07.20\\realtimeHack.10.11.17\\buffer.exe"

    host = 'localhost'

    command = "start cmd /K " + path_buffer_executable + " " + host.__str__() + " " + port.__str__() + " -&"
    print(command)

    subprocess.Popen(command, shell=True)  # start buffer

    ftc = FieldTrip2.Client()  # create buffer object
    ftc.connect(host, port)  # connect to buffer
    ftc.putHeader(Number.axes, 0, FieldTrip2.DATATYPE_FLOAT32, None, None)  # put header - clears the buffer memory?

    ftc.putData(array.astype((np.float32)))  # put data

    hdr = ftc.getHeader()  # get header
    # print(hdr)  # print header

    D2 = ftc.getData((0, hdr.nSamples-1))  # get data
    # print(np.shape(D2))  # print data

    return(D2)

close_buffers()

CURSOR = 1
D2 = np.empty((2, Number.frames, 10))
D2[:] = np.nan

port = []

for TRIAL in range(0, 10):
    D2[:,:,TRIAL] = np.transpose(buffer_trial(port=TRIAL+1000, array=np.transpose(cursor_xy[:, :, TRIAL, CURSOR])))
    port.append(TRIAL+1000)

np.all(D2[:,:,:] == cursor_xy[:,:,0:10,1].astype(np.float32))


import pygame
from ..components import ui

# main menu screen
class Main_Menu:
  def __init__(self, parent, resources, load_map_selector, load_difficulty_change, load_map_creator):

    self.parent = parent
    self.resources = resources
    self.load_map_selector = load_map_selector
    self.load_difficulty_change = load_difficulty_change
    self.load_map_creator = load_map_creator

    self.screen_size = (parent.get_width(), parent.get_height())

    # images for buttons
    self.start_button_image = self.resources["start_button.png"]
    self.difficulty_button_image = self.resources["difficulty_button.png"]

    # set font
    self.font = pygame.font.SysFont("Arial", 18)

    self.buttons = []  # contains all buttons

    # position start button
    self.start_button = ui.Button(self.parent, self.resources["start_button.png"], (0, 0), self.load_map_selector)
    self.start_button.rect.centerx = self.screen_size[0]/2
    self.start_button.rect.top = 70
    self.buttons.append(self.start_button)

    # position change difficulty button
    self.difficulty_button = ui.Button(self.parent, self.resources["difficulty_button.png"], (0, 0), self.load_difficulty_change)
    self.difficulty_button.rect.centerx = self.screen_size[0]/2
    self.difficulty_button.rect.top = self.start_button.rect.bottom + 30
    self.buttons.append(self.difficulty_button)

    # create map creator button
    self.map_creator_button = ui.Button(self.parent, self.resources["map_creator_button.png"], (0, 0), self.load_map_creator)
    self.map_creator_button.rect.centerx = self.screen_size[0]/2
    self.map_creator_button.rect.top = self.difficulty_button.rect.bottom + 15
    self.buttons.append(self.map_creator_button)

    # reminder to turn on sound text
    sound_reminder_content = "Turn on sound for the best experience!"
    self.sound_reminder_text = self.font.render(sound_reminder_content, True, "black")
    self.sound_reminder_pos = self.sound_reminder_text.get_rect()
    self.sound_reminder_pos.centerx = self.screen_size[0]/2
    self.sound_reminder_pos.bottom = self.screen_size[1] - 30

  # called once per tick by main.py
  def update(self):
    self.handle_events()
    self.render()

  # handles events (mostly button press)
  def handle_events(self):
    # event handling
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
        pygame.quit()

      # handle clicks on buttons
      if event.type == pygame.MOUSEBUTTONDOWN:
        if event.button == 1:
          for button in self.buttons:
            button.check_click(event.pos)

  # draws everything
  def render(self):
    self.parent.fill("burlywood1")
    for button in self.buttons:
      button.draw()
    self.parent.blit(self.sound_reminder_text, self.sound_reminder_pos)


import nltk

program = input("Enter a program: ")
count = 0
All_token = []

def remove_Spaces(program):
    scanned_Program = []
    for line in program:
        if line.strip() != '':
            scanned_Program.append(line.strip())
    return scanned_Program

prog = program.split('\n')
scanned_Prog = remove_Spaces(prog)
scanned_Program = '\n'.join([str(elem) for elem in scanned_Prog])
scanned_Program_lines = scanned_Program.split('\n')
match_counter = 0

Source_Code = []
for line in scanned_Program_lines:
    Source_Code.append(line)
print(Source_Code)
display_counter = 0

for line in Source_Code:
    count = count + 1

    tokens = nltk.wordpunct_tokenize(line)
    for token in tokens:
        All_token.append(token)

print("There Are total: ", len(All_token), " Tokens: ", All_token)

# int main() { int a,b=20,c;}
# float x = a + 1b, y=a++b2, z= c+2;


from flask import Blueprint, jsonify, request, abort
from paramiko import AuthenticationException, SSHException
from src.config.netmiko_config import cisco_device
from netmiko import ConnectHandler, NetMikoTimeoutException
from src.utils.network_template import template
from src.utils.ip_verif import ip_belongs_to_cidr

network_bp = Blueprint('network', __name__)

@network_bp.route('/test', methods=['GET'])
def test():
    try:
        # Intenta establecer una conexión SSH al dispositivo Cisco
        net_connect = ConnectHandler(**cisco_device)
        print("test")
        # Realiza una operación simple para verificar que Netmiko está funcionando
        prompt = net_connect.find_prompt()

        # Cierra la conexión
        net_connect.disconnect()

        return jsonify({'message': 'Netmiko está funcionando correctamente.'})

    except (NetMikoTimeoutException, SSHException, AuthenticationException) as e:
        return jsonify({'error': str(e)}), 500

@network_bp.route('/vlaninf', methods=['POST'])
def vlaninf():
    try:
        data = request.get_json()
        if 'mac' not in data:
            abort(400)
        mac = data['mac']
        # Iniciar la conexión SSH
        net_connect = ConnectHandler(**cisco_device)
        command_output = net_connect.send_command(
            f'show mac address-table address {mac}', use_textfsm=True)
        print(f'show mac address-table address {mac}')
        # Verificar si la respuesta contiene al menos una entrada válida de MAC
        print(command_output)
        if not command_output or not isinstance(command_output, list):
            print("No se encontro la mac")
            abort(404)

        tmp = command_output[0]['vlan']
        command_output2 = (net_connect.send_command(
            f'show ip interface vlan {tmp}', use_textfsm=True))[0]

        # Combinar todas las ipaddr y mask en un solo formato (ipaddr/mask)
        ipaddr_mask_list = []
        for ip, mask in zip(command_output2['ipaddr'], command_output2['mask']):
            ipaddr_mask_list.append(f"{ip}/{mask}")

        # Modificar el objeto para incluir la lista de ipaddr/mask
        command_output2['cidr'] = ipaddr_mask_list
        return jsonify({"vlan": command_output2['intf'], "segments": ipaddr_mask_list})
    except Exception as e:
        print(str(e))
        # return jsonify({'error': str(e)})
        abort(404)

@network_bp.route('/check_ip', methods=['POST'])
def check_ip():
    try:
        data = request.get_json()
        if 'ip' not in data or 'cidr' not in data:
            return jsonify({'error': 'Se requiere una dirección IP y un CIDR en el JSON.'}), 400

        ip = data['ip']
        cidr = data['cidr']

        if ip_belongs_to_cidr(ip, cidr):
            return jsonify({'status': True})
        else:
            return jsonify({'status': False})
    except Exception as e:
        return jsonify({'error': str(e)}), 404

@network_bp.route('/test2', methods=['GET'])
def test2():
    try:
        # Intenta establecer una conexión SSH al dispositivo Cisco
        net_connect = ConnectHandler(**cisco_device)

        # Ejecuta un comando para obtener todas las MAC addresses de la VLAN 1
        mac_addresses = net_connect.send_command(
            'show mac address-table vlan 1', use_textfsm=True)

        # Cierra la conexión
        net_connect.disconnect()

        # Extrae las MAC addresses y las devuelve como respuesta JSON
        mac_list = [entry['destination_address'] for entry in mac_addresses]

        return jsonify({'mac_addresses': mac_list})

    except (NetMikoTimeoutException, SSHException, AuthenticationException) as e:
        return jsonify({'error': str(e)}), 500


import pytest

from nameko.testing.services import entrypoint_hook

from statistics.service import StatisticsService

@pytest.fixture
def service_container(test_config, container_factory):
    container = container_factory(StatisticsService)
    container.start()
    return container

@pytest.mark.skip(reason="connection to Redis needs to be fixed")
def test_update_get_statistics(service_container):
    with entrypoint_hook(service_container, 'update_statistics') as \
            update_statistics:
        update_statistics(['a', 's', 'd'])

        with entrypoint_hook(service_container, 'get_statistics') as \
                get_statistics:
            amount = get_statistics()

    assert amount == 3


import socket
import  os
import threading
import time
from email.utils import formatdate
import mimetypes
import random

class MyServer(threading.Thread):
    def __init__(self,client_connection,ip,port):
        threading.Thread.__init__(self)
        self.client_connection = client_connection
        self.ip = ip
        self.port = port

    def run(self):

        request = self.client_connection.recv(1024).decode('utf-8')
       # print(request)

        string_list = request.split(" ")
        method = string_list[0]
        resource = string_list[1]
        resource = resource[1:]

        #print(p)
        file_path = p + resource
        try:
            print("file:",file_path)
            f = open(file_path, 'rb')
            l = f.read()
            with my_lock:
                my_dict[resource] += 1
            f.close()

            print("Client {0} connected on port {1} requested for {2} count - {3}".format(self.ip, self.port,resource,my_dict[resource]))

            date = formatdate(timeval=None, localtime=False, usegmt=True)

            type = mimetypes.guess_type(file_path,True)
           # print(type[0])
            m=os.path.getmtime(file_path)
            m= formatdate(timeval=m,localtime=False,usegmt=True)
            r = "HTTP/1.1 200 OK\r\n"+"Content-Length: " + str(len(l))+ "\r\n" + "Content-Type: "+ type[0] +"; charset=utf-8\r\n"+"Date: "+date+"\r\n" + "Server: Mani v1.1\r\n"+"Last-Modified: "+m+"\r\n" + "\r\n";
           # print(r)
            r = r.encode("utf-8")
            self.client_connection.send(r+l);
           # print(r)
           # print(r.decode('utf-8'))
        except BaseException as e:
            print(e)
            header = 'HTTP/1.1 404 FILE NOT FOUND\n'
            type = 'text/html'
            header += 'Content-Type:' + type
            final_response = header.encode('utf-8')
            self.client_connection.send(final_response)
        self.client_connection.close()
script_loc = os.path.abspath(__file__)
script_dir = os.path.split(script_loc)[0]
p = os.path.split(script_dir)[0]
p += "/www/"
print(p)
HOST = ''
PORT = random.choice(range(1024,49150,100))

g = os.listdir(p)

print("Files List: {0}".format(g))
my_dict = {}
for v in g:
    my_dict[v] = 0

print(my_dict)

listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

listen_socket.bind((HOST, PORT))
threads = []

print ('Serving HTTP on port {0} ...'.format(PORT))
my_lock = threading.Lock()
while True:
    listen_socket.listen(5)
   # print(time.time())
    (client_connection, (ip,port) )= listen_socket.accept()
    t = MyServer(client_connection,ip,port)
    t.start()
    threads.append(t)

for t in threads:
    t.join()


import numpy as np
import pandas as pd
import riskfolio as rp
from statsmodels.tsa.stattools import grangercausalitytests
from tigramite import data_processing as pp
from tigramite import plotting as tp
from tigramite.pcmci import PCMCI
from tigramite.independence_tests.parcorr import ParCorr

def make_positive_definite(cov_matrix, epsilon=1e-2):
    eigvals, eigvecs = np.linalg.eigh(cov_matrix)

    if np.any(eigvals < epsilon):
        eigvals[eigvals < epsilon] = epsilon
        positive_definite_cov = np.dot(eigvecs, np.dot(np.diag(eigvals), eigvecs.T))
    else:
        positive_definite_cov = cov_matrix

    return positive_definite_cov

def equal_weights(returns):
    n_assets = returns.shape[1]
    w = np.full(n_assets, 1.0 / n_assets)
    w = pd.DataFrame(w, index=returns.columns, columns = ['weights'])
    return w

def random_weights(returns):
    n_assets = returns.shape[1]
    w = np.random.random(n_assets)
    w /= np.sum(w)
    w = pd.DataFrame(w, index=returns.columns, columns = ['weights'])
    return w

def mv_portfolio(returns, mv_conf, constraints = [None, None]):
    port = rp.Portfolio(returns=returns)

    print(f'\n{returns.index[0].date()}')
    print(f'{returns.index[-1].date()}')

    # # Add portfolio constraints
    # port.ainequality = constraints[0] # A
    # port.binequality = constraints[1] # B

    method_mu = mv_conf['method_mu']
    method_cov = mv_conf['method_cov']

    port.assets_stats(method_mu=method_mu, method_cov=method_cov, d=mv_conf['d_lib_const'])

    # port.cov = make_positive_definite(port.cov)

    # -------------------------------------------------------------- #
    # DPhil
    # port.cov = grangers_causation_matrix(Y, variables = Y.columns)
    # port.cov.reset_index(drop=True, inplace=True)
    # -------------------------------------------------------------- #

    # port.solvers = ['MOSEK']
    port.alpha = mv_conf['alpha']
    model= mv_conf['model'] # Could be Classic (historical), BL (Black Litterman) or FM (Factor Model)
    rm = mv_conf['rm'] # Risk measure used, this time will be variance
    obj = mv_conf['obj'] # Objective function, could be MinRisk, MaxRet, Utility or Sharpe
    hist = mv_conf['hist'] # Use historical scenarios for risk measures that depend on scenarios
    rf = mv_conf['rf'] # Risk free rate
    l = mv_conf['l'] # Risk aversion factor, only useful when obj is 'Utility'
    try:
        w = port.optimization(model=model, rm=rm, obj=obj, rf=rf, l=l, hist=hist)
        print(f'weights successfully calculated for {returns.index[0].date()}-{returns.index[-1].date()}')
    except:
        w = None
        print(f'weights index unsuccessful for {returns.index[0].date()}-{returns.index[-1].date()}. weights.tail(1).T used.\n')
    return w, port.cov

# -------------------------------------------------------------- #
# My DPhil Functions
# -------------------------------------------------------------- #

def grangers_causation_matrix(data, variables, maxlag, test='ssr_chi2test', verbose=False):
    df = pd.DataFrame(np.zeros((len(variables), len(variables))), columns=variables, index=variables)
    for c in df.columns:
        for r in df.index:
            test_result = grangercausalitytests(data[[r, c]], maxlag=maxlag, verbose=False)
            p_values = [round(test_result[i+1][0][test][1],4) for i in range(maxlag)]
            if verbose: print(f'Y = {r}, X = {c}, P Values = {p_values}')
            min_p_value = np.min(p_values)
            df.loc[r, c] = min_p_value
    df.columns = [var + '_x' for var in variables]
    df.index = [var + '_y' for var in variables]
    return df

def grangers_causation_matrix_portfolio(returns, mv_config, grangers_causation_matrix_config, constraints = [None, None]):

    port = rp.Portfolio(returns=returns)
    print(f'\n{returns.index[0].date()}')
    print(f'{returns.index[-1].date()}')

    # # Add portfolio constraints
    # port.ainequality = constraints[0] # A
    # port.binequality = constraints[1] # B

    method_mu = mv_config['method_mu']
    method_cov = mv_config['method_cov']
    port.assets_stats(method_mu=method_mu, method_cov=method_cov, d=mv_config['d_lib_const'])

    # -------------------------------------------------------------- #
    # DPhil
    port.cov = grangers_causation_matrix(returns, variables = returns.columns, maxlag = grangers_causation_matrix_config['maxlag'], test = grangers_causation_matrix_config['test'])
    port.cov.reset_index(drop=True, inplace=True)
    # -------------------------------------------------------------- #

    # port.solvers = ['MOSEK']
    port.alpha = mv_config['alpha']
    model= mv_config['model'] # Could be Classic (historical), BL (Black Litterman) or FM (Factor Model)
    rm = mv_config['rm'] # Risk measure used, this time will be variance
    obj = mv_config['obj'] # Objective function, could be MinRisk, MaxRet, Utility or Sharpe
    hist = mv_config['hist'] # Use historical scenarios for risk measures that depend on scenarios
    rf = mv_config['rf'] # Risk free rate
    l = mv_config['l'] # Risk aversion factor, only useful when obj is 'Utility'
    try:
        w = port.optimization(model=model, rm=rm, obj=obj, rf=rf, l=l, hist=hist)
        print(f'\nweights successfully calculated')
    except:
        w = None
        print(f'\nweights index unsuccessful. weights.tail(1).T used.\n')
    return w, port.cov

def PCMCI_wrapped(returns, mv_config, PCMCI_wrapped_causation_matrix_config, constraints = [None, None]):

    port = rp.Portfolio(returns=returns)
    print(f'\n{returns.index[0].date()}')
    print(f'{returns.index[-1].date()}')

    # # Add portfolio constraints
    # port.ainequality = constraints[0] # A
    # port.binequality = constraints[1] # B

    method_mu = mv_config['method_mu']
    method_cov = mv_config['method_cov']
    port.assets_stats(method_mu=method_mu, method_cov=method_cov, d=mv_config['d_lib_const'])

    # -------------------------------------------------------------- #
    # DPhil

    print('\nPCMCI\n')

    var_names = list(returns.columns)
    dataframe = pp.DataFrame(returns.values, var_names=var_names)
    alpha = PCMCI_wrapped_causation_matrix_config['pcmci_alpha']
    tau_max = PCMCI_wrapped_causation_matrix_config['pcmci_tau_max']

    if PCMCI_wrapped_causation_matrix_config['pcmci_cond_ind_test'] == 'ParCorr':
        pcmci_object = PCMCI(dataframe=dataframe, cond_ind_test=ParCorr())

    # results = pcmci_object.run_pcmci(tau_max=tau_max, pc_alpha=alpha)
    results = pcmci_object.run_pcmci(tau_max=tau_max, pc_alpha=None)

    # p-value omitting
    p_matrix = results['p_matrix']
    val_matrix = results['val_matrix']
    if PCMCI_wrapped_causation_matrix_config['pcmci_drop_val_below_alpha'] == True:
        val_matrix[p_matrix > alpha] = 0

    # --------- #
    # slice research !!

    # PCMCI_wrapped_causation_matrix_config['pcmci_relationships_slice']
    # simultanious slice: only current relationships ('0') - no lags
    # PCMCI_matrix = pd.DataFrame(val_matrix[:,:,PCMCI_wrapped_causation_matrix_config['pcmci_relationships_slice']])

    # Sum !
    sum_across_slices = val_matrix.sum(axis=2)
    PCMCI_matrix = pd.DataFrame(sum_across_slices)

    PCMCI_matrix.columns = returns.columns
    PCMCI_matrix.index = returns.columns

    if PCMCI_wrapped_causation_matrix_config['pcmci_plus_diag_cov'] == True:
        df2_diag = np.diag(port.cov)
        for i in range(len(PCMCI_matrix)):
            PCMCI_matrix.iat[i, i] += df2_diag[i]

    print('\n', PCMCI_matrix)

    port.cov = PCMCI_matrix
    port.cov.reset_index(drop=True, inplace=True)

    # -------------------------------------------------------------- #

    # port.solvers = ['MOSEK']
    port.alpha = mv_config['alpha']
    model= mv_config['model'] # Could be Classic (historical), BL (Black Litterman) or FM (Factor Model)
    rm = mv_config['rm'] # Risk measure used, this time will be variance
    obj = mv_config['obj'] # Objective function, could be MinRisk, MaxRet, Utility or Sharpe
    hist = mv_config['hist'] # Use historical scenarios for risk measures that depend on scenarios
    rf = mv_config['rf'] # Risk free rate
    l = mv_config['l'] # Risk aversion factor, only useful when obj is 'Utility'
    try:
        w = port.optimization(model=model, rm=rm, obj=obj, rf=rf, l=l, hist=hist)
        print(f'\nweights successfully calculated')
    except:
        w = None
        print(f'\nweights index unsuccessful. weights.tail(1).T used.\n')
    return w, port.cov


#!/usr/bin/env python
# -*- coding: UTF-8 -*-

# imported libs
import Libraries.Muta as MUTA
import Libraries.Attributes as ATTRIBUTES
import Libraries.Folders as PATHS
import Strings.Build as BUILD
import Strings.Attributes as ATTRSTR

# system libs
import logging
import os

logging.basicConfig(level=BUILD.LOGGER)

class Master:
	def __init__(self):
		self.writefile = BUILD.MASTER_META_FILE
		PATHS.clear_file(self.writefile)
		self.filelist = PATHS.search_valid_files(BUILD.TEST_DIRECTORY_MASTER, BUILD.VALID_FILE_EXTENSIONS)
		self.generate_meta_master()

	def generate_meta_master(self):
		for filename in self.filelist:
			audio_file = MUTA.Audio(filename, BUILD.TEST_DIRECTORY_MASTER)
			logging.info("Reading file: "+audio_file.file_path)
			with open(self.writefile,'a') as mpy:
				logging.info("Writing attributes ...")
				mpy.write(ATTRSTR.FNAME.format(audio_file.file_path))
				for attr in ATTRIBUTES.attributes_list:
					mpy.write(ATTRSTR.ATTRIBUTE.format(ATTRIBUTES.write_attributes_ID3_map[attr],getattr(audio_file,attr)))

if __name__ == "__main__":
	Master()


from datetime import datetime
from django.shortcuts import render, Http404, redirect, get_object_or_404
from django.contrib.auth.models import User
from .models import Team

# View teams manager
def team_manager_view(request):
    users = User.objects.all()

    if request.method == 'GET':
        order_by = request.GET.get('order_by', 'create_date')
        search = request.GET.get('search', '')
        teams = Team.objects.filter(name__icontains=search).order_by('{}'.format(order_by))
        context = {'teams': teams, 'users': users}
        return render(request, 'team/team_manager.html', context)
    elif request.method == 'POST':
        name = request.POST.get('name', None)
        user_id_list = request.POST.getlist('selected_users', None)
        users_list = []
        for user_id in user_id_list:
            users_list.append(get_object_or_404(User, pk=user_id))
        slug = "{}-{}".format(name.lower().replace(' ', '-'), datetime.today())
        new_team = Team.objects.create(name=name, slug=slug)
        new_team.members.set(users_list)
        order_by = request.GET.get('order_by', 'create_date')
        teams = Team.objects.order_by('{}'.format(order_by))
        context = {'teams': teams, 'users': users}

        return render(request, 'team/team_manager.html', context)
    else:
        return Http404('Not allowed')

# Edit team view, update the object attributes
def edit_team_view(request, team_id):
    team = get_object_or_404(Team, pk=team_id)

    users = User.objects.all()
    context = {'users': users}
    if request.method == 'POST':
        name = request.POST.get('new_team_name', None)
        new_users_list = request.POST.getlist('new_selected_users', None)
        users_list = []
        for user_id in new_users_list:
            users_list.append(get_object_or_404(User, pk=user_id))
        Team.objects.filter(pk=team_id).update(name=name)
        team.members.set(users_list)
        return redirect('team_manager')
    if request.method == 'GET':
        return render(request, 'team/edit_team.html', context)

    else:
        return Http404('Not allowed')

# Delete team view, delete the specific team object and use CASCADE to delete the boards, columns and tasks related
def delete_team_view(request, team_id):
    context = {}
    if request.method == 'POST':
        Team.objects.filter(pk=team_id).delete()
        return redirect('team_manager')
    if request.method == 'GET':
        return render(request, 'team/delete_team.html', context)

    else:
        return Http404('Not allowed')


#!/usr/bin/python3
"""Recursive function that queries the Reddit API and returns a list
containing the titles of all hot articles for a given subreddit."""
import requests

def recurse(subreddit, hot_list=[], data_after=''):
    """Fx to make the query and return list with titles of all articles"""
    url = "https://www.reddit.com/r/{}/hot.json?after={}".format(subreddit,
                                                                 data_after)
    headers_dict = {
        'User-Agent':
        'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.2.3) \
        Gecko/20100401 Firefox/3.6.3 (FM Scene 4.6.1)'}
    res = requests.get(url, headers=headers_dict, allow_redirects=False)
    if res.status_code == 200:
        data_after = res.json().get('data').get('after')
        data_children = res.json().get('data').get('children')
        for elem in data_children:
            hot_list.append(elem.get('data').get('title'))
        if data_after is None:
            return hot_list
        return recurse(subreddit, hot_list, data_after)
    else:
        return None


import statistics

import matplotlib.pyplot as plt
from matplotlib import ticker
import seaborn

import untappd

CHECKINS = untappd.load_latest_checkins()

START = min(c.datetime for c in CHECKINS)
END = max(c.datetime for c in CHECKINS)
by_year = {
    cat: {
        year: statistics.mean([
            c.rating
            for c in CHECKINS
            if c.datetime.year == year and c.beer.get_style_category() == cat
        ])
        for year in range(START.year, END.year + 1)
    }
    for cat in untappd.CATEGORY_KEYWORDS
}

seaborn.set()
plt.figure(figsize=(12.8, 7.2))
for year, checkins_by_cat in by_year.items():
    plt.bar(
        [f"{year} {cat}" for cat in checkins_by_cat.keys()],
        checkins_by_cat.values(),
    )
plt.xticks(rotation=-45)

all_vals = [v for year in by_year.values() for v in year.values()]
plt.ylim([min(all_vals) - 0.25, max(all_vals)])
plt.gca().yaxis.set_major_locator(ticker.MultipleLocator(0.1))
plt.ylabel("average rating")
plt.show()


# -*- coding: utf-8 -*-
from os.path import dirname, join

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec
from scipy.interpolate import interp1d
from tqdm import tqdm

def plot_vsys_kp(
    ax,
    res,
    title="",
    plot_rectangle=False,
    plot_lines=True,
    xlabels=False,
    ylabels=False,
    vmin=None,
    vmax=None,
):
    ax.set_title(title)

    # vmax = np.nanmax(np.abs(res["combined"]))
    # vmin = -vmax
    ax.imshow(
        res["combined"],
        aspect="auto",
        origin="lower",
        interpolation="none",
        vmin=vmin,
        vmax=vmax,
    )
    if plot_rectangle:
        ax.add_patch(
            plt.Rectangle(
                (
                    res["vsys_peak"] - res["vsys_width"],
                    res["kp_peak"] - res["kp_width"],
                ),
                2 * res["vsys_width"],
                2 * res["kp_width"],
                fill=False,
                color="red",
            )
        )
    if plot_lines:
        gap = 0.05
        n, m = res["combined"].shape
        x = np.interp(res["vsys_expected"], res["vsys"], np.arange(m)) + 0.5
        y = np.interp(res["kp_expected"], res["kp"], np.arange(n)) + 0.5
        ax.axvline(x, 0, y / n - gap, color="k", linestyle="dashed", alpha=0.5)
        ax.axvline(x, y / n + gap, 1, color="k", linestyle="dashed", alpha=0.5)
        ax.axhline(y, 0, x / m - gap, color="k", linestyle="dashed", alpha=0.5)
        ax.axhline(y, x / m + gap, 1, color="k", linestyle="dashed", alpha=0.5)

        if res["vsys_popt"] is not None and res["kp_popt"] is not None:
            x = np.interp(res["vsys_popt"][1], res["vsys"], np.arange(m)) + 0.5
            y = np.interp(res["kp_popt"][1], res["kp"], np.arange(n)) + 0.5
            ax.axvline(x, 0, y / n - gap, color="w", linestyle="dashdot", alpha=0.5)
            ax.axvline(x, y / n + gap, 1, color="w", linestyle="dashdot", alpha=0.5)
            ax.axhline(y, 0, x / m - gap, color="w", linestyle="dashdot", alpha=0.5)
            ax.axhline(y, x / m + gap, 1, color="w", linestyle="dashdot", alpha=0.5)

    xticks = np.unique(res["vsys"] // 50) * 50
    xticks_labels = np.array([f"{x:.3g}" for x in xticks])
    npoints = res["combined"].shape[1]
    xticks = interp1d(res["vsys"], np.arange(npoints), fill_value="extrapolate")(xticks)
    xticks_labels = xticks_labels[(xticks >= 0) & (xticks <= npoints)]
    xticks = xticks[(xticks >= 0) & (xticks <= npoints)]
    ax.set_xticks(xticks)
    if xlabels:
        ax.set_xticklabels(xticks_labels, fontsize="large")
        ax.set_xlabel("vsys [km/s]", fontsize="x-large")
    else:
        ax.set_xticklabels([])

    yticks = np.unique(res["kp"] // 50) * 50
    yticks_labels = np.array([f"{x:.3g}" for x in yticks])
    npoints = res["combined"].shape[0]
    yticks = interp1d(res["kp"], np.arange(npoints), fill_value="extrapolate")(yticks)
    yticks_labels = yticks_labels[(yticks >= 0) & (yticks <= npoints)]
    yticks = yticks[(yticks >= 0) & (yticks <= npoints)]
    ax.set_yticks(yticks)
    if ylabels:
        ax.set_yticklabels(yticks_labels, fontsize="large")
        ax.set_ylabel("Kp [km/s]", fontsize="x-large")
    else:
        ax.set_yticklabels([])

star = "WASP-107"
planet = "b"
n1 = 0
elem = ("H2O",)
elem_str = "_".join(elem)

ns = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
# ns = [1, 2, 3, 4, 8]
vmin = -4
vmax = 4

fig = plt.figure(figsize=(16, 9))
gs = GridSpec(3, len(ns), figure=fig, wspace=0.1, hspace=0.1)

# this is one column
# ax1 = fig.add_subplot(gs[0, 0])
# ax2 = fig.add_subplot(gs[1, 0])
# ax3 = fig.add_subplot(gs[2, 0])
# ax4 = fig.add_subplot(gs[3, 0])

for i, n2 in tqdm(enumerate(ns), total=len(ns)):
    n_sec = 1
    for j, (k, selection) in tqdm(
        enumerate([(1, "IT"), (1, "OOT")]), total=2, leave=False
    ):
        folder = join(
            dirname(__file__),
            (
                f"../plots/{star}_{planet}_{n1}_{n2}_{elem_str}_real_{k}_{n_sec}_{selection}"
            ),
        )
        try:
            data = np.load(join(folder, "data.npz"), allow_pickle=True)
            res = data["res"][()]
            selection = data["selection"][()]
            rv_array = data["rv_array"]
            cc_data = data["cc_data"]
            combined = data["combined"]

            if j == 0:
                title = f"{n2}"
            else:
                title = ""

            ax = fig.add_subplot(gs[j, i])
            plot_vsys_kp(
                ax,
                res,
                title=title,
                plot_lines=True,
                xlabels=j == 1,
                ylabels=i == 0,
                vmin=vmin,
                vmax=vmax,
            )

            if j == 0:
                in_transit = res["in_transit"]
                vp_idx = np.interp(res["vp"], rv_array, np.arange(rv_array.size))
                vp_new = res["vsys"][res["vsys_peak"]] + res["kp"][
                    res["kp_peak"]
                ] * np.sin(2 * np.pi * res["phi"])
                vp_idx_new = np.interp(vp_new, rv_array, np.arange(rv_array.size))

                n_obs, n_points = combined.shape

                ax = fig.add_subplot(gs[-1, i])
                ax.imshow(combined, aspect="auto", origin="lower")
                ax.axhline(np.arange(n_obs)[in_transit][0] - 0.5, c="k", ls="--")
                ax.axhline(np.arange(n_obs)[in_transit][-1] + 0.5, c="k", ls="--")

                vp_y = np.where(in_transit, np.nan, np.arange(len(vp_idx)))
                ax.plot(vp_idx, vp_y, "k--", alpha=0.5)

                vp_y = np.where(in_transit, np.nan, np.arange(len(vp_idx_new)))
                ax.plot(vp_idx_new, vp_y, "w--", alpha=0.5)

        except FileNotFoundError:
            print(f"File not found: {folder}")
            pass

plt.suptitle(elem_str)
plt.show()
pass


# coding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals

import errno
import json
import os
import platform
import sys

from pip._vendor.packaging.requirements import Requirement

from ._compat import makedirs
from .exceptions import PipToolsError
from .utils import as_tuple, key_from_req, lookup_table

_PEP425_PY_TAGS = {"cpython": "cp", "pypy": "pp", "ironpython": "ip", "jython": "jy"}

def _implementation_name():
    """similar to PEP 425, however the minor version is separated from the
    major to differentation "3.10" and "31.0".
    """
    implementation_name = platform.python_implementation().lower()
    implementation = _PEP425_PY_TAGS.get(implementation_name, "??")
    return "{}{}.{}".format(implementation, *sys.version_info)

class CorruptCacheError(PipToolsError):
    def __init__(self, path):
        self.path = path

    def __str__(self):
        lines = [
            "The dependency cache seems to have been corrupted.",
            "Inspect, or delete, the following file:",
            "  {}".format(self.path),
        ]
        return os.linesep.join(lines)

def read_cache_file(cache_file_path):
    with open(cache_file_path, "r") as cache_file:
        try:
            doc = json.load(cache_file)
        except ValueError:
            raise CorruptCacheError(cache_file_path)

        # Check version and load the contents
        if doc["__format__"] != 1:
            raise ValueError("Unknown cache file format")
        return doc["dependencies"]

class DependencyCache(object):
    """
    Creates a new persistent dependency cache for the current Python version.
    The cache file is written to the appropriate user cache dir for the
    current platform, i.e.

        ~/.cache/pip-tools/depcache-pyX.Y.json

    Where py indicates the Python implementation.
    Where X.Y indicates the Python version.
    """

    def __init__(self, cache_dir):
        makedirs(cache_dir, exist_ok=True)
        cache_filename = "depcache-{}.json".format(_implementation_name())

        self._cache_file = os.path.join(cache_dir, cache_filename)
        self._cache = None

    @property
    def cache(self):
        """
        The dictionary that is the actual in-memory cache.  This property
        lazily loads the cache from disk.
        """
        if self._cache is None:
            self.read_cache()
        return self._cache

    def as_cache_key(self, ireq):
        """
        Given a requirement, return its cache key. This behavior is a little weird
        in order to allow backwards compatibility with cache files. For a requirement
        without extras, this will return, for example:

        ("ipython", "2.1.0")

        For a requirement with extras, the extras will be comma-separated and appended
        to the version, inside brackets, like so:

        ("ipython", "2.1.0[nbconvert,notebook]")
        """
        name, version, extras = as_tuple(ireq)
        if not extras:
            extras_string = ""
        else:
            extras_string = "[{}]".format(",".join(extras))
        return name, "{}{}".format(version, extras_string)

    def read_cache(self):
        """Reads the cached contents into memory."""
        try:
            self._cache = read_cache_file(self._cache_file)
        except IOError as e:
            if e.errno != errno.ENOENT:
                raise
            self._cache = {}

    def write_cache(self):
        """Writes the cache to disk as JSON."""
        doc = {"__format__": 1, "dependencies": self._cache}
        with open(self._cache_file, "w") as f:
            json.dump(doc, f, sort_keys=True)

    def clear(self):
        self._cache = {}
        self.write_cache()

    def __contains__(self, ireq):
        pkgname, pkgversion_and_extras = self.as_cache_key(ireq)
        return pkgversion_and_extras in self.cache.get(pkgname, {})

    def __getitem__(self, ireq):
        pkgname, pkgversion_and_extras = self.as_cache_key(ireq)
        return self.cache[pkgname][pkgversion_and_extras]

    def __setitem__(self, ireq, values):
        pkgname, pkgversion_and_extras = self.as_cache_key(ireq)
        self.cache.setdefault(pkgname, {})
        self.cache[pkgname][pkgversion_and_extras] = values
        self.write_cache()

    def reverse_dependencies(self, ireqs):
        """
        Returns a lookup table of reverse dependencies for all the given ireqs.

        Since this is all static, it only works if the dependency cache
        contains the complete data, otherwise you end up with a partial view.
        This is typically no problem if you use this function after the entire
        dependency tree is resolved.
        """
        ireqs_as_cache_values = [self.as_cache_key(ireq) for ireq in ireqs]
        return self._reverse_dependencies(ireqs_as_cache_values)

    def _reverse_dependencies(self, cache_keys):
        """
        Returns a lookup table of reverse dependencies for all the given cache keys.

        Example input:

            [('pep8', '1.5.7'),
             ('flake8', '2.4.0'),
             ('mccabe', '0.3'),
             ('pyflakes', '0.8.1')]

        Example output:

            {'pep8': ['flake8'],
             'flake8': [],
             'mccabe': ['flake8'],
             'pyflakes': ['flake8']}

        """
        # First, collect all the dependencies into a sequence of (parent, child)
        # tuples, like [('flake8', 'pep8'), ('flake8', 'mccabe'), ...]
        return lookup_table(
            (key_from_req(Requirement(dep_name)), name)
            for name, version_and_extras in cache_keys
            for dep_name in self.cache[name][version_and_extras]
        )


import logging

from .ged import get_inner_html
from .parser2009 import Parser2009
from ..models import elev2010

class Parser2010(Parser2009):
    """Parser for the year 2010 onwards"""

    _logger = logging.getLogger(__name__ + '.' + 'Parser2010')

    Elev = elev2010.Elev

    tr1_cols = (
        None, # Nr. crt.
        None, # Nume... <script>
        None, # Pozitia in ierarhie...
        None, # Pozitia in ierarhie...
        'scoala',
        'judet',
        'promotie_anterioara',
        'forma_invatamant',
        'specializare',
        'd_romana_competente', 'd_romana_scris_nota', 'd_romana_scris_nota_contestatie', 'd_romana_scris_nota_finala',
        'd_limba_materna_nume',
        'd_limba_moderna_nume', 'd_limba_moderna_nota',
        'd_profil_scris_nume',
        'd_alegere_scris_nume',
        'd_competente_digitale',
        None, # LuatDePe_Bac...
        None, # Luat_DePe_Bac...
        )

    tr2_cols = (
        'd_limba_materna_competente', 'd_limba_materna_scris_nota', 'd_limba_materna_scris_nota_contestatie', 'd_limba_materna_scris_nota_finala',
        'd_profil_scris_nota', 'd_profil_scris_nota_contestatie', 'd_profil_scris_nota_finala',
        'd_alegere_scris_nota', 'd_alegere_scris_nota_contestatie', 'd_alegere_scris_nota_finala'
        )

    @classmethod
    def data_from_tr_filter(cls, s):
        return s.replace('&nbsp', '').strip()

    @classmethod
    def get_extra_data_from_tr(cls, tr):
        items = cls.get_luat_de_pe_bacalaureat(tr)
        return {
            'nume': items[0][0].replace('<br>', ''),
            'rezultat_final': items[2][1]}

    @classmethod
    def get_main_table_from_file(cls, f):
        """Return the mainTable table from file f while taking care of all the
        obfuscation and garbage.
        """

        for line in f:
            html = get_inner_html(line)
            if html:
                break
        else:
            return None
        html = html[html.index('<HTML>'):] # remove leading garbage
        return cls.get_main_table_from_html(html)


import sys
from collections import deque

gear = {}
for i in range(4):
    gear[i+1] = deque(list(map(int, sys.stdin.readline().rstrip())))
K = int(sys.stdin.readline().rstrip())
command_rotate = [list(map(int, sys.stdin.readline().split())) for _ in range(K)]
for g, r in command_rotate:
    #1번과 2번, 2번과 3번, 3번과 4번 연동 회전 여부
    rotate_true = [False] * 3
    for i in range(3):
        if gear[i+1][2] != gear[i+2][6]:
            rotate_true[i] = True
    #기어 회전
    gear[g].rotate(r)
    for i in range(g-1,3):
        if rotate_true[i]:gear[i+2].rotate(r*((-1)**(g-i+2)))
        else:break
    for i in range(g-2,-1,-1):
        if rotate_true[i]:gear[i+1].rotate(r*((-1)**(g-i+1)))
        else:break
result = 0
for i in range(1,5):
    if gear[i][0] == 1:
        result += 2**(i-1)
print(result)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created in April 2019
@author: Nathan de Lara <nathan.delara@polytechnique.org>
"""
import warnings
from typing import Optional, Union

import numpy as np

def get_values(shape: tuple, values: Union[np.ndarray, dict], default_value: float = -1) -> np.ndarray:
    """Get values as array."""
    n = shape[0]
    if isinstance(values, np.ndarray):
        if len(values) != n:
            raise ValueError('Dimensions mismatch between adjacency and values.')
        else:
            values = values.astype(float)
    elif isinstance(values, dict):
        keys, values_ = np.array(list(values.keys())), np.array(list(values.values()))
        if np.min(values_) < 0:
            warnings.warn(Warning("Negative values will not be taken into account."))
        values = default_value * np.ones(n)
        values[keys] = values_
    else:
        values = np.ones(n)
    return values

def stack_values(shape: tuple, values_row: Optional[Union[np.ndarray, dict]],
                 values_col: Optional[Union[np.ndarray, dict]] = None, default_value: float = -1) -> np.ndarray:
    """Process values for rows and columns and stack the results into a single vector."""
    n_row, n_col = shape
    if values_row is None and values_col is None:
        values_row = np.ones(n_row)
        values_col = default_value * np.ones(n_col)
    elif values_row is None:
        values_row = default_value * np.ones(n_row)
    elif values_col is None:
        values_col = default_value * np.ones(n_col)
    values_row = get_values(shape, values_row, default_value)
    values_col = get_values((n_col,), values_col, default_value)
    return np.hstack((values_row, values_col))

def values2prob(n: int, values: np.ndarray = None) -> np.ndarray:
    """Transform seed values into probability vector.

    Parameters
    ----------
    n : int
        Number of nodes.
    values :
        If ``None``, the uniform distribution is used.
        Otherwise, a non-negative, non-zero vector or a dictionary must be provided.

    Returns
    -------
    probs: np.ndarray
        A probability vector.
    """
    if values is None:
        return np.ones(n) / n
    else:
        values = get_values((n,), values)
        probs = np.zeros_like(values, dtype=float)
        ix = (values > 0)
        probs[ix] = values[ix]
        if probs.sum() > 0:
            return probs / probs.sum()
        else:
            raise ValueError('At least one value must be positive.')


import datetime
from pydantic import BaseModel, Field
from bson import ObjectId
from typing import Optional

class PyObjectId(ObjectId):
    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, v):
        if not ObjectId.is_valid(v):
            raise ValueError("Invalid objectid")
        return ObjectId(v)

    @classmethod
    def __modify_schema__(cls, field_schema):
        field_schema.update(type="string")

class LikeModel(BaseModel):
    id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
    userId: PyObjectId = Field(...)
    postId: Optional[PyObjectId]
    created_at: datetime.datetime = None

    class Config:
        allow_population_by_field_name = True
        arbitrary_types_allowed = True
        json_encoders = {ObjectId: str}
        schema_extra = {
            "example": {
                "post": "Ceci est un exemple de post que vous avez liké",
                "created_at": "2022-10-12T11:08:54.712000"
            }
        }


"""
Configure the application to be able to use a redis client through
`app.config`. Configuration of Redis endpoint location is done through
environment variables.
"""
import redis
import os

def configure(app):
    """
    Configures the app to have a redis client instance available globally.
    To configure the host, port, and db the app connects to, you must set the
    following environment variables:

        REDIS_HOST="localhost"
        REDIS_PORT=6379
        REDIS_DB=0

    """
    redis_host =os.environ.get("REDIS_HOST", "localhost")
    redis_port =os.environ.get("REDIS_PORT", 6379)
    redis_db = os.environ.get("REDIS_DB", 0)

    app.config.update(
        redis=redis.StrictRedis(
            host=redis_host,
            port=redis_port,
            db=redis_db
        )
    )


import boto3

region="us-east-1"
_ec = boto3.client('ec2',region_name=region)

def listInstances():
    try:
        list_of_instances=[]
        instances= _ec.describe_instances()
        for item in instances['Reservations']:
            for instance in item['Instances']:
                list_of_instances.append(instance['InstanceId'])
        return list_of_instances
    except Exception as e:
        print(e)

def StopInstances(Instance_list):
    try:
         _ec.stop_instances(InstanceIds=Instance_list)
    except Exception as e:
        print(e)

def StartInstances(Instance_list):
    _ec.start_instances(InstanceIds=Instance_list)