from tencentcloud.common.abstract_model import AbstractModel

class Conditions(AbstractModel):
    """状态

    """

    def __init__(self):
        """
        :param Reason: 原因
        :type Reason: str
        :param Count: 具有相同原因的副本个数
        :type Count: int
        """
        self.Reason = None
        self.Count = None

    def _deserialize(self, params):
        self.Reason = params.get("Reason")
        self.Count = params.get("Count")

class CreateServiceConfigRequest(AbstractModel):
    """CreateServiceConfig请求参数结构体

    """

    def __init__(self):
        """
        :param Name: 配置名称
        :type Name: str
        :param Runtime: 运行环境
        :type Runtime: str
        :param ModelUri: 模型地址，支持cos路径，格式为 cos://bucket名-appid.cos.region名.myqcloud.com/模型文件夹路径。为模型文件的上一层文件夹地址。
        :type ModelUri: str
        :param Cpu: 处理器配置, 单位为1/1000核；范围[100, 256000]
        :type Cpu: int
        :param Memory: 内存配置, 单位为1M；范围[100, 256000]
        :type Memory: int
        :param TflopUnits: GPU算力配置，单位为1/100 tflops，范围 [0, 256000]
        :type TflopUnits: int
        :param GpuMemory: 显存配置, 单位为1M，范围 [0, 256000]
        :type GpuMemory: int
        """
        self.Name = None
        self.Runtime = None
        self.ModelUri = None
        self.Cpu = None
        self.Memory = None
        self.TflopUnits = None
        self.GpuMemory = None

    def _deserialize(self, params):
        self.Name = params.get("Name")
        self.Runtime = params.get("Runtime")
        self.ModelUri = params.get("ModelUri")
        self.Cpu = params.get("Cpu")
        self.Memory = params.get("Memory")
        self.TflopUnits = params.get("TflopUnits")
        self.GpuMemory = params.get("GpuMemory")

class CreateServiceConfigResponse(AbstractModel):
    """CreateServiceConfig返回参数结构体

    """

    def __init__(self):
        """
        :param ServiceConfig: 服务配置
        :type ServiceConfig: :class:`tencentcloud.tiems.v20190416.models.ServiceConfig`
        :param RequestId: 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
        :type RequestId: str
        """
        self.ServiceConfig = None
        self.RequestId = None

    def _deserialize(self, params):
        if params.get("ServiceConfig") is not None:
            self.ServiceConfig = ServiceConfig()
            self.ServiceConfig._deserialize(params.get("ServiceConfig"))
        self.RequestId = params.get("RequestId")

class CreateServiceRequest(AbstractModel):
    """CreateService请求参数结构体

    """

    def __init__(self):
        """
        :param Scaler: 扩缩容配置
        :type Scaler: :class:`tencentcloud.tiems.v20190416.models.Scaler`
        :param ServiceConfigId: 服务配置Id
        :type ServiceConfigId: int
        :param Name: 服务名称
        :type Name: str
        :param ScaleMode: 扩缩容方式，支持AUTO, MANUAL，分别表示自动扩缩容和手动扩缩容
        :type ScaleMode: str
        :param Cluster: 集群，不填则使用默认集群。
        :type Cluster: str
        """
        self.Scaler = None
        self.ServiceConfigId = None
        self.Name = None
        self.ScaleMode = None
        self.Cluster = None

    def _deserialize(self, params):
        if params.get("Scaler") is not None:
            self.Scaler = Scaler()
            self.Scaler._deserialize(params.get("Scaler"))
        self.ServiceConfigId = params.get("ServiceConfigId")
        self.Name = params.get("Name")
        self.ScaleMode = params.get("ScaleMode")
        self.Cluster = params.get("Cluster")

class CreateServiceResponse(AbstractModel):
    """CreateService返回参数结构体

    """

    def __init__(self):
        """
        :param Service: 服务
        :type Service: :class:`tencentcloud.tiems.v20190416.models.Service`
        :param RequestId: 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
        :type RequestId: str
        """
        self.Service = None
        self.RequestId = None

    def _deserialize(self, params):
        if params.get("Service") is not None:
            self.Service = Service()
            self.Service._deserialize(params.get("Service"))
        self.RequestId = params.get("RequestId")

class DeleteServiceConfigRequest(AbstractModel):
    """DeleteServiceConfig请求参数结构体

    """

    def __init__(self):
        """
        :param ServiceConfigId: 服务配置Id (deprecated)
        :type ServiceConfigId: int
        :param ServiceConfigName: 服务配置名称
        :type ServiceConfigName: str
        """
        self.ServiceConfigId = None
        self.ServiceConfigName = None

    def _deserialize(self, params):
        self.ServiceConfigId = params.get("ServiceConfigId")
        self.ServiceConfigName = params.get("ServiceConfigName")

class DeleteServiceConfigResponse(AbstractModel):
    """DeleteServiceConfig返回参数结构体

    """

    def __init__(self):
        """
        :param RequestId: 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
        :type RequestId: str
        """
        self.RequestId = None

    def _deserialize(self, params):
        self.RequestId = params.get("RequestId")

class DeleteServiceRequest(AbstractModel):
    """DeleteService请求参数结构体

    """

    def __init__(self):
        """
        :param ServiceId: 服务Id
        :type ServiceId: int
        """
        self.ServiceId = None

    def _deserialize(self, params):
        self.ServiceId = params.get("ServiceId")

class DeleteServiceResponse(AbstractModel):
    """DeleteService返回参数结构体

    """

    def __init__(self):
        """
        :param RequestId: 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
        :type RequestId: str
        """
        self.RequestId = None

    def _deserialize(self, params):
        self.RequestId = params.get("RequestId")

class DescribeRuntimesRequest(AbstractModel):
    """DescribeRuntimes请求参数结构体

    """

class DescribeRuntimesResponse(AbstractModel):
    """DescribeRuntimes返回参数结构体

    """

    def __init__(self):
        """
        :param Runtimes: TIEMS支持的运行环境列表
        :type Runtimes: list of Runtime
        :param UserAccess: 用户对runtime对权限
注意：此字段可能返回 null，表示取不到有效值。
        :type UserAccess: int
        :param RequestId: 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
        :type RequestId: str
        """
        self.Runtimes = None
        self.UserAccess = None
        self.RequestId = None

    def _deserialize(self, params):
        if params.get("Runtimes") is not None:
            self.Runtimes = []
            for item in params.get("Runtimes"):
                obj = Runtime()
                obj._deserialize(item)
                self.Runtimes.append(obj)
        self.UserAccess = params.get("UserAccess")
        self.RequestId = params.get("RequestId")

class DescribeServiceConfigsRequest(AbstractModel):
    """DescribeServiceConfigs请求参数结构体

    """

    def __init__(self):
        """
        :param Filters: 筛选选项，支持按照name等进行筛选
        :type Filters: list of Filter
        :param Offset: 偏移量，默认为0
        :type Offset: int
        :param Limit: 返回数量，默认为20，最大值为1000
        :type Limit: int
        :param Order: 输出列表的排列顺序。取值范围：ASC：升序排列 DESC：降序排列
        :type Order: str
        :param OrderField: 排序的依据字段， 取值范围 "CREATE_TIME", "UPDATE_TIME", "NAME"
        :type OrderField: str
        """
        self.Filters = None
        self.Offset = None
        self.Limit = None
        self.Order = None
        self.OrderField = None

    def _deserialize(self, params):
        if params.get("Filters") is not None:
            self.Filters = []
            for item in params.get("Filters"):
                obj = Filter()
                obj._deserialize(item)
                self.Filters.append(obj)
        self.Offset = params.get("Offset")
        self.Limit = params.get("Limit")
        self.Order = params.get("Order")
        self.OrderField = params.get("OrderField")

class DescribeServiceConfigsResponse(AbstractModel):
    """DescribeServiceConfigs返回参数结构体

    """

    def __init__(self):
        """
        :param ServiceConfigs: 服务配置
        :type ServiceConfigs: list of ServiceConfig
        :param TotalCount: 服务配置总数
        :type TotalCount: int
        :param RequestId: 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
        :type RequestId: str
        """
        self.ServiceConfigs = None
        self.TotalCount = None
        self.RequestId = None

    def _deserialize(self, params):
        if params.get("ServiceConfigs") is not None:
            self.ServiceConfigs = []
            for item in params.get("ServiceConfigs"):
                obj = ServiceConfig()
                obj._deserialize(item)
                self.ServiceConfigs.append(obj)
        self.TotalCount = params.get("TotalCount")
        self.RequestId = params.get("RequestId")

class DescribeServicesRequest(AbstractModel):
    """DescribeServices请求参数结构体

    """

    def __init__(self):
        """
        :param Filters: 筛选选项，支持按照name等字段进行筛选
        :type Filters: list of Filter
        :param Offset: 偏移量，默认为0
        :type Offset: int
        :param Limit: 返回数量，默认为20，最大值为100
        :type Limit: int
        :param Order: 输出列表的排列顺序。取值范围：ASC：升序排列 DESC：降序排列
        :type Order: str
        :param OrderField: 排序的依据字段， 取值范围 "CREATE_TIME" "UPDATE_TIME"
        :type OrderField: str
        """
        self.Filters = None
        self.Offset = None
        self.Limit = None
        self.Order = None
        self.OrderField = None

    def _deserialize(self, params):
        if params.get("Filters") is not None:
            self.Filters = []
            for item in params.get("Filters"):
                obj = Filter()
                obj._deserialize(item)
                self.Filters.append(obj)
        self.Offset = params.get("Offset")
        self.Limit = params.get("Limit")
        self.Order = params.get("Order")
        self.OrderField = params.get("OrderField")

class DescribeServicesResponse(AbstractModel):
    """DescribeServices返回参数结构体

    """

    def __init__(self):
        """
        :param Services: 服务列表
        :type Services: list of Service
        :param TotalCount: 服务总数
        :type TotalCount: int
        :param RequestId: 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
        :type RequestId: str
        """
        self.Services = None
        self.TotalCount = None
        self.RequestId = None

    def _deserialize(self, params):
        if params.get("Services") is not None:
            self.Services = []
            for item in params.get("Services"):
                obj = Service()
                obj._deserialize(item)
                self.Services.append(obj)
        self.TotalCount = params.get("TotalCount")
        self.RequestId = params.get("RequestId")

class Filter(AbstractModel):
    """筛选项

    """

    def __init__(self):
        """
        :param Name: 名称
        :type Name: str
        :param Values: 取值
        :type Values: list of str
        """
        self.Name = None
        self.Values = None

    def _deserialize(self, params):
        self.Name = params.get("Name")
        self.Values = params.get("Values")

class Option(AbstractModel):
    """配置项

    """

    def __init__(self):
        """
        :param Name: 名称
        :type Name: str
        :param Value: 取值
        :type Value: int
        """
        self.Name = None
        self.Value = None

    def _deserialize(self, params):
        self.Name = params.get("Name")
        self.Value = params.get("Value")

