#data=EV_popu_WA_data
#X=EV_popu_WA_data[['longitudinal','lateral']]

import warnings
warnings.filterwarnings("ignore")
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import numpy as np
import pandas as pd

data=pd.read_excel('https://github.com/xinyu998/WA-EV-population-ML-project/blob/main/EVprocessed_data.xlsx?raw=true')
X=data[['longitudinal','lateral']]

## K-mean Elbow method to find the best k value
from sklearn import metrics
from scipy.spatial.distance import cdist
distortions = []
inertias = []
mapping1 = {}
mapping2 = {}
K=range(2,12)

for k in K:
    # Building and fitting the model
    kmeanModel = KMeans(n_clusters=k).fit(X)
    kmeanModel.fit(X)

    distortions.append(sum(np.min(cdist(X, kmeanModel.cluster_centers_,
                                        'euclidean'), axis=1)) / X.shape[0])
    inertias.append(kmeanModel.inertia_)

    mapping1[k] = sum(np.min(cdist(X, kmeanModel.cluster_centers_,
                                   'euclidean'), axis=1)) / X.shape[0]
    mapping2[k] = kmeanModel.inertia_
for key, val in mapping1.items():
    print(f'{key} : {val}')
# plt.plot(K, distortions, 'bx-')
# plt.xlabel('Values of K')
# plt.ylabel('Distortion')
# plt.title('The Elbow Method using Distortion')
# plt.show()

kmeans_model=KMeans(init="k-means++",n_clusters=6)
kmeans_model.fit(X)
h=.02
#print(X.iloc[:,0].min())
# Plot the decision boundary
x_min, x_max = X.iloc[:, 0].min()-1, X.iloc[:, 0].max()+1
y_min, y_max = X.iloc[:, 1].min()-1, X.iloc[:, 1].max()+1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

#Obtain labels for each point in mesh. Use last trained model.
Z = kmeans_model.predict(np.c_[xx.ravel(), yy.ravel()])

# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure(figsize=(15,8))
plt.imshow(Z, interpolation="nearest", extent=(xx.min(), xx.max(), yy.min(), yy.max()),
           cmap='coolwarm', aspect="auto", origin="lower")

# Plot the projected data on 2D space
plt.plot(X.iloc[:, 0], X.iloc[:, 1], 'k.', markersize=2)

# Plot the centroids as a white X
centroids = kmeans_model.cluster_centers_
plt.scatter(centroids[:, 0], centroids[:, 1], marker="x", s=120, linewidths=5, color="w", zorder=10)

plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.show()

# get sample points from each cluster
#data=pd.read_excel('https://github.com/xinyu998/WA-EV-population-ML-project/blob/main/EVprocessed_data.xlsx?raw=true')

"""**Plot of Each Clusters**"""

#i th cluster

## get sample points from each cluster
cluster_map=pd.DataFrame()
cluster_map['data_index'] = data.index.values
cluster_map['cluster'] = kmeans_model.labels_
cluster_map['longitudinal']=data.longitudinal
cluster_map['lateral']=data.lateral
cluster_map['year']=data.ModelYear
cluster_map['make']=data.Make
cluster_map['range']=data.ElectricRange
#cluster_map.to_excel('cluster3.xlsx')

# fig, axs = plt.subplots(2,3)
# for i,axs in zip(range (0,6),axs.ravel()):
#     cluster= cluster_map.loc[cluster_map['cluster']==i]
#     x_min, x_max = cluster.iloc[:,2].min()-0.2, cluster.iloc[:,2].max()+0.2
#     y_min, y_max = cluster.iloc[:,3].min()-0.2, cluster.iloc[:,3].max()+0.2
#     axs.plot(cluster.iloc[:,2], cluster.iloc[:, 3],'k.',markersize=2)
#     axs.set_xlim(x_min, x_max)
#     axs.set_ylim(y_min, y_max)
#     axs.set_title('cluster '+str([i]))
# plt.show()

"""**Shape of Clusters**"""

for i in range (0,6):
  cluster= cluster_map.loc[cluster_map['cluster']==i]
  print("cluster"+str(i) +"shape: ", cluster.shape)

cluster0=cluster_map.loc[cluster_map['cluster']==0]
X0=cluster0[['longitudinal','lateral']]
kmeans_model=KMeans(init="k-means++",n_clusters=5)
kmeans_model.fit(X0)
h=.02
#print(X.iloc[:,0].min())
# Plot the decision boundary
x_min, x_max = X0.iloc[:, 0].min()-1, X0.iloc[:, 0].max()+1
y_min, y_max = X0.iloc[:, 1].min()-1, X0.iloc[:, 1].max()+1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

#Obtain labels for each point in mesh. Use last trained model.
Z = kmeans_model.predict(np.c_[xx.ravel(), yy.ravel()])

# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure(figsize=(15,8))
plt.imshow(Z, interpolation="nearest", extent=(xx.min(), xx.max(), yy.min(), yy.max()),
           cmap='coolwarm', aspect="auto", origin="lower")

# Plot the projected data on 2D space
plt.plot(X0.iloc[:, 0], X0.iloc[:, 1], 'k.', markersize=2)

# Plot the centroids as a white X
centroids0 = kmeans_model.cluster_centers_
plt.scatter(centroids0[:, 0], centroids0[:, 1], marker="x", s=120, linewidths=5, color="w", zorder=10)

plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.show()
cluster0['newcluster']=kmeans_model.labels_
cluster0.to_excel('cluster0.xlsx')

#dividing cluster0
cluster0_0=cluster0.loc[cluster0['newcluster']==0]
X00=cluster0_0[['longitudinal','lateral']]
kmeans_model=KMeans(init="k-means++",n_clusters=5)
kmeans_model.fit(X00)
centroids00 = kmeans_model.cluster_centers_
cluster0_0['new2cluster']=kmeans_model.labels_
cluster0_0.to_excel('cluster00.xlsx')

cluster0_1=cluster0.loc[cluster0['newcluster']==1]
X01=cluster0_1[['longitudinal','lateral']]
kmeans_model=KMeans(init="k-means++",n_clusters=5)
kmeans_model.fit(X01)
centroids01 = kmeans_model.cluster_centers_
cluster0_1['new2cluster']=kmeans_model.labels_
cluster0_1.to_excel('cluster01.xlsx')

cluster0_2=cluster0.loc[cluster0['newcluster']==2]
X02=cluster0_2[['longitudinal','lateral']]
kmeans_model=KMeans(init="k-means++",n_clusters=5)
kmeans_model.fit(X02)
centroids02 = kmeans_model.cluster_centers_
cluster0_2['new2cluster']=kmeans_model.labels_
cluster0_2.to_excel('cluster02.xlsx')

cluster0_3=cluster0.loc[cluster0['newcluster']==3]
X03=cluster0_3[['longitudinal','lateral']]
kmeans_model=KMeans(init="k-means++",n_clusters=5)
kmeans_model.fit(X03)
centroids03 = kmeans_model.cluster_centers_
cluster0_3['new2cluster']=kmeans_model.labels_
cluster0_3.to_excel('cluster03.xlsx')

cluster0_4=cluster0.loc[cluster0['newcluster']==4]
X04=cluster0_4[['longitudinal','lateral']]
kmeans_model=KMeans(init="k-means++",n_clusters=5)
kmeans_model.fit(X04)
centroids04 = kmeans_model.cluster_centers_
cluster0_4['new2cluster']=kmeans_model.labels_
cluster0_4.to_excel('cluster04.xlsx')

#average distance of EV and Charging station
cluster0_0=cluster0.loc[cluster0['newcluster']==0]
#calculate number of charging ports
range00=np.mean(cluster0_0[['range']])
X00=cluster0_0[['longitudinal','lateral']]
size=X00.shape
print(size)
#dis_value=[]
#for i in range (0,9049):
 # dis_value[i,0]=((X00.iloc[i,0]*54.6-centroids0[0,0]*54.6)**2+(X00.iloc[i,1]*69-centroids0[0,1]*69)**2)**0.5
#print(dis_value)
#dis_mean=np.mean(dis_value)
#print(dis_mean)

cluster1=cluster_map.loc[cluster_map['cluster']==1]
X1=cluster1[['longitudinal','lateral']]
kmeans_model=KMeans(init="k-means++",n_clusters=5)
kmeans_model.fit(X1)
h=.02
#print(X.iloc[:,0].min())
# Plot the decision boundary
x_min, x_max = X1.iloc[:, 0].min()-1, X1.iloc[:, 0].max()+1
y_min, y_max = X1.iloc[:, 1].min()-1, X1.iloc[:, 1].max()+1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

#Obtain labels for each point in mesh. Use last trained model.
Z = kmeans_model.predict(np.c_[xx.ravel(), yy.ravel()])

# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure(figsize=(15,8))
plt.imshow(Z, interpolation="nearest", extent=(xx.min(), xx.max(), yy.min(), yy.max()),
           cmap='coolwarm', aspect="auto", origin="lower")

# Plot the projected data on 2D space
plt.plot(X1.iloc[:, 0], X1.iloc[:, 1], 'k.', markersize=2)

# Plot the centroids as a white X
centroids1 = kmeans_model.cluster_centers_
plt.scatter(centroids1[:, 0], centroids1[:, 1], marker="x", s=120, linewidths=5, color="w", zorder=10)

plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.show()
cluster1['newcluster']=kmeans_model.labels_
cluster1.to_excel('cluster1.xlsx')

cluster2=cluster_map.loc[cluster_map['cluster']==2]
X2=cluster2[['longitudinal','lateral']]
kmeans_model=KMeans(init="k-means++",n_clusters=5)
kmeans_model.fit(X2)
h=.02
#print(X.iloc[:,0].min())
# Plot the decision boundary
x_min, x_max = X2.iloc[:, 0].min()-1, X2.iloc[:, 0].max()+1
y_min, y_max = X2.iloc[:, 1].min()-1, X2.iloc[:, 1].max()+1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

#Obtain labels for each point in mesh. Use last trained model.
Z = kmeans_model.predict(np.c_[xx.ravel(), yy.ravel()])

# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure(figsize=(15,8))
plt.imshow(Z, interpolation="nearest", extent=(xx.min(), xx.max(), yy.min(), yy.max()),
           cmap='coolwarm', aspect="auto", origin="lower")

# Plot the projected data on 2D space
plt.plot(X2.iloc[:, 0], X2.iloc[:, 1], 'k.', markersize=2)

# Plot the centroids as a white X
centroids2 = kmeans_model.cluster_centers_
plt.scatter(centroids2[:, 0], centroids2[:, 1], marker="x", s=120, linewidths=5, color="w", zorder=10)

plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.show()
cluster2['newcluster']=kmeans_model.labels_
cluster2.to_excel('cluster2.xlsx')

cluster3=cluster_map.loc[cluster_map['cluster']==3]
X3=cluster3[['longitudinal','lateral']]
kmeans_model=KMeans(init="k-means++",n_clusters=6)
kmeans_model.fit(X3)
h=.02
#print(X.iloc[:,0].min())
# Plot the decision boundary
x_min, x_max = X3.iloc[:, 0].min()-1, X3.iloc[:, 0].max()+1
y_min, y_max = X3.iloc[:, 1].min()-1, X3.iloc[:, 1].max()+1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

#Obtain labels for each point in mesh. Use last trained model.
Z = kmeans_model.predict(np.c_[xx.ravel(), yy.ravel()])

# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure(figsize=(15,8))
plt.imshow(Z, interpolation="nearest", extent=(xx.min(), xx.max(), yy.min(), yy.max()),
           cmap='coolwarm', aspect="auto", origin="lower")

# Plot the projected data on 2D space
plt.plot(X3.iloc[:, 0], X3.iloc[:, 1], 'k.', markersize=2)

# Plot the centroids as a white X
centroids3 = kmeans_model.cluster_centers_
plt.scatter(centroids3[:, 0], centroids3[:, 1], marker="x", s=120, linewidths=5, color="w", zorder=10)

plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.show()
cluster3['newcluster']=kmeans_model.labels_
cluster3.to_excel('cluster3.xlsx')

cluster4=cluster_map.loc[cluster_map['cluster']==4]
X4=cluster4[['longitudinal','lateral']]
kmeans_model=KMeans(init="k-means++",n_clusters=5)
kmeans_model.fit(X4)
h=.02
#print(X.iloc[:,0].min())
# Plot the decision boundary
x_min, x_max = X4.iloc[:, 0].min()-1, X4.iloc[:, 0].max()+1
y_min, y_max = X4.iloc[:, 1].min()-1, X4.iloc[:, 1].max()+1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