class Runtime(AbstractModel):
    """运行环境

    """

    def __init__(self):
        """
        :param Name: 运行环境名称
        :type Name: str
        :param Framework: 运行环境框架
        :type Framework: str
        :param Description: 运行环境描述
        :type Description: str
        :param Public: 是否为公开运行环境
注意：此字段可能返回 null，表示取不到有效值。
        :type Public: bool
        :param HealthCheckOn: 是否打开健康检查
注意：此字段可能返回 null，表示取不到有效值。
        :type HealthCheckOn: bool
        :param Image: 镜像地址
注意：此字段可能返回 null，表示取不到有效值。
        :type Image: str
        :param CreateTime: 创建时间
注意：此字段可能返回 null，表示取不到有效值。
        :type CreateTime: str
        """
        self.Name = None
        self.Framework = None
        self.Description = None
        self.Public = None
        self.HealthCheckOn = None
        self.Image = None
        self.CreateTime = None

    def _deserialize(self, params):
        self.Name = params.get("Name")
        self.Framework = params.get("Framework")
        self.Description = params.get("Description")
        self.Public = params.get("Public")
        self.HealthCheckOn = params.get("HealthCheckOn")
        self.Image = params.get("Image")
        self.CreateTime = params.get("CreateTime")

class Scaler(AbstractModel):
    """扩缩容配置

    """

    def __init__(self):
        """
        :param MaxReplicas: 最大副本数
        :type MaxReplicas: int
        :param MinReplicas: 最小副本数
        :type MinReplicas: int
        :param StartReplicas: 起始副本数
        :type StartReplicas: int
        :param HpaMetrics: 扩缩容指标，选择自动扩缩容时至少需要选择一个指标，支持CPU-UTIL、MEMORY-UTIL
        :type HpaMetrics: list of Option
        """
        self.MaxReplicas = None
        self.MinReplicas = None
        self.StartReplicas = None
        self.HpaMetrics = None

    def _deserialize(self, params):
        self.MaxReplicas = params.get("MaxReplicas")
        self.MinReplicas = params.get("MinReplicas")
        self.StartReplicas = params.get("StartReplicas")
        if params.get("HpaMetrics") is not None:
            self.HpaMetrics = []
            for item in params.get("HpaMetrics"):
                obj = Option()
                obj._deserialize(item)
                self.HpaMetrics.append(obj)

class Service(AbstractModel):
    """模型服务

    """

    def __init__(self):
        """
        :param Id: 服务ID
        :type Id: int
        :param Cluster: 运行集群
        :type Cluster: str
        :param Name: 服务名称
        :type Name: str
        :param Runtime: 运行环境
        :type Runtime: str
        :param ModelUri: 模型地址
        :type ModelUri: str
        :param Cpu: 处理器配置, 单位为1/1000核
        :type Cpu: int
        :param Memory: 内存配置, 单位为1M
        :type Memory: int
        :param TflopUnits: 处理器配置, 单位为1/100 tflops
        :type TflopUnits: int
        :param GpuMemory: 显存配置, 单位为1M
        :type GpuMemory: int
        :param CreateTime: 创建时间
        :type CreateTime: str
        :param UpdateTime: 更新时间
        :type UpdateTime: str
        :param ScaleMode: 支持AUTO, MANUAL
        :type ScaleMode: str
        :param Scaler: 弹性伸缩配置
        :type Scaler: :class:`tencentcloud.tiems.v20190416.models.Scaler`
        :param Status: 服务状态
        :type Status: :class:`tencentcloud.tiems.v20190416.models.ServiceStatus`
        :param ServingIp: 服务地址
        :type ServingIp: str
        :param AccessToken: 访问密钥
        :type AccessToken: str
        :param ServiceConfigId: 服务配置Id
        :type ServiceConfigId: int
        :param ServiceConfigName: 服务配置名
        :type ServiceConfigName: str
        :param ServeSeconds: 服务运行时长
        :type ServeSeconds: int
        :param ServiceConfigVersion: 配置版本
        :type ServiceConfigVersion: str
        """
        self.Id = None
        self.Cluster = None
        self.Name = None
        self.Runtime = None
        self.ModelUri = None
        self.Cpu = None
        self.Memory = None
        self.TflopUnits = None
        self.GpuMemory = None
        self.CreateTime = None
        self.UpdateTime = None
        self.ScaleMode = None
        self.Scaler = None
        self.Status = None
        self.ServingIp = None
        self.AccessToken = None
        self.ServiceConfigId = None
        self.ServiceConfigName = None
        self.ServeSeconds = None
        self.ServiceConfigVersion = None

    def _deserialize(self, params):
        self.Id = params.get("Id")
        self.Cluster = params.get("Cluster")
        self.Name = params.get("Name")
        self.Runtime = params.get("Runtime")
        self.ModelUri = params.get("ModelUri")
        self.Cpu = params.get("Cpu")
        self.Memory = params.get("Memory")
        self.TflopUnits = params.get("TflopUnits")
        self.GpuMemory = params.get("GpuMemory")
        self.CreateTime = params.get("CreateTime")
        self.UpdateTime = params.get("UpdateTime")
        self.ScaleMode = params.get("ScaleMode")
        if params.get("Scaler") is not None:
            self.Scaler = Scaler()
            self.Scaler._deserialize(params.get("Scaler"))
        if params.get("Status") is not None:
            self.Status = ServiceStatus()
            self.Status._deserialize(params.get("Status"))
        self.ServingIp = params.get("ServingIp")
        self.AccessToken = params.get("AccessToken")
        self.ServiceConfigId = params.get("ServiceConfigId")
        self.ServiceConfigName = params.get("ServiceConfigName")
        self.ServeSeconds = params.get("ServeSeconds")
        self.ServiceConfigVersion = params.get("ServiceConfigVersion")

class ServiceConfig(AbstractModel):
    """服务配置

    """

    def __init__(self):
        """
        :param Id: Id
        :type Id: int
        :param Name: 配置名
        :type Name: str
        :param ModelUri: 模型地址
        :type ModelUri: str
        :param Cpu: 处理器配置, 单位为1/1000核
        :type Cpu: int
        :param Memory: 内存配置, 单位为1M
        :type Memory: int
        :param TflopUnits: GPU算力，单位为1/100 tflops
注意：此字段可能返回 null，表示取不到有效值。
        :type TflopUnits: int
        :param GpuMemory: 显存配置, 单位为1M
注意：此字段可能返回 null，表示取不到有效值。
        :type GpuMemory: int
        :param CreateTime: 创建时间
        :type CreateTime: str
        :param UpdateTime: 更新时间
        :type UpdateTime: str
        :param Runtime: 运行环境
        :type Runtime: str
        :param Version: 配置版本
        :type Version: str
        """
        self.Id = None
        self.Name = None
        self.ModelUri = None
        self.Cpu = None
        self.Memory = None
        self.TflopUnits = None
        self.GpuMemory = None
        self.CreateTime = None
        self.UpdateTime = None
        self.Runtime = None
        self.Version = None

    def _deserialize(self, params):
        self.Id = params.get("Id")
        self.Name = params.get("Name")
        self.ModelUri = params.get("ModelUri")
        self.Cpu = params.get("Cpu")
        self.Memory = params.get("Memory")
        self.TflopUnits = params.get("TflopUnits")
        self.GpuMemory = params.get("GpuMemory")
        self.CreateTime = params.get("CreateTime")
        self.UpdateTime = params.get("UpdateTime")
        self.Runtime = params.get("Runtime")
        self.Version = params.get("Version")

class ServiceStatus(AbstractModel):
    """服务状态

    """

    def __init__(self):
        """
        :param DesiredReplicas: 预期副本数
        :type DesiredReplicas: int
        :param CurrentReplicas: 当前副本数
        :type CurrentReplicas: int
        :param Status: Normal：正常运行中；Abnormal：服务异常，例如容器启动失败等；Waiting：服务等待中，例如容器下载镜像过程等；Stopped：已停止 Stopping 停止中；Resuming：重启中；Updating：服务更新中
        :type Status: str
        :param Conditions: 服务处于当前状态的原因集合
注意：此字段可能返回 null，表示取不到有效值。
        :type Conditions: list of Conditions
        :param Replicas: 副本名称
注意：此字段可能返回 null，表示取不到有效值。
        :type Replicas: list of str
        """
        self.DesiredReplicas = None
        self.CurrentReplicas = None
        self.Status = None
        self.Conditions = None
        self.Replicas = None

    def _deserialize(self, params):
        self.DesiredReplicas = params.get("DesiredReplicas")
        self.CurrentReplicas = params.get("CurrentReplicas")
        self.Status = params.get("Status")
        if params.get("Conditions") is not None:
            self.Conditions = []
            for item in params.get("Conditions"):
                obj = Conditions()
                obj._deserialize(item)
                self.Conditions.append(obj)
        self.Replicas = params.get("Replicas")

class UpdateServiceRequest(AbstractModel):
    """UpdateService请求参数结构体

    """

    def __init__(self):
        """
        :param ServiceId: 服务Id
        :type ServiceId: int
        :param Scaler: 扩缩容配置
        :type Scaler: :class:`tencentcloud.tiems.v20190416.models.Scaler`
        :param ServiceConfigId: 服务配置Id
        :type ServiceConfigId: int
        :param ScaleMode: 支持AUTO, MANUAL，分别表示自动扩缩容，手动扩缩容
        :type ScaleMode: str
        :param ServiceAction: 支持STOP(停止) RESUME(重启)
        :type ServiceAction: str
        """
        self.ServiceId = None
        self.Scaler = None
        self.ServiceConfigId = None
        self.ScaleMode = None
        self.ServiceAction = None

    def _deserialize(self, params):
        self.ServiceId = params.get("ServiceId")
        if params.get("Scaler") is not None:
            self.Scaler = Scaler()
            self.Scaler._deserialize(params.get("Scaler"))
        self.ServiceConfigId = params.get("ServiceConfigId")
        self.ScaleMode = params.get("ScaleMode")
        self.ServiceAction = params.get("ServiceAction")

class UpdateServiceResponse(AbstractModel):
    """UpdateService返回参数结构体

    """

    def __init__(self):
        """
        :param Service: 服务
        :type Service: :class:`tencentcloud.tiems.v20190416.models.Service`
        :param RequestId: 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
        :type RequestId: str
        """
        self.Service = None
        self.RequestId = None

    def _deserialize(self, params):
        if params.get("Service") is not None:
            self.Service = Service()
            self.Service._deserialize(params.get("Service"))
        self.RequestId = params.get("RequestId")


from yargy import (
    rule,
    and_, or_, not_
)
from yargy.relations import gnc_relation
from yargy.interpretation import fact
from yargy.predicates import gram

gnc = gnc_relation()

Name = fact(
    'Name',
    ['first', 'last', 'middle']
)

NAME = and_(gram('Name'))

PATR = and_(gram('Patr'))

SURN = and_(gram('Surn'))

ABBR = and_(gram('Abbr'))

FIRST = NAME.interpretation(Name.first).match(gnc)

LAST = and_(SURN, not_(ABBR)).interpretation(Name.last).match(gnc)

MIDDLE = PATR.interpretation(Name.middle).match(gnc)

FIRST_LAST = rule(FIRST, LAST)

LAST_FIRST = rule(LAST, FIRST)

FIRST_MIDDLE = rule(FIRST, MIDDLE)

FIRST_MIDDLE_LAST = rule(FIRST, MIDDLE, LAST)

LAST_FIRST_MIDDLE = rule(LAST, FIRST, MIDDLE)

NAME = or_(
    FIRST,
    LAST,
    MIDDLE,
    FIRST_MIDDLE,
    FIRST_LAST,
    FIRST_MIDDLE_LAST,
    LAST_FIRST,
    LAST_FIRST_MIDDLE
).interpretation(
    Name
)


#!/usr/bin/env python3

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

def readFile(yay):
    new = []
    with open(yay, 'r') as f:
        f = f.readlines()

    for l in f:
        l = l.replace('\n', "")
        l = l.split()
        new.append(l)
    return new

def getCoords(data):
    list_dist = []
    list_freq = []
    betterData = np.zeros(len(data))
    for i in range(len(data)):
        betterData[i] = float(data[i][1])

    betterData.sort()

    for i in range(len(betterData)):
        if i == 0:
            #print('no')
            list_dist.append(betterData[i])
            list_freq.append(1)
            continue

        for j in range(len(list_dist)):
            if i == 0: print('crap')
            if betterData[i] == list_dist[j]:
                #print('yah')
                list_freq[j] = list_freq[j] + 1
        else:
            list_dist.append(betterData[i])
            list_freq.append(1)

    distance = np.array(list_dist)
    frequency = np.array(list_freq)

    return distance, frequency

def main():
    for filename in glob.glob('distance*.dat'):
        data = readFile(filename)
        dist, freq = getCoords(data)
        plt.plot(dist, freq)

        plt.xlabel('distance')
        plt.ylabel('frequency')

        plt.show()

        print('done')

if __name__ == '__main__':
    main()


import sys
from students import sorted_conflicts as student_matrix
from students import total_course_conflicts
from instructors import sorted_conflicts as instructor_matrix
from instructors import course_names

class Schedule:
    def __init__(self, instructor_matrix, student_matrix, num_colors, num_classes):
        self.instructors = instructor_matrix
        self.students = student_matrix
        self.colors = []
        for i in range(0, num_colors):
            self.colors.append(i)
        self.num_classes = num_classes
        self.conflict_sum = 0

    def get_coloring(self):
        self.result = []
        for i in range(0, self.num_classes):
            self.result.append(-1)

        def check_vertex(vertex):
            if vertex >= self.num_classes:
                return

            self.conflicts = {}
            for color in self.colors:
                if vertex >= self.num_classes:
                    return
                if (self.is_possible(vertex, color)):
                    self.conflicts = self.get_student_conflicts(vertex, color)

            least = sys.maxsize
            color = 0
            for key, val in self.conflicts.items():
                if val < least:
                    least = val
                    color = key
            self.conflict_sum = self.conflict_sum + least
            self.result[vertex] = color
            check_vertex(vertex+1)
            return

        if len(self.instructors) > 0:
            check_vertex(0)
        print(self.conflict_sum)
        return self.result

    def get_student_conflicts(self, vertex, color):
        if color not in self.conflicts:
            self.conflicts[color] = 0
        for v in range(0, self.num_classes):
            if(self.result[v] == color):
                self.conflicts[color] = self.conflicts[color] + self.students[v][vertex]
        return self.conflicts

    def is_possible(self, vertex, color):
        for v in range(0, self.num_classes):
            if (self.instructors[v][vertex] >= 1 and self.result[v] == color):
                return False
        return True

schedule = Schedule(instructor_matrix, student_matrix, 8, 45)
res1 = schedule.get_coloring()

print("Schedule:")
print()
print("Block #1")
for i, val in enumerate(res1):
    if val == 0:
        print(course_names[total_course_conflicts[i][0]])

print()
print("Block #2")
for i, val in enumerate(res1):
    if val == 1:
        print(course_names[total_course_conflicts[i][0]])

print()
print("Block #3")
for i, val in enumerate(res1):
    if val == 2:
        print(course_names[total_course_conflicts[i][0]])

print()
print("Block #4")
for i, val in enumerate(res1):
    if val == 3:
        print(course_names[total_course_conflicts[i][0]])

print()
print("Block #5")
for i, val in enumerate(res1):
    if val == 4:
        print(course_names[total_course_conflicts[i][0]])

print()
print("Block #6")
for i, val in enumerate(res1):
    if val == 5:
        print(course_names[total_course_conflicts[i][0]])

print()
print("Block #7")
for i, val in enumerate(res1):
    if val == 6:
        print(course_names[total_course_conflicts[i][0]])

print()
print("Block #8")
for i, val in enumerate(res1):
    if val == 7:
        print(course_names[total_course_conflicts[i][0]])


import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name="gnttb-a2ohm",
    version="1",
    author="Antoine",
    author_email="antoine@2ohm.fr",
    description="A Greek New Testament toolbox",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/a2ohm/gnttb",
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
)


# 예시1 <개미 전사>
import sys

N = int(sys.stdin.readline())
stores = list(map(int, sys.stdin.readline().split())) # 모든 식량 정보 입력

dp = [0]*N # 앞서 계산된 결과를 저장하기 위한 DP 테이블 초기화 (0으로)
dp[0] = stores[0]
dp[1] = max(stores[0], stores[1])

# 다이나믹 프로그래밍 진행 (바텀업 방식)
for i in range(2, N):
    a = dp[i-1] # 바로 뒤의 최대값 (현재 창고는 털지 않는 경우)
    b = dp[i-2] + stores[i] # 2칸 뒤의 최대값 (현재 창고도 터는 경우)
    dp[i] = max(a, b) # 위의 2가지 경우 중 더 큰 경우로 dp테이블에 넣어준다.

print(dp[N-1])


import cv2
import numpy as np

def gamma_correction(img: np.ndarray, gamma: float):
    look_up_table = np.empty((1,256), np.uint8)
    for i in range(256):
        look_up_table[0,i] = np.clip(pow(i / 255.0, gamma) * 255.0, 0, 255)
    res = cv2.LUT(img, look_up_table)
    return res

def get_overexposed_mask(gray_img: np.ndarray, threshold: int, need_blur: bool = True):
    """
    Получить маску засвеченных областей с заданным порогом
    на основе перехода к grayscale
    """
    gray = gray_img.copy()
    if need_blur:
        gray = cv2.GaussianBlur(gray_img, (11, 11), 0)
    return cv2.threshold(gray, threshold, 255, cv2.THRESH_BINARY)[1]

def get_masked(img: np.ndarray, mask: np.ndarray):
    """Получить фрагменты изображения под маской"""
    return cv2.bitwise_and(img, img, mask=mask)

def apply_masked_changes(img: np.ndarray,
                         changed_image: np.ndarray,
                         mask: np.ndarray):
    """Заменить в img маскированные области на области из changed_image"""
    img[np.where(mask == 255)] = changed_image[np.where(mask == 255)]
    return img

def get_map_mask(img, radius):
    bin = get_overexposed_mask(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), 220)
    not_bin = cv2.bitwise_not(bin)
    dist = cv2.distanceTransform(not_bin, cv2.DIST_L2, cv2.DIST_MASK_3, not_bin)
    cv2.normalize(dist, dist, 0.0, radius, cv2.NORM_MINMAX)
    not_mask = np.zeros(dist.shape, dtype=np.uint8)
    not_mask[np.where(dist > 1)] = 255
    mask = np.zeros(dist.shape, dtype=np.uint8)
    mask[np.where(not_mask == 0)] = 255
    # cv2.imshow("map", mask)
    return mask

def reduce(img):
    source = img.copy()
    res = img.copy()
    for radius in range(10, 15):
        overexposed_mask = get_map_mask(res, radius)
        mask_inv = cv2.bitwise_not(overexposed_mask)
        source = cv2.bitwise_and(res, res, mask = mask_inv)
        res = cv2.bitwise_and(res, res, mask = overexposed_mask)
        res = gamma_correction(res, 1.1)
        res = cv2.add(source, res)
    cv2.imshow("res", res)
    # return img

if __name__ == '__main__':
    img = cv2.imread('test_1.png')
    img = cv2.resize(img, (650, 350), interpolation=cv2.INTER_AREA)
    reduce(img)
    # get_map_mask(img)
    # cv2.imshow('img', img)
    cv2.waitKey()


import sqlite3
import json

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    #d['subscript'] = ""
    #d['superscript'] = ""
    return d

def complete(search, db, prefix=False, limit=20, accents=True):
    db.row_factory = dict_factory
    c = db.cursor()

    query = ["SELECT  name, name_ascii, entry_id FROM complete ",
             "WHERE name like ? " + (" and prefix != '' " if prefix else "") ,
             "GROUP BY entry_id ORDER BY lower(name_ascii)  LIMIT ? "
            ]
    query = " ".join(query)
    c.execute( query , ( search+'%',limit) )

    rows = c.fetchall()
    entries =  [ d['entry_id'] for d in  rows ]
    if len(entries) == 1 :
        entries = ['oooooooo'] + entries

    SELECT = "SELECT  uuid, entry_id, entry, name, name_ascii, lexnum as num, prefix, subscript, superscript from complete"
    WHERE =  " WHERE entry_id IN  {}".format(str(tuple(entries)))
    ORDER =  " ORDER BY lower(name_ascii), length(name), prefix, subscript, superscript, cast(lexnum as integer) asc , lexnum asc ";

    c.execute( "%s %s %s " % (SELECT , WHERE, ORDER) )
    rows =  c.fetchall()
    return rows

def complete_id(search, db):

    c = db.cursor()
    c.execute( "select  uuid, entry_id, entry, name, lexnum as num , prefix, subscript, superscript from complete where entry=? ORDER BY name asc, lexnum asc", ( search, ) )
    rows =  c.fetchall()
    return rows

def complete_uuids(item, db, limit=50):

    db.row_factory = dict_factory
    c = db.cursor()

    args = [ item.get(e) for e in ['prefix', 'name', 'subscript', 'superscript', 'num'] ]
    args += [limit]
    c.execute( "select  uuid, entry_id, entry, name , lexnum as num , prefix, subscript, superscript from complete where prefix = ? and name = ? and subscript = ? and superscript = ? and num = ? ORDER BY name asc, lexnum asc limit ?", tuple(args) )
    rows = c.fetchall()

    if len(rows) == 0 :
        if len(args[2]):
            c.execute( "select  uuid,  entry_id, entry, name , lexnum as num , prefix, subscript, superscript from complete where name = ? and subscript = ? ORDER BY name asc, lexnum asc limit ?", ( item.get('name'),item.get('subscript'), limit) )
        else:
            c.execute( "select  uuid,  entry_id, entry, name , lexnum as num , prefix, subscript, superscript from complete where name = ? ORDER BY name asc, lexnum asc limit ?", ( item.get('name'), limit) )
        rows = c.fetchall()

    return rows


# 1 X 1 크기 정사각형 n x n
# 길과 벽
# 길 칸 하나에 캐릭터 하나

# 캐릭터 꽃 심음
# 1. 상하좌우 방향 정함
# 1-1. 이동 불가능 할경우, 현재 위치에 꽃 심고 더 이동X
# 2. 현재 위치에 꽃 심고 *** 1번에서 정한  방향으로 이동
# 3. 더 이동하지 못할 때까지 방향 유지하고 이동

# 벽, 꽃 심어진 칸 이동 불가
# 방향 이동 불가능하면 방향 바꾸기 위해 1번 과정으로 이동

# 모든길에 꽃 심기 가능하면 1, 아니면 0

# 맵 개수 2~10
# 맵 세로가로 길이 3~10
# 벽0 길1 캐릭터2

boards = [["1111", "1121", "1001", "1111"]]
answer = []

import copy

# 바이러스 이동 방향
dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]