#Obtain labels for each point in mesh. Use last trained model.
Z = kmeans_model.predict(np.c_[xx.ravel(), yy.ravel()])

# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure(figsize=(15,8))
plt.imshow(Z, interpolation="nearest", extent=(xx.min(), xx.max(), yy.min(), yy.max()),
           cmap='coolwarm', aspect="auto", origin="lower")

# Plot the projected data on 2D space
plt.plot(X4.iloc[:, 0], X4.iloc[:, 1], 'k.', markersize=2)

# Plot the centroids as a white X
centroids4 = kmeans_model.cluster_centers_
plt.scatter(centroids4[:, 0], centroids4[:, 1], marker="x", s=120, linewidths=5, color="w", zorder=10)

plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.show()
cluster4['newcluster']=kmeans_model.labels_
cluster4.to_excel('cluster4.xlsx')

cluster5=cluster_map.loc[cluster_map['cluster']==5]
X5=cluster5[['longitudinal','lateral']]
kmeans_model=KMeans(init="k-means++",n_clusters=5)
kmeans_model.fit(X5)
h=.02
#print(X.iloc[:,0].min())
# Plot the decision boundary
x_min, x_max = X5.iloc[:, 0].min()-1, X5.iloc[:, 0].max()+1
y_min, y_max = X5.iloc[:, 1].min()-1, X5.iloc[:, 1].max()+1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

#Obtain labels for each point in mesh. Use last trained model.
Z = kmeans_model.predict(np.c_[xx.ravel(), yy.ravel()])

# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure(figsize=(15,8))
plt.imshow(Z, interpolation="nearest", extent=(xx.min(), xx.max(), yy.min(), yy.max()),
           cmap='coolwarm', aspect="auto", origin="lower")

# Plot the projected data on 2D space
plt.plot(X5.iloc[:, 0], X5.iloc[:, 1], 'k.', markersize=2)

# Plot the centroids as a white X
centroids5 = kmeans_model.cluster_centers_
plt.scatter(centroids5[:, 0], centroids5[:, 1], marker="x", s=120, linewidths=5, color="w", zorder=10)

plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.show()
cluster5['newcluster']=kmeans_model.labels_
cluster5.to_excel('cluster5.xlsx')

#Plot the total station area
SC=np.concatenate((centroids00,centroids01,centroids02,centroids03,centroids04,centroids1,centroids2,centroids3,centroids4,centroids5))
print(SC)
plt.figure()
plt.scatter(SC[:,0], SC[:,1], marker="^", s=120, linewidths=1, color="blue", zorder=10)
plt.show()
SC=pd.DataFrame(SC)
SC.to_excel('Chargingstation.xlsx')


import logging

def init_logging(logger, log_level = "INFO"):
    """ initializes logging """
    log = logging.getLogger(logger)  # get reference to logger
    # test if we have set up the logger before
    if not len(log.handlers):
        # perform setup by adding handler:
        formatter = logging.Formatter('%(asctime)s %(name)s(%(levelname)s): %(message)s',"%H:%M:%S")
        handler_stream = logging.StreamHandler()
        handler_stream.setFormatter(formatter)
        log.addHandler(handler_stream)
        # using this decorator, we can count the number of error messages
        class callcounted(object):
            """Decorator to determine number of calls for a method"""
            def __init__(self,method):
                self.method=method
                self.counter=0
            def __call__(self,*args,**kwargs):
                self.counter+=1
                return self.method(*args,**kwargs)
        log.error=callcounted(log.error)
        # set the logging level
        numeric_level = getattr(logging, log_level,
                                None)  # default: INFO messages and above
        log.setLevel(numeric_level)
    return log


import feedparser
import time
import re

def get_rss_episodes(feed_url):

    def get_mp3_url(entry):
        mp3_links = [
            link['href']
            for link in entry["links"]
            if link["type"] == "audio/mpeg" and re.search(r'\.mp3(\?|$)', link["href"])
        ]
        if mp3_links:
            return mp3_links[0]

        return ''

    rss_parsed = feedparser.parse(feed_url)

    all_rss_episodes = [
        {
            "title": entry["title"],
            "published": entry["published_parsed"],
            "date_str": time.strftime("%Y-%m-%d", entry["published_parsed"]),
            "mp3_url": get_mp3_url(entry)
        }
        for entry in rss_parsed.entries
    ]

    return all_rss_episodes


import os
import sys
from inaSpeechSegmenter import Segmenter
from inaSpeechSegmenter.export_funcs import seg2csv, seg2textgrid
from collections import deque
import common
import seg

logger = common.getLogger(__file__)

CONFIG_WORK_KEY = "split"

def main(input_file):
    # txtファイルに出力された無音検出結果から、音声ファイルをどのように分割するかを決定する（実際に分割はしない）
    logger.info("2-1. 音声分割設定開始 - {}".format(os.path.basename(input_file)))

    config = common.readConfig(input_file)
    if config["DEFAULT"].get(CONFIG_WORK_KEY) == common.DONE:
        logger.info("完了済みのためスキップ(音声分割設定)")
        return

    # 入力の音声ファイルのパスを指定
    logger.info("音声ファイル：{}".format(os.path.basename(input_file)))

    type = os.path.splitext(os.path.basename(input_file))[1][1:]  # 拡張子(読み込み時のフォーマット指定)

    # 分析結果ファイルを順に開く
    seg_resultfile_index = 0
    segmentation = deque()
    connect = False
    prev_fixed = False
    prev_noEnergy_length = 0  # 前回の無音部分の長さ
    prev_length = 0  # 前回の長さ
    index = 0

    logger.info("分析結果ファイル読み込み中…")

    isRecognizeNoize = common.isRecognizeNoize()
    logger.info("ノイズ部分も認識対象にするかどうか：{}".format(isRecognizeNoize))

    split_len = config["DEFAULT"].getint(
        seg.CONFIG_SEG_SPLIT, common.getSegTmpAudioLength()
    )  # 分割単位(バージョンによっては音声のiniに書いていないので、commonから取得)
    logger.info("分割単位：{}min".format(int(split_len / 60 / 1000)))

    while True:
        seg_result_file = common.getSegResultFile(input_file, seg_resultfile_index)

        # 分析結果ファイルがなければ終了
        if os.path.exists(seg_result_file) == False:
            break

        logger.info(
            "分析結果ファイル：{}({})".format(
                os.path.basename(seg_result_file), seg_resultfile_index + 1
            )
        )

        # 分析結果ファイル（タブ区切り）を開く
        with open(seg_result_file, "r") as f:
            segment_label = ""

            f.readline()  # ヘッダを読み捨て

            file_data = f.readlines()
            for line in file_data:
                segment = line.split("\t")

                index += 1
                # logger.info ("分析結果ファイル読み込み中… {}".format(index))

                segment_label = segment[0]

                # 区間の開始時刻の単位を秒からミリ秒に変換 + ファイル番号によって補正
                start_time = float(segment[1]) * 1000 + float(
                    split_len * seg_resultfile_index
                )
                end_time = float(segment[2]) * 1000 + float(
                    split_len * seg_resultfile_index
                )
                org_start_time = start_time
                org_end_time = end_time

                # 認識対象とするかどうか
                is_target = False
                if isRecognizeNoize:  # 無音区間以外を認識対象とする
                    if segment_label != "noEnergy":  # 無音区間以外なら認識対象とする（noiseなども対象）
                        is_target = True
                else:
                    if segment_label == "speech":  #  'speech' のみ認識対象とする
                        is_target = True

                if is_target:
                    if connect:  # 1つ前と連結させる
                        prev = segmentation.pop()
                        start_time = prev["start_time"]
                        org_start_time = prev["org_start_time"]
                    else:  # 今回が音がある部分の先頭
                        start_time -= min(
                            prev_noEnergy_length, 500
                        )  # 前回の無音部分の0.5秒を頭に入れる

                    connect = False
                    prev_fixed = False
                    prev_length = end_time - start_time

                    mlength = 2 * 60 * 1000  # N分ごとに区切る(これ以上長いと音声認識がエラーを返す可能性がある)
                    while True:
                        length = end_time - start_time

                        if length < mlength:
                            segmentation.append(
                                {
                                    "segment_label": segment_label,
                                    "start_time": start_time,
                                    "end_time": end_time,
                                    "org_start_time": org_start_time,
                                    "org_end_time": org_end_time,
                                }
                            )  # push(音声の末尾部分)
                            break
                        else:
                            segmentation.append(
                                {
                                    "segment_label": segment_label,
                                    "start_time": start_time,
                                    "end_time": start_time + mlength,
                                    "org_start_time": org_start_time,
                                    "org_end_time": start_time + mlength,
                                }
                            )  # push(N分)
                            start_time += mlength
                            org_start_time = start_time
                            logger.debug("length > mlength: length={}".format(length))

                else:  # 無音区間
                    length = end_time - start_time
                    prev_noEnergy_length = length
                    connect = False
                    if len(segmentation) > 0:
                        if (
                            length < 1 * 1000 and length + prev_length < 5 * 1000
                        ):  # 無音がX秒未満(息継ぎとかを無視したい)、Y秒未満の場合(長すぎにならないようにする)は、次の音声と接続させる
                            connect = True
                            logger.debug("connect. len:{}".format(length))
                        elif prev_fixed == False:
                            prev = (
                                segmentation.pop()
                            )  # 無音がX秒以上の場合は、前の音声が確定する。前の音声の終了時間を伸ばす（最後に無音がつく。最大5秒とする。5秒でいいかは微妙）⇒認識が遅くなるが、こっちの方が精度がいい
                            prev["end_time"] += min(length, 5000)
                            segmentation.append(prev)  # push
                            prev_fixed = True  # 何度も連結しないようにする
                            logger.debug(
                                "prev_fixed. {},{}".format(
                                    prev["start_time"], prev["end_time"]
                                )
                            )

        seg_resultfile_index += 1  # 次のファイルへ
        if segment_label != "noEnergy":  # 音声ありの状態でファイルが閉じた場合、次のファイルと連結させるために長さ0の無音区間を作る
            t = split_len * seg_resultfile_index
            segmentation.append(
                {
                    "segment_label": "noEnergy",
                    "start_time": t,
                    "end_time": t,
                    "org_start_time": t,
                    "org_end_time": t,
                }
            )
            logger.debug("ファイルの区切りで無音追加：{}({})".format(seg_resultfile_index, t))

    # 音声を分割する
    split_result_file = common.getSplitResultFile(input_file)
    logger.info("分割結果ファイル：{}".format(os.path.basename(split_result_file)))
    base = os.path.splitext(os.path.basename(input_file))[0]  # 拡張子なしのファイル名（話者）

    with open(split_result_file, "w") as f:  # 分割結果ファイルに結果書き込み+音声書き込み
        speech_segment_index = 1
        index = 0

        # 分割して出力する音声ファイルのフォルダとプレフィックスまで指定
        audio_file_prefix = common.getSplitAudioFilePrefix(input_file)

        logger.debug("音声分割設定中… {}".format(base))

        for segment in segmentation:
            # segmentはタプル
            # タプルの第1要素が区間のラベル
            segment_label = segment["segment_label"]

            index = index + 1
            # logger.debug ("音声分割中… {}/{}".format(index, len(segmentation)))

            if (index % 100) == 0 or (
                len(segmentation) == index
            ):  # 100行ごとか、最後の1行で進捗を出す
                logger.debug(
                    "　音声分割設定中… {} {}/{}".format(base, index, len(segmentation))
                )

            if segment_label != "noEnergy":  # 無音区間以外の部分だけを出力する
                start_time = segment["start_time"]
                end_time = segment["end_time"]
                org_start_time = segment["org_start_time"]
                org_end_time = segment["org_end_time"]

                filename = "{}{}.flac".format(audio_file_prefix, speech_segment_index)

                # 分割結果の時間やファイル名など
                # ID,分割した音声ファイル名(flac),開始時間(冒頭無音あり),終了時間(末尾無音あり),長さ(無音あり),開始時間(冒頭無音なし),長さ(末尾無音なし)の順
                f.write(
                    "{}	{}	{}	{}	{}	{}	{}\n".format(
                        speech_segment_index,
                        filename,
                        start_time,
                        end_time,
                        end_time - start_time,
                        org_start_time,
                        org_end_time,
                    )
                )

                speech_segment_index += 1

    # 終了したことをiniファイルに保存
    common.updateConfig(input_file, {CONFIG_WORK_KEY: common.DONE})

    logger.info("音声分割設定終了！ {}".format(os.path.basename(input_file)))