# 캐릭터가 이동할 수 있을 떄까지 직진
def move(x, y, i):
    #  맵 밖이거나 벽에 부딪히거나 꽃이 있을 경우 방향 회전
    if change_direction:
        for d in range(4):
            if d % 2 != i % 2:
                move(x, y, d)

    # 현재 위치에 꽃 배치
    temp[x][y] = -1

    # 다음 위치
    nx = x + dx[i]
    ny = y + dy[i]
    # 맵 내에서 움직임
    if nx >= 0 and nx < len_board and ny >= 0 and ny < len_board:
        # 길 위일 경우 재귀적 수행
        if temp[nx][ny] == 1:
            move(nx, ny, i)
        else:
            x = nx - dx[i]
            y = ny - dy[i]
            change_direction = True

for board in boards:
    global temp, len_board, change_direction
    new_board = []
    len_board = len(board)
    temp = []
    x, y = 0, 0
    change_directio = False
    for i in range(len_board):
        new_board.append(list(map(int, board[i])))
        # 캐릭터 위치
        if new_board[i].count(2) != 0:
            x, y = i, new_board[i].index(2)

    possible = False # 모든 길에 꽃을 심을 수 있는지
    for j in range(4):
        # 꽃을 심을 수 있는 방법을 발견한 경우
        if possible:
            break
        # 이동
        temp = copy.deepcopy(new_board)
        move(x, y, j)

        for k in range(len_board):
            # 꽃이 심어지지 않은 길이 있을 경우
            if temp[k].count(1) == 0:
                possible = True
            else:
                possible = False
                break
    if possible:
        answer.append(1)
    else:
        answer.append(0)

print(answer)


#creates a PDF image of a t-shirt with overlay of text: x took CS50!

from fpdf import FPDF

name = input("What is your name? ")
pdf = FPDF(orientation="landscape", format="A5")
pdf.add_page()
pdf.set_font('helvetica', size=12)
pdf.image("shirtificate.png",x = 0, y=70)
pdf.text(x =100, y=100, txt=(f"{name} took CS50"))
pdf.output("shirtificate.pdf")


from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
from flask_sqlalchemy import SQLAlchemy
import json

# ==================================== CONNECTION SPECIFICATION ====================================== #
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://root:password@database-1.c9bzkzbvdsli.ap-southeast-1.rds.amazonaws.com:3306/region'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
CORS(app)

class Region(db.Model):
    __tablename__ = 'region'

    regionID = db.Column(db.Integer)
    spawnDate = db.Column(db.String(50))
    regionName = db.Column(db.String(50), primary_key=True)
    Points = db.Column(db.Integer, nullable=False)

    def __init__(self, regionID,regionName,Points,spawnDate):
        self.regionID = regionID
        self.spawnDate = spawnDate
        self.regionName = regionName
        self.Points = Points

    def json(self):
        region_entry = {
            "regionID": self.regionID,
            "regionName": self.regionName,
            "points": self.Points,
            "spawnDate": self.spawnDate
        }
        return region_entry

    def setSpawnDate(self, spawnDate):
        self.spawnDate = spawnDate
        return True

#region map
class regionMap(db.Model):
    __tablename__ = 'regionMap'
    regionID = db.Column(db.String(50), primary_key=False)
    postalcode = db.Column(db.String(50), primary_key=True)

    def __init__(self, regionID,postalcode):
        self.regionID = regionID
        self.postalcode = postalcode

    def json(self):
        region_entrymap = {
            "regionID": self.regionID,
            "postalcode": self.postalcode
        }
        return region_entrymap

# method to retireve all region maps

# retrieve particular region map area
@app.route("/getCustRegion/<string:postalcode>", methods=["GET"])
@cross_origin(supports_credentials=True)
def getRegionMap(postalcode):
    f2 = postalcode[0] + postalcode[1]
    allRegions = regionMap.query.filter_by(postalcode=f2).first()
    regionID = allRegions.regionID
    reg = Region.query.filter_by(regionID = regionID).first()
    print (reg)

    if reg:
        return jsonify({"RegionName" : reg.regionName}),200
    else:
        return jsonify(False), 404

@app.route("/getSpawnDate/<string:regionName>", methods=["GET"])
@cross_origin(supports_credentials=True)
def getSpawnDate(regionName):
    records = Region.query.get(regionName)
    return jsonify({"spawnDate" :records.spawnDate})

@app.route ("/updateSpawnDate/<string:spawnDate>/<string:regionName>", methods=["PUT"])
@cross_origin(supports_credentials=True)
def updateSpawnDate(spawnDate, regionName):
    records = Region.query.get(regionName)
    records.setSpawnDate(spawnDate)
    db.session.commit()
    return jsonify(True)

@app.route("/getRegions", methods=["GET"])
@cross_origin(supports_credentials=True)
def getRegions():
    return jsonify({"Regions": [region.json() for region in Region.query.all()]})

if __name__=='__main__':
    app.run(host='0.0.0.0',port=5004, debug=True)


import sys
sys.path.append('C:/Users/Mengke/Dropbox/Mengke_Mike/SourceCode/RedditPushshiftAPI')
import utilFunc
import compare_fun

#load new data
prefixDir_new = 'C:/Users/Mengke/Dropbox/Mengke_Mike/Data/Data_COVID/COVID_new/'
jsonFileList_new = ['coronavirusus_Feb2020.json','coronavirusus_March2020.json','coronavirusus_April2020.json']
#['CanadaCoronavirus_Feb2020.json','CoronavirusCanada_Feb2020.json']
#['CoronavirusDownunder_Feb2020.json','CoronavirusAustralia_Feb2020.json']
#['CoronavirusUK_Feb2020.json']
data_new = utilFunc.loadJson(jsonFileList_new, prefixDir_new)

#load old data
prefixDir_old = 'C:/Users/Mengke/Dropbox/Mengke_Mike/Data/Data_COVID/COVID_old/'
jsonFileList_old = ['coronavirusus_Jan2Apil_2020.json']
#['CanadaCoronavirus_Jan2June2020.json','CoronavirusCanada_Jan2April2020.json']
#['CoronavirusDownunder_Jan2June2020.json','CoronavirusAustralia_Jan2June2020.json']
#['CoronavirusUK_Jan2June2020.json']
data_old = utilFunc.loadJson(jsonFileList_old, prefixDir_old)

#check utc range:
min_old,max_old = compare_fun.UTC_range(data_old)
min_new, max_new = compare_fun.UTC_range(data_new)
print('old range',min_old,max_old)
print('new range',min_new,max_new)

#checking missing data between old and new
missingData_newINold = compare_fun.check_missing_submission_newINold(data_new, data_old)
missingData_oldINnew = compare_fun.check_missing_submission_oldINnew(data_new, data_old)

print('missing new in old:',len(missingData_newINold),'missing old in new:',len(missingData_oldINnew))


from __future__ import division
import numpy as np
import itertools
import logging

from .endclasses import endarray, lton, wc
from .energetics_basic import EnergeticsBasic

LOGGER = logging.getLogger(__name__)

__all__ = [
    'values_chunked', 'get_accept_set', 'find_end_set_uniform',
    'enhist', 'easyends', 'easy_space', 'spacefilter_standard',
    'endfilter_standard', 'endfilter_standard_advanced', 'energy_array_uniform',
    'endchooser_standard', 'endchooser_random'
]

def values_chunked(items, endtype, chunk_dim=10):
    """
    Given a list of lists of acceptable numbers for each position in a row of
    an array, create every possible row, and return an iterator that returns
    chunks of every possible row up to chunk_dim, iterating dimensions higher
    than chunk_dim.  This probably doesn't need to be called directly, and may
    have a _ added in the future.

    Return this as an endarray, with set endtype. This can be easily emoved
    for use elsewhere.
    """
    ilengths = [len(x) for x in items]
    n = len(items)
    items = [np.array(x) for x in items]
    if n > chunk_dim:
        p = n - chunk_dim
        q = chunk_dim
        outer = itertools.product(*(items[0:p]))
    else:
        p = 0
        q = n

        def outer_iter():
            yield ()

        outer = outer_iter()

    chunk = np.zeros(
        [np.prod(ilengths[p:]), len(items)], dtype=int).view(endarray)
    chunk.endtype = endtype
    chunk[:, p:] = np.indices(ilengths[p:]).reshape(q, -1).T
    for i in range(p, n):
        chunk[:, i] = items[i][chunk[:, i]]
    for seq in outer:
        chunk[:, :p] = seq
        yield chunk

def get_accept_set(endtype,
                   length,
                   interaction,
                   fdev,
                   maxendspurious,
                   spacefilter=None,
                   adjacents=['n', 'n'],
                   alphabet='n',
                   energetics=None):
    if not energetics:
        energetics = EnergeticsBasic()
    if not spacefilter:
        spacefilter = spacefilter_standard(interaction, interaction * fdev,
                                           maxendspurious)
    # Generate the template.
    if endtype == 'DT':
        template = [lton[adjacents[0]]] + [lton[alphabet.lower()]] \
                   * length + [lton[wc[adjacents[1]]]]
    elif endtype == 'TD':
        template = [lton[wc[adjacents[1]]]] + [lton[alphabet.lower()]] \
                   * length + [lton[adjacents[0]]]
    elif endtype == 'S':
        template = [lton[alphabet.lower()]]*length

    LOGGER.info("Length {0}, type {1}, adjacents {2}, alphabet {3}.".format(
        length, endtype, adjacents, alphabet))
    LOGGER.debug("Have template %s, endtype %s.", template, endtype)

    # Create the chunk iterator
    endchunk = values_chunked(template, endtype)

    # Use spacefilter to filter chunks down to usable sequences
    matcharrays = []
    chunknum = 0
    totchunks = None
    totends = np.product([len(x) for x in template])
    LOGGER.debug(
        "Have {0} ends in total before any filtering.".format(totends))
    for chunk in endchunk:
        matcharrays.append(spacefilter(chunk, energetics))
        if not totchunks:
            totchunks = totends // len(chunk)
        chunknum += 1
        LOGGER.debug("Found {0} filtered ends in chunk {1} of {2}.".format(
            len(matcharrays[-1]), chunknum, totchunks))
    LOGGER.debug("Done with spacefiltering.")
    availends = np.vstack(matcharrays).view(endarray)
    availends.endtype = endtype
    return availends

def _make_avail(endtype,
                length,
                spacefilter,
                endfilter,
                endchooser,
                energetics,
                adjacents=['n', 'n'],
                num=0,
                numtries=1,
                oldendfilter=None,
                oldends=[],
                alphabet='n'):
        # Generate the template.
    if endtype == 'DT':
        template = [lton[adjacents[0]]] + [lton[alphabet.lower()]] \
                   * length + [lton[wc[adjacents[1]]]]
    elif endtype == 'TD':
        template = [lton[wc[adjacents[1]]]] + [lton[alphabet.lower()]] \
                   * length + [lton[adjacents[0]]]
    elif endtype == 'S':
        template = [lton[alphabet.lower()]]*length

    LOGGER.info("Length {0}, type {1}, adjacents {2}, alphabet {3}.".format(
        length, endtype, adjacents, alphabet))
    LOGGER.debug("Have template %s, endtype %s", template, endtype)

    # Create the chunk iterator
    endchunk = values_chunked(template, endtype)

    # Use spacefilter to filter chunks down to usable sequences
    matcharrays = []
    chunknum = 0
    totchunks = None
    totends = np.product([len(x) for x in template])
    LOGGER.debug(
        "Have {0} ends in total before any filtering.".format(totends))
    for chunk in endchunk:
        matcharrays.append(spacefilter(chunk, energetics))
        if not totchunks:
            totchunks = totends // len(chunk)
        chunknum += 1
        LOGGER.debug("Found {0} filtered ends in chunk {1} of {2}.".format(
            len(matcharrays[-1]), chunknum, totchunks))
    LOGGER.debug("Done with spacefiltering.")
    availends = np.vstack(matcharrays).view(endarray)
    availends.endtype = endtype

    # Use endfilter to filter available sequences taking into account old
    # sequences.
    if len(oldends) > 0:
        if oldendfilter:
            availends = oldendfilter(oldends, None, availends, energetics)
        else:
            availends = endfilter(oldends, None, availends, energetics)

    return availends

def find_end_set_uniform(endtype,
                         length,
                         spacefilter,
                         endfilter,
                         endchooser,
                         energetics,
                         adjacents=['n', 'n'],
                         num=0,
                         numtries=1,
                         oldendfilter=None,
                         oldends=[],
                         alphabet='n',
                         _presetavail=False):
    """
    Find a set of ends of uniform length and type satisfying uniform
    constraint functions (eg, constrant functions are the same for each
    end).

    This function is intended to be complicated and featureful. If you want
    something simpler, try easy_ends

    Parameters
    ----------

    endtype : str
      right now 'DT' for 3'-terminal ends, and 'TD' for
      5'-terminal ends,
    length : int
      length of ends, not including adjacent bases, if applicable.
    adjacents : list of str
      (defaults to ['n','n']): acceptable bases for adjacents
      (eg, ['n','n'] or ['c', 'c']) for the ends and their complements,
    num : int
      (defaults to 0): number of ends to find (0 keeps finding until
      available ends are exhausted)
    numtries : int
      (defaults to 1): if > 1, the function will return a list of
      sets of ends that all individually satisfy the constraints, so that
      the best one can be selected manually
    spacefilter: function
        a "spacefilter" function that takes endarrays and
        filters them down to ends that, not considering spurious
        interactions, are acceptable.
    endfilter: function
        an "endfilter" function that takes current ends in the
        set, available ends (filtered with current ends), and new ends added,
        and filters the available ends, considering interactions between ends
        (eg, spurious interactions).
    endchooser : function
        an "endchooser" function that takes current ends in the
        set and available ends, and returns a new end to add to the set.
    energetics : function
        an "energyfunctions" class that provides the energy
        functions for everything to use.
    oldends : endarray
        an endarray of old ends to consider as part of the set
    alphabet : str
        a single letter specifying what the alphabet for the ends
        should be (eg, four or three-letter code)
    oldendfilter : str
        a different "endfilter" function for use when filtering
        the available ends using interactions with old ends. This is normally
        not useful, but can be useful if you want, for example, to create a
        sets with higher cross-interactions between two subsets than within
        the two subsets.

    Returns
    -------

    endarray
      an endarray of generated ends, including provided old ends
    """

    if len(oldends) > 0:
        if type(oldends[0]) is str:
            oldends = endarray(oldends, endtype)

    if isinstance(_presetavail, endarray):
        startavail = _presetavail
    else:
        startavail = _make_avail(endtype,
                                 length,
                                 spacefilter,
                                 endfilter,
                                 endchooser,
                                 energetics,
                                 adjacents,
                                 num,
                                 numtries,
                                 oldendfilter,
                                 oldends,
                                 alphabet)
    endsets = []
    availends = startavail.copy()
    LOGGER.debug("Starting with {0} ends.".format(len(availends)))
    while len(endsets) < numtries:
        curends = oldends
        availends = startavail.copy()
        numends = 0
        while True:
            newend = endarray(
                np.array([endchooser(curends, availends, energetics)]),
                endtype)
            LOGGER.debug("Chose end {0}.".format(repr(newend)))
            newend.endtype = endtype
            availends = endfilter(newend, curends, availends, energetics)
            LOGGER.debug("Done filtering.")
            if curends is None:
                curends = newend
            elif len(curends) == 0:
                curends = newend
            else:
                curends = curends.append(newend)
            numends += 1
            LOGGER.debug("Now have {0} ends in set, and {1} ends available.".format(numends, len(availends)))
            if len(availends) == 0:
                LOGGER.info("Found {0} ends.".format(numends))
                break
            if numends >= num and num > 0:
                break
        endsets.append(curends)

    # Verification:
    # Note: this currently gives weird output that is not helpful when it fails.
    # But if this fails, you've done something very weird, most likely, because
    # this is just internal sanity checking.
    for endset in endsets:
        oldr = np.arange(0, len(oldends))
        newr = np.arange(len(oldends), len(endset))
        allr = np.arange(0, len(endset))
        # All new ends must satisfy old ends:
        if oldendfilter is None and len(oldends) > 0:
            assert np.asarray(
                endfilter(endset[oldr, :], None,
                          endset[newr, :], energetics) ==
                endset[newr, :]).all()
        elif len(oldends) > 0:
            assert np.asarray(
                oldendfilter(endset[oldr, :], None,
                             endset[newr, :], energetics) ==
                endset[newr, :]).all()
        # Each new end must allow all others
        for i in newr:
            if oldendfilter is None:
                assert np.asarray(
                    endfilter(endset[i, :][None, :], None,
                              endset, energetics) ==
                    endset[i != allr, :]).all()
            else:
                assert np.asarray(
                    oldendfilter(endset[i, :][None, :], None,
                                 endset[oldr, :], energetics) ==
                    endset[oldr, :]).all()
                assert np.asarray(
                    endfilter(endset[i, :][None, :], None,
                              endset[newr, :], energetics) ==
                    endset[newr[i != newr], :]).all()

    if len(endsets) > 1:
        return endsets
    else:
        if _presetavail is None or isinstance(_presetavail,endarray):
            return endsets[0], startavail
        else:
            return endsets[0]

def enhist(endtype,
           length,
           adjacents=['n', 'n'],
           alphabet='n',
           bins=None,
           energetics=None,
           plot=False,
           color='b'):
    if endtype == 'DT':
        template = [lton[adjacents[0]]] +\
                   [lton[alphabet.lower()]] * length + [lton[wc[adjacents[1]]]]
    elif endtype == 'TD':
        template = [lton[wc[adjacents[1]]]] +\
                   [lton[alphabet.lower()]] * length + [lton[adjacents[0]]]
    elif endtype == 'S':
        template = [lton[alphabet.lower()]]*length

    if not energetics:
        energetics = EnergeticsBasic()

    minbin = 0.8 * energetics.matching_uniform(
        endarray([([0, 3] * length)[0:length + 2]], endtype))
    maxbin = 1.1 * energetics.matching_uniform(
        endarray([([1, 2] * length)[0:length + 2]], endtype))

    if not bins:
        bins = np.arange(minbin, maxbin, 0.1)

    LOGGER.debug("Have template {0} and type {1}.".format(template, endtype))

    # Create the chunk iterator
    endchunk = values_chunked(template, endtype)

    hist = np.zeros(len(bins) - 1, dtype='int')
    totends = np.product([len(x) for x in template])
    finishedends = 0
    info = {'min': np.inf, 'max': -np.inf, 'mean': 0}
    for chunk in endchunk:
        matchens = energetics.matching_uniform(chunk)
        hist += np.histogram(matchens, bins)[0]
        info['max'] = max(info['max'], np.amax(matchens))
        info['min'] = min(info['min'], np.amin(matchens))
        info['mean'] = (info['mean']*(finishedends)/(len(chunk)+finishedends)
                        + np.mean(matchens) * len(chunk) /
                        (len(chunk)+finishedends))
        finishedends += len(matchens)
        LOGGER.debug("Done with {0}/{1} ends.".format(finishedends, totends))

    x = (bins[:-1] + bins[1:]) / 2
    n = hist
    info['emean'] = np.sum(n * x, dtype='double') / np.sum(n, dtype='int64')
    info['estd'] = np.sqrt(
        np.sum(n * (
            x - info['emean'])**2, dtype='double') / np.sum(n, dtype='int64'))
    cs = np.cumsum(n)
    info['emedian'] = x[np.flatnonzero(cs >= cs[-1] / 2.0)[0]]

    if plot:
        import matplotlib.pyplot as plt

        plt.bar(
            bins[:-1],
            hist,
            width=(bins[1] - bins[0]),
            label="Type {3}, Length {0}, Adjs {1}, Alph {2}".format(
                length, adjacents, alphabet, endtype),
            color=color)
        plt.title(
            "Matching Energies of Ends of Type {3}, Length {0}, Adjs {1}, Alph {2}".
            format(length, adjacents, alphabet, endtype))
        plt.xlabel("Standard Free Energy (-kcal/mol)")
        plt.ylabel("Number of Ends")
        # plt.show()

    return (hist, bins, info)

def easyends(endtype,
             endlength,
             number=0,
             interaction=None,
             fdev=0.05,
             maxspurious=0.5,
             maxendspurious=None,
             tries=1,
             oldends=[],
             adjs=['n', 'n'],
             energetics=None,
             alphabet='n',
             echoose=None,
             absolute=False,
             _presetavail=False):
    """
    Easyends is an attempt at creating an easy-to-use function for finding sets
    of ends.

    * endtype: specifies the type of end being considered. The system for
      classifying end types goes from 5' to 3', and consists of letters
      describing each side of the end. For example, an end that starts after a
      double-stranded region on the 5' side and ends at the end of the strand
      would be 'DT', while one that starts at the beginning of a strand on the
      5' side and ends in a double-stranded region would be 'TD'. 'T' stands
      for terminal, 'D' stands for double-stranded region, and 'S' stands for
      single-stranded region. 'S', however, is not currently supported.
    * endlength: specifies the length of end being considered, not including
      adjacent bases.
    * number (optional): specifies the number of ends to find.  If zero or not
      provided, easyends tries to find as many ends as possible.
    * interaction (optional): a positive number corresponding to the desired
      standard free energy for hybridization of matching sticky ends. If not
      provided, easyends calculates an optimal value based on the sequence
      space.
    * fdev (default 0.05): the fractional deviation (above or below) of
      allowable matching energies.  maxspurious (default 0.5): the maximum
      spurious interaction, as a fraction of the matching interaction.
    * maxendspurious (default None): if provided, maxspurious is only used for
      spurious interactions between ends defined as ends, and ends defined as
      complements. Maxendspurious is then the maximum spurious interaction
      between ends and ends, and complements and complements. In a system
      where spurious interactions between ends and complements are more important
      than other spurious interactions, this can allow for better sets of ends.
    * tries (default 1): if > 1, easyends will return a list of sets of ends,
      all satisfying the constraints.
    * oldends (optional): a list of ends to be considered as already part of
      the set.
    * adjacents (default ['n','n']): allowable adjacent bases for ends and
      complements.
    * absolute (default False): fdev, maxspurious, and maxendspurious to be
      interpreted as absolute kcal/mol values rather than fractional values.
    * energetics (optional): an energetics class providing the energy
      calculation functions. You probably don't need to change this.
    * alphabet (default 'n'): The alphabet to use for ends, allowing
      for three-letter codes.
    """

    if not energetics:
        efunc = EnergeticsBasic()
    else:
        efunc = energetics
    if (not interaction) or (interaction == 0):
        interaction = enhist(
            endtype,
            endlength,
            energetics=efunc,
            adjacents=adjs,
            alphabet=alphabet)[2]['emedian']
        LOGGER.info("Calculated optimal interaction energy is {0}.".format(
            interaction))
    if not absolute:
        mult = interaction
    else:
        mult = 1.0

    maxcompspurious = maxspurious * mult
    if not maxendspurious:
        maxendspurious = maxspurious * mult
    else:
        maxendspurious = maxendspurious * mult

    sfilt = spacefilter_standard(interaction, mult * fdev,
                                 maxendspurious)
    efilt = endfilter_standard_advanced(maxcompspurious, maxendspurious)
    if not echoose:
        echoose = endchooser_standard(interaction)

    return find_end_set_uniform(
        endtype,
        endlength,
        sfilt,
        efilt,
        echoose,
        energetics=efunc,
        numtries=tries,
        oldends=oldends,
        adjacents=adjs,
        num=number,
        alphabet=alphabet,
        _presetavail=_presetavail)