# 直接起動した場合
if __name__ == "__main__":
    if len(sys.argv) < 2:
        logger.error("ファイルが指定されていません")
        sys.exit(1)

    main(sys.argv[1])


import pyspark
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils
import sys
from kafka import KafkaProducer
from pyspark import SparkContext
import json
from datetime import datetime
from constants import topic_name1, topic_name2, topic_name3
from constants import prg_topics, states

def time_to_format(t):
    return datetime.strftime(datetime.fromtimestamp(t / 1000.0), "%Y.%m.%d-%H:%M:%S")

def filter_topics(x):
    for topic in x["group"]["group_topics"]:
        if topic["topic_name"] in prg_topics:
            return True
    return False

def handler(message, topic, producer):
    records = message.take(1000000000000000000000)  # collect doesn't work :(
    for record in records:
        producer.send(topic, str(record))

def to_appropriate_format(x):
    current_time = datetime.now()
    return {
        "cities": [x["group"]["group_city"]],
        "day": current_time.day,
        "month": current_time.month,
        "minute": current_time.minute,
        "hour": current_time.hour,
        "year": current_time.year
    }

def reduce_data(x, y):
    x["cities"] += y["cities"]
    return x

if __name__ == "__main__":
    print(pyspark.__version__)
    producer = KafkaProducer(bootstrap_servers=sys.argv[1],
                             value_serializer=lambda x: x.encode('UTF-8')) #localhost:9092

    sc = SparkContext("local[*]", "MeetsUp")
    sc.setLogLevel("ERROR")

    ssc = StreamingContext(sc, 5)
    kvs = KafkaUtils.createStream(ssc, sys.argv[2], "1", {"meetsup-input": 3}) # localhost:2181
    us_ss = kvs.map(lambda x: json.loads(x[1])) \
        .filter(lambda x: x['group']['group_country'] == 'us')

    us_meetsup = us_ss.map(lambda x: {
        "event": {
            "event_name": x["event"]["event_name"],
            "event_id": x["event"]["event_id"],
            "time": time_to_format(x["event"]["time"])

        },
        "group_city": x["group"]["group_city"],
        "group_id": x["group"]["group_id"],
        "group_name": x["group"]["group_name"],
        "group_state": states[x["group"]["group_state"]],
    }) \
        .foreachRDD(lambda x: handler(x, topic_name1, producer))

    us_cities = us_ss.window(60, 60) \
        .map(to_appropriate_format) \
        .reduce(reduce_data).foreachRDD(lambda x: handler(x, topic_name2, producer))

    prog_meetups = us_ss.filter(filter_topics).map(lambda x: {
        "event": {
            "event_name": x["event"]["event_name"],
            "event_id": x["event"]["event_id"],
            "time": time_to_format(x["event"]["time"])

        },
        "group_topics": list(map(lambda y: y["topic_name"], x["group"]["group_topics"])),
        "group_city": x["group"]["group_city"],
        "group_id": x["group"]["group_id"],
        "group_name": x["group"]["group_name"],
        "group_state": states[x["group"]["group_state"]],
    }) \
        .foreachRDD(lambda x: handler(x, topic_name3, producer))

    ssc.start()
    ssc.awaitTermination()


import subprocess
import os
from PyQt6.QtCore import QThread

script_code = """
import carla

client = carla.Client('localhost', 2000)
client.set_timeout(5.0)
world = client.get_world()

walker_list = world.get_actors().filter('walker.pedestrian.*')
vehicle_list = world.get_actors().filter('vehicle.*')

for walker in walker_list:
    walker.destroy()

if len(vehicle_list) == 0:
  settings = world.get_settings()
  settings.synchronous_mode = False
  settings.no_rendering_mode = False
  settings.fixed_delta_seconds = None
  world.apply_settings(settings)
"""

class RemoveAllWalkersThread(QThread):
  def __init__(self, MainWindow, parent=None):
    super().__init__(parent)
    self.MainWindow = MainWindow

  def run(self):
    with open("remove_all_walkers_script.py", "w") as f:
      f.write(script_code)

    try:
      subprocess.run(["python", "remove_all_walkers_script.py"])
    except KeyboardInterrupt:
      pass
    finally:
      os.remove("remove_all_walkers_script.py")

      if os.path.exists("generate_walkers_script.py"):
        os.remove("generate_walkers_script.py")

      self.MainWindow.ui.generate_walkers_button.setEnabled(True)
      self.MainWindow.ui.walker_list_widget.clear()
      self.MainWindow.ui.walker_count_label.setText("0")


# part 1
question=["Which animal is known as the ‘Ship of the Desert?(1000)","How many letters are there in the English alphabet?(2000)","What do you call the person who brings a letter to your home from post office?(3000)","How many consonants are there in the English alphabet? (5000)","Which country is Delhi located in?(10,000)"]

# part 2
first_option=["1.cat","1.22","1.postman","1.57","1.USA"]
second_option=["2.camel","2.28","2.police","2.29","2.India"]
third_option=["3.cow","3.26","3.doctor","3.32","3.Switzerland"]
fourth_option=["4.bull","4.29","4.teacher","4.22","4.England"]

#part 3
all_options=[first_option,second_option,third_option,fourth_option]

#part 4
ans_key=[2,3,1,4,2]
# part 1
price=1000
for i in range(len(question)):
	print (question[i], len(question[i]))
	print (first_option[i])
	print (second_option[i])
	print (third_option[i])
	print (fourth_option[i])
	user=int(input("Enter your answer "))
	if user==ans_key[i]:
		print ("apka answer sahi hai  ")
		price+=1000
		print(price)
	else:
		print ("sadly apka answer wrong hai  ")
		break


# https://leetcode.com/problems/valid-palindrome/description/

class Solution(object):
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if len(s) < 2: return True
        ps = 0
        pe = len(s)-1
        while(ps < pe):
            if not s[ps].isalpha() and not s[ps].isdigit():
                ps += 1
                continue
            if not s[pe].isalpha() and not s[pe].isdigit():
                pe -= 1
                continue
            if s[ps].lower() != s[pe].lower():
                return False
            ps += 1
            pe -= 1
        return True