def easy_space(endtype,
               endlength,
               interaction=None,
               fdev=0.05,
               maxspurious=0.5,
               maxendspurious=None,
               tries=1,
               oldends=[],
               adjs=['n', 'n'],
               energetics=None,
               alphabet='n',
               echoose=None):
    length = endlength
    if not energetics:
        efunc = EnergeticsBasic()
        energetics = efunc
    else:
        efunc = energetics
    if (not interaction) or (interaction == 0):
        interaction = enhist(
            endtype,
            endlength,
            energetics=efunc,
            adjacents=adjs,
            alphabet=alphabet)[2]['emedian']
        LOGGER.info("Calculated optimal interaction energy is {0}.".format(
            interaction))
    maxcompspurious = maxspurious * interaction
    if not maxendspurious:
        maxendspurious = maxspurious * interaction
    else:
        maxendspurious = maxendspurious * interaction

    sfilt = spacefilter_standard(interaction, interaction * fdev,
                                 maxendspurious)
    spacefilter = sfilt

    if not echoose:
        echoose = endchooser_standard(interaction)

    adjacents = adjs

    if endtype == 'DT':
        template = [lton[adjacents[0]]] + [lton[alphabet.lower()]] \
                   * length + [lton[wc[adjacents[1]]]]
    elif endtype == 'TD':
        template = [lton[wc[adjacents[1]]]] + [lton[alphabet.lower()]] \
                   * length + [lton[adjacents[0]]]

    # Create the chunk iterator
    endchunk = values_chunked(template, endtype)

    # Use spacefilter to filter chunks down to usable sequences
    matcharrays = []
    chunknum = 0
    totchunks = None
    totends = np.product([len(x) for x in template])
    LOGGER.info(
        "Have {0} ends in total before any filtering.".format(totends))
    for chunk in endchunk:
        matcharrays.append(spacefilter(chunk, energetics))
        if not totchunks:
            totchunks = totends // len(chunk)
        chunknum += 1
        LOGGER.debug("Found {0} filtered ends in chunk {1} of {2}.".format(
            len(matcharrays[-1]), chunknum, totchunks))
    LOGGER.debug("Done with spacefiltering.")
    availends = np.vstack(matcharrays).view(endarray)
    availends.endtype = endtype

    availendsr = np.repeat(availends, len(availends), axis=0)
    availendst = np.tile(availends, (len(availends), 1))

    vals_ee = energetics.uniform(availendsr.ends, availendst.ends)
    vals_ec = energetics.uniform(availendsr.ends, availendst.comps)
    vals_ce = energetics.uniform(availendsr.comps, availendst.ends)
    vals_cc = energetics.uniform(availendsr.comps, availendst.comps)

    vals_tf = ((vals_ee < maxendspurious) & (vals_cc < maxendspurious) &
               (vals_ec < maxcompspurious) & (vals_ce < maxcompspurious))
    zipendsnf = zip(availendsr.tolist(), availendst.tolist())
    zipends = [zipendsnf[x] for x in np.flatnonzero(vals_tf)]

    return zipends

def spacefilter_standard(desint, dev, maxself):
    """
    A spacefilter function: filters to ends that have a end-complement
    interaction of between desint-dev and desint+dev, and a self-interaction
    (end-end or comp-comp) of less than maxself.
    """

    def spacefilter(fullends, energetics):
        matchenergies = energetics.matching_uniform(fullends)
        g4 = np.zeros(fullends.shape[0])
        for w in range(0, (fullends.shape[1] - 3)):
            g4 += (np.sum(
                np.array(fullends[:, w:(w + 4)] == [2, 2, 2, 2]), axis=1) == 4)
            g4 += (np.sum(
                np.array(fullends[:, w:(w + 4)] == [1, 1, 1, 1]), axis=1) == 4)
        i = np.flatnonzero((matchenergies < desint + dev) &
                           (matchenergies > desint - dev) & (g4 == 0))
        matchenergies = matchenergies[i]
        fullends = fullends[i]
        selfselfenergies = energetics.uniform(fullends.ends, fullends.ends)
        compcompenergies = energetics.uniform(fullends.comps, fullends.comps)
        i = np.flatnonzero((selfselfenergies < maxself) & (compcompenergies <
                                                           maxself))
        return fullends[i]

    return spacefilter

def endfilter_standard(maxspurious):
    """
    An endfilter function: filters out ends that have any (end-end, end-comp,
    comp-end, comp-comp) interactions with new ends above maxspurious.
    """

    def endfilter(newends, currentends, availends, energetics):
        endendspurious = energetics.uniform(
            np.repeat(newends.ends, len(availends), 0),
            np.tile(availends.ends, (len(newends), 1))).reshape(
                len(availends), len(newends), order='F')
        endcompspurious = energetics.uniform(
            np.repeat(newends.ends, len(availends), 0),
            np.tile(availends.comps, (len(newends), 1))).reshape(
                len(availends), len(newends), order='F')
        compendspurious = energetics.uniform(
            np.repeat(newends.comps, len(availends), 0),
            np.tile(availends.ends, (len(newends), 1))).reshape(
                len(availends), len(newends), order='F')
        compcompspurious = energetics.uniform(
            np.repeat(newends.comps, len(availends), 0),
            np.tile(availends.comps, (len(newends), 1))).reshape(
                len(availends), len(newends), order='F')
        highspurious = np.amax(
            np.hstack((endendspurious, compendspurious, endcompspurious,
                       compcompspurious)), 1)

        return availends[highspurious < maxspurious]

    return endfilter

def endfilter_standard_advanced(maxcompspurious, maxendspurious):
    """
    An endfilter function: filters out ends that have end-comp or comp-end
    interactions above maxcompspurious, and end-end or comp-comp interactions
    above maxendspurious.
    """

    def endfilter(newends, currentends, availends, energetics):
        endendspurious = energetics.uniform(
            np.repeat(newends.ends, len(availends), 0),
            np.tile(availends.ends, (len(newends), 1))).reshape(
                len(availends), len(newends), order='F')
        endcompspurious = energetics.uniform(
            np.repeat(newends.ends, len(availends), 0),
            np.tile(availends.comps, (len(newends), 1))).reshape(
                len(availends), len(newends), order='F')
        compendspurious = energetics.uniform(
            np.repeat(newends.comps, len(availends), 0),
            np.tile(availends.ends, (len(newends), 1))).reshape(
                len(availends), len(newends), order='F')
        compcompspurious = energetics.uniform(
            np.repeat(newends.comps, len(availends), 0),
            np.tile(availends.comps, (len(newends), 1))).reshape(
                len(availends), len(newends), order='F')
        highendspurious = np.amax(
            np.hstack((endendspurious, compcompspurious)), 1)
        highcompspurious = np.amax(
            np.hstack((compendspurious, endcompspurious)), 1)

        return availends[(highendspurious < maxendspurious)
                         & (highcompspurious < maxcompspurious)]

    return endfilter

def energy_array_uniform(seqs, energetics):
    """
    Given an endarray and a set of sequences, return an array of the
    interactions between them, including their complements.
    """
    seqs = seqs.ends.append(seqs.comps)
    return energetics.uniform(
        np.repeat(seqs, seqs.shape[0], 0), np.tile(
            seqs, (seqs.shape[0], 1))).reshape((seqs.shape[0], seqs.shape[0]))

def endchooser_standard(desint, wiggle=0.0):
    """
    An endchooser function: return a random end with end-comp energy closest to
    desint.
    """

    def endchooser(currentends, availends, energetics):
        ddiff = np.abs(energetics.matching_uniform(availends) - desint)
        choices = np.flatnonzero(ddiff <= np.amin(ddiff)+wiggle)
        newend = availends[choices[np.random.randint(0, len(choices))]]
        return newend

    return endchooser

def endchooser_random():
    """
    An endchooser function: return a random end with end-comp energy closest to
    desint.
    """

    def endchooser(currentends, availends, energetics):
        newend = availends[np.random.randint(0, len(availends))]
        return newend

    return endchooser


import psycopg2
from os import environ, path
from dotenv import load_dotenv

basedir = path.abspath(path.dirname(__file__))
load_dotenv(path.join(basedir, ".env"))

class Config:
    """Configuration from environment variables."""

    #SECRET_KEY = environ.get("SECRET_KEY")
    FLASK_ENV = environ.get("FLASK_ENV")
    FLASK_APP = "wsgi.py"

    # Flask-Assets
    #LESS_BIN = environ.get("LESS_BIN")
    #ASSETS_DEBUG = True
    #LESS_RUN_IN_DEBUG = True

    # Static Assets
    STATIC_FOLDER = "static"
    TEMPLATES_FOLDER = "templates"
    COMPRESSOR_DEBUG = True

    # Datadog
    # DD_SERVICE = environ.get("DD_SERVICE")

    # API
    # BEST_BUY_API_KEY = environ.get("BEST_BUY_API_KEY")

def connect():
    """ Connect to the PostgreSQL database server """
    conn = None
    try:
        # read connection parameters
        params = config()

        # connect to the PostgreSQL server
        print('Connecting to the PostgreSQL database...')
        conn = psycopg2.connect(**params)

        # create a cursor
        cur = conn.cursor()

	# execute a statement
        print('PostgreSQL database version:')
        cur.execute('SELECT version()')

        # display the PostgreSQL database server version
        db_version = cur.fetchone()
        print(db_version)

	# close the communication with the PostgreSQL
        cur.close()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()
            print('Database connection closed.')

if __name__ == '__main__':
    connect()


# -*- coding: utf-8 -*
import os
import sys

os.chdir(sys.path[0])
from flyai.model.base import Base
import torch
from torch.utils.data import DataLoader

from Seq2seq_Transformer import args
from Seq2seq_Transformer.util import AudioDataset, Util
from Seq2seq_Transformer.module import Transformer, Recognizer

DEVICE = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')

class Model(Base):
    def __init__(self, dataset):
        self.dataset = dataset
        self.args = args

    def predict(self, **data):
        audio_path = self.dataset.predict_data(**data)[0]

        # 定义评估模型
        eval_model = Transformer(input_size=self.args.input_size,
                                 vocab_size=self.args.vocab_size,
                                 d_model=self.args.model_size,
                                 n_heads=self.args.n_heads,
                                 d_ff=self.args.model_size * 4,
                                 num_enc_blocks=self.args.num_enc_blocks,
                                 num_dec_blocks=self.args.num_dec_blocks,
                                 residual_dropout_rate=0.0,
                                 share_embedding=self.args.share_embedding)

        if torch.cuda.is_available():
            eval_model.cuda()  # 将模型加载到GPU中

        # 将模型加载
        idx2unit = {}
        with open(self.args.vocab_txt_path, 'r', encoding='utf-8') as fr:
            for line in fr:
                unit, idx = line.strip().split()
                idx2unit[int(idx)] = unit

        # 将模型加载
        dataset = AudioDataset(audios_list=[audio_path])
        dataloader = DataLoader(dataset, batch_size=1, shuffle=False, num_workers=0, pin_memory=False,
                                collate_fn=Util.collate_fn)
        checkpoints = torch.load(os.path.join(self.args.data_model_dir, 'model.epoch.59.pt'))
        eval_model.load_state_dict(checkpoints)

        recognizer = Recognizer(eval_model, unit2char=idx2unit)

        print('Begin to decode test set!')
        for step, inputs in enumerate(dataloader):
            # 将输入加载到GPU中
            if torch.cuda.is_available():
                inputs = inputs.cuda()
            preds = recognizer.recognize(inputs)

            return preds

    def predict_all(self, datas):
        labels = []
        for data in datas:
            predicts = self.predict(audio_path=data['audio_path'])

            labels.append(predicts)

        return labels