r"""Functions to find peaks in data above a certain threshold.

:copyright:
    EQcorrscan developers.

:license:
    GNU Lesser General Public License, Version 3
    (https://www.gnu.org/copyleft/lesser.html)
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import random
import numpy as np

from obspy import UTCDateTime
from scipy import ndimage

def is_prime(number):
    """
    Function to test primality of a number. Function lifted from online
    resource:
        http://www.codeproject.com/Articles/691200/Primality-test-algorithms-Prime-test-The-fastest-w

    This function is distributed under a separate licence:
        This article, along with any associated source code and files, is \
        licensed under The Code Project Open License (CPOL)

    :type number: int
    :param number: Integer to test for primality

    :returns: bool

    >>> is_prime(4)
    False
    >>> is_prime(3)
    True
    """
    ''' if number != 1 '''
    if number > 1:
        ''' repeat the test few times '''
        for time in range(3):
            ''' Draw a RANDOM number in range of number ( Z_number )  '''
            randomNumber = random.randint(2, number - 1)
            ''' Test if a^(n-1) = 1 mod n '''
            if pow(randomNumber, number - 1, number) != 1:
                return False
        return True
    else:
        ''' case number == 1 '''
        return False

def find_peaks2_short(arr, thresh, trig_int, debug=0, starttime=False,
                      samp_rate=1.0):
    """
    Determine peaks in an array of data above a certain threshold.

    Uses a mask to remove data below threshold and finds peaks in what is left.

    :type arr: numpy.ndarray
    :param arr: 1-D numpy array is required
    :type thresh: float
    :param thresh: The threshold below which will be considered noise and \
        peaks will not be found in.
    :type trig_int: int
    :param trig_int: The minimum difference in samples between triggers,\
        if multiple peaks within this window this code will find the highest.
    :type debug: int
    :param debug: Optional, debug level 0-5
    :type starttime: obspy.core.utcdatetime.UTCDateTime
    :param starttime: Starttime for plotting, only used if debug > 2.
    :type samp_rate: float
    :param samp_rate: Sampling rate in Hz, only used for plotting if debug > 2.

    :return: peaks: Lists of tuples of peak values and locations.
    :rtype: list

    >>> import numpy as np
    >>> arr = np.random.randn(100)
    >>> threshold = 10
    >>> arr[40] = 20
    >>> arr[60] = 100
    >>> find_peaks2_short(arr, threshold, 3)
    [(20.0, 40), (100.0, 60)]
    """
    if not starttime:
        starttime = UTCDateTime(0)
    # Set everything below the threshold to zero
    image = np.copy(arr)
    image = np.abs(image)
    image[image < thresh] = 0
    if len(image[image > thresh]) == 0:
        if debug > 0:
            print('No values over threshold found')
        return []
    if debug > 0:
        print(' '.join(['Found', str(len(image[image > thresh])),
                        'samples above the threshold']))
    initial_peaks = []
    peaks = []
    # Find the peaks
    labeled_image, number_of_objects = ndimage.label(image)
    peak_slices = ndimage.find_objects(labeled_image)
    for peak_slice in peak_slices:
        # print('Width of peak='+str(peak_slice[0].stop-peak_slice[0].start)
        window = arr[peak_slice[0].start: peak_slice[0].stop]
        initial_peaks.append((max(window),
                              int(peak_slice[0].start + np.argmax(window))))
    # Sort initial peaks according to amplitude
    peaks_sort = sorted(initial_peaks, key=lambda amplitude: amplitude[0],
                        reverse=True)
    # Debugging
    if debug >= 4:
        for peak in initial_peaks:
            print(peak)
    if initial_peaks:
        peaks.append(peaks_sort[0])  # Definitely take the biggest peak
        if debug > 3:
            print(' '.join(['Added the biggest peak of', str(peaks[0][0]),
                            'at sample', str(peaks[0][1])]))
        if len(initial_peaks) > 1:
            if debug > 3:
                msg = ' '.join(['Multiple peaks found, checking',
                                'them now to see if they overlap'])
                print(msg)
            for next_peak in peaks_sort:
                # i in range(1,len(peaks_sort)):
                # Loop through the amplitude sorted peaks
                # if the next highest amplitude peak is within trig_int of any
                # peak already in peaks then we don't want it, else, add it
                # next_peak=peaks_sort[i]
                if debug > 3:
                    print(next_peak)
                for peak in peaks:
                    # Use add as a switch for whether or not to append
                    # next peak to peaks, if once gone through all the peaks
                    # it is True, then we will add it, otherwise we won't!
                    if abs(next_peak[1] - peak[1]) < trig_int:
                        if debug > 3:
                            msg = ' '.join(['Difference in time is',
                                            str(next_peak[1] - peak[1]), '\n',
                                            'Which is less than',
                                            str(trig_int)])
                            print(msg)
                        add = False
                        # Need to exit the loop here if false
                        break
                    else:
                        add = True
                if add:
                    if debug > 3:
                        msg = ' '.join(['Adding peak of', str(next_peak[0]),
                                        'at sample', str(next_peak[1])])
                        print(msg)
                    peaks.append(next_peak)
                elif debug > 3:
                    msg = ' '.join(['I did not add peak of', str(next_peak[0]),
                                    'at sample', str(next_peak[1])])
                    print(msg)

        if debug >= 3:
            from eqcorrscan.utils import plotting
            _fname = ''.join(['peaks_',
                              starttime.datetime.strftime('%Y-%m-%d'),
                              '.pdf'])
            plotting.peaks_plot(data=image, starttime=starttime,
                                samp_rate=samp_rate, save=True,
                                peaks=peaks, savefile=_fname)
        peaks = sorted(peaks, key=lambda time: time[1], reverse=False)
        return peaks
    else:
        print('No peaks for you!')
        return peaks

def find_peaks_dep(arr, thresh, trig_int, debug=0, starttime=False,
                   samp_rate=1.0):
    """
    Determine peaks in an array of data above a certain threshold: depreciated.

    Depreciated peak-finding routine, very slow, but accurate.  If all else \
    fails this one should work.

    :type arr: numpy.ndarray
    :param arr: 1-D numpy array is required
    :type thresh: float
    :param thresh: The threshold below which will be considered noise and \
        peaks will not be found in.
    :type trig_int: int
    :param trig_int: The minimum difference in samples between triggers,\
        if multiple peaks within this window this code will find the highest.
    :type starttime: obspy.core.utcdatetime.UTCDateTime
    :param starttime: Starttime for plotting, only used if debug > 2.
    :type samp_rate: float
    :param samp_rate: Sampling rate in Hz, only used for plotting if debug > 2.

    :return: peaks: Lists of tuples of peak values and locations.
    :rtype: list

    >>> import numpy as np
    >>> arr = np.random.randn(100)
    >>> threshold = 10
    >>> arr[40] = 20
    >>> arr[60] = 100
    >>> find_peaks_dep(arr, threshold, 3)
    [(20.0, 40), (100.0, 60)]
    """
    if not starttime:
        starttime = UTCDateTime(0)
    # Perform some checks
    if trig_int < 3:
        msg = 'Trigger interval must be greater than 2 samples to find maxima'
        raise IOError(msg)
    # from joblib import Parallel, delayed
    # Will find peaks in the absolute then transfer these to the true values
    sig = np.abs(arr) - thresh
    true_peaks = []
    for i in range(int(trig_int), int(len(sig) - trig_int), int(trig_int)):
        window = sig[i - trig_int: i + trig_int]
        # Define a moving window containing data from +/- the trigger iterval
        peaks = []
        locs = []
        for j in range(1, len(window) - 1):
            # Find all turning points within the window
            if window[j] > 0.0 and window[j] > window[j + 1] and\
               window[j] > window[j - 1]:
                peaks.append(window[j])
                locs.append(i - trig_int + j)
        # Find maximum peak in window
        if peaks:
            true_peaks.append((np.max(np.array(peaks)),
                               locs[np.argmax(np.array(peaks))]))
    # Get unique values
    peaks = sorted(list(set(true_peaks)), key=lambda loc: loc[1])
    # Find highest peak in peaks within trig_int of each other
    for i in range(1, len(peaks) - 1):
        if peaks[i + 1][1] - peaks[i][1] < trig_int:
            if peaks[i][0] < peaks[i + 1][0]:
                peaks[i] = peaks[i + 1]
            else:
                peaks[i + 1] = peaks[i]
        elif peaks[i][1] - peaks[i - 1][1] < trig_int:
            if peaks[i][0] < peaks[i - 1][0]:
                peaks[i] = peaks[i - 1]
            else:
                peaks[i - 1] = peaks[i]
    peaks = sorted(list(set(peaks)), key=lambda loc: loc[1])
    if debug >= 3:
        from eqcorrscan.utils import plotting
        _fname = ''.join(['peaks_',
                          starttime.datetime.strftime('%Y-%m-%d'),
                          '.pdf'])
        plotting.peaks_plot(arr, starttime, samp_rate, True, peaks,
                            _fname)
    peaks = [(peak[0] + thresh, peak[1]) for peak in peaks]
    return peaks

def coin_trig(peaks, stachans, samp_rate, moveout, min_trig, trig_int):
    """
    Find network coincidence triggers within peaks of detection statistics.

    Useful for finding network detections from sets of detections on individual
    stations.

    :type peaks: list
    :param peaks: List of lists of tuples of (peak, index) for each \
        station-channel.  Index should be in samples.
    :type stachans: list
    :param stachans: List of tuples of (station, channel) in the order of \
        peaks.
    :type samp_rate: float
    :param samp_rate: Sampling rate in Hz
    :type moveout: float
    :param moveout: Allowable network moveout in seconds.
    :type min_trig: int
    :param min_trig: Minimum station-channels required to declare a trigger.
    :type trig_int: float
    :param trig_int:
        Minimum allowable time between network triggers in seconds.

    :return:
        List of tuples of (peak, index), for the earliest detected station.
    :rtype: list

    >>> peaks = [[(0.5, 100), (0.3, 800)], [(0.4, 120), (0.7, 850)]]
    >>> triggers = coin_trig(peaks, [('a', 'Z'), ('b', 'Z')], 10, 3, 2, 1)
    >>> print(triggers)
    [(0.45, 100)]
    """
    triggers = []
    for stachan, _peaks in zip(stachans, peaks):
        for peak in _peaks:
            trigger = (peak[1], peak[0], '.'.join(stachan))
            triggers.append(trigger)
    coincidence_triggers = []
    for i, master in enumerate(triggers):
        slaves = triggers[i + 1:]
        coincidence = 1
        trig_time = master[0]
        trig_val = master[1]
        for slave in slaves:
            if abs(slave[0] - master[0]) <= (moveout * samp_rate) and \
               slave[2] != master[2]:
                coincidence += 1
                if slave[0] < master[0]:
                    trig_time = slave[0]
                trig_val += slave[1]
        if coincidence >= min_trig:
            coincidence_triggers.append((trig_val / coincidence,
                                         trig_time))
    # Sort by trigger-value, largest to smallest - remove duplicate detections
    if coincidence_triggers:
        coincidence_triggers.sort(key=lambda tup: tup[0], reverse=True)
        output = [coincidence_triggers[0]]
        for coincidence_trigger in coincidence_triggers[1:]:
            add = True
            for peak in output:
                # If the event occurs within the trig_int time then do not add
                # it, and break out of the inner loop.
                if abs(coincidence_trigger[1] - peak[1]) < (trig_int *
                                                            samp_rate):
                    add = False
                    break
            if add:
                output.append((coincidence_trigger[0],
                               coincidence_trigger[1]))
        output.sort(key=lambda tup: tup[1])
        return output
    else:
        return []

if __name__ == "__main__":
    import doctest
    doctest.testmod()


import matplotlib.pyplot as plt

if __name__ == "__main__":
    fig = plt.figure()
    ax = plt.axes()

    W, H = map(int, input().split())

    # plot all points to be valid
    for i in range(W):
        for j in range(H):
            plt.plot([i], [j], "go")

    # graves
    for _ in range(int(input())):
        x, y = map(int, input().split())
        plt.plot(x, y, "ro")

    quivers = list()

    # portals
    for _ in range(int(input())):
        x1, y1, x2, y2, t = map(int, input().split())
        plt.text((x1+x2) / 2, (y1+y2) / 2, str(t))
        plt.plot([x1, x2], [y1, y2], "g--")
        quivers.append((x1, y1, (x2-x1)/2, (y2-y1)/2))

    plt.quiver([a[0] for a in quivers], [b[1] for b in quivers],
               [c[2] for c in quivers], [d[3] for d in quivers], scale=5)

    # boundaries
    plt.plot([-1, W, W, -1, -1], [-1, -1, H, H, -1], "b--")

    # start, goal is cyan dot
    plt.plot([W-1], [H-1], "co")

    # start, goal is cyan dot
    plt.plot([0], [0], "co")

    # make sure you see the whole map
    plt.ylim([-2, H+2])
    plt.xlim([-2, W+2])

    plt.show()


from exp1 import kl_div
import models as model
import utils_plots as disply
import matplotlib.pyplot as plt
import numpy as np

MAX_ITER = 500
# 2-dim example
DIM_Z = 2  # dimension of z

## defining target dist, p(z)
PROBS = np.array( [0.7, 0.3] )
MU_ARR  = np.array([ [1, 1],\
                   [-1, -1]  ])
VAR_ARR = np.zeros((2,2,2))
VAR_ARR[0,:,:] = np.eye(2)
VAR_ARR[1,:,:] = np.eye(2)/2.
log_pz,_ = model.gaussian_mix_init(MU_ARR, VAR_ARR, PROBS)

## defining the variational model
PSEUDO_SIZE = 1000
SAMPLING_SIZE = 100

gp_var = 1
gp_len = 100000
(gp_s,gp_t) = model.pseudo_data_gen(DIM_Z,PSEUDO_SIZE)

log_qw, w_gen = model.uniform_init(-1,+1)

w_samples = w_gen(SAMPLING_SIZE)

z = model.reparam(w_samples, gp_var, gp_len, gp_s, gp_t)
#plt.plot(gp_s, gp_t[:,1],'r--')
#plt.plot(w_samples, z[:,1], 'b.')

kl_distance = kl_div( gp_t, gp_var, gp_len, w_samples, gp_s, log_pz, log_qw )
print('KL: %s' % (kl_distance))

i=0
while (not np.isnan(kl_distance)) and (i<MAX_ITER) :
    i+=1
    w_samples = w_gen(SAMPLING_SIZE)
    kl_distance = kl_div( gp_t, gp_var, gp_len, w_samples, gp_s, log_pz, log_qw )
    print('KL -%s : %s' % (i,kl_distance))

#plt.show()


import gym
from code import MultiArmedBandit, QLearning
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

env = gym.make('FrozenLake-v0')

def getavg(no=1, algo=MultiArmedBandit):
    lists = []
    out = pd.DataFrame()
    for i in range((no+1)):
        agent = algo()
        action_values, rewards = agent.fit(env, steps=500)
        lists.append(rewards)
    df = pd.DataFrame(lists, columns=list(range(100)))
    return list(df.mean())

def lrl(arr):
    return list(range(len(arr)))

#guy1 = getavg(no=1, algo=MultiArmedBandit)
#guy2 = getavg(no=5, algo=MultiArmedBandit)
print("mab")
guy3 = getavg(no=10, algo=MultiArmedBandit)

#q1 = getavg(no=1, algo=QLearning)
#q5 = getavg(no=5, algo=QLearning)
print("ql")
q10 = getavg(no=10, algo=QLearning)

fig, ax = plt.subplots()

#ax.plot(lrl(guy1), guy1, c='b', label="MAB-1")
#ax.plot(lrl(guy2), guy2, c='r', label="MAB-5")
ax.plot(lrl(guy3), guy3, c='g', label="MAB-10")

#ax.plot(lrl(q1), q1, c='y', label="QL-1")
#ax.plot(lrl(q5), q5, c='k', label="QL-5")
ax.plot(lrl(q10), q10, c='m', label="QL-10")

plt.legend(loc="lower right")
ax.set(xlabel='Index', ylabel='Rewards',
       title='Problem 2B')
ax.grid()

fig.savefig("2C.png")
plt.show()


from celery import shared_task
from django.core.management import call_command
from io import StringIO
from constance import config
from django.core.mail import send_mail

from urllib3.exceptions import InsecureRequestWarning
import requests
import urllib

from airfields.tasks import pull_airfields, pull_airfields_maps, get_airfieldmap_model
from radionav.tasks import pull_radionav
from acc.tasks import pull_sectors

# disable warning message when using verify=False
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

@shared_task
def download_last_airac():
    out = StringIO()
    call_command("download_last_airac", stdout=out)
    return out.getvalue().split("\n")

@shared_task
def pull_from_diapason():
    if not config.FALLBACK_URL:
        raise ValueError("FALLBACK_URL n'a pas été configuré correctement")
    session = requests.session()
    session.proxies = urllib.request.getproxies()
    pull_airfields(session)
    pull_airfields_maps(session)
    pull_radionav(session)
    pull_sectors(session)
    notify_managers()
    return True

def notify_managers():
    if config.AIRAC_UPDATE_MANAGERS:
        map_count = get_airfieldmap_model().objects.filter(pdf__isnull=False).count()
        success_message = "Les données disponibles sur Coconuts ont bien été mises à jour à partir de {} :\n{} cartes ont été téléchargées.".format(
            config.FALLBACK_URL, map_count)
        print(success_message)
        send_mail(
            '{}{}'.format(config.EMAIL_SUBJECT_PREFIX,
                          "Coconuts mis à jour grâce à {}".format(config.FALLBACK_URL)),
            success_message, config.EMAIL_ADMIN,
            config.AIRAC_UPDATE_MANAGERS.split(';'), fail_silently=False)


# -*- coding: utf-8 -*-
# @Time : 2022/9/13 下午4:02
# @Author : qu hao
# @File : excute_image_data.py

import os

def excute_image(root_path, label):
    image_path = root_path+label+'_image'
    label_path = root_path+label+'_label'
    image = os.listdir(image_path)
    for i in image:
        # 命名格式
        txt_path = i[:-4] + '.txt'
        full_path = os.path.join(label_path, txt_path)
        file = open(full_path, 'w')
        # 写入的语句
        file.write(label)

    print('成功写入-'+label+'-：'+str(len(image)))

def main():
    # txt文件的存放路径
    root_path = "data/train/"
    excute_image(root_path, 'ants')
    excute_image(root_path, 'bees')

if __name__ == '__main__':
    main()


import math
import pandas as pd
import requests
import re
import numpy as np
import Hauser_matrix_functions as hmf
import itertools

meta_url = 'https://gpcrdb.org/services/residues/extended/'

gpcr_keys_1 = ['ICL1','ICL2','ICL3','ECL1','ECL2','ECL3','C-term','N-term']

def get_meta_df(url, file_path):
    """
    Obtiene los metadatos para cada GPCR, mediante la GPCRdb.
    :param url: URL donde consulta los datos de GPCRdb.
    :param file_path: Ruta donde se encuentra alojado el archivo estructural, para obtener el nombre del GPCR.
    :return: Un dataframe que contiene los metadatos para cada GPCR a procesar.
    """
    pdb_name = file_path.split('/')[-1][:-4].lower()
    url_pdb = url + pdb_name.lower()
    res = requests.get(url_pdb).json()
    df = pd.DataFrame(res)
    reduced_df = df[['sequence_number',
                     'amino_acid',
                     'protein_segment',
                     'display_generic_number']]
    reduced_df['display_generic_number'].fillna('Nan', inplace=True)
    return reduced_df

def df_2_list_of_lists(reduced_df):
    """
    Convierte el dataframe de metadatos en una lista de columnas (Row_list).
    :param reduced_df: El dataframe de metadatos.
    :return: La Row_list generada.
    """
    Row_list = []
    for index, rows in reduced_df.iterrows():
        append_list = [rows.sequence_number,
                       rows.amino_acid,
                       rows.protein_segment,
                       rows.display_generic_number]
        Row_list.append(append_list)
    Row_list = obtain_ballest_repr(Row_list)
    return Row_list

def selector_representacion_ballesteros(key_helix, ballest_index):
    """
    Genera las nuevas representaciones para los fragmentos de las helices de los GPCR.
    :param key_helix: Nombre de la helice a buscar.
    :param ballest_index: Indice de ballesteros a buscar.
    :return: Nueva representación para cada aminoacido en las helices del GPCR.
    """
    if key_helix in hmf.gpcr_keys_0.keys():
        for key, value in hmf.gpcr_keys_0[key_helix].items():
            try:
                if ballest_index in key:
                    return key_helix + value
            except:
                if ballest_index == key:
                    return key_helix + value
    elif key_helix in gpcr_keys_1:
        return key_helix

def make_ballest_index(generic_number):
    """
    Genera los índices de Ballesteros a partir de los números genéricos de GPCRdb
    :param generic_number: Número generico de GPCRdb.
    :return: Indice de Ballesteros
    """
    if generic_number != 'Nan':
        list_generic = re.split('\.|x', generic_number)
        return int(list_generic[-1])

def obtain_ballest_repr(Row_list):
    """
    Para cada elemento en la Row_list genera la representación de los fragmentos del GPCR.
    :param Row_list: Lista de columnas con los metadatos del GPCR.
    :return: Nueva lista de columnas (Row_list), donde el último valor ahora es la representación de fragmentos para
             el GPCR.
    """
    for aa in Row_list:
        repr_ballesteros = selector_representacion_ballesteros(aa[-2], make_ballest_index(aa[-1]))
        aa.append(repr_ballesteros)
    return Row_list

def filtrar_contactos_relevantes(mapa, filtro1, filtro2):
    """
    Filtra solo los contactos del mapa CAM que se encuentren entre las cotas establecidas pro el
    filtro1 y el filtro2.
    :param mapa: Mapa CAM a filtrar.
    :param filtro1: Cota inferior del filtro.
    :param filtro2: Cota superior del filtro.
    :return: Mapa CAM filtrado con los contactos relevantes de acuerdo a las cotas.
    """
    coord_filtro = []
    coordenadas_filtro_tupla = np.where((filtro2 >= mapa) & (mapa > filtro1))
    coord_x, coord_y = coordenadas_filtro_tupla
    for x, y in zip(coord_x, coord_y):
        coord_filtro.append([x, y])
    return coord_filtro

def get_claves_matriz(lista_coordenadas, diccionario_claves):
    """
    Genera una lista que almacena los contactos establecidos, a partir de un diccionario con coordenadas y una
    lista con contactos.
    :param lista_coordenadas: Lista con los residuos que establecen contacto.
    :param diccionario_claves: Diccionario que almacena las coordenadas de los residuos.
    :return: Lista con las coordenadas de los residuos que establecen contacto.
    """
    coords = []
    keys = list(diccionario_claves.keys())
    values = list(diccionario_claves.values())
    for coord in lista_coordenadas:
        index_x = values.index(coord[0])
        index_y = values.index(coord[1])
        key_x = keys[index_x]
        key_y = keys[index_y]
        coords.append((key_x, key_y))
    return coords

def get_secciones_relevantes(mapa, cota_inferior=0.5):
    """
    Encuentra las secciones que establecen contactos, de acuerdo a su relevancia en los mapas CAM.
    :param mapa: Mapa a evaluar.
    :param cota_inferior: Valor mínimo de los mapas CAM desde el que se evaluara la relevancia.
    :return: Diccionario {rango evaluado : secciones del GPCR con contactos relevantes en el rango evaluado}.
    """
    secciones = {}
    val = np.max(mapa) * 10
    frontera = math.ceil(val)
    c = cota_inferior * 10
    while c < frontera:
        cota_inf = c / 10
        cota_sup = (c + 1) / 10
        contactos = filtrar_contactos_relevantes(mapa, cota_inf, cota_sup)
        secciones[(cota_inf, cota_sup)] = get_claves_matriz(contactos, hmf.coords_matrix_ballesteros)
        c += 1
    return secciones

def get_row_list_protein(file_route_pdb):
    """
    Obtiene la información de los residuos del PDB correspondiente a 'file_route_pdb'.
    :param file_route_pdb: Ruta url del PDB a analizar.
    :return: Lista con la información de los residuos del PDB.
    """
    reduced_pdb_df = get_meta_df(url=meta_url, file_path=file_route_pdb)
    row_list = df_2_list_of_lists(reduced_df=reduced_pdb_df)
    return row_list

def get_relevant_residues(row_list, set_sections):
    """
    Obtiene los residuos relevantes por sección.
    :param row_list:
    :param set_sections:
    :return:
    """
    residuos = []
    for i in row_list:
        if i[-1] in set_sections:
            residuos.append(i[0])
    return residuos

def get_contact_residues(cam, pdb_path):
    """
    Obtiene los contactos relevantes que se establecen de acuerdo con un mapa CAM.
    :param cam: Mapa CAM a analizar.
    :param pdb_path: Ruta del PDB correspondiente.
    :return: Diccionario con los contactos relevantes por sección de acuerdo al mapa CAM.
    """
    contacts_by_section_dict = {}
    secc = get_secciones_relevantes(cam)
    row = get_row_list_protein(pdb_path)
    for key, value in secc.items():
        contacts_by_section_dict[key] = set()
        for contact_set in value:
            values_residues = get_relevant_residues(row,
                                                    contact_set)
            contacts_by_section_dict[key].update(set(values_residues))
    return contacts_by_section_dict

def to_ranges(iterable):
    """
    Genera mediante un 'yield' los intervalos numéricos de un iterable.
    :param iterable: iterable con los elementos numéricos.
    """
    iterable = sorted(set(iterable))
    for key, group in itertools.groupby(enumerate(iterable),
                                        lambda t: t[1] - t[0]):
        group = list(group)
        yield group[0][1], group[-1][1]

def prepare_pymol_strings(dict_contacts):
    """
    Genera un diccionario {sección:intervalo_residuos}, donde el intervalo_residuos es un string de los residuos a
    seleccionar en Pymol.
    :param dict_contacts: Diccionario que almacena los residuos involucrados en contactos por sección.
    :return: Diccionario {sección:intervalo_residuos}.
    """
    dict_pymol ={}
    for key, value in dict_contacts.items():
        x_range = to_ranges(list(value))
        dict_pymol[key]=f'select resi {list(x_range)}'
    return dict_pymol


"""Schemas for various badge operations"""

from typing import List
from uuid import UUID

from pydantic import BaseModel, Field, model_validator

class UpdateBadges(BaseModel):
    """Update Badges schema"""

    new_badge_names: List[str] = Field(
        ...,
        description="List of new badges to be assigned to the user",
        max_length=2,
        min_length=1,
    )
    old_badge_names: List[str] = Field(
        ...,
        description="List of badges to be updated",
        max_length=2,
        min_length=1,
    )

    @model_validator(mode="before")
    # pylint: disable=E0213
    def validate_number_of_badges_to_update(
        cls,
        values,
    ):
        """Validate the number of badges to be updated

        :param values: schema values
        :return: schema values
        """
        new_badges = values.get("new_badge_names")
        old_badges = values.get("old_badge_names")
        if len(new_badges) != len(old_badges):
            raise ValueError("Number of new badges must match the number of old badges")

        return values

class AddBadges(BaseModel):
    """Add badges schema"""

    badge_names: List[str] = Field(
        ...,
        description="List of badges to be added to the user",
        max_length=2,
        min_length=1,
    )

class DeleteBadges(BaseModel):
    """Delete badges schema"""

    badge_names: List[str] = Field(
        ...,
        description="List of badges to be deleted to the user",
        max_length=2,
        min_length=1,
    )

class BadgeSchema(BaseModel):
    """Badge schema"""

    badge_name: str = Field(None, description="Badge name")

class UserSchema(BaseModel):
    """User schema"""

    id: UUID = Field(None, description="user id")
    customer_alias: str = Field(None, description="Customer alias")
    badges: List[BadgeSchema]

    class ConfigDict:
        """Configuration for this schema class"""

        from_attributes = True


import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import json

# Setup constants

# Buffer sizes
BUFFER_SIZES = [512 * 2 ** exp for exp in range(0, 16)]

# Total size, kept constant at 16MB
TOTAL_SIZE = BUFFER_SIZES[-1]

# Number of trials for each measurement.
# Note: When the measurements were taken, the first sample was discarded.
NUM_TRIALS = 10

# IPC modes
IPC_MODES = ["-i pipe", "-i local", "-s -i local"];

# Process modes
PROC_MODES = ["2thread", "2proc"]

# Performance counters
PMC = ["l1d", "l1i", "l2", "mem", "axi", "tlb"]

# JSON fields for l1d
L1D = ["INSTR_EXECUTED",
       "CLOCK_CYCLES",
       "CLOCK_CYCLES/INSTR_EXECUTED",
       "L1_DCACHE_ACCESS",
       "L1_DCACHE_ACCESS/INSTR_EXECUTED",
       "L1_DCACHE_ACCESS/CLOCK_CYCLES",
       "L1_DCACHE_REFILL",
       "L1_DCACHE_REFILL/INSTR_EXECUTED",
       "L1_DCACHE_REFILL/CLOCK_CYCLES"]

# JSON fields for l1i
L1I = ["INSTR_EXECUTED",
       "CLOCK_CYCLES",
       "CLOCK_CYCLES/INSTR_EXECUTED",
       "L1_ICACHE_REFILL",
       "L1_ICACHE_REFILL/INSTR_EXECUTED",
       "L1_ICACHE_REFILL/CLOCK_CYCLES"]

# JSON fields for l2
L2 = ["INSTR_EXECUTED",
      "CLOCK_CYCLES",
      "CLOCK_CYCLES/INSTR_EXECUTED",
      "L2_ACCESS",
      "L2_ACCESS/INSTR_EXECUTED",
      "L2_ACCESS/CLOCK_CYCLES"]

# JSON fields for mem
MEM = ["INSTR_EXECUTED",
       "CLOCK_CYCLES",
       "CLOCK_CYCLES/INSTR_EXECUTED",
       "MEM_READ",
       "MEM_READ/INSTR_EXECUTED",
       "MEM_READ/CLOCK_CYCLES",
       "MEM_WRITE",
       "MEM_WRITE/INSTR_EXECUTED",
       "MEM_WRITE/CLOCK_CYCLES"]

# JSON fields for axi
AXI = ["INSTR_EXECUTED",
       "CLOCK_CYCLES",
       "CLOCK_CYCLES/INSTR_EXECUTED",
       "AXI_READ",
       "AXI_READ/INSTR_EXECUTED",
       "AXI_READ/CLOCK_CYCLES",
       "AXI_WRITE",
       "AXI_WRITE/INSTR_EXECUTED",
       "AXI_WRITE/CLOCK_CYCLES"]

# JSON fields for tlb
TLB = ["INSTR_EXECUTED",
       "CLOCK_CYCLES",
       "CLOCK_CYCLES/INSTR_EXECUTED",
       "ITLB_REFILL",
       "ITLB_REFILL/INSTR_EXECUTED",
       "ITLB_REFILL/CLOCK_CYCLES",
       "DTLB_REFILL",
       "DTLB_REFILL/INSTR_EXECUTED",
       "DTLB_REFILL/CLOCK_CYCLES"]

# Note: each data point also has a "bandwidth" field
# Note: when taking measurements, the benchmarks looped over IPC modes, and for each IPC mode over process modes

# Define a helper function for reading in a file and decoding the json
# Arguments:
#   pmc: string, one of ["l1d", "l1i", "l2", "mem", "axi", "tlb"]
def loadFile(pmc):
    filename = "ipc-static-pmc-" + pmc + ".txt"
    f = open(filename, "r")
    res = json.load(f)
    f.close()
    return res

ls = {"-i pipe" : "-", "-i local": "--", "-s -i local": "-."}

# A helper function plots two graphs, one for each process mode
# Arguments:
#   data: the output of loadFile
#   key: the counter to plot (e.g. "AXI_READ/INSTR_EXECUTED")
#   ylabel: the y-label for the graph
#   lines: x-coordinates of values at which the function should draw a vertical line
def plotProcModesSeparately(data, key, ylabel, lines):
    fig, read = plt.subplots(1, 2, sharex=True, sharey=True)

    i = 0
    for proc_mode in PROC_MODES:
        read[i].set_title(key + " " + proc_mode)
        read[i].set_xlabel("Buffer size (Bytes)")
        read[i].set_ylabel(ylabel)
        read[i].set_xscale("log")
        for ipc_mode in IPC_MODES:
            # Reshape into an array of dimensions len(BUFFER_SIZE) x NUM_TRIALS
            data_float = [float(x) for x in data[ipc_mode][proc_mode][key]]
            data_res = np.reshape(data_float, (len(BUFFER_SIZES), NUM_TRIALS))[:,:]
            # print data

            # Convert into a Panda DataFrame
            df = pd.DataFrame(data_res, index=BUFFER_SIZES)

            # Compute error bars based on the 25 and 75 quantile values
            # Note: The error bars should be small indicating that the experiment is tightly controlled
            error_bars = df.quantile([.25, .75], axis=1)
            error_bars.loc[[0.25]] = df.median(1) - error_bars.loc[[0.25]]
            error_bars.loc[[0.75]] = error_bars.loc[[0.75]] - df.median(1)
            error_bars_values = [error_bars.values]

            # Add the series to the plot
            df.median(1).plot(ax=read[i], figsize=(10, 4), yerr=error_bars_values, label=ipc_mode, legend=True, linestyle=ls[ipc_mode])
        i = i + 1

    for i in range(0, 2):
        for l in lines[i]:
            read[i].axvline(x=(l[0])*1024, linestyle=":")
            read[i].text((l[0] + l[0]/4)*1024, l[1], l[2])

    plt.show()
    # figname = "graphs/" + key + "_proc_modes_sep.pdf"
    # plt.savefig(figname)

# A helper function plots three graphs, one for each IPC mode
# Arguments:
#   data: the output of loadFile
#   key: the counter to plot (e.g. "AXI_READ/INSTR_EXECUTED")
#   ylabel: the y-label for the graph
#   lines: x-coordinates of values at which the function should draw a vertical line
def plotIPCModesSeparately(data, key, ylabel, lines):
    fig, read = plt.subplots(1, 3, sharex=True, sharey=True)
    plt.suptitle(key)

    ls = {"2thread" : "-", "2proc" : "--"}

    i = 0
    for ipc_mode in IPC_MODES:
        read[i].set_title(ipc_mode)
        read[i].set_xlabel("Buffer size(Bytes)")
        read[i].set_ylabel(ylabel)
        read[i].set_xscale("log")
        for proc_mode in PROC_MODES:
            # Reshape into an array of dimensions len(BUFFER_SIZE) x NUM_TRIALS
            data_float = [float(x) for x in data[ipc_mode][proc_mode][key]]
            data_res = np.reshape(data_float, (len(BUFFER_SIZES), NUM_TRIALS))[:,:]

            # Convert into a Panda DataFrame
            df = pd.DataFrame(data_res, index=BUFFER_SIZES)

            # Compute error bars based on the 25 and 75 quantile values
            # Note: The error bars should be small indicating that the experiment is tightly controlled
            error_bars = df.quantile([.25, .75], axis=1)
            error_bars.loc[[0.25]] = df.median(1) - error_bars.loc[[0.25]]
            error_bars.loc[[0.75]] = error_bars.loc[[0.75]] - df.median(1)
            error_bars_values = [error_bars.values]

            # Add the series to the plot
            lgnd = ipc_mode == "-s -i local"
            df.median(1).plot(ax=read[i], figsize=(10, 3), yerr=error_bars_values, label=proc_mode, legend=lgnd, linestyle=ls[proc_mode])
        i = i + 1

    for i in range(0, 3):
        for l in lines:
            read[i].axvline(x=(l[0])*1024, linestyle=":")
            read[i].text((l[0] + l[0]/4)*1024, l[1], l[2])

    plt.subplots_adjust(top=0.85)
    plt.show()
    # figname = "graphs/" + key + "_ipc_modes_sep.pdf"
    # plt.savefig(figname)

# Example usage:
l1d_data = loadFile("l1d")
plotProcModesSeparately(l1d_data, "L1_DCACHE_ACCESS", "Count", [(4, 130000000, "P")])


"""
Katex Render Plugin for Pelican
Literally no settings
"""
import os
import sys

from pelican import signals, generators
from bs4 import BeautifulSoup

from .pelican_katex_markdown_extension import PelicanKatexExtension

def process_settings(pelicanobj):
    """Sets user specified Katex settings"""

    katex_settings = {}

    katex_settings['auto_insert'] = True
    katex_settings['process_summary'] = True

    return katex_settings

def process_summary(article):
    """Ensures summaries are not cut off. Also inserts
    katex script so that math will be rendered"""

    summary = article.summary
    summary_parsed = BeautifulSoup(summary, 'html.parser')
    math = summary_parsed.find_all(class_='math')

    if len(math) > 0:
        last_math_text = math[-1].get_text()
        if len(last_math_text) > 3 and last_math_text[-3:] == '...':
            content_parsed = BeautifulSoup(
                article.content,
                'html.parser'
            )
            full_text = content_parsed.find_all(
                class_='math'
            )[len(math) - 1].get_text()
            math[-1].string = "%s ..." % full_text
            summary = summary_parsed.decode()

        article.summary = "%s<script type='text/javascript'>%s</script>" % (
            summary, process_summary.katex_script)

def process_katex_script(katex_settings):
    """Load the katex script template from file and render
    with settings"""

    with open(os.path.dirname(os.path.realpath(__file__))
              + '/katex_script_template', 'r') as script_template:
        return script_template.read()

def configure_typogrify(pelicanobj, katex_settings):
    """Instructs Typogrify to ignore math tags - which allows Typogrify
    to play nicely with math related content"""

    # If Typogrify is not being used, then just exit
    if not pelicanobj.settings.get('TYPOGRIFY', False):
        return

    try:
        import typogrify
        from distutils.version import LooseVersion

        if LooseVersion(typogrify.__version__) < LooseVersion('2.0.7'):
            raise TypeError('Incorrect version of Typogrify')

        from typogrify.filters import typogrify

        # At this point, we are happy to use Typogrify, meaning
        # it is installed and it is a recent enough version
        # that can be used to ignore all math
        # Instantiate markdown extension and append it to the current extensions
        pelicanobj.settings['TYPOGRIFY_IGNORE_TAGS'].extend(
            ['.math', 'script'])  # ignore math class and script

    except (ImportError, TypeError) as e:
        pelicanobj.settings['TYPOGRIFY'] = False  # disable Typogrify

        if isinstance(e, ImportError):
            print("\nTypogrify is not installed, so it is being ignored.\nIf you want to use it, please install via: pip install typogrify\n")

        if isinstance(e, TypeError):
            print("\nA more recent version of Typogrify is needed for the render_katex module.\nPlease upgrade Typogrify to the latest version (anything equal or above version 2.0.7 is okay).\nTypogrify will be turned off due to this reason.\n")

def katex_for_markdown(pelicanobj, katex_script, katex_settings):
    """Instantiates a customized markdown extension for handling
    katx related content"""

    config = {}
    config['katex_script'] = katex_script
    config['math_tag_class'] = 'math'
    config['auto_insert'] = katex_settings['auto_insert']

    try:
        if isinstance(pelicanobj.settings.get('MD_EXTENSIONS'), list):  # pelican 3.6.3 and earlier
            pelicanobj.settings['MD_EXTENSIONS'].append(PelicanKatexExtension(config))
        else:
            pelicanobj.settings['MARKDOWN'].setdefault(
                'extensions', []).append(PelicanKatexExtension(config))
    except:
        sys.excepthook(*sys.exc_info())
        sys.stderr.write(
            "\nError - the pelican katex markdown extension failed to configure. katex is non-functional.\n")
        sys.stderr.flush()

def rst_add_katex(content):
    """Adds katex script for reStructuredText"""

    # .rst is the only valid extension for reStructuredText files
    _, ext = os.path.splitext(os.path.basename(content.source_path))
    if ext != '.rst':
        return

    # If math class is present in text, add the javascript
    # note that RST hardwires mathjax to be class "math"
    if 'class="math"' in content.content:
        content.content += "<script type='text/javascript'>%s</script>" % rst_add_katex.katex_script

def mathjax_for_rst(pelicanobj, katex_script):
    """Setup math for RST"""
    docutils_settings = pelicanobj.settings.get('DOCUTILS_SETTINGS', {})
    docutils_settings['math_output'] = 'Katex'
    pelicanobj.settings['DOCUTILS_SETTINGS'] = docutils_settings
    rst_add_katex.katex_script = katex_script

def pelican_init(pelicanobj):
    """
    Loads the katex script. Instantiate the Python markdown
    extension, passing in the katex sript as config parameter
    """

    katex_settings = process_settings(pelicanobj)

    katex_script = process_katex_script(katex_settings)

    # Configure Typogrify
    configure_typogrify(pelicanobj, katex_settings)

    katex_for_markdown(pelicanobj, katex_script,
                       katex_settings)

    process_summary.katex_script = None
    if katex_settings['process_summary']:
        process_summary.katex_script = katex_script

def process_rst_and_summaries(content_generators):
    for generator in content_generators:
        if isinstance(generator, generators.ArticlesGenerator):
            for article in (
                generator.articles +
                generator.translations +
                generator.drafts
            ):
                rst_add_katex(article)
                if process_summary.katex_script is not None:
                    process_summary(article)
        elif isinstance(generator, generators.PagesGenerator):
            for page in generator.pages:
                rst_add_katex(page)

def register():
    """Plugin registration"""
    signals.initialized.connect(pelican_init)
    signals.all_generators_finalized.connect(process_rst_and_summaries)


from neuraxle.pipeline import Pipeline
from neuraxle.steps.loop import ForEach
from neuraxle.steps.misc import TransformCallbackStep, TapeCallbackFunction, FitCallbackStep, \
    FitTransformCallbackStep

def test_fit_for_each_should_fit_all_steps_for_each_data_inputs_expected_outputs():
    tape = TapeCallbackFunction()
    p = Pipeline([
        ForEach(Pipeline([
            FitCallbackStep(tape.callback, ["1"]),
            FitCallbackStep(tape.callback, ["2"]),
        ]))
    ])
    data_inputs = [[0, 1], [1, 2]]
    expected_outputs = [[2, 3], [4, 5]]

    p = p.fit(data_inputs, expected_outputs)

    assert isinstance(p, Pipeline)
    assert tape.get_name_tape() == ["1", "2", "1", "2"]
    assert tape.data == [([0, 1], [2, 3]), ([0, 1], [2, 3]), ([1, 2], [4, 5]), ([1, 2], [4, 5])]

def test_fit_transform_should_fit_transform_all_steps_for_each_data_inputs_expected_outputs():
    tape = TapeCallbackFunction()
    tape_fit = TapeCallbackFunction()
    p = Pipeline([
        ForEach(Pipeline([
            FitTransformCallbackStep(tape.callback, tape_fit, ["1"]),
            FitTransformCallbackStep(tape.callback, tape_fit, ["2"]),
        ]))
    ])
    data_inputs = [[0, 1], [1, 2]]
    expected_outputs = [[2, 3], [4, 5]]

    p, outputs = p.fit_transform(data_inputs, expected_outputs)

    assert tape.get_name_tape() == ["1", "2", "1", "2"]
    assert tape_fit.get_name_tape() == ["1", "2", "1", "2"]
    assert tape_fit.data == [([0, 1], [2, 3]), ([0, 1], [2, 3]), ([1, 2], [4, 5]), ([1, 2], [4, 5])]

def test_transform_should_transform_all_steps_for_each_data_inputs_expected_outputs():
    tape = TapeCallbackFunction()
    p = Pipeline([
        ForEach(Pipeline([
            TransformCallbackStep(tape.callback, ["1"]),
            TransformCallbackStep(tape.callback, ["2"]),
        ]))
    ])
    data_inputs = [[0, 1], [1, 2]]

    outputs = p.transform(data_inputs)

    assert tape.get_name_tape() == ["1", "2", "1", "2"]


# In[]
import requests
import json
import time
import random
from Services import *

key = '031-45-155'
ip = 'http://localhost'
server_device_url = 'http://39.106.138.175/device/upload/'
server_service_url = 'http://39.106.138.175/scene/service/'

port = 39000
headers = {'Content-Type': 'application/json'}

# In[]
with open('/home/pi/Scripts/Devices.json') as f:
    data_dict = json.load(f)
with open('/home/pi/Scripts/Services.json') as f:
    service_dict = json.load(f)
# In[]
sendAll = 1
while 1:
    current_dict = {'sensors':[], 'accessories':[]}
    for i in range(len(data_dict['sensors'])):
        try:
            url = ip + ':' + str(port) + '/characteristics?id=' + str(data_dict['sensors'][i]['aid']) + '.' + str(data_dict['sensors'][i]['iid'])
            r = requests.get(url)
            di = json.loads(r.text)
            data_dict['sensors'][i]['type']['currentvalue'] = di['characteristics'][0]['value']
            current_dict['sensors'].append(data_dict['sensors'][i])
            print('Current ' + data_dict['sensors'][i]['name'] + ' value:' + str(data_dict['sensors'][i]['type']['currentvalue']))
        except:
            print(str(time.localtime().tm_hour) + ':' + str(time.localtime().tm_min) + ':' + str(time.localtime().tm_sec) + "    " + "DataToServer.py: Local Django no Response")

    for i in range(len(data_dict['accessories'])):
        try:
            for j in range(len(data_dict['accessories'][i]['iids'])):
                url = ip + ':' + str(port) + '/characteristics?id=' + str(data_dict['accessories'][i]['aid']) + '.' + str(data_dict['accessories'][i]['iids'][j]['iid'])
                r = requests.get(url)
                di = json.loads(r.text)
                #print(di)
                if(data_dict['accessories'][i]['iids'][j]['currentvalue'] != di['characteristics'][0]['value']):
                    data_dict['accessories'][i]['iids'][j]['currentvalue'] = di['characteristics'][0]['value']
                    current_dict['accessories'].append(data_dict['accessories'][i])
                print('Current ' + data_dict['accessories'][i]['name'] + ' value:' + str(data_dict['accessories'][i]['iids'][j]['currentvalue']))
        except:
            print(str(time.localtime().tm_hour) + ':' + str(time.localtime().tm_min) + ':' + str(time.localtime().tm_sec) + "    " + "DataToServer.py: HB no Response")
    # Send to Server
    try:
        if(sendAll == 1):
            response_server = requests.post(url=server_device_url, headers=headers, data=json.dumps(data_dict))
            sendAll = 0
        else:
            response_server = requests.post(url=server_device_url, headers=headers, data=json.dumps(current_dict))
        current_dict = {'sensors':[], 'accessories':[]}
        # Status Refresh
        # Alarm Switch
        try:
            ServerResponse_dict = json.loads(response_server.text)
            #alarm = alarm_control_service()
            #lamp_1 = lamp_control_service_1()
            #lamp_2 = lamp_control_service_2()

            try:
                # Power switch of all accessories
                for i in range(len(data_dict['accessories'])):
                    for j in range(len(ServerResponse_dict['accessories'])):
                        try:
                            if(data_dict['accessories'][i]['aid'] == ServerResponse_dict['accessories'][j]['aid']):
                                #print(data_dict['accessories'][i]['iids'][0]['currentvalue'])
                                #print(ServerResponse_dict['accessories'][i]['iids'][0]['currentvalue'])
                                try:
                                    if(data_dict['accessories'][i]['iids'][0]['currentvalue'] != ServerResponse_dict['accessories'][j]['iids'][0]['currentvalue']):
                                        data_dict['accessories'][i]['iids'][0]['currentvalue'] = ServerResponse_dict['accessories'][j]['iids'][0]['currentvalue']
                                        Control = ControlService(data_dict['accessories'][i]['aid'], data_dict['accessories'][i]['iids'][0]['iid'])
                                        Control.set_value(data_dict['accessories'][i]['iids'][0]['currentvalue'])
                                except:
                                    print(str(time.localtime().tm_hour) + ':' + str(time.localtime().tm_min) + ':' + str(time.localtime().tm_sec) + "    " + "DataToServer.py: Control Service Error")
                        except:
                            print(str(time.localtime().tm_hour) + ':' + str(time.localtime().tm_min) + ':' + str(time.localtime().tm_sec) + "    " + "DataToServer.py: ServerResponse_dict Value['accessories'][j]['aid'] Error")
            except:
                print(str(time.localtime().tm_hour) + ':' + str(time.localtime().tm_min) + ':' + str(time.localtime().tm_sec) + "    " + "DataToServer.py: ServerResponse_dict Value Error")
        except:
            print(str(time.localtime().tm_hour) + ':' + str(time.localtime().tm_min) + ':' + str(time.localtime().tm_sec) + "    " + "DataToServer.py: ServerResponse_dict loads failed")
    except:
        print(str(time.localtime().tm_hour) + ':' + str(time.localtime().tm_min) + ':' + str(time.localtime().tm_sec) + "    " + "DataToServer.py: Data post failed, Server no Response")

    try:
        requests.post(url=server_service_url, headers=headers, data=json.dumps(service_dict))
    except:
        print(str(time.localtime().tm_hour) + ':' + str(time.localtime().tm_min) + ':' + str(time.localtime().tm_sec) + "    " + "DataToServer.py: Service post failed, Server no Response")
    time.sleep(5)


import math

from geometry_solver import theory_manager as tm
from geometry_solver.relationships.perpendicular import Perpendicular
from geometry_solver.common.finder import Finder
from geometry_solver.common.utils import symbol

@tm.theoried(Perpendicular)
def perpendicular_angle(perpendicular: Perpendicular,
                       finder: Finder) -> None:
    line1 = perpendicular.line1
    line2 = perpendicular.line2
    # Extend line first.
    line1 = finder.extend_line(line1)
    line2 = finder.extend_line(line2)
    # Find intersection.
    intersection = finder.find_lines_intersection(line1, line2)
    if len(intersection) != 1:
        raise Exception('Perpendicular relationship is suppposed to include '
                        'two perpendicular line. Except 1, got {}.'
                        .format(len(intersection)))
    cross_p = intersection[0]
    for p1 in line1.ends:
        for p2 in line2.ends:
            if p1 == cross_p or p2 == cross_p:
                continue
            line1_ = finder.find_line_by_ends(p1, cross_p)
            line2_ = finder.find_line_by_ends(p2, cross_p)
            angle = finder.find_angle_by_sides(line1_, line2_)
            yield symbol(angle, 'angle') - 90
            # angle.angle = 90


import speech_recognition as sr
from gtts import gTTS
import os

# Créez un objet recognizer
recognizer = sr.Recognizer()

# Un dictionnaire pour faire correspondre les mots aux chiffres
word_to_number = {
    'zero': '0',
    'one': '1',
    'two': '2',
    'three': '3',
    'four': '4',
    'five': '5',
    'six': '6',
    'seven': '7',
    'eight': '8',
    'nine': '9',
}

def convert_words_to_numbers(text):
    # Convertit les mots en chiffres
    words = text.split()
    converted_words = []
    for word in words:
        if word.lower() in word_to_number:
            converted_words.append(word_to_number[word.lower()])
        else:
            converted_words.append(word)
    return ' '.join(converted_words)

def get_operations():
    while True:
        with sr.Microphone() as source:
            print("Speak your operations...")
            try:
                # Enregistrez les données audio
                audio_data = recognizer.listen(source, timeout=5)
                # Convertissez la parole en texte
                text = recognizer.recognize_google(audio_data, language='en-US')
                print(f"Recognized text: {text}")  # Ajout de cette ligne pour afficher la transcription
                return text
            except sr.WaitTimeoutError:
                print("Timeout: No speech detected. Please try again.")
            except sr.UnknownValueError:
                print("Speech not recognized. Please try again.")
            except sr.RequestError as e:
                print(f"Error with the service; {e}. Please try again.")

def convert_words_to_numbers(text):
    # Convertit les mots en chiffres
    words = text.split()
    for i, word in enumerate(words):
        if word.lower() in word_to_number:
            words[i] = word_to_number[word.lower()]
    return ' '.join(words)

def calculate_results(operations):
    results = []
    # Supprimez tous les espaces et séparez les opérations par le signe "+"
    operation_list = operations.replace(" ", "").split('+')

    for operation in operation_list:
        try:
            result = eval(operation)
            results.append(result)
        except (ValueError, SyntaxError):
            print(f"Invalid operation: {operation}. Skipping it.")

    return results

def speak_results(results):
    if results:
        total_result = sum(results)
        tts = gTTS(f'Total result: {total_result}')
        tts.save("result.mp3")
        os.system("start result.mp3")
    else:
        print("No valid results to speak.")

# Programme principal
if __name__ == "__main__":
    while True:
        operations = get_operations()
        if operations:
            results = calculate_results(operations)
            speak_results(results)
        else:
            print("No valid operations detected. Please try again.")

#merci


from robotlibcore import keyword
from FlaUILibrary.flaui.interface import InterfaceType
from FlaUILibrary.flaui.module import ToggleButton

class RadioButtonKeywords:
    """
    Interface implementation from robotframework usage for radio button keywords.
    """

    def __init__(self, module):
        """
        Constructor for radiobutton keywords.

        ``module`` Automation framework module like UIA3 to handle element interaction.
        """
        self._module = module

    @keyword
    def select_radiobutton(self, identifier, msg=None):
        """
        Select given radiobutton by xpath.

        XPath syntax is explained in `XPath locator`.

        If element could not be found by xpath an error message will be thrown.

        Arguments:
        | Argument   | Type   | Description                   |
        | identifier | string | XPath identifier from element |
        | msg        | string | Custom error message          |

        Examples:
        | Select Radiobutton  <XPATH> |

        """
        element = self._module.get_element(identifier, InterfaceType.RADIOBUTTON, msg=msg)
        self._module.action(ToggleButton.Action.SET_TOGGLE_BUTTON_STATE,
                            self._create_value_container(element=element, state=True),
                            msg)

    @keyword
    def get_radiobutton_state(self, identifier, msg=None):
        """
        Return actual state ${True} or ${False} from radiobutton.

        XPath syntax is explained in `XPath locator`.

        If element could not be found by xpath an error message will be thrown.

        Arguments:
        | Argument   | Type   | Description                   |
        | identifier | string | XPath identifier from element |
        | msg        | string | Custom error message          |

        Examples:
        | ${value}  Get Radiobutton State <XPATH> |
        | Should Be Equal  ${value}  ${False/True} |

        """
        element = self._module.get_element(identifier, InterfaceType.RADIOBUTTON, msg=msg)
        return self._module.action(ToggleButton.Action.GET_TOGGLE_BUTTON_STATE,
                                   self._create_value_container(element=element),
                                   msg)

    @staticmethod
    def _create_value_container(element=None, state=None):
        """
        Helper to create container object.
        """
        return ToggleButton.Container(element=element,
                                      state=None if not state else bool(state))


'''
< 토마토 >
https://www.acmicpc.net/problem/7569
문제)
- 높이H, 세로N, 가로M
- 익은 토마토에 인접한 익지 않은 토마토들이 영향을 받아 익는다.
- 몇일 뒤에 토마토들이 다 익게 되는지 최소 일수
- 빈칸, 익은토마토, 익지않은토마토
입력)
- 1     : 상자의 가로 칸 M, 상자의 세로칸 N, 상자수 H
        - M ~ [2 \ 100], N ~ [2 \ 100], H ~ [1 \ 100]
- 2[NxH]: 익은 1, 익지않은 0, 토마토없는경우 -1
출력)
- 모두 익을 때까지 걸리는 일수
    - 초기에 모두 익어있으면 0
    - 모두 익지 못하면 -1
'''
from collections import deque
import sys
input = sys.stdin.readline

dr = (0, 1, 0, -1, 0, 0)
dc = (1, 0, -1, 0, 0, 0)
dl = (0, 0, 0, 0, 1, -1)

m, n, h = map(int, input().split()) # c, r, h
a = [[list(map(int, input().split())) for _ in range(n)] for _ in range(h)]
visited = [[[0] * m for _ in range(n)] for _ in range(h)]
t = []
ans = -1
for k in range(h): # l
    for i in range(n): # r
        for j in range(m): # c
            if a[k][i][j] == 1:
                t.append((0, k, i, j)) # d, l, r, c
                visited[k][i][j] = 1

def bfs():
    global t, ans
    q = deque(t)
    while q:
        d, l, r, c = q.popleft()
        ans = max(ans, d)
        for i in range(6):
            nr = r + dr[i]
            nc = c + dc[i]
            nl = l + dl[i]
            if 0 <= nr < n and 0 <= nc < m and 0 <= nl < h:
                if visited[nl][nr][nc]: continue
                if a[nl][nr][nc]: continue # 1익은 -1없음 pass
                a[nl][nr][nc] = 1
                visited[nl][nr][nc] = 1
                q.append((d + 1, nl, nr, nc))

bfs()
flag = True
for k in range(h):
    for i in range(n):
        for j in range(m):
            # if a[k][i][j] == 0: flag = False
            if a[k][i][j] == 0: print(-1); exit(0)

print(ans)


import functools
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
from PIL import ImageTk, Image
import shutil
import os
import datetime

from Code.DBMS_Connect import DbmsConnect
from Code.userprofile import UserProfile

class NewsFeed:
    IMG_PATH = r"D:\Study material\miniproject\PriorNet\Data\Photos"
    Images = r"D:\Study material\miniproject\PriorNet\PriorNet\resources\Images"
    X = datetime.datetime.now()
    TIME_NOW = X.strftime("%Y") + X.strftime("%m") + X.strftime("%d") + X.strftime("%H") + \
               X.strftime("%M") + X.strftime("%S")
    DATE_OF_UPLOAD = X.strftime("%Y-%m-%d")
    image_name = ""
    post_id = ''

    def __init__(self, master, root, user_id, username):
        self.user_id = user_id
        self.username = username
        self.win = root
        self.win.title("PriorNet-Newsfeed")
        self.win.geometry("1000x600+400+200")

        def quit_news_feed():
            self.win.withdraw()
            children_widgets = self.win.winfo_children()
            for child_widget in children_widgets:
                if child_widget.winfo_class() == 'Entry':
                    child_widget.delete(0, tk.END)
            master.deiconify()

        self.win.protocol("WM_DELETE_WINDOW", quit_news_feed)

        tk.Grid.columnconfigure(self.win, 0, weight=1)
        tk.Grid.columnconfigure(self.win, 1, weight=1)

        # Left Frame for profile---------------------------------------------------------------------------
        self.left_frame = tk.Frame(self.win, highlightbackground="Grey", highlightthickness=2)
        self.left_frame.pack(fill=tk.Y, side=tk.LEFT)
        tk.Grid.columnconfigure(self.left_frame, 0, weight=1)

        img_path = DbmsConnect("priornet")
        img_path.get_data_from_database(f"Select photo from profile where user_id='{user_id}'")
        try:
            for img in img_path.data:
                imgg = ''.join(img)
            image = Image.open(os.path.join(self.IMG_PATH, self.username, imgg))
        except Exception as e:
            print(e)
            image = Image.open(os.path.join(self.Images, "profile.jpg"))

        image = image.resize((190, 190))
        image = ImageTk.PhotoImage(image)
        self.image_lbl = tk.Label(self.left_frame, image=image)
        self.image_lbl.grid(column=0, row=0, padx=10, pady=10)

        self.user_label = tk.Label(self.left_frame, text=username)
        self.user_label.grid(column=0, row=1)

        def edit_profile():
            image = filedialog.askopenfilename(title='Select Profile picture')
            if image != "":
                image_name = os.path.basename(image)
                ext = os.path.splitext(image_name)[1]
                exact_path = os.path.join(self.IMG_PATH, self.username)
                shutil.copy(image, exact_path)
                try:
                    os.rename(os.path.join(exact_path, image_name),
                              os.path.join(exact_path, f"Profile_{self.user_id}{ext}"))
                except FileExistsError:
                    os.remove(os.path.join(exact_path, f"Profile_{self.user_id}{ext}"))
                    os.rename(os.path.join(exact_path, image_name),
                              os.path.join(exact_path, f"Profile_{self.user_id}{ext}"))

                image_name = f"Profile_{self.user_id}{ext}"
                update_profile = DbmsConnect("priornet")
                try:
                    update_profile.insert_into_database(f"update profile set photo='{image_name}' where user_id='{self.user_id}'")
                except:
                    messagebox.showerror("Error", "Please,try again later!")
            self.win.withdraw()
            self.win.deiconify()
        self.update_profile_btn = tk.Button(self.left_frame, text="Update profile picture", command=edit_profile)
        self.update_profile_btn.grid(column=0, row=2)

        def back_to_home():
            self.win.withdraw()
            children_widgets = self.win.winfo_children()
            for child_widget in children_widgets:
                if child_widget.winfo_class() == 'Entry':
                    child_widget.delete(0, tk.END)
            master.deiconify()

        self.back_to_home_btn = tk.Button(self.left_frame, text="Back To Home", command=back_to_home)
        self.back_to_home_btn.grid(column=0, row=3)

        # Right frame for newsfeed---------------------------------------------------------------------------
        self.right = tk.Frame(self.win, bg="black")
        tk.Grid.columnconfigure(self.right, 0, weight=1)

        tk.Grid.rowconfigure(self.right, 1, weight=1)
        self.right.pack(fill=tk.BOTH, expand=True)

        # Entry to write status------------------------------------------------------------------------------
        self.right_upper_part = tk.Frame(self.right)
        self.right_upper_part.grid(row=0, column=0, sticky="new")
        tk.Grid.columnconfigure(self.right_upper_part, 0, weight=1)
        tk.Grid.columnconfigure(self.right_upper_part, 1, weight=1)

        self.upload_status = tk.Text(self.right_upper_part, width=50, height=5)
        self.upload_status.grid(column=0, row=0, sticky="WE", padx=10, pady=10)

        self.button_frame = tk.Frame(self.right_upper_part)
        self.button_frame.grid(column=1, row=0, sticky=tk.E)

        def open_img():
            self.FLAG = False
            x = filedialog.askopenfilename(title='open')
            try:
                post_count = DbmsConnect("priornet")
                post_count.get_data_from_database(f"Select post_count from user_count")
                post_count = post_count.data[0][0]
                confirm_text.set("Photo Selected")
                self.image_name = os.path.basename(x)
                print(self.image_name)
                exact_path = os.path.join(self.IMG_PATH, username)
                ext = os.path.splitext(self.image_name)[1]
                if not os.path.exists(exact_path):
                    os.makedirs(exact_path)
                shutil.copy(x, exact_path)
                os.rename(os.path.join(exact_path, self.image_name), os.path.join(exact_path, f"{self.TIME_NOW}_{post_count}{ext}"))
                self.post_id = f"{self.TIME_NOW}_{post_count}"
                self.image_name = f"{self.TIME_NOW}_{post_count}{ext}"
                self.FLAG = True
                self.confirm_label.grid(column=0, row=1)
            except AttributeError:
                messagebox.showwarning("Error", "Some Error occurred")

        self.choose_img_btn = tk.Button(self.button_frame, text="Choose Photo", command=open_img)
        self.choose_img_btn.grid(column=0, row=0, pady=10, padx=5)

        confirm_text = tk.StringVar()
        self.confirm_label = tk.Label(self.right_upper_part, textvariable=confirm_text)

        def upload():
            status = self.upload_status.get("1.0", tk.END)
            self.upload_status.delete("1.0", tk.END)
            if status.strip() != "" or self.image_name.strip() != '':
                try:
                    upload = DbmsConnect("priornet")
                    if status == "":
                        status = "NULL"
                    elif self.image_name == "":
                        self.image_name = "NULL"

                    upload.insert_into_database(f"insert into posts values('{self.post_id}', '{user_id}', '{status}',"
                                                f" '{self.image_name}', '{self.DATE_OF_UPLOAD}')")
                    messagebox.showinfo("Success", "Uploaded successfully")
                    self.confirm_label.grid_remove()
                    self.FLAG = False

                except Exception as e:
                    messagebox.showerror("Failure", "Some error occurred!")
                    print(e)
            else:
                messagebox.showwarning("Empty", "Empty values received")

        self.upload_button = tk.Button(self.button_frame, text="Upload", command=upload)
        self.upload_button.grid(column=0, row=1)

        # for displaying the posts of friends--------------------------------------------------------------------
        self.right_lower_part = tk.Frame(self.right, bg="black")
        self.right_lower_part.grid(row=1, column=0, sticky="nsew")
        try:
            self.friends_details = DbmsConnect('priornet')
            self.friends_details.get_data_from_database(
                f"select U.username, U.user_id, P.Text, P.Image, P.date_of_upload from User U, posts P where P.UID = "
                f"U.user_id and U.user_id in(select user_id from user where user_id in (select FriendIDs from friends "
                f"where UID = '{self.user_id}'or FriendIDs ='{self.user_id}') or user_id in (select UID from friends "
                f"where UID = '{self.user_id}'or FriendIDs='{self.user_id}')) and P.date_of_upload >= "
                f"DATE_SUB(CURDATE(),INTERVAL 7 day) ORDER BY P.PID DESC;")

        except Exception as e:
            print("[Exception in Newsfeed]", e)

        self.display_posts = tk.Canvas(self.right_lower_part, bg="white")
        self.display_posts.pack(side="left", fill=tk.BOTH, expand=True)

        self.display_posts.update()
        screen_width = self.display_posts.winfo_width()

        self.scrollbar = ttk.Scrollbar(self.right_lower_part, orient="vertical", command=self.display_posts.yview)
        self.scrollbar.pack(side="right", fill=tk.Y)

        self.scrollable_frame = ttk.Frame(self.display_posts)
        self.scrollable_frame.bind(
            "<Configure>",
            lambda e: self.display_posts.configure(
                scrollregion=self.display_posts.bbox("all")
            )
        )

        self.display_posts.create_window((0, 0), window=self.scrollable_frame, anchor="nw", width=screen_width)
        self.display_posts.configure(yscrollcommand=self.scrollbar.set)

        post_count = 0

        def goto_profile(idx):
            friend_name = self.friends_details.data[idx][0]
            friend_id = self.friends_details.data[idx][1]
            self.win.withdraw()

            UserProfile(self.win, friend_name, friend_id)

        for frn_name, frn_id, text, img, date in self.friends_details.data:
            self.frame = tk.Frame(self.scrollable_frame)
            self.frame.pack()

            if frn_name == self.username:
                self.name_button = tk.Button(self.frame, text="You", borderwidth=0, font=(20,),
                                             command=functools.partial(goto_profile, idx=post_count))
                self.name_button.grid(column=0, row=0, sticky='w')
            else:
                self.name_button = tk.Button(self.frame, text=frn_name, borderwidth=0, font=(20,),
                                             command=functools.partial(goto_profile, idx=post_count))
                self.name_button.grid(column=0, row=0, sticky='w')

            self.date_of_upload = tk.Label(self.frame, text=date)
            self.date_of_upload.grid(column=1, row=0, ipady=10)

            if text != "NULL" and text != "\n":
                self.text_lbl = tk.Label(self.scrollable_frame, text=text)
                self.text_lbl.pack()

            if img != "NULL" and img is not None:
                try:
                    photo = Image.open(os.path.join(self.IMG_PATH, frn_name, img))
                    photo = photo.resize((400, 400))
                    photo = ImageTk.PhotoImage(photo)
                    self.image_lbl = tk.Label(self.scrollable_frame, image=photo, width=screen_width)
                    self.image_lbl.photo = photo
                    self.image_lbl.pack(fill=tk.X)
                except Exception as e:
                    print(e)
                    pass

            separator = ttk.Separator(self.scrollable_frame)
            separator.pack(fill=tk.X)

            post_count += post_count

        self.win.mainloop()

# root = tk.Tk()
#
# win = tk.Toplevel(root)
# NewsFeed(root, win, "PN000000", "Rama")
#
# root.mainloop()