#!/usr/bin/env python3

import sys
import math
import time
import threading
import susanow
import susanow.d2 as d2

def d2out_ignition(vnf, nfvi, threshold):
    perf = vnf.perfred() * 100
    return (perf < threshold)

def d2in_ignition(vnf, nfvi, data):
    perf = vnf.perfred()
    rate = vnf.rxrate()
    p = math.floor((rate * perf) * (rate * perf))

    data_ = data
    diff = 0 if (data[-5]['a']==0) else data[-1]['a'] / data[-5]['a']
    if (diff < 0.7):
        return True
    return False

def d2agent_func(vnf, nfvi):
    cnt = 0
    while (True):
        cnt = cnt + 1
        vnf.sync()
        n_core = vnf.n_core()
        rxrate = vnf.rxrate()
        perf = math.floor(vnf.perfred() * 100)
        perf = 100 if (perf>100) else perf
        # print('{:03}% rxrate={}'.format(perf, rxrate))

        max_rate = 17000000

        if (n_core == 1):

            if (perf < 90):
                print('out')
                d2.d2out(vnf, nfvi)

        elif (n_core == 2):

            if (perf < 90):
                print('out')
                d2.d2out(vnf, nfvi)

            if (perf > 85):
                if (rxrate < (max_rate*0.3)):
                    print('in2')
                    d2.d2in(vnf, nfvi)

        elif (n_core == 4):

            if (perf > 85):
                if (rxrate < (max_rate*0.6)):
                    print('in1')
                    d2.d2in(vnf, nfvi)

        time.sleep(0.5)


class Solution(object):
    def kthLargestNumber(self, nums, k):
        """
        :type nums: List[str]
        :type k: int
        :rtype: str
        """
        hq = []
        for num in nums:
            heapq.heappush(hq, -int(num))
        ans = -1
        while k>0:
            k -= 1
            ans = abs(heapq.heappop(hq))
        return str(ans)


import json
from typing import Dict, List, Optional
from pathlib import Path
from unitunes.file_manager import FileManager
from unitunes.index import Index
from unitunes.matcher import MatcherStrategy
from unitunes.playlist import Playlist
from unitunes.searcher import SearcherStrategy
from unitunes.services.musicbrainz import MusicBrainz, MusicBrainzWrapper
from unitunes.services.services import (
    Searchable,
    StreamingService,
    TrackPullable,
)

from unitunes.services.spotify import (
    SpotifyAPIWrapper,
    SpotifyService,
)
from unitunes.services.ytm import YTM, YtmAPIWrapper
from unitunes.track import Track
from unitunes.types import ServiceType
from unitunes.uri import PlaylistURIs, TrackURI

def service_factory(
    service_type: ServiceType,
    name: str,
    cache_path: Path,
    config_path: Optional[Path] = None,
) -> StreamingService:

    if service_type == ServiceType.SPOTIFY:
        assert config_path is not None
        index = json.load(config_path.open())
        return SpotifyService(name, SpotifyAPIWrapper(index, cache_path))
    elif service_type == ServiceType.YTM:
        assert config_path is not None
        return YTM(name, YtmAPIWrapper(config_path, cache_path))
    elif service_type == ServiceType.MB:
        return MusicBrainz(MusicBrainzWrapper(cache_path))
    else:
        raise ValueError(f"Unknown service type: {service_type}")

class PlaylistManager:
    index: Index
    file_manager: FileManager
    playlists: Dict[str, Playlist]
    services: Dict[str, StreamingService]

    def __init__(self, index: Index, file_manager: FileManager) -> None:
        self.index = index
        self.file_manager = file_manager
        self.playlists = {}
        self.services = {}

        self.load_services()

        # create playlist objects
        for name in self.index.playlists:
            self.playlists[name] = self.file_manager.load_playlist(name)

    def load_services(self) -> None:
        self.services[ServiceType.MB.value] = service_factory(
            ServiceType.MB,
            "MusicBrainz",
            cache_path=self.file_manager.cache_path,
        )
        for s in self.index.services.values():
            service_config_path = Path(s.config_path)
            self.services[s.name] = service_factory(
                ServiceType(s.service),
                s.name,
                config_path=service_config_path,
                cache_path=self.file_manager.cache_path,
            )

    def add_service(
        self, service: ServiceType, service_config_path: Path, name: str
    ) -> None:
        self.index.add_service(
            name, service.value, service_config_path.absolute().as_posix()
        )
        self.load_services()
        self.file_manager.save_index(self.index)

    def remove_service(self, name: str) -> None:
        if name not in self.index.services:
            raise ValueError(f"Service {name} not found")
        self.index.remove_service(name)

        for playlist in self.playlists.values():
            playlist.remove_service(name)
            self.file_manager.save_playlist(playlist)

        self.file_manager.save_index(self.index)

    def add_playlist(self, name: str) -> None:
        """Initialize a UP. Raise ValueError if the playlist already exists."""
        self.index.add_playlist(name)
        self.playlists[name] = Playlist(name=name)
        self.file_manager.save_index(self.index)
        self.file_manager.save_playlist(self.playlists[name])

    def remove_playlist(self, name: str) -> None:
        """Remove a playlist from the index and filesystem."""
        if name not in self.index.playlists:
            raise ValueError(f"Playlist {name} not found")
        self.file_manager.delete_playlist(name)
        del self.playlists[name]
        self.index.remove_playlist(name)
        self.file_manager.save_index(self.index)

    def add_uri_to_playlist(
        self, playlist_name: str, service_name: str, uri: PlaylistURIs
    ) -> None:
        """Link a playlist URI to a UP. UP must exist."""
        pl = self.playlists[playlist_name]
        pl.add_uri(service_name, uri)

        self.file_manager.save_index(self.index)
        self.file_manager.save_playlist(pl)

    def save_playlist(self, playlist_name: str) -> None:
        self.file_manager.save_playlist(self.playlists[playlist_name])

    def is_tracking_playlist(self, uri: PlaylistURIs) -> bool:
        for playlist in self.playlists.values():
            for uris in playlist.uris.values():
                if uri in uris:
                    return True
        return False

def get_predicted_tracks(
    target_service: StreamingService,
    track: Track,
    searcher: SearcherStrategy,
) -> List[Track]:
    if not isinstance(target_service, Searchable):
        raise ValueError(f"Service {target_service.name} is not searchable")

    return searcher.search(target_service, track)

def get_prediction_track(
    target_service: StreamingService,
    track: Track,
    matcher: MatcherStrategy,
    searcher: SearcherStrategy,
    threshold: float = 0.8,
) -> Optional[Track]:
    matches = get_predicted_tracks(target_service, track, searcher)
    matches = [m for m in matches if not any(uri in track.bad_uris for uri in m.uris)]
    if len(matches) == 0:
        return None
    best_match = matches[0]

    if matcher.similarity(track, best_match) >= threshold:
        return best_match
    return None

def get_prediction_uri(
    source_service: StreamingService,
    target_service: StreamingService,
    uri: TrackURI,
    matcher: MatcherStrategy,
    searcher: SearcherStrategy,
    threshold: float = 0.8,
) -> Optional[TrackURI]:
    if not isinstance(source_service, TrackPullable):
        raise ValueError(f"Service {source_service} is not pullable")
    track = source_service.pull_track(uri)
    prediction = get_prediction_track(
        target_service, track, matcher, searcher, threshold
    )
    return prediction.uris[0] if prediction else None


a = 1
b = 1
c = 998
found = False
while not found:
    if a ** 2 + b ** 2 == c ** 2:
        found = True
        break
    c -= 1
    b += 1
    if b >= c:
        a += 1
        c = 1000 - a - 1
        b = 1
print(a * b * c)
print(a, b, c)


import customtkinter
from tkinter.messagebox import showinfo
import os
import tkinter as tk
from mtranslate import translate
import gtts
import pygame

language={
   "Arabic" :"ar",
    "bulgarian": "bg",
   "croatian":"hr",
   "czech":"cs",
    "danish":"da",
   "german":"de",
   "greek" :"el",
    "english":"en",
   " Estonian" :"et",
   "spanish":"es",
   "finnish": "fi",
    "french": "fr",
   "irish": "ga",
   "hindi":"hi",
   "bulgarian": "hu",
   "Hebrew" :"iw",
   "Italian": "it",
   "japanese": "ja",
   "korean": "ko",
   " latvian" :"lv",
    "Lithuanian" :"lt",
   "Dutch" :"nl",
    "norwegian": "no",
   "polish":"pl",
    "portuguese":"pt",
   "swedish": "sv",
    "roman" :"ro",
  "russian": "ru",
    "srt":"sr",
    "slovak": "sk",
    "slovenian": "sl",
  "taiwanese" :"th",
    "turkish":"tr",
   " Ukrainian" :"uk",
   " Chinese (simplified)": "zh-CN",
    "Chinese (traditional)": "zh-TW"
}
lan=list(language.keys())
root=customtkinter.CTk()
customtkinter.set_appearance_mode("Dark")
customtkinter.set_default_color_theme("dark-blue")
root.title("Translator")
root.geometry("1000x700")

def paste():
    text=root.clipboard_get()
    fromlabel.delete("1.0","end")
    fromlabel.insert("1.0",text)

def copy():
    root.clipboard_clear()
    text = Tolabel.get("1.0", "end-1c")
    root.clipboard_append(text)

def translat():
    try:
        Tolabel.delete("1.0","end")
        translation = translate(fromlabel.get("1.0", "end-1c"),language[tselect.get()] )
        Tolabel.insert("1.0",translation)
    except:
        showinfo("Erorr","Please Check Your Connection")

def fspek():
    try:
        tts = gtts.gTTS(fromlabel.get("1.0", "end-1c"), lang=language[fselect.get()])
        tts.save("data.mp3")
        pygame.mixer.init()
        pygame.mixer.music.load("data.mp3")
        pygame.mixer.music.play()
    except PermissionError:
        pygame.mixer.music.unload()
        os.remove("data.mp3")
        fspek()

def tspek():
    try:
        tts = gtts.gTTS(Tolabel.get("1.0", "end-1c"), lang=language[tselect.get()])
        tts.save("data.mp3")
        pygame.mixer.init()
        pygame.mixer.music.load("data.mp3")
        pygame.mixer.music.play()

    except PermissionError:
        pygame.mixer.music.unload()
        os.remove("data.mp3")
        tspek()

def clear():
    Tolabel.delete("1.0","end")
    fromlabel.delete("1.0","end")

fselect=customtkinter.CTkOptionMenu(root,fg_color="#ffffff",text_color="black",values=lan,)
fselect.place(x=240,y=20)

f=customtkinter.CTkLabel(root,text="From:",font=("Roborto",20),text_color="#ffffff")
f.place(x=150,y=20)
fromlabel=customtkinter.CTkTextbox(root,width=400,height=250,font=("arial",14))
fromlabel.place(x=50,y=70)
pasteb=customtkinter.CTkButton(root,text="Paste",fg_color="#ffffff",text_color="black",command=paste)
pasteb.place(x=180,y=370)
fspeek=customtkinter.CTkButton(root,text="Speek",text_color="black",fg_color="#ffffff",width=40,height=20,command=fspek)
fspeek.place(y=320,x=50)

tselect=customtkinter.CTkOptionMenu(root,fg_color="#ffffff",text_color="black",values=lan)
tselect.place(x=760,y=20)
t=customtkinter.CTkLabel(root,text="To:",font=("Roborto",20),text_color="#ffffff")
t.place(x=670,y=20)
Tolabel=customtkinter.CTkTextbox(root,width=400,height=250,font=("arial",14))
Tolabel.place(x=550,y=70)
copyb=customtkinter.CTkButton(root,text="Copy",fg_color="#ffffff",text_color="black",command=copy)
copyb.place(x=680,y=370)
tspeek=customtkinter.CTkButton(root,text="Speek",text_color="black",fg_color="#ffffff",width=40,height=20,command=tspek)
tspeek.place(y=320,x=900)

clearb=customtkinter.CTkButton(root,text="Clear",text_color="black",fg_color="#ffffff",command=clear)
clearb.place(y=370,x=430)

trans=customtkinter.CTkButton(root,text="Translate",text_color="black",fg_color="#ffffff",command=translat)
trans.place(y=420,x=430)

root.mainloop()


#!/usr/bin/env python3
import sys
import freetype
import string
import math
import os.path
import struct
from functools import reduce
import itertools

CHARS = string.ascii_letters + string.digits + string.punctuation + " "
CHAR_NUMS = [ord(x) for x in CHARS]

FLAG_COMPRESSED = 1
FLAG_ITALIC = 2
FLAG_BOLD = 4
FLAG_KERNDAT = 8

if len(sys.argv) not in [4, 5]:
    print("Usage: {} <font file> <font size in pixels> <output path> [flags]".format(sys.argv[0]))
    print("       where flags is a combination of:")
    print("          c -- compressed")
    exit(1)
else:
    face_name = sys.argv[1]
    size_pixels = int(sys.argv[2])
    output_path = sys.argv[3]
    flags = sys.argv[4] if len(sys.argv) == 5 else ""

    compressed = "c" in flags

face = freetype.Face(face_name)
face.set_pixel_sizes(0, size_pixels)

def get_character_as_bool_array(c):
    """
    Render character c

    Result contains bitmap data in a 2d bool-valued list
    """
    global face

    face.load_char(c, freetype.FT_LOAD_RENDER | freetype.FT_LOAD_TARGET_MONO)

    bitmap = face.glyph.bitmap

    result = []
    buffercopy = bitmap.buffer

    if bitmap.pitch == 0 or bitmap.rows == 0 :
        return [[]]

    for i in range(0, bitmap.rows * bitmap.pitch, bitmap.pitch):
        arr = []
        seen = []
        for j in range(bitmap.width):
            byte, bit = divmod(j, 8)
            bit = 7 - bit
            if byte not in seen:
                seen.append(byte)
            arr.append(buffercopy[i+byte] & (1 << bit) != 0)
        result.append(arr)

    return result

def get_metrics(c):
    """
    Return metrics for character c in pixels:

    advance, bearingX, bearingY
    """
    global face

    face.load_char(c, freetype.FT_LOAD_TARGET_MONO)
    return [
            int(face.glyph.metrics.horiAdvance / 64.0),
            int(face.glyph.metrics.horiBearingX / 64.0),
            int(face.glyph.metrics.horiBearingY / 64.0)
    ]

def round_away_from_zero(x):
    a = abs(x)
    r = math.floor(a) + math.floor(2 * (a % 1))
    return r if x >= 0 else -r

def calc_kerning(c):
    """
    Create kerning data for character c as first character
    """
    global face

    entries = []
    for other in sorted(CHAR_NUMS):
        kerning = face.get_kerning(c, chr(other))
        pix = int(round_away_from_zero(kerning.x / 64))
        if pix == 0:
            continue
        else:
            entries.append((ord(c), other, pix))
    return entries

def convert_bitmap(bitmap, compress, bytelength=-1):
    """
    Convert bitmap to bytes (optionally compressing it)

    returns (compress = 0? data)
            (compress = 1? data bytelength newwidth)
    """

    width = len(bitmap[0])

    if compress and bytelength == -1:
        options = [[convert_bitmap(bitmap, True, 0), 0, len(bitmap[0])]]

        def appendoption(width, bitmap):
            nonlocal options
            for bl in range(width):
                if width % (bl + 1) != 0:
                    continue
                options.append((convert_bitmap(bitmap, True, bl+1), bl+1, width))

        appendoption(width, bitmap)

        # create one extended if width % 2 == 1
        if width % 2 == 1:
            newbitmap = []
            for i in bitmap:
                newbitmap.append(i[:] + [0])
            appendoption(width + 1, newbitmap)

        value = min(options, key=lambda x: len(x[0]))

        return value

    height = len(bitmap)

    if not compress:
        stride = (width // 8 + 1) if width % 8 != 0 else width // 8
        data = [0 for x in range((stride) * height)]

        for y in range(height):
            for x in range(stride):
                data[y*(stride) + x] = reduce(lambda x, y: (x << 1) | int(y), reversed(bitmap[y][x*8:(x+1)*8]), 0)

        return data

    # Try and compress
    bits = []

    if bytelength > 0:
        for y in range(height):
            if y != 0 and bitmap[y] == bitmap[y-1]:
                bits.extend((0, 0, 1))
            else:
                possible = []
                usefull = True
                for x in range(0, width, bytelength):
                    segment = bitmap[y][x:x+bytelength]
                    if y != 0 and segment == bitmap[y - 1][x:x+bytelength] and sum(int(x) for x in segment) != 0:
                        possible.extend((0, 0, 0))
                        usefull = False
                    else:
                        if sum(int(x) for x in segment) == 0:
                            possible.extend((1, 1))
                            usefull = False
                        else:
                            possible.extend((0, 1))
                            possible.extend(int(x) for x in segment)
                if usefull:
                    bits.extend((1, 0))
                    bits.extend(int(x) for x in bitmap[y])
                else:
                    bits.extend(possible)
    else:
        bits.extend((0, 0))
        for i in bitmap:
            bits.extend(i)

    while len(bits) % 8 != 0:
        bits.append(0)  # pad

    return [reduce(lambda x, y: (x << 1) | y, bits[v:v+8], 0) for v in range(0, len(bits), 8)]

# metrics about the bitmaps
metrics = {}
bitmaps = {}

# generate the data arrays
for i in range(256):
    if i in CHAR_NUMS:
        img = get_character_as_bool_array(chr(i))
        bitmaps[i] = img
        metrics[i] = len(img[0]), len(img), int(math.ceil(len(img[0]) / 8))

for i in range(256):
    if i not in metrics:
        continue
    j = list(metrics[i])
    j.extend(get_metrics(chr(i)))
    metrics[i] = j

# full table of kerning
table = []
if face.has_kerning:
    for i in sorted(CHAR_NUMS):
        table.extend(calc_kerning(chr(i)))

# convert all bitmaps
for i in CHAR_NUMS:
    if compressed:
        bitmaps[i], metrics[i][2], metrics[i][0] = convert_bitmap(bitmaps[i], True)
    else:
        bitmaps[i] = convert_bitmap(bitmaps[i], False)

# link all the data together

# start by creating the datablob
bitmap_ptrs = {} # offset from the dataptr
datablb = bytearray()
for i in CHAR_NUMS:
    bitmap_ptrs[i] = len(datablb)
    metric = metrics[i]
    datablb.extend(struct.pack("<BBBbbb", *metric))
    datablb.extend(bitmaps[i])

# finally, create the kerning blob
kernblb = bytearray()
for i in table:
    kernblb.extend(struct.pack("<BBb", *i))

payloadblb = bytearray() + kernblb  # create a copy
dataptr_base = len(payloadblb) + 0xC + 512 # length of dataptr table
payloadblb += datablb

# create entire file
payload = bytearray()

payload += "MFnt".encode("ascii")

flags = 0
if compressed:
    flags |= FLAG_COMPRESSED
if face.has_kerning:
    flags |= FLAG_KERNDAT

# todo italic

payload += struct.pack("<BxHHH", flags, 0xC, len(table), 0xC + 512)

# create ptrtable

dataptrtable = bytearray()
for i in range(256):
    dataptrtable.extend(struct.pack("<H", dataptr_base + bitmap_ptrs[i]) if i in bitmap_ptrs else (0, 0))

payload += dataptrtable
payload += payloadblb

with open(output_path, "wb") as f:
    f.write(payload)


from .db import db, environment, SCHEMA, add_prefix_for_prod
from .catalog import catalogs
from datetime import datetime

if environment == "production":
    catalogs.schema = SCHEMA
class Movie(db.Model):
    __tablename__ = 'movies'

    if environment == "production":
        __table_args__ = {'schema': SCHEMA}

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey(add_prefix_for_prod('users.id')), nullable=False)
    title = db.Column(db.String(100), nullable=False, unique=True)
    art = db.Column(db.String(255), nullable=False, unique=True)
    tagline = db.Column(db.String(150), nullable=False, unique=True)
    summary = db.Column(db.Text, nullable=False, unique=True)
    rating = db.Column(db.String(5), nullable=False)
    year = db.Column(db.Integer, nullable=False)
    genre = db.Column(db.String(20), nullable=False)
    director = db.Column(db.String(60), nullable=False)
    writer = db.Column(db.String(60), nullable=False)
    cast = db.Column(db.Text, nullable=False)
    trailer_url = db.Column(db.String(100))
    createdAt = db.Column(db.DateTime, nullable=False, default=datetime.now())
    updatedAt = db.Column(db.DateTime, nullable=False, default=datetime.now())

# EXAMPLE
    user = db.relationship('User', back_populates='movies')
    reviews = db.relationship('Review', back_populates='movie', cascade="all, delete")
    lists = db.relationship('List', secondary=catalogs, back_populates='movies')

    def to_dict(self):
        reviews = [review.to_dict() for review in self.reviews]
        num_likes = 0
        total_stars = 0
        for review in reviews:
            total_stars += review['stars']
            if review['like']:
                num_likes += 1

        return {
            'id': self.id,
            'title': self.title,
            'user_id': self.user_id,
            'art': self.art,
            'tagline': self.tagline,
            'summary': self.summary,
            'rating': self.rating,
            'year': self.year,
            'genre': self.genre,
            'director': self.director,
            'writer': self.writer,
            'cast': self.cast,
            'trailer_url': self.trailer_url,
            'createdAt': self.createdAt,
            'updatedAt': self.updatedAt,
            'num_lists': len(self.lists),
            'user': self.user.to_dict(),
            'reviews': reviews,
            'likes': num_likes,
            'star_rating': total_stars / len(reviews) if len(reviews) > 0 else 'New'
        }

    def to_dict_review(self):
        return {
            'id': self.id,
            'title': self.title,
            'user_id': self.user_id,
            'art': self.art,
            'year': self.year
        }