from tencentcloud.common.abstract_model import AbstractModel

class AbnormalEvent(AbstractModel):
    """造成异常体验可能的异常事件类型

    """

    def __init__(self):
        """
        :param AbnormalEventId: 异常事件ID，具体值查看附录：异常体验ID映射表：https://cloud.tencent.com/document/product/647/44916
        :type AbnormalEventId: int
        :param PeerId: 远端用户ID,""：表示异常事件不是由远端用户产生
注意：此字段可能返回 null，表示取不到有效值。
        :type PeerId: str
        """
        self.AbnormalEventId = None
        self.PeerId = None

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

class AbnormalExperience(AbstractModel):
    """用户的异常体验及可能的原因

    """

    def __init__(self):
        """
        :param UserId: 用户ID
        :type UserId: str
        :param ExperienceId: 异常体验ID
        :type ExperienceId: int
        :param RoomId: 字符串房间号
        :type RoomId: str
        :param AbnormalEventList: 异常事件数组
        :type AbnormalEventList: list of AbnormalEvent
        :param EventTime: 异常事件的上报时间
        :type EventTime: int
        """
        self.UserId = None
        self.ExperienceId = None
        self.RoomId = None
        self.AbnormalEventList = None
        self.EventTime = None

    def _deserialize(self, params):
        self.UserId = params.get("UserId")
        self.ExperienceId = params.get("ExperienceId")
        self.RoomId = params.get("RoomId")
        if params.get("AbnormalEventList") is not None:
            self.AbnormalEventList = []
            for item in params.get("AbnormalEventList"):
                obj = AbnormalEvent()
                obj._deserialize(item)
                self.AbnormalEventList.append(obj)
        self.EventTime = params.get("EventTime")

class CreateTroubleInfoRequest(AbstractModel):
    """CreateTroubleInfo请求参数结构体

    """

    def __init__(self):
        """
        :param SdkAppId: 应用的ID
        :type SdkAppId: str
        :param RoomId: 房间ID
        :type RoomId: str
        :param TeacherUserId: 老师用户ID
        :type TeacherUserId: str
        :param StudentUserId: 学生用户ID
        :type StudentUserId: str
        :param TroubleUserId: 体验异常端（老师或学生）的用户 ID。
        :type TroubleUserId: str
        :param TroubleType: 异常类型。
1. 仅视频异常
2. 仅声音异常
3. 音视频都异常
5. 进房异常
4. 切课
6. 求助
7. 问题反馈
8. 投诉
        :type TroubleType: int
        :param TroubleTime: 异常发生的UNIX 时间戳，单位为秒。
        :type TroubleTime: int
        :param TroubleMsg: 异常详情
        :type TroubleMsg: str
        """
        self.SdkAppId = None
        self.RoomId = None
        self.TeacherUserId = None
        self.StudentUserId = None
        self.TroubleUserId = None
        self.TroubleType = None
        self.TroubleTime = None
        self.TroubleMsg = None

    def _deserialize(self, params):
        self.SdkAppId = params.get("SdkAppId")
        self.RoomId = params.get("RoomId")
        self.TeacherUserId = params.get("TeacherUserId")
        self.StudentUserId = params.get("StudentUserId")
        self.TroubleUserId = params.get("TroubleUserId")
        self.TroubleType = params.get("TroubleType")
        self.TroubleTime = params.get("TroubleTime")
        self.TroubleMsg = params.get("TroubleMsg")

class CreateTroubleInfoResponse(AbstractModel):
    """CreateTroubleInfo返回参数结构体

    """

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

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

class DescribeAbnormalEventRequest(AbstractModel):
    """DescribeAbnormalEvent请求参数结构体

    """

    def __init__(self):
        """
        :param SdkAppId: 用户SDKAppID，查询SDKAppID下任意20条异常体验事件（可能不同房间）
        :type SdkAppId: str
        :param StartTime: 查询开始时间
        :type StartTime: int
        :param EndTime: 查询结束时间
        :type EndTime: int
        :param RoomId: 房间号，查询房间内任意20条以内异常体验事件
        :type RoomId: str
        """
        self.SdkAppId = None
        self.StartTime = None
        self.EndTime = None
        self.RoomId = None

    def _deserialize(self, params):
        self.SdkAppId = params.get("SdkAppId")
        self.StartTime = params.get("StartTime")
        self.EndTime = params.get("EndTime")
        self.RoomId = params.get("RoomId")

class DescribeAbnormalEventResponse(AbstractModel):
    """DescribeAbnormalEvent返回参数结构体

    """

    def __init__(self):
        """
        :param Total: 返回的数据总条数
        :type Total: int
        :param AbnormalExperienceList: 异常体验列表
        :type AbnormalExperienceList: list of AbnormalExperience
        :param RequestId: 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
        :type RequestId: str
        """
        self.Total = None
        self.AbnormalExperienceList = None
        self.RequestId = None

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

class DescribeCallDetailRequest(AbstractModel):
    """DescribeCallDetail请求参数结构体

    """

    def __init__(self):
        """
        :param CommId: 通话 ID（唯一标识一次通话）： sdkappid_roomgString（房间号_createTime（房间创建时间，unix时间戳，单位为s）例：1400353843_218695_1590065777。通过 DescribeRoomInformation（查询房间列表）接口获取（链接：https://cloud.tencent.com/document/product/647/44050）
        :type CommId: str
        :param StartTime: 查询开始时间，14天内。本地unix时间戳（1588031999s）
        :type StartTime: int
        :param EndTime: 查询结束时间，本地unix时间戳（1588031999s）
        :type EndTime: int
        :param SdkAppId: 用户SDKAppID（1400188366）
        :type SdkAppId: str
        :param UserIds: 需查询的用户数组，不填默认返回6个用户,最多可填6个用户
        :type UserIds: list of str
        :param DataType: 需查询的指标，不填则只返回用户列表，填all则返回所有指标。
appCpu：APP CPU使用率；
sysCpu：系统 CPU使用率；
aBit：上/下行音频码率；
aBlock：音频卡顿时长；
bigvBit：上/下行视频码率；
bigvCapFps：视频采集帧率；
bigvEncFps：视频发送帧率；
bigvDecFps：渲染帧率；
bigvBlock：视频卡顿时长；
aLoss：上/下行音频丢包；
bigvLoss：上/下行视频丢包；
bigvWidth：上/下行分辨率宽；
bigvHeight：上/下行分辨率高
        :type DataType: list of str
        :param PageNumber: 设置分页index，从0开始（PageNumber和PageSize 其中一个不填均默认返回6条数据）
        :type PageNumber: str
        :param PageSize: 设置分页大小（PageNumber和PageSize 其中一个不填均默认返回6条数据,DataType，UserIds不为null，PageSize最大不超过6，DataType，UserIds为null，PageSize最大不超过100）
        :type PageSize: str
        """
        self.CommId = None
        self.StartTime = None
        self.EndTime = None
        self.SdkAppId = None
        self.UserIds = None
        self.DataType = None
        self.PageNumber = None
        self.PageSize = None

    def _deserialize(self, params):
        self.CommId = params.get("CommId")
        self.StartTime = params.get("StartTime")
        self.EndTime = params.get("EndTime")
        self.SdkAppId = params.get("SdkAppId")
        self.UserIds = params.get("UserIds")
        self.DataType = params.get("DataType")
        self.PageNumber = params.get("PageNumber")
        self.PageSize = params.get("PageSize")

class DescribeCallDetailResponse(AbstractModel):
    """DescribeCallDetail返回参数结构体

    """

    def __init__(self):
        """
        :param Total: 返回的用户总条数
        :type Total: int
        :param UserList: 用户信息列表
注意：此字段可能返回 null，表示取不到有效值。
        :type UserList: list of UserInformation
        :param Data: 质量数据
注意：此字段可能返回 null，表示取不到有效值。
        :type Data: list of QualityData
        :param RequestId: 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
        :type RequestId: str
        """
        self.Total = None
        self.UserList = None
        self.Data = None
        self.RequestId = None

    def _deserialize(self, params):
        self.Total = params.get("Total")
        if params.get("UserList") is not None:
            self.UserList = []
            for item in params.get("UserList"):
                obj = UserInformation()
                obj._deserialize(item)
                self.UserList.append(obj)
        if params.get("Data") is not None:
            self.Data = []
            for item in params.get("Data"):
                obj = QualityData()
                obj._deserialize(item)
                self.Data.append(obj)
        self.RequestId = params.get("RequestId")

class DescribeDetailEventRequest(AbstractModel):
    """DescribeDetailEvent请求参数结构体

    """

    def __init__(self):
        """
        :param CommId: 通话 ID（唯一标识一次通话）： sdkappid_roomgString（房间号_createTime（房间创建时间，unix时间戳，单位s）。通过 DescribeRoomInformation（查询房间列表）接口获取。（链接：https://cloud.tencent.com/document/product/647/44050）
        :type CommId: str
        :param StartTime: 查询开始时间，14天内。本地unix时间戳（1588031999s）
        :type StartTime: int
        :param EndTime: 查询结束时间，本地unix时间戳（1588031999s）
        :type EndTime: int
        :param UserId: 用户id
        :type UserId: str
        :param RoomId: 房间号
        :type RoomId: str
        """
        self.CommId = None
        self.StartTime = None
        self.EndTime = None
        self.UserId = None
        self.RoomId = None

    def _deserialize(self, params):
        self.CommId = params.get("CommId")
        self.StartTime = params.get("StartTime")
        self.EndTime = params.get("EndTime")
        self.UserId = params.get("UserId")
        self.RoomId = params.get("RoomId")

class DescribeDetailEventResponse(AbstractModel):
    """DescribeDetailEvent返回参数结构体

    """

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

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

class DescribeHistoryScaleRequest(AbstractModel):
    """DescribeHistoryScale请求参数结构体

    """

    def __init__(self):
        """
        :param SdkAppId: 用户sdkappid
        :type SdkAppId: str
        :param StartTime: 查询开始时间，5天内。本地unix时间戳（1588031999s）
        :type StartTime: int
        :param EndTime: 查询结束时间，本地unix时间戳（1588031999s）
        :type EndTime: int
        """
        self.SdkAppId = None
        self.StartTime = None
        self.EndTime = None

    def _deserialize(self, params):
        self.SdkAppId = params.get("SdkAppId")
        self.StartTime = params.get("StartTime")
        self.EndTime = params.get("EndTime")

class DescribeHistoryScaleResponse(AbstractModel):
    """DescribeHistoryScale返回参数结构体

    """

    def __init__(self):
        """
        :param Total: 返回的数据条数
        :type Total: int
        :param ScaleList: 返回的数据
注意：此字段可能返回 null，表示取不到有效值。
        :type ScaleList: list of ScaleInfomation
        :param RequestId: 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
        :type RequestId: str
        """
        self.Total = None
        self.ScaleList = None
        self.RequestId = None

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

class DescribeRealtimeNetworkRequest(AbstractModel):
    """DescribeRealtimeNetwork请求参数结构体

    """

    def __init__(self):
        """
        :param StartTime: 查询开始时间，24小时内，本地unix时间戳（1588031999s）
        :type StartTime: int
        :param EndTime: 查询结束时间，本地unix时间戳（1588031999s）
        :type EndTime: int
        :param SdkAppId: 用户sdkappid
        :type SdkAppId: str
        :param DataType: 需查询的数据类型
sendLossRateRaw：上行丢包率
recvLossRateRaw：下行丢包率
        :type DataType: list of str
        """
        self.StartTime = None
        self.EndTime = None
        self.SdkAppId = None
        self.DataType = None

    def _deserialize(self, params):
        self.StartTime = params.get("StartTime")
        self.EndTime = params.get("EndTime")
        self.SdkAppId = params.get("SdkAppId")
        self.DataType = params.get("DataType")

class DescribeRealtimeNetworkResponse(AbstractModel):
    """DescribeRealtimeNetwork返回参数结构体

    """

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

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

class DescribeRealtimeQualityRequest(AbstractModel):
    """DescribeRealtimeQuality请求参数结构体

    """

    def __init__(self):
        """
        :param StartTime: 查询开始时间，24小时内。本地unix时间戳（1588031999s）
        :type StartTime: int
        :param EndTime: 查询结束时间，本地unix时间戳（1588031999s）
        :type EndTime: int
        :param SdkAppId: 用户sdkappid
        :type SdkAppId: str
        :param DataType: 查询的数据类型
enterTotalSuccPercent：进房成功率
fistFreamInSecRate：首帧秒开率
blockPercent：视频卡顿率
audioBlockPercent：音频卡顿率
        :type DataType: list of str
        """
        self.StartTime = None
        self.EndTime = None
        self.SdkAppId = None
        self.DataType = None

    def _deserialize(self, params):
        self.StartTime = params.get("StartTime")
        self.EndTime = params.get("EndTime")
        self.SdkAppId = params.get("SdkAppId")
        self.DataType = params.get("DataType")

class DescribeRealtimeQualityResponse(AbstractModel):
    """DescribeRealtimeQuality返回参数结构体

    """

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

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

class DescribeRealtimeScaleRequest(AbstractModel):
    """DescribeRealtimeScale请求参数结构体

    """

    def __init__(self):
        """
        :param StartTime: 查询开始时间，24小时内。本地unix时间戳（1588031999s）
        :type StartTime: int
        :param EndTime: 查询结束时间，本地unix时间戳（1588031999s）
        :type EndTime: int
        :param SdkAppId: 用户sdkappid
        :type SdkAppId: str
        :param DataType: 查询的数据类型
UserNum：通话人数；
RoomNum：房间数
        :type DataType: list of str
        """
        self.StartTime = None
        self.EndTime = None
        self.SdkAppId = None
        self.DataType = None

    def _deserialize(self, params):
        self.StartTime = params.get("StartTime")
        self.EndTime = params.get("EndTime")
        self.SdkAppId = params.get("SdkAppId")
        self.DataType = params.get("DataType")

class DescribeRealtimeScaleResponse(AbstractModel):
    """DescribeRealtimeScale返回参数结构体

    """

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

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

class DescribeRecordStatisticRequest(AbstractModel):
    """DescribeRecordStatistic请求参数结构体

    """

    def __init__(self):
        """
        :param StartTime: 查询开始日期。
        :type StartTime: str
        :param EndTime: 查询结束日期。
        :type EndTime: str
        :param SdkAppId: 应用ID，可不传。传应用ID时返回的是该应用的用量，不传时返回多个应用的合计值。
        :type SdkAppId: int
        """
        self.StartTime = None
        self.EndTime = None
        self.SdkAppId = None

    def _deserialize(self, params):
        self.StartTime = params.get("StartTime")
        self.EndTime = params.get("EndTime")
        self.SdkAppId = params.get("SdkAppId")

class DescribeRecordStatisticResponse(AbstractModel):
    """DescribeRecordStatistic返回参数结构体

    """

    def __init__(self):
        """
        :param SdkAppIdUsages: 应用的用量信息数组。
        :type SdkAppIdUsages: list of SdkAppIdRecordUsage
        :param RequestId: 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
        :type RequestId: str
        """
        self.SdkAppIdUsages = None
        self.RequestId = None

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

class DescribeRoomInformationRequest(AbstractModel):
    """DescribeRoomInformation请求参数结构体

    """

    def __init__(self):
        """
        :param SdkAppId: 用户sdkappid
        :type SdkAppId: str
        :param StartTime: 查询开始时间，14天内。本地unix时间戳（1588031999s）
        :type StartTime: int
        :param EndTime: 查询结束时间，本地unix时间戳（1588031999s）
        :type EndTime: int
        :param RoomId: 字符串房间号
        :type RoomId: str
        :param PageNumber: 分页index，从0开始（PageNumber和PageSize 其中一个不填均默认返回10条数据）
        :type PageNumber: str
        :param PageSize: 分页大小（PageNumber和PageSize 其中一个不填均默认返回10条数据,最大不超过100）
        :type PageSize: str
        """
        self.SdkAppId = None
        self.StartTime = None
        self.EndTime = None
        self.RoomId = None
        self.PageNumber = None
        self.PageSize = None

    def _deserialize(self, params):
        self.SdkAppId = params.get("SdkAppId")
        self.StartTime = params.get("StartTime")
        self.EndTime = params.get("EndTime")
        self.RoomId = params.get("RoomId")
        self.PageNumber = params.get("PageNumber")
        self.PageSize = params.get("PageSize")

class DescribeRoomInformationResponse(AbstractModel):
    """DescribeRoomInformation返回参数结构体

    """

    def __init__(self):
        """
        :param Total: 返回当页数据总数
        :type Total: int
        :param RoomList: 房间信息列表
        :type RoomList: list of RoomState
        :param RequestId: 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
        :type RequestId: str
        """
        self.Total = None
        self.RoomList = None
        self.RequestId = None

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

class DescribeTrtcInteractiveTimeRequest(AbstractModel):
    """DescribeTrtcInteractiveTime请求参数结构体

    """

    def __init__(self):
        """
        :param StartTime: 查询开始时间，格式为YYYY-MM-DD。
        :type StartTime: str
        :param EndTime: 查询结束时间，格式为YYYY-MM-DD。
单次查询统计区间最多不能超过31天。
        :type EndTime: str
        :param SdkAppId: 应用ID，可不传。传应用ID时返回的是该应用的用量，不传时返回所有应用的合计值。
        :type SdkAppId: int
        """
        self.StartTime = None
        self.EndTime = None
        self.SdkAppId = None

    def _deserialize(self, params):
        self.StartTime = params.get("StartTime")
        self.EndTime = params.get("EndTime")
        self.SdkAppId = params.get("SdkAppId")

class DescribeTrtcInteractiveTimeResponse(AbstractModel):
    """DescribeTrtcInteractiveTime返回参数结构体

    """

    def __init__(self):
        """
        :param Usages: 应用的用量信息数组。
        :type Usages: list of OneSdkAppIdUsagesInfo
        :param RequestId: 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
        :type RequestId: str
        """
        self.Usages = None
        self.RequestId = None

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

class DescribeTrtcMcuTranscodeTimeRequest(AbstractModel):
    """DescribeTrtcMcuTranscodeTime请求参数结构体

    """

    def __init__(self):
        """
        :param StartTime: 查询开始时间，格式为YYYY-MM-DD。
        :type StartTime: str
        :param EndTime: 查询结束时间，格式为YYYY-MM-DD。
单次查询统计区间最多不能超过31天。
        :type EndTime: str
        :param SdkAppId: 应用ID，可不传。传应用ID时返回的是该应用的用量，不传时返回多个应用的合计值。
        :type SdkAppId: int
        """
        self.StartTime = None
        self.EndTime = None
        self.SdkAppId = None

    def _deserialize(self, params):
        self.StartTime = params.get("StartTime")
        self.EndTime = params.get("EndTime")
        self.SdkAppId = params.get("SdkAppId")

class DescribeTrtcMcuTranscodeTimeResponse(AbstractModel):
    """DescribeTrtcMcuTranscodeTime返回参数结构体

    """

    def __init__(self):
        """
        :param Usages: 应用的用量信息数组。
        :type Usages: list of OneSdkAppIdTranscodeTimeUsagesInfo
        :param RequestId: 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
        :type RequestId: str
        """
        self.Usages = None
        self.RequestId = None

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

class DescribeUserInformationRequest(AbstractModel):
    """DescribeUserInformation请求参数结构体

    """

    def __init__(self):
        """
        :param CommId: 通话 ID（唯一标识一次通话）： sdkappid_roomgString（房间号_createTime（房间创建时间，unix时间戳，单位为s）例：1400353843_218695_1590065777。通过 DescribeRoomInformation（查询房间列表）接口获取（链接：https://cloud.tencent.com/document/product/647/44050）
        :type CommId: str
        :param StartTime: 查询开始时间，14天内。本地unix时间戳（1588031999s）
        :type StartTime: int
        :param EndTime: 查询结束时间，本地unix时间戳（1588031999s）
        :type EndTime: int
        :param SdkAppId: 用户SDKAppID（1400188366）
        :type SdkAppId: str
        :param UserIds: 需查询的用户数组，不填默认返回6个用户,最多可填6个用户
        :type UserIds: list of str
        :param PageNumber: 设置分页index，从0开始（PageNumber和PageSize 其中一个不填均默认返回6条数据）
        :type PageNumber: str
        :param PageSize: 设置分页大小（PageNumber和PageSize 其中一个不填均默认返回6条数据,PageSize最大不超过100）
        :type PageSize: str
        """
        self.CommId = None
        self.StartTime = None
        self.EndTime = None
        self.SdkAppId = None
        self.UserIds = None
        self.PageNumber = None
        self.PageSize = None

    def _deserialize(self, params):
        self.CommId = params.get("CommId")
        self.StartTime = params.get("StartTime")
        self.EndTime = params.get("EndTime")
        self.SdkAppId = params.get("SdkAppId")
        self.UserIds = params.get("UserIds")
        self.PageNumber = params.get("PageNumber")
        self.PageSize = params.get("PageSize")

class DescribeUserInformationResponse(AbstractModel):
    """DescribeUserInformation返回参数结构体

    """

    def __init__(self):
        """
        :param Total: 返回的用户总条数
        :type Total: int
        :param UserList: 用户信息列表
注意：此字段可能返回 null，表示取不到有效值。
        :type UserList: list of UserInformation
        :param RequestId: 唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
        :type RequestId: str
        """
        self.Total = None
        self.UserList = None
        self.RequestId = None

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

class DismissRoomByStrRoomIdRequest(AbstractModel):
    """DismissRoomByStrRoomId请求参数结构体

    """

    def __init__(self):
        """
        :param SdkAppId: TRTC的SDKAppId。
        :type SdkAppId: int
        :param RoomId: 房间号。
        :type RoomId: str
        """
        self.SdkAppId = None
        self.RoomId = None

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

class DismissRoomByStrRoomIdResponse(AbstractModel):
    """DismissRoomByStrRoomId返回参数结构体

    """

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

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

class DismissRoomRequest(AbstractModel):
    """DismissRoom请求参数结构体

    """

    def __init__(self):
        """
        :param SdkAppId: TRTC的SDKAppId。
        :type SdkAppId: int
        :param RoomId: 房间号。
        :type RoomId: int
        """
        self.SdkAppId = None
        self.RoomId = None

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

class DismissRoomResponse(AbstractModel):
    """DismissRoom返回参数结构体

    """

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

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

class EncodeParams(AbstractModel):
    """MCU混流输出流编码参数

    """

    def __init__(self):
        """
        :param AudioSampleRate: 混流-输出流音频采样率。取值为[48000, 44100, 32000,24000,, 16000, 12000, 8000]，单位是Hz。
        :type AudioSampleRate: int
        :param AudioBitrate: 混流-输出流音频码率。取值范围[8,500]，单位为Kbps。
        :type AudioBitrate: int
        :param AudioChannels: 混流-输出流音频声道数，取值范围[1,2]，1表示混流输出音频为单声道，2表示混流输出音频为双声道。
        :type AudioChannels: int
        :param VideoWidth: 混流-输出流宽，音视频输出时必填。取值范围[0,1920]，单位为像素值。
        :type VideoWidth: int
        :param VideoHeight: 混流-输出流高，音视频输出时必填。取值范围[0,1080]，单位为像素值。
        :type VideoHeight: int
        :param VideoBitrate: 混流-输出流码率，音视频输出时必填。取值范围[1,10000]，单位为Kbps。
        :type VideoBitrate: int
        :param VideoFramerate: 混流-输出流帧率，音视频输出时必填。取值范围[1,60]，表示混流的输出帧率可选范围为1到60fps。
        :type VideoFramerate: int
        :param VideoGop: 混流-输出流gop，音视频输出时必填。取值范围[1,5]，单位为秒。
        :type VideoGop: int
        :param BackgroundColor: 混流-输出流背景色。
        :type BackgroundColor: int
        :param BackgroundImageId: 混流-输出流背景图片，取值为实时音视频控制台上传的图片ID。
        :type BackgroundImageId: int
        """
        self.AudioSampleRate = None
        self.AudioBitrate = None
        self.AudioChannels = None
        self.VideoWidth = None
        self.VideoHeight = None
        self.VideoBitrate = None
        self.VideoFramerate = None
        self.VideoGop = None
        self.BackgroundColor = None
        self.BackgroundImageId = None

    def _deserialize(self, params):
        self.AudioSampleRate = params.get("AudioSampleRate")
        self.AudioBitrate = params.get("AudioBitrate")
        self.AudioChannels = params.get("AudioChannels")
        self.VideoWidth = params.get("VideoWidth")
        self.VideoHeight = params.get("VideoHeight")
        self.VideoBitrate = params.get("VideoBitrate")
        self.VideoFramerate = params.get("VideoFramerate")
        self.VideoGop = params.get("VideoGop")
        self.BackgroundColor = params.get("BackgroundColor")
        self.BackgroundImageId = params.get("BackgroundImageId")

class EventList(AbstractModel):
    """sdk或webrtc的事件列表。

    """

    def __init__(self):
        """
        :param Content: 数据内容
        :type Content: list of EventMessage
        :param PeerId: 发送端的userId
        :type PeerId: str
        """
        self.Content = None
        self.PeerId = None

    def _deserialize(self, params):
        if params.get("Content") is not None:
            self.Content = []
            for item in params.get("Content"):
                obj = EventMessage()
                obj._deserialize(item)
                self.Content.append(obj)
        self.PeerId = params.get("PeerId")

class EventMessage(AbstractModel):
    """事件信息，包括，事件时间戳，事件ID,

    """

    def __init__(self):
        """
        :param Type: 视频流类型：
0：与视频无关的事件；
2：视频为大画面；
3：视频为小画面；
7：视频为旁路画面；
        :type Type: int
        :param Time: 事件上报的时间戳，unix时间（1589891188801ms)
        :type Time: int
        :param EventId: 事件Id：分为sdk的事件和webrtc的事件，详情见：附录/事件 ID 映射表：https://cloud.tencent.com/document/product/647/44916
        :type EventId: int
        :param ParamOne: 事件的第一个参数，如视频分辨率宽
        :type ParamOne: int
        :param ParamTwo: 事件的第二个参数，如视频分辨率高
        :type ParamTwo: int
        """
        self.Type = None
        self.Time = None
        self.EventId = None
        self.ParamOne = None
        self.ParamTwo = None

    def _deserialize(self, params):
        self.Type = params.get("Type")
        self.Time = params.get("Time")
        self.EventId = params.get("EventId")
        self.ParamOne = params.get("ParamOne")
        self.ParamTwo = params.get("ParamTwo")

class LayoutParams(AbstractModel):
    """MCU混流布局参数

    """

    def __init__(self):
        """
        :param Template: 混流布局模板ID，0为悬浮模板(默认);1为九宫格模板;2为屏幕分享模板;3为画中画模板;4为自定义模板。
        :type Template: int
        :param MainVideoUserId: 屏幕分享模板、悬浮模板、画中画模板中有效，代表大画面对应的用户ID。
        :type MainVideoUserId: str
        :param MainVideoStreamType: 屏幕分享模板、悬浮模板、画中画模板中有效，代表大画面对应的流类型，0为摄像头，1为屏幕分享。左侧大画面为web用户时此值填0。
        :type MainVideoStreamType: int
        :param SmallVideoLayoutParams: 画中画模板中有效，代表小画面的布局参数。
        :type SmallVideoLayoutParams: :class:`tencentcloud.trtc.v20190722.models.SmallVideoLayoutParams`
        :param MainVideoRightAlign: 屏幕分享模板有效。设置为1时代表大画面居右，小画面居左布局。默认为0。
        :type MainVideoRightAlign: int
        :param MixVideoUids: 悬浮模板、九宫格、屏幕分享模板有效。设置此参数后，输出流混合此参数中包含用户的音视频，以及其他用户的纯音频。最多可设置16个用户。
        :type MixVideoUids: list of str
        :param PresetLayoutConfig: 自定义模板中有效，指定用户视频在混合画面中的位置。
        :type PresetLayoutConfig: list of PresetLayoutConfig
        """
        self.Template = None
        self.MainVideoUserId = None
        self.MainVideoStreamType = None
        self.SmallVideoLayoutParams = None
        self.MainVideoRightAlign = None
        self.MixVideoUids = None
        self.PresetLayoutConfig = None

    def _deserialize(self, params):
        self.Template = params.get("Template")
        self.MainVideoUserId = params.get("MainVideoUserId")
        self.MainVideoStreamType = params.get("MainVideoStreamType")
        if params.get("SmallVideoLayoutParams") is not None:
            self.SmallVideoLayoutParams = SmallVideoLayoutParams()
            self.SmallVideoLayoutParams._deserialize(params.get("SmallVideoLayoutParams"))
        self.MainVideoRightAlign = params.get("MainVideoRightAlign")
        self.MixVideoUids = params.get("MixVideoUids")
        if params.get("PresetLayoutConfig") is not None:
            self.PresetLayoutConfig = []
            for item in params.get("PresetLayoutConfig"):
                obj = PresetLayoutConfig()
                obj._deserialize(item)
                self.PresetLayoutConfig.append(obj)

class OneSdkAppIdTranscodeTimeUsagesInfo(AbstractModel):
    """旁路转码时长的查询结果

    """

    def __init__(self):
        """
        :param SdkAppIdTranscodeTimeUsages: 旁路转码时长查询结果数组
        :type SdkAppIdTranscodeTimeUsages: list of SdkAppIdTrtcMcuTranscodeTimeUsage
        :param TotalNum: 查询记录数量
        :type TotalNum: int
        :param SdkAppId: 所查询的应用ID，可能值为:1-应用的应用ID，2-total，显示为total则表示查询的是所有应用的用量合计值。
        :type SdkAppId: str
        """
        self.SdkAppIdTranscodeTimeUsages = None
        self.TotalNum = None
        self.SdkAppId = None

    def _deserialize(self, params):
        if params.get("SdkAppIdTranscodeTimeUsages") is not None:
            self.SdkAppIdTranscodeTimeUsages = []
            for item in params.get("SdkAppIdTranscodeTimeUsages"):
                obj = SdkAppIdTrtcMcuTranscodeTimeUsage()
                obj._deserialize(item)
                self.SdkAppIdTranscodeTimeUsages.append(obj)
        self.TotalNum = params.get("TotalNum")
        self.SdkAppId = params.get("SdkAppId")

class OneSdkAppIdUsagesInfo(AbstractModel):
    """单个SdkAppId的音视频互动计费时长用量数组和数组长度。

    """

    def __init__(self):
        """
        :param TotalNum: 该 SdkAppId 对应的用量记录数长度
        :type TotalNum: int
        :param SdkAppIdTrtcTimeUsages: 用量数组
        :type SdkAppIdTrtcTimeUsages: list of SdkAppIdTrtcUsage
        :param SdkAppId: 应用ID
        :type SdkAppId: str
        """
        self.TotalNum = None
        self.SdkAppIdTrtcTimeUsages = None
        self.SdkAppId = None

    def _deserialize(self, params):
        self.TotalNum = params.get("TotalNum")
        if params.get("SdkAppIdTrtcTimeUsages") is not None:
            self.SdkAppIdTrtcTimeUsages = []
            for item in params.get("SdkAppIdTrtcTimeUsages"):
                obj = SdkAppIdTrtcUsage()
                obj._deserialize(item)
                self.SdkAppIdTrtcTimeUsages.append(obj)
        self.SdkAppId = params.get("SdkAppId")

class OutputParams(AbstractModel):
    """MCU混流的输出参数

    """

    def __init__(self):
        """
        :param StreamId: 直播流 ID，由用户自定义设置，该流 ID 不能与用户旁路的流 ID 相同。
        :type StreamId: str
        :param PureAudioStream: 取值范围[0,1]， 填0：直播流为音视频(默认); 填1：直播流为纯音频
        :type PureAudioStream: int
        :param RecordId: 自定义录制文件名
        :type RecordId: str
        :param RecordAudioOnly: 取值范围[0,1]，填0无实际含义; 填1：指定录制文件格式为mp3
        :type RecordAudioOnly: int
        """
        self.StreamId = None
        self.PureAudioStream = None
        self.RecordId = None
        self.RecordAudioOnly = None

    def _deserialize(self, params):
        self.StreamId = params.get("StreamId")
        self.PureAudioStream = params.get("PureAudioStream")
        self.RecordId = params.get("RecordId")
        self.RecordAudioOnly = params.get("RecordAudioOnly")

class PresetLayoutConfig(AbstractModel):
    """自定义模板中有效，指定用户视频在混合画面中的位置。

    """

    def __init__(self):
        """
        :param UserId: 指定显示在该画面上的用户ID。如果不指定用户ID，会按照用户加入房间的顺序自动匹配PresetLayoutConfig中的画面设置。
        :type UserId: str
        :param StreamType: 当该画面指定用户时，代表用户的流类型。0为摄像头，1为屏幕分享。小画面为web用户时此值填0。
        :type StreamType: int
        :param ImageWidth: 该画面在输出时的宽度，单位为像素值，不填默认为0。
        :type ImageWidth: int
        :param ImageHeight: 该画面在输出时的高度，单位为像素值，不填默认为0。
        :type ImageHeight: int
        :param LocationX: 该画面在输出时的X偏移，单位为像素值，LocationX与ImageWidth之和不能超过混流输出的总宽度，不填默认为0。
        :type LocationX: int
        :param LocationY: 该画面在输出时的Y偏移，单位为像素值，LocationY与ImageHeight之和不能超过混流输出的总高度，不填默认为0。
        :type LocationY: int
        :param ZOrder: 该画面在输出时的层级，单位为像素值，不填默认为0。
        :type ZOrder: int
        :param RenderMode: 该画面在输出时的显示模式：0为裁剪，1为缩放，不填默认为0。
        :type RenderMode: int
        """
        self.UserId = None
        self.StreamType = None
        self.ImageWidth = None
        self.ImageHeight = None
        self.LocationX = None
        self.LocationY = None
        self.ZOrder = None
        self.RenderMode = None

    def _deserialize(self, params):
        self.UserId = params.get("UserId")
        self.StreamType = params.get("StreamType")
        self.ImageWidth = params.get("ImageWidth")
        self.ImageHeight = params.get("ImageHeight")
        self.LocationX = params.get("LocationX")
        self.LocationY = params.get("LocationY")
        self.ZOrder = params.get("ZOrder")
        self.RenderMode = params.get("RenderMode")

class QualityData(AbstractModel):
    """Es返回的质量数据

    """

    def __init__(self):
        """
        :param Content: 数据内容
        :type Content: list of TimeValue
        :param UserId: 用户ID
        :type UserId: str
        :param PeerId: 对端Id,为空时表示上行数据
注意：此字段可能返回 null，表示取不到有效值。
        :type PeerId: str
        :param DataType: 数据类型
        :type DataType: str
        """
        self.Content = None
        self.UserId = None
        self.PeerId = None
        self.DataType = None

    def _deserialize(self, params):
        if params.get("Content") is not None:
            self.Content = []
            for item in params.get("Content"):
                obj = TimeValue()
                obj._deserialize(item)
                self.Content.append(obj)
        self.UserId = params.get("UserId")
        self.PeerId = params.get("PeerId")
        self.DataType = params.get("DataType")

class RealtimeData(AbstractModel):
    """查询秒级监控返回的数据

    """

    def __init__(self):
        """
        :param Content: 返回的数据
注意：此字段可能返回 null，表示取不到有效值。
        :type Content: list of TimeValue
        :param DataType: 数据类型字段
        :type DataType: str
        """
        self.Content = None
        self.DataType = None

    def _deserialize(self, params):
        if params.get("Content") is not None:
            self.Content = []
            for item in params.get("Content"):
                obj = TimeValue()
                obj._deserialize(item)
                self.Content.append(obj)
        self.DataType = params.get("DataType")

class RecordUsage(AbstractModel):
    """录制的使用信息。

    """

    def __init__(self):
        """
        :param TimeKey: 本组数据对应的时间点，格式如:2020-09-07或2020-09-07 00:05:05。
        :type TimeKey: str
        :param Class1VideoTime: 视频时长-标清SD，单位：秒。
        :type Class1VideoTime: int
        :param Class2VideoTime: 视频时长-高清HD，单位：秒。
        :type Class2VideoTime: int
        :param Class3VideoTime: 视频时长-超清HD，单位：秒。
        :type Class3VideoTime: int
        :param AudioTime: 语音时长，单位：秒。
        :type AudioTime: int
        """
        self.TimeKey = None
        self.Class1VideoTime = None
        self.Class2VideoTime = None
        self.Class3VideoTime = None
        self.AudioTime = None

    def _deserialize(self, params):
        self.TimeKey = params.get("TimeKey")
        self.Class1VideoTime = params.get("Class1VideoTime")
        self.Class2VideoTime = params.get("Class2VideoTime")
        self.Class3VideoTime = params.get("Class3VideoTime")
        self.AudioTime = params.get("AudioTime")

class RemoveUserByStrRoomIdRequest(AbstractModel):
    """RemoveUserByStrRoomId请求参数结构体

    """

    def __init__(self):
        """
        :param SdkAppId: TRTC的SDKAppId。
        :type SdkAppId: int
        :param RoomId: 房间号。
        :type RoomId: str
        :param UserIds: 要移出的用户列表，最多10个。
        :type UserIds: list of str
        """
        self.SdkAppId = None
        self.RoomId = None
        self.UserIds = None

    def _deserialize(self, params):
        self.SdkAppId = params.get("SdkAppId")
        self.RoomId = params.get("RoomId")
        self.UserIds = params.get("UserIds")

class RemoveUserByStrRoomIdResponse(AbstractModel):
    """RemoveUserByStrRoomId返回参数结构体

    """

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

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

class RemoveUserRequest(AbstractModel):
    """RemoveUser请求参数结构体

    """

    def __init__(self):
        """
        :param SdkAppId: TRTC的SDKAppId。
        :type SdkAppId: int
        :param RoomId: 房间号。
        :type RoomId: int
        :param UserIds: 要移出的用户列表，最多10个。
        :type UserIds: list of str
        """
        self.SdkAppId = None
        self.RoomId = None
        self.UserIds = None

    def _deserialize(self, params):
        self.SdkAppId = params.get("SdkAppId")
        self.RoomId = params.get("RoomId")
        self.UserIds = params.get("UserIds")

class RemoveUserResponse(AbstractModel):
    """RemoveUser返回参数结构体

    """

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

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

class RoomState(AbstractModel):
    """房间信息列表

    """

    def __init__(self):
        """
        :param CommId: 通话ID（唯一标识一次通话）
        :type CommId: str
        :param RoomString: 房间号
        :type RoomString: str
        :param CreateTime: 房间创建时间
        :type CreateTime: int
        :param DestroyTime: 房间销毁时间
        :type DestroyTime: int
        :param IsFinished: 房间是否已经结束
        :type IsFinished: bool
        :param UserId: 房间创建者Id
        :type UserId: str
        """
        self.CommId = None
        self.RoomString = None
        self.CreateTime = None
        self.DestroyTime = None
        self.IsFinished = None
        self.UserId = None

    def _deserialize(self, params):
        self.CommId = params.get("CommId")
        self.RoomString = params.get("RoomString")
        self.CreateTime = params.get("CreateTime")
        self.DestroyTime = params.get("DestroyTime")
        self.IsFinished = params.get("IsFinished")
        self.UserId = params.get("UserId")

class ScaleInfomation(AbstractModel):
    """历史规模信息

    """

    def __init__(self):
        """
        :param Time: 每天开始的时间
        :type Time: int
        :param UserNumber: 房间人数，用户重复进入同一个房间为1次
注意：此字段可能返回 null，表示取不到有效值。
        :type UserNumber: int
        :param UserCount: 房间人次，用户每次进入房间为一次
注意：此字段可能返回 null，表示取不到有效值。
        :type UserCount: int
        :param RoomNumbers: sdkappid下一天内的房间数
注意：此字段可能返回 null，表示取不到有效值。
        :type RoomNumbers: int
        """
        self.Time = None
        self.UserNumber = None
        self.UserCount = None
        self.RoomNumbers = None

    def _deserialize(self, params):
        self.Time = params.get("Time")
        self.UserNumber = params.get("UserNumber")
        self.UserCount = params.get("UserCount")
        self.RoomNumbers = params.get("RoomNumbers")

class SdkAppIdRecordUsage(AbstractModel):
    """SdkAppId级别录制时长数据。

    """

    def __init__(self):
        """
        :param SdkAppId: SdkAppId的值。
        :type SdkAppId: str
        :param Usages: 统计的时间点数据。
        :type Usages: list of RecordUsage
        """
        self.SdkAppId = None
        self.Usages = None

    def _deserialize(self, params):
        self.SdkAppId = params.get("SdkAppId")
        if params.get("Usages") is not None:
            self.Usages = []
            for item in params.get("Usages"):
                obj = RecordUsage()
                obj._deserialize(item)
                self.Usages.append(obj)

class SdkAppIdTrtcMcuTranscodeTimeUsage(AbstractModel):
    """查询旁路转码计费时长。
    查询时间小于等于1天时，返回每5分钟粒度的数据；查询时间大于1天时，返回按天汇总的数据。

    """

    def __init__(self):
        """
        :param TimeKey: 本组数据对应的时间点，格式如：2020-09-07或2020-09-07 00:05:05。
        :type TimeKey: str
        :param AudioTime: 语音时长，单位：秒。
        :type AudioTime: int
        :param VideoTimeSd: 视频时长-标清SD，单位：秒。
        :type VideoTimeSd: int
        :param VideoTimeHd: 视频时长-高清HD，单位：秒。
        :type VideoTimeHd: int
        :param VideoTimeFhd: 视频时长-全高清FHD，单位：秒。
        :type VideoTimeFhd: int
        """
        self.TimeKey = None
        self.AudioTime = None
        self.VideoTimeSd = None
        self.VideoTimeHd = None
        self.VideoTimeFhd = None

    def _deserialize(self, params):
        self.TimeKey = params.get("TimeKey")
        self.AudioTime = params.get("AudioTime")
        self.VideoTimeSd = params.get("VideoTimeSd")
        self.VideoTimeHd = params.get("VideoTimeHd")
        self.VideoTimeFhd = params.get("VideoTimeFhd")

class SdkAppIdTrtcUsage(AbstractModel):
    """查询音视频互动时长的输出数据。
    查询时间小于等于1天时，返回每5分钟粒度的数据；查询时间大于1天时，返回按天汇总的数据。

    """

    def __init__(self):
        """
        :param TimeKey: 本组数据对应的时间点，格式如：2020-09-07或2020-09-07 00:05:05。
        :type TimeKey: str
        :param AudioTime: 语音时长，单位：秒。
        :type AudioTime: int
        :param AudioVideoTime: 音视频时长，单位：秒。
2019年10月11日前注册，没有变更为 [新计费模式](https://cloud.tencent.com/document/product/647/17157) 的用户才会返回此值。
        :type AudioVideoTime: int
        :param VideoTimeSd: 视频时长-标清SD，单位：秒。
        :type VideoTimeSd: int
        :param VideoTimeHd: 视频时长-高清HD，单位：秒。
        :type VideoTimeHd: int
        :param VideoTimeHdp: 视频时长-超清HD，单位：秒。
        :type VideoTimeHdp: int
        """
        self.TimeKey = None
        self.AudioTime = None
        self.AudioVideoTime = None
        self.VideoTimeSd = None
        self.VideoTimeHd = None
        self.VideoTimeHdp = None

    def _deserialize(self, params):
        self.TimeKey = params.get("TimeKey")
        self.AudioTime = params.get("AudioTime")
        self.AudioVideoTime = params.get("AudioVideoTime")
        self.VideoTimeSd = params.get("VideoTimeSd")
        self.VideoTimeHd = params.get("VideoTimeHd")
        self.VideoTimeHdp = params.get("VideoTimeHdp")

class SmallVideoLayoutParams(AbstractModel):
    """画中画模板中有效，代表小画面的布局参数

    """

    def __init__(self):
        """
        :param UserId: 代表小画面对应的用户ID。
        :type UserId: str
        :param StreamType: 代表小画面对应的流类型，0为摄像头，1为屏幕分享。小画面为web用户时此值填0。
        :type StreamType: int
        :param ImageWidth: 小画面在输出时的宽度，单位为像素值，不填默认为0。
        :type ImageWidth: int
        :param ImageHeight: 小画面在输出时的高度，单位为像素值，不填默认为0。
        :type ImageHeight: int
        :param LocationX: 小画面在输出时的X偏移，单位为像素值，LocationX与ImageWidth之和不能超过混流输出的总宽度，不填默认为0。
        :type LocationX: int
        :param LocationY: 小画面在输出时的Y偏移，单位为像素值，LocationY与ImageHeight之和不能超过混流输出的总高度，不填默认为0。
        :type LocationY: int
        """
        self.UserId = None
        self.StreamType = None
        self.ImageWidth = None
        self.ImageHeight = None
        self.LocationX = None
        self.LocationY = None

    def _deserialize(self, params):
        self.UserId = params.get("UserId")
        self.StreamType = params.get("StreamType")
        self.ImageWidth = params.get("ImageWidth")
        self.ImageHeight = params.get("ImageHeight")
        self.LocationX = params.get("LocationX")
        self.LocationY = params.get("LocationY")

class StartMCUMixTranscodeByStrRoomIdRequest(AbstractModel):
    """StartMCUMixTranscodeByStrRoomId请求参数结构体

    """

    def __init__(self):
        """
        :param SdkAppId: TRTC的SDKAppId。
        :type SdkAppId: int
        :param StrRoomId: 字符串房间号。
        :type StrRoomId: str
        :param OutputParams: 混流输出控制参数。
        :type OutputParams: :class:`tencentcloud.trtc.v20190722.models.OutputParams`
        :param EncodeParams: 混流输出编码参数。
        :type EncodeParams: :class:`tencentcloud.trtc.v20190722.models.EncodeParams`
        :param LayoutParams: 混流输出布局参数。
        :type LayoutParams: :class:`tencentcloud.trtc.v20190722.models.LayoutParams`
        """
        self.SdkAppId = None
        self.StrRoomId = None
        self.OutputParams = None
        self.EncodeParams = None
        self.LayoutParams = None

    def _deserialize(self, params):
        self.SdkAppId = params.get("SdkAppId")
        self.StrRoomId = params.get("StrRoomId")
        if params.get("OutputParams") is not None:
            self.OutputParams = OutputParams()
            self.OutputParams._deserialize(params.get("OutputParams"))
        if params.get("EncodeParams") is not None:
            self.EncodeParams = EncodeParams()
            self.EncodeParams._deserialize(params.get("EncodeParams"))
        if params.get("LayoutParams") is not None:
            self.LayoutParams = LayoutParams()
            self.LayoutParams._deserialize(params.get("LayoutParams"))

class StartMCUMixTranscodeByStrRoomIdResponse(AbstractModel):
    """StartMCUMixTranscodeByStrRoomId返回参数结构体

    """

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

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

class StartMCUMixTranscodeRequest(AbstractModel):
    """StartMCUMixTranscode请求参数结构体

    """

    def __init__(self):
        """
        :param SdkAppId: TRTC的SDKAppId。
        :type SdkAppId: int
        :param RoomId: 房间号。
        :type RoomId: int
        :param OutputParams: 混流输出控制参数。
        :type OutputParams: :class:`tencentcloud.trtc.v20190722.models.OutputParams`
        :param EncodeParams: 混流输出编码参数。
        :type EncodeParams: :class:`tencentcloud.trtc.v20190722.models.EncodeParams`
        :param LayoutParams: 混流输出布局参数。
        :type LayoutParams: :class:`tencentcloud.trtc.v20190722.models.LayoutParams`
        """
        self.SdkAppId = None
        self.RoomId = None
        self.OutputParams = None
        self.EncodeParams = None
        self.LayoutParams = None

    def _deserialize(self, params):
        self.SdkAppId = params.get("SdkAppId")
        self.RoomId = params.get("RoomId")
        if params.get("OutputParams") is not None:
            self.OutputParams = OutputParams()
            self.OutputParams._deserialize(params.get("OutputParams"))
        if params.get("EncodeParams") is not None:
            self.EncodeParams = EncodeParams()
            self.EncodeParams._deserialize(params.get("EncodeParams"))
        if params.get("LayoutParams") is not None:
            self.LayoutParams = LayoutParams()
            self.LayoutParams._deserialize(params.get("LayoutParams"))

class StartMCUMixTranscodeResponse(AbstractModel):
    """StartMCUMixTranscode返回参数结构体

    """

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

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

class StopMCUMixTranscodeByStrRoomIdRequest(AbstractModel):
    """StopMCUMixTranscodeByStrRoomId请求参数结构体

    """

    def __init__(self):
        """
        :param SdkAppId: TRTC的SDKAppId。
        :type SdkAppId: int
        :param StrRoomId: 字符串房间号。
        :type StrRoomId: str
        """
        self.SdkAppId = None
        self.StrRoomId = None

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

class StopMCUMixTranscodeByStrRoomIdResponse(AbstractModel):
    """StopMCUMixTranscodeByStrRoomId返回参数结构体

    """

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

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

class StopMCUMixTranscodeRequest(AbstractModel):
    """StopMCUMixTranscode请求参数结构体

    """

    def __init__(self):
        """
        :param SdkAppId: TRTC的SDKAppId。
        :type SdkAppId: int
        :param RoomId: 房间号。
        :type RoomId: int
        """
        self.SdkAppId = None
        self.RoomId = None

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

class StopMCUMixTranscodeResponse(AbstractModel):
    """StopMCUMixTranscode返回参数结构体

    """

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

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

class TimeValue(AbstractModel):
    """返回的质量数据，时间:值

    """

    def __init__(self):
        """
        :param Time: 时间，unix时间戳（1590065877s)
        :type Time: int
        :param Value: 当前时间返回参数取值，如（bigvCapFps在1590065877取值为0，则Value：0 ）
        :type Value: float
        """
        self.Time = None
        self.Value = None

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

class UserInformation(AbstractModel):
    """用户信息，包括用户进房时间，退房时间等

    """

    def __init__(self):
        """
        :param RoomStr: 房间号
        :type RoomStr: str
        :param UserId: 用户Id
        :type UserId: str
        :param JoinTs: 用户进房时间
        :type JoinTs: int
        :param LeaveTs: 用户退房时间，用户没有退房则返回当前时间
        :type LeaveTs: int
        :param DeviceType: 终端类型
        :type DeviceType: str
        :param SdkVersion: Sdk版本号
        :type SdkVersion: str
        :param ClientIp: 客户端IP地址
        :type ClientIp: str
        :param Finished: 判断用户是否已经离开房间
        :type Finished: bool
        """
        self.RoomStr = None
        self.UserId = None
        self.JoinTs = None
        self.LeaveTs = None
        self.DeviceType = None
        self.SdkVersion = None
        self.ClientIp = None
        self.Finished = None

    def _deserialize(self, params):
        self.RoomStr = params.get("RoomStr")
        self.UserId = params.get("UserId")
        self.JoinTs = params.get("JoinTs")
        self.LeaveTs = params.get("LeaveTs")
        self.DeviceType = params.get("DeviceType")
        self.SdkVersion = params.get("SdkVersion")
        self.ClientIp = params.get("ClientIp")
        self.Finished = params.get("Finished")


import dask
import dask.dataframe as dd
import pandas as pd
import s3fs
import json
import dask.bag as db
import ast
import logging
import os
import datetime

import logging_utils as logUtils

def get_current_datetime():
    return str(datetime.datetime.now().strftime("%Y%m%d_%H%M%S"))

def read_csv_from_url(data_url, data_file_cols=None):
    rating_movie_tv = dd.read_csv(data_url)
    rating_movie_tv.columns = data_file_cols
    return rating_movie_tv

def read_json_from_url(meta_url):
    meta_movie_tv = db.read_text(meta_url).map(ast.literal_eval)
    return meta_movie_tv

def write_datafile_to_S3(ddf, path, st_opt):
    ddf.to_csv(path, storage_options=st_opt)

def write_metadatafile_to_S3(dbag, path, st_opt):
    dbag.map(json.dumps).to_textfiles(path, storage_options=st_opt)

if __name__ == "__main__":
    logger = logging.getLogger("ingestion")
    err_code = 0
    app_name = "Data_Loading_toS3"

    code_home = os.getcwd()
    log_home = os.path.join(code_home, "log")

    if not os.path.exists(log_home):
        os.mkdir(log_home)

    log_name = "{0}_{1}.log".format(get_current_datetime(), app_name)

    log_path = os.path.join(log_home, log_name)
    logUtils.init_log(log_path)

    try:
        logger.info("-----------------------------------Script Commencement------------------------------------------")
        logger.info("Arguements Passed : {0}".format(args))

        config_file_path = os.path.join(code_home, "config.json")
        f = open(config_file_path)
        config = json.load(f)

        logger.info("Reading Data file from URL")
        rating_mv_tv_data = read_csv_from_url(config["DataFileUrl"], config["DataFileColumns"])

        logger.info("Writing Data file to S3")
        str_options = {"anon" : False, "key" : config["S3AccessKey"], "secret" : config["S3SecretKey"]}
        s3_file_path = "/".join["s3:/", config["S3BucketName"], config["S3DataFileName"]]
        logger.info("s3_file_path : ", s3_file_path)
        write_datafile_to_S3(rating_mv_tv_data, s3_file_path, str_options)

        logger.info("Reading MetaData file from URL")
        rating_mv_tv_meta = read_json_from_url(config["MetadataFileUrl"])

        logger.info("Writing MetaData file to S3")
        s3_meta_file_path = "/".join["s3:/", config["S3BucketName"], config["S3MetadataFileName"]]
        logger.info("s3_meta_file_path : ", s3_meta_file_path)
        write_metadatafile_to_S3(rating_mv_tv_meta, s3_meta_file_path, str_options)

    except Exception as e:
        logger.error(e)
        err_code = 1

    finally:
        logger.info("Progress exit with error code : {0}".format(err_code))
        exit(err_code)


import sys
import random
import numpy as np
import pickle
from collections import Counter
ordered = np.load(sys.argv[2])

def read_images(a):
    images = []
    for line in a:
        images.append(line.strip()[1:-2])
    return images

a = open(sys.argv[1],'r')
b = open(sys.argv[3],'r')
images = read_images(a) #c.strip() for c in a.readlines()] #read_images(a)
boundaries = read_images(b)

print("legnth of images:", len(images))
sets = dict()
counter = 0

sets[counter] = []
images_num = dict()
for idx, image in enumerate(images):
    images_num[image] = idx
    if image not in boundaries:
       sets[counter].append(image)
    else:
       counter =  counter +1
       sets[counter] = []
       sets[counter].append(image)

pickle.dump(sets, open('sets.pkl','wb'))

for cnt in sets:
    print(cnt, len(sets[cnt]))

pairs = []
pairs_nums = []
for j in range(0, ordered.shape[0]):
   a = ordered[j]
   pos = np.where(a>0)[0]
   neg = np.where(a<0)[0]
   if len(pos) > 0 and len(neg) > 0:
      if images[pos[0]] in sets[0] or images[pos[0]] in sets[1]:
         continue
      if images[neg[0]] in sets[0] or images[neg[0]] in sets[1]:
         continue

      pos_image = images[pos[0]]
      neg_image = images[neg[0]]
      pairs_nums.append((pos[0], neg[0]))
      pairs.append((pos_image, neg_image))

#np.save('pairs_nums.npy', pairs_nums)

features = np.load('features_rank.npy')
weight = np.load('weight_rank_1.npy')
#scores_load = pickle.load(open('scores.pkl','rb'))
#print(scores_load.keys())
scores = {}
for idx, key in enumerate(images):
    scores[key] = np.dot(features[idx], weight)
count  = 0
correct = 0
for pair in pairs:
    if pair[0] in scores and pair[1] in scores:
       count = count +1
       if scores[pair[0]] > scores[pair[1]] :
          correct = correct + 1

print(correct, count)
#np.save('pairs_names.npy',pairs)


def nwd(a, b):
    while b:
        a, b = b, a % b
    return a

number_of_cases = input()
for x in range(int(number_of_cases)):
    line = input()
    numbers = list(line.split(" "))
    num1 = int(numbers[0])
    num2 = int(numbers[1])
    print(int((num1 * num2) / nwd(num1, num2)))


stacks = [ "VQWMBNZC", "BCWRZH", "JRQF", "TMNFHWSZ", "PQNLWFG", "WPL", "JQCGRDBV", "WBNQZ", "JTGCFLH"]

stacks = [list(s) for s in stacks]
[s.reverse() for s in stacks]

with open("input5.txt") as f:
    lines = f.read().splitlines();

import re

def move(string):
    n, f, t = re.findall(r'\d+', string)
    n = int(n)
    f = int(f)
    t = int(t)

    print([len(s) for s in stacks], string)
    stacks[t-1].extend(stacks[f-1][-n:])
    [stacks[f-1].pop() for n in range(n)]

    #[stacks[t-1].append(stacks[f-1].pop()) for i in range(n)]

[move(l) for l in lines]

print(stacks)
print("".join([s[-1] for s in stacks]))


# USAGE
# python barcode_scanner.py
# python barcode_scanner.py -o results.csv -v "path to a video file"
# python barcode_scanner.py -o results.csv -v videos/coupon.mov

# Importing relevant libraries
from imutils.video import VideoStream
from pyzbar import pyzbar
import argparse
import datetime
from datetime import datetime
import imutils
import time
import cv2
import winsound
frequency = 2500  # Set Frequency To 2500 Hertz
duration = 800  # Set Duration To 1000 ms == 1 second

# Parsing Arguments
ap = argparse.ArgumentParser()
ap.add_argument("-o", "--output", type=str, default="barcodesData.csv",
	help="path to output CSV file ")
ap.add_argument("-v", "--video",
	help="path to the (optional) video file")
ap.add_argument("-i", "--image",
	help="path to the (optional) image file")
args = vars(ap.parse_args())

# Taking care of the output header
import csv
csvWrite = open(args["output"], "a")
# checking if the file already exists and getting the number of records
csvfile = open(args["output"], "r")
csv_dict = [row for row in csv.DictReader(csvfile)]
if len(csv_dict) == 0:
	count=0
	# Checking if the header already exists
	f = open(args["output"])
	line = f.readline()
	f.close()
	if len(line) == 0:
		csvWrite.write("{},{},{}\n".format("TIMESTAMP (YYYY-MM-DD)","DATA","TYPE"))
else:
    count=len(csv_dict)
csvfile.close()

def write_records(bar_codes):
    records_written=len(bar_codes)
    if records_written == 0:
        print( "\n No Barcodes found in the Video.")
    else:
        print( "\n {} new Records written to the Database".format(records_written))
    print("\n Total number of records in {}   :   {}".format(args["output"],count+records_written))

# if the video path was not supplied, grab the reference to the
# camera
if not args.get("video", False):
	vs = VideoStream(src=0).start()
	time.sleep(2.0)
	print("Starting Webcam !!!")

#otherwise load the video
else:
    print("Loading Video !!!")
    vs = cv2.VideoCapture(args["video"])

found = set()
while True:
	frameData = vs.read()
	frameData = frameData[1] if args.get("video", False) else imutils.resize(frameData, width=600)
	# If the video is over
	if frameData is None:
    		break
	# Getting the barcodes from the frame
	barcodes = pyzbar.decode(frameData)

	# Looping through each barcode and extracting info
	for barcode in barcodes:
		(x, y, width, height) = barcode.rect
		cv2.rectangle(frameData, (x, y), (x + width, y + height), (0, 0, 255), 2)
		barcodeData = barcode.data.decode("utf-8")
		barcodeType = barcode.type
		textData = "{} ({})".format(barcodeData, barcodeType)
		cv2.putText(frameData, textData, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)

		# Checking for duplicate barcodes and writing info in the csv file
		if barcodeData not in found:
			csvWrite.write("{},{},{}\n".format(datetime.today().strftime('%Y-%m-%d'),barcodeData,barcodeType))
			csvWrite.flush()
			found.add(barcodeData)

			# Producing sound on identification of a barcode
			winsound.Beep(frequency, duration)

	# Displaying info inside the video
	cv2.imshow("Barcode Scanner", frameData)
	key = cv2.waitKey(1) & 0xFF

	# press e to terminate the camera
	if key == ord("e"):
		break

# close the output CSV file do a bit of cleanup
write_records(found)

csvWrite.close()
cv2.destroyAllWindows()

# if we are not using a video file, stop the video file stream
if not args.get("video", False):
	vs.stop()

# otherwise, release the camera pointer
else:
	vs.release()


import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
from tkinter import simpledialog
import sys

class TextEditorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("PANNO!")
        self.text = tk.Text(root)
        self.text.pack(fill=tk.BOTH, expand=True)
        self.undo_stack = []
        self.redo_stack = []
        self.bind_keyboard_shortcuts()
        self.current_file = None  # Variable to store the current file name
        self.file_dialog_open = False  # Flag to track if file dialog is open

        # Create the menu bar
        menu_bar = tk.Menu(root)
        file_menu = tk.Menu(menu_bar, tearoff=0)
        file_menu.add_command(label="Open", command=self.load_file)
        file_menu.add_command(label="Save", command=self.save_file)
        menu_bar.add_cascade(label="File", menu=file_menu)
        root.config(menu=menu_bar)

        # Create the toolbar
        toolbar = tk.Frame(root)
        toolbar.pack(side=tk.TOP, fill=tk.X)

        load_button = tk.Button(toolbar, text="Load", command=self.load_file)
        load_button.pack(side=tk.LEFT)

        save_button = tk.Button(toolbar, text="Save", command=self.save_file)
        save_button.pack(side=tk.LEFT)

        redo_button = tk.Button(toolbar, text="Redo", command=self.redo)
        redo_button.pack(side=tk.LEFT)

        # Bind the right-click event for the text widget
        self.text.bind("<Button-3>", self.show_text_context_menu)

        # Check if file path is passed as an argument
        if len(sys.argv) > 1:
            file_path = sys.argv[1]
            self.load_file(file_path)

    def bind_keyboard_shortcuts(self):
        self.root.bind("<Control-s>", self.save_file)
        self.root.bind("<Control-z>", self.undo)
        self.root.bind("<Control-y>", self.redo)

    def load_file(self, file_path=None):
        if not file_path:
            file_path = filedialog.askopenfilename()

        if file_path:
            try:
                with open(file_path, "r") as file:
                    self.text.delete("1.0", tk.END)
                    self.text.insert(tk.END, file.read())
                    self.current_file = file_path  # Update the current file name
                    self.update_title()  # Update the title
            except FileNotFoundError:
                messagebox.showerror("Error", "File not found.")
            except Exception as e:
                messagebox.showerror("Error", f"An error occurred: {str(e)}")

    def save_file(self, event=None):
        if self.current_file:
            try:
                with open(self.current_file, "w") as file:
                    file.write(self.text.get("1.0", tk.END))
                    messagebox.showinfo("Save", "File saved successfully.")
            except Exception as e:
                messagebox.showerror("Error", f"An error occurred: {str(e)}")
        else:
            file_path = filedialog.asksaveasfilename(defaultextension=".txt")
            if file_path:
                try:
                    with open(file_path, "w") as file:
                        file.write(self.text.get("1.0", tk.END))
                        self.current_file = file_path  # Update the current file name
                        self.update_title()  # Update the title
                        messagebox.showinfo("Save", "File saved successfully.")
                except Exception as e:
                    messagebox.showerror("Error", f"An error occurred: {str(e)}")

    def undo(self, event=None):
        if self.undo_stack:
            text = self.undo_stack.pop()
            self.redo_stack.append(self.text.get("1.0", tk.END))
            self.text.delete("1.0", tk.END)
            self.text.insert(tk.END, text)

    def redo(self, event=None):
        if self.redo_stack:
            text = self.redo_stack.pop()
            self.undo_stack.append(self.text.get("1.0", tk.END))
            self.text.delete("1.0", tk.END)
            self.text.insert(tk.END, text)

    def update_title(self):
        if self.current_file:
            self.root.title(f"Text Editor - {self.current_file}")
        else:
            self.root.title("Text Editor")

    def show_text_context_menu(self, event):
        text_context_menu = tk.Menu(self.root, tearoff=0)
        text_context_menu.add_command(label="Cut", command=lambda: self.text.event_generate("<<Cut>>"))
        text_context_menu.add_command(label="Copy", command=lambda: self.text.event_generate("<<Copy>>"))
        text_context_menu.add_command(label="Paste", command=lambda: self.text.event_generate("<<Paste>>"))
        text_context_menu.add_separator()
        text_context_menu.add_command(label="Select All", command=lambda: self.text.tag_add("sel", "1.0", tk.END))
        text_context_menu.post(event.x_root, event.y_root)

if __name__ == "__main__":
    root = tk.Tk()
    app = TextEditorApp(root)
    root.mainloop()


import os

from pydantic import BaseSettings

class Settings(BaseSettings):
    FASTAPI_APP_ALLOW_ORIGINS: str
    REDIS_HOST: str
    REDIS_PORT: int

    class Config:
        env_file = os.getenv('ENV_FILE')

settings = Settings()


import numpy as np
from scipy import stats
import pandas as pd
import matplotlib.pyplot as plt

import statsmodels.api as sm

from statsmodels.graphics.api import qqplot

# Sunspots Dataset Metadata
print(sm.datasets.sunspots.NOTE)
# Load Data
dta = sm.datasets.sunspots.load_pandas().data
# Plotting Sun Activity
dta.index = pd.Index(pd.date_range("1700", end="2009", freq="A-DEC"))
del dta["YEAR"]
dta.plot(figsize=(12,4));

# Plotting Autocorrelation and Partial Correlation
fig = plt.figure(figsize=(12,8))
ax1 = fig.add_subplot(211)
fig = sm.graphics.tsa.plot_acf(dta.values.squeeze(), lags=40, ax=ax1)
ax2 = fig.add_subplot(212)
fig = sm.graphics.tsa.plot_pacf(dta, lags=40, ax=ax2)

# Print Model Parameters
arma_mod20 = sm.tsa.statespace.SARIMAX(dta, order=(2,0,0), trend='c').fit(disp=False)
print(arma_mod20.aic, arma_mod20.bic, arma_mod20.hqic)
print(arma_mod20.params)

# Print Model Parameters
arma_mod30 = sm.tsa.statespace.SARIMAX(dta, order=(3,0,0), trend='c').fit(disp=False)
print(arma_mod30.aic, arma_mod30.bic, arma_mod30.hqic)
print(arma_mod30.params)

# Does our Model Obey the Theory?
## Calculate and Plot the Residuals
print(sm.stats.durbin_watson(arma_mod30.resid))

fig = plt.figure(figsize=(12,4))
ax = fig.add_subplot(111)
ax = plt.plot(arma_mod30.resid)

resid = arma_mod30.resid
print(stats.normaltest(resid))

fig = plt.figure(figsize=(12,4))
ax = fig.add_subplot(111)
fig = qqplot(resid, line='q', ax=ax, fit=True)

# Show Plots
plt.show()

Article08 - 5 Python's Time Series Analysis Libraries/demo02_statsmodel.py


import torch
import torch.nn as nn
import pandas as pd
import numpy as np
from collections import Iterable
from splitbaseline import SplitBaselineConfig,SplitBaseline

class MergeSplitBaselineConfig:
    def __init__(self,
            atlas_roi_path="atlas_roi.csv",
            atlas=["Hammers"],
            ctype="all",
            out_dim = 3,
            dropout = 0.6,
            folds = 10
        ):
        self.atlas_roi_path=atlas_roi_path
        self.atlas=atlas
        self.ctype=ctype
        self.out_dim = out_dim
        self.dropout = dropout
    def initialize(self):
        self.splitbaselineconfig = SplitBaselineConfig(
            atlas_roi_path=self.atlas_roi_path,
            atlas=self.atlas,
            ctype=self.ctype,
            out_dim = self.out_dim,
            dropout = self.dropout
        )
        self.splitbaselineconfig.initialize()

class MergeSplitBaseline(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.config = config
        self.net_fold1 = SplitBaseline(self.config.splitbaselineconfig)
        self.net_fold2 = SplitBaseline(self.config.splitbaselineconfig)
        self.net_fold3 = SplitBaseline(self.config.splitbaselineconfig)
        self.net_fold4 = SplitBaseline(self.config.splitbaselineconfig)
        self.net_fold5 = SplitBaseline(self.config.splitbaselineconfig)
        self.net_fold6 = SplitBaseline(self.config.splitbaselineconfig)
        self.net_fold7 = SplitBaseline(self.config.splitbaselineconfig)
        self.net_fold8 = SplitBaseline(self.config.splitbaselineconfig)
        self.net_fold9 = SplitBaseline(self.config.splitbaselineconfig)
        self.net_fold10 = SplitBaseline(self.config.splitbaselineconfig)

    def load_models(self,paths):
        self.net_fold1.load_state_dict(torch.load(paths[0], map_location='cpu'))
        self.net_fold2.load_state_dict(torch.load(paths[1], map_location='cpu'))
        self.net_fold3.load_state_dict(torch.load(paths[2], map_location='cpu'))
        self.net_fold4.load_state_dict(torch.load(paths[3], map_location='cpu'))
        self.net_fold5.load_state_dict(torch.load(paths[4], map_location='cpu'))
        self.net_fold6.load_state_dict(torch.load(paths[5], map_location='cpu'))
        self.net_fold7.load_state_dict(torch.load(paths[6], map_location='cpu'))
        self.net_fold8.load_state_dict(torch.load(paths[7], map_location='cpu'))
        self.net_fold9.load_state_dict(torch.load(paths[8], map_location='cpu'))
        self.net_fold10.load_state_dict(torch.load(paths[9], map_location='cpu'))

    def judge_class(self,res):
        max_v = torch.max(res)
        res = res > max_v*0.999999
        print(res)
        for i in range(3):
            if res[i]:
                return i

    def forward(self,x):
        # x : [batchsize,feature_len]
        xs = []
        xs.append(self.net_fold1(x).squeeze())
        xs.append(self.net_fold2(x).squeeze())
        xs.append(self.net_fold3(x).squeeze())
        xs.append(self.net_fold4(x).squeeze())
        xs.append(self.net_fold5(x).squeeze())
        xs.append(self.net_fold6(x).squeeze())
        xs.append(self.net_fold7(x).squeeze())
        xs.append(self.net_fold8(x).squeeze())
        xs.append(self.net_fold9(x).squeeze())
        xs.append(self.net_fold10(x).squeeze())
        x = torch.stack(xs)
        ids = range(1,10)
        x = x[ids,:]
        print(x)
        x = torch.mean(x,dim=0)
        return x

def merge_models():
    # best_epoches = [261,417,457,449,496,468,309,285,370,490]
    # best_epoches = [266,127,481,468,215,401,489,441,325,439]      # with label smooth
    best_epoches = [900,797,921,914,780,811,796,781,546,922]      # Hammers Best
    #best_epoches = [923,825,921,892,990,811,796,786,547,829]      # Hammers
    #best_epoches = [479 for i in range(10)]
    paths = [
        "../model/Hammers/baseline_Hammers_lr1.e-3_dp0.6_fold%d_epoch%d.pth"%(x,y) for x,y in zip(range(1,11),best_epoches)
    ]
    print(paths)
    config = MergeSplitBaselineConfig()
    config.initialize()
    model = MergeSplitBaseline(config)
    model.load_models(paths)
    torch.save(model.state_dict(), "model.pth")
    # do a simple test here

def test():
    config = MergeSplitBaselineConfig()
    config.initialize()
    print(config.__dict__)
    model = MergeSplitBaseline(config)
    model.load_state_dict(torch.load("model.pth", map_location ='cpu'))
    model.eval()
    x = np.load("../data/train/Subject_0002.npy")
    x = np.nan_to_num(x,  nan=1.e-10, posinf=1.e-10, neginf=1.e-10)
    mean = np.load("mean.npy")
    std = np.load("std.npy")
    x = (x - mean)/std
    x = np.nan_to_num(x,  nan=1.e-10, posinf=1.e-10, neginf=1.e-10)
    x = torch.tensor(x).unsqueeze(0).float()
    print(x.shape)
    y = model(x)
    print(y)

if __name__ == "__main__":
    merge_models()
    test()


import json
import os
import time
start = time.time()

def get_input(fname):
    fo = open(r".\count\\" + fname.split("\\")[-1], "w", encoding="UTF-8")
    with open(fname, "r", encoding="utf-8-SIG") as load_f:
        load_dict = json.load(load_f)
        for i in load_dict:
            if "NotSupported" in i and "dotnet" in i["NotSupported"]:
                fo.write(i["Input"]+"\n")
    fo.close

def get_all_dir(path):
    filess = os.listdir(path)
    print(filess)
    for files in filess:
        if files != "README.md":
            if os.path.isdir(path+files):
                print("dir:"+files)
                get_all_dir(path+files+'\\')
            else:
                get_input(path+"\\"+files)

path = r".\Specs\DateTime\Spanish\\"
getAllDir(path)
end = time.time()
print(end-start)


# -*- coding: utf-8 -*-
"""
Created on Mon May 13 10:42:54 2019

@author: Administrator
"""

import requests

api_key = "_your_api_key_"

url = "https://goo.gl/maps/QGs5TLGaAjdaG6oN8"

center = "Dehradun"
zoom = 10

r = requests.get(url + "center =" + center + "&zoom =" +
                   str(zoom) + "&size = 400x400&key =" +
                             api_key + "sensor = false")

f = open('address of the file location ', 'wb')
f.write(r.content)
f.close()


import asyncio
from typing import AsyncGenerator, Tuple

from pydantic import BaseModel

from simple_aiokafka import (
    ConsumerRecord,
    kafka_consumer,
    kafka_processor,
    kafka_producer,
)

class Document(BaseModel):
    text: str
    id: int
    note: str = None

def document_serializer(document: Document):
    return document.json().encode()

@kafka_producer(value_serializer=document_serializer)
async def produce() -> AsyncGenerator[Tuple[str, Document], None]:
    for i in range(100):
        yield str(i), Document(text="Hello Kafka", id=i)
        await asyncio.sleep(1)

@kafka_consumer("aiokafka.result", value_deserializer=Document.parse_raw)
async def consume(msg: ConsumerRecord = None) -> None:
    print("Consume Message:", msg)

@kafka_processor(
    input_topic="aiokafka.output",
    output_topic="aiokafka.result",
    consumer_args={"value_deserializer": Document.parse_raw},
    producer_args={"value_serializer": document_serializer},
)
async def process(msg: ConsumerRecord = None) -> Tuple[str, str]:
    document = msg.value
    document.note = "Hello Kafka :)"
    return msg.key, document

async def main():
    asyncio.create_task(produce())
    asyncio.create_task(process())
    await consume()

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())


#本文件用于各种指标的对比与图形绘制

import os
import pandas as pd
import time
import numpy as np
import scipy.io as io
import re
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
sns.set(style='whitegrid')
matplotlib.rcParams['font.sans-serif']=['KaiTi'] #显示中文标签

filename_workday='dd_03.csv'
filename_weekend='dd_04.csv'
kmeansfile_workday='k_means_dd_03.csv'
kmeansfile_weekend='k_means_dd_04.csv'
df_data1=pd.read_csv('.\\4 after_clussify\\'+filename_workday)
df_data2=pd.read_csv('.\\4 after_clussify\\'+filename_weekend)
#df_kind=pd.read_csv('.\\7 AnotherData\\kmeansKind\\'+kmeansfile_workday)
#工作日与周末各时段平均出行量分布对比
def lineplot(sORe):
    time_order1=dict()
    for i in df_data1.index:
        time=df_data1[sORe][i].split(' ')[1].split(':')[0]
        if int(time) not in time_order1:
            time_order1[int(time)] = 1
        else:
            time_order1[int(time)] += 1
    for i in range(24):
        if i not in time_order1:
            time_order1[i]=0
    order1=[time_order1[i] for i in range(24)]
    time_order2=dict()
    for i in df_data2.index:
        time=df_data2[sORe][i].split(' ')[1].split(':')[0]
        if int(time) not in time_order2:
            time_order2[int(time)] = 1
        else:
            time_order2[int(time)] += 1
    for i in range(24):
        if i not in time_order2:
            time_order2[i]=0
    order2=[time_order2[i] for i in range(24)]
    df_time_order=pd.DataFrame([[order1[i],order2[i]] for i in range(24)],index=range(24),columns=['工作日','周  末'])
    sns.lineplot(data=df_time_order)
    plt.xlabel('时间(时)')
    plt.ylabel('订单次数(次)')
    print(sORe)
    if sORe=='起点时间':
        print(1)
        plt.savefig('.\\6 DataAna\\order_time_workday&weekend(start)')
    if sORe=='终点时间':
        print(2)
        plt.savefig('.\\6 DataAna\\order_time_workday&weekend(end)')
    plt.show()

lineplot('起点时间')
lineplot('终点时间')


"""
Using the Python language, have the function FirstReverse(str) take the
 str parameter being passed and return the string in reversed order.
 For example: if the input string is "Hello World and Coders" then your program
 should return the string sredoC dna dlroW olleH.
 """

def first_reverse(sen):
    reverse_string = ""
    for i in reversed(sen):
        reverse_string += i
    return reverse_string

print(first_reverse("this is a test"))


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf

from layer import *
from model_tuple import Model
from consts import *

def create_generator(generator_inputs, generator_outputs_channels, style_id, embedding_scope, a,
                     style_id2=None, weight=None, external_emb=None):
    layers = []

    # encoder_1: [batch, 256, 256, in_channels] => [batch, 128, 128, ngf]
    with tf.variable_scope("encoder_1"):
        output = gen_conv(generator_inputs, a.ngf, a.separable_conv)
        layers.append(output)

    layer_specs = [
        a.ngf * 2,  # encoder_2: [batch, 128, 128, ngf] => [batch, 64, 64, ngf * 2]
        a.ngf * 4,  # encoder_3: [batch, 64, 64, ngf * 2] => [batch, 32, 32, ngf * 4]
        a.ngf * 8,  # encoder_4: [batch, 32, 32, ngf * 4] => [batch, 16, 16, ngf * 8]
        a.ngf * 8,  # encoder_5: [batch, 16, 16, ngf * 8] => [batch, 8, 8, ngf * 8]
        a.ngf * 8,  # encoder_6: [batch, 8, 8, ngf * 8] => [batch, 4, 4, ngf * 8]
        a.ngf * 8,  # encoder_7: [batch, 4, 4, ngf * 8] => [batch, 2, 2, ngf * 8]
        a.ngf * 8,  # encoder_8: [batch, 2, 2, ngf * 8] => [batch, 1, 1, ngf * 8]
    ]

    for out_channels in layer_specs:
        with tf.variable_scope("encoder_%d" % (len(layers) + 1)):
            rectified = lrelu(layers[-1], 0.2)
            # [batch, in_height, in_width, in_channels] => [batch, in_height/2, in_width/2, out_channels]
            convolved = gen_conv_sn(rectified, out_channels, a.separable_conv)
            output = batchnorm(convolved)
            layers.append(output)

    with tf.variable_scope(embedding_scope, reuse=True):
        style_embedding_table = tf.get_variable('style_embedding')

    if external_emb is None:
        style_embedded = tf.nn.embedding_lookup(style_embedding_table, style_id)
    else:
        style_embedded = external_emb
    style_embedded = tf.reshape(style_embedded, [-1, 1, 1, a.emb_dim])

    if not style_id2 is None:
        style_embedded_2 = tf.nn.embedding_lookup(style_embedding_table, style_id2)
        style_embedded_2 = tf.reshape(style_embedded_2, [-1, 1, 1, a.emb_dim])

        style_embedded = weight * style_embedded + (1 - weight) * style_embedded_2

    layer_specs = [
        (a.ngf * 8 * 2, 0.5),  # decoder_8: [batch, 1, 1, ngf * 8] => [batch, 2, 2, ngf * 8 * 2]
        (a.ngf * 8 * 2, 0.5),  # decoder_7: [batch, 2, 2, ngf * 8 * 2] => [batch, 4, 4, ngf * 8 * 2]
        (a.ngf * 8 * 2, 0.5),  # decoder_6: [batch, 4, 4, ngf * 8 * 2] => [batch, 8, 8, ngf * 8 * 2]
        (a.ngf * 8, 0.0),  # decoder_5: [batch, 8, 8, ngf * 8 * 2] => [batch, 16, 16, ngf * 8 * 2]
        (a.ngf * 4, 0.0),  # decoder_4: [batch, 16, 16, ngf * 8 * 2] => [batch, 32, 32, ngf * 4 * 2]
        (a.ngf * 2, 0.0),  # decoder_3: [batch, 32, 32, ngf * 4 * 2] => [batch, 64, 64, ngf * 2 * 2]
        (a.ngf, 0.0),  # decoder_2: [batch, 64, 64, ngf * 2 * 2] => [batch, 128, 128, ngf * 2]
    ]

    num_encoder_layers = len(layers)
    for decoder_layer, (out_channels, dropout) in enumerate(layer_specs):
        skip_layer = num_encoder_layers - decoder_layer - 1
        with tf.variable_scope("decoder_%d" % (skip_layer + 1)):
            if decoder_layer == 0:
                # first decoder layer doesn't have skip connections
                # since it is directly connected to the skip_layer
                input = layers[-1]
                rectified = tf.nn.relu(input)
                rectified = tf.concat([rectified, style_embedded], axis=3)

            else:
                input = tf.concat([layers[-1], layers[skip_layer]], axis=3)
                rectified = tf.nn.relu(input)

            # [batch, in_height, in_width, in_channels] => [batch, in_height*2, in_width*2, out_channels]
            output = gen_deconv_sn(rectified, out_channels, a.separable_conv)
            output = batchnorm(output)

            if dropout > 0.0:
                output = tf.nn.dropout(output, keep_prob=1 - dropout)

            layers.append(output)

    # decoder_1: [batch, 128, 128, ngf * 2] => [batch, 256, 256, generator_outputs_channels]
    with tf.variable_scope("decoder_1"):
        input = tf.concat([layers[-1], layers[0]], axis=3)
        rectified = tf.nn.relu(input)
        output = gen_deconv_sn(rectified, generator_outputs_channels, a.separable_conv)
        output = tf.tanh(output)
        layers.append(output)

    return layers[-1], style_embedded

def create_encoder(generator_inputs, discrim_targets, a):
    n_layers = 3
    layers = []

    # 2x [batch, height, width, in_channels] => [batch, height, width, in_channels * 2]
    input = tf.concat([generator_inputs, discrim_targets], axis=3)

    # layer_1: [batch, 256, 256, in_channels * 2] => [batch, 128, 128, ndf]
    with tf.variable_scope("layer_1"):
        convolved = discrim_conv_sn(input, a.ndf, stride=2)
        rectified = lrelu(convolved, 0.2)
        layers.append(rectified)

    # layer_2: [batch, 128, 128, ndf] => [batch, 64, 64, ndf * 2]
    # layer_3: [batch, 64, 64, ndf * 2] => [batch, 32, 32, ndf * 4]
    # layer_4: [batch, 32, 32, ndf * 4] => [batch, 31, 31, ndf * 8]
    for i in range(n_layers):
        with tf.variable_scope("layer_%d" % (len(layers) + 1)):
            out_channels = a.ndf * min(2 ** (i + 1), 8)
            stride = 1 if i == n_layers - 1 else 2  # last layer here has stride 1
            convolved = discrim_conv_sn(layers[-1], out_channels, stride=stride)
            normalized = batchnorm(convolved)
            rectified = lrelu(normalized, 0.2)
            layers.append(rectified)

    # layer_5: [batch, 31, 31, ndf * 8] => [batch, 30, 30, 1]
    with tf.variable_scope("layer_%d" % (len(layers) + 1)):
        convolved = discrim_conv_sn(rectified, out_channels=1, stride=1)
        normalized = batchnorm(convolved)
        output = lrelu(normalized, 0.2)
        layers.append(output)

    image_compressed = tf.reshape(layers[-1], [-1, 900])

    layer_specs = [
        a.ngf * 16,
        a.ngf * 16,
        a.ngf * 16,
    ]

    layers.append(image_compressed)

    for dense_layer, out_chal in enumerate(layer_specs):
        output = tf.layers.dense(inputs=layers[-1], units=out_chal, activation=None)
        output = lrelu(output, 0.2)
        layers.append(output)

    output = tf.layers.dense(inputs=layers[-1], units=a.emb_dim, activation=None)

    with tf.variable_scope("emb_result"):
        inf_emb = tf.reshape(output, [-1, a.emb_dim])

    return inf_emb

def create_model(inputs, targets, test_inputs, test_targets, labels, test_labels, a,
                 labels2=None, weight=None, external_emb=False):
    def create_discriminator(discrim_inputs, discrim_targets, style_id, embedding_scope, a):

        with tf.variable_scope(embedding_scope, reuse=True):
            style_embedding_table = tf.get_variable('style_embedding')

        style_embedded = tf.nn.embedding_lookup(style_embedding_table, style_id)
        style_embedded = tf.reshape(style_embedded, [-1, a.emb_dim])

        n_layers = 3
        layers = []
        activation = []

        # 2x [batch, height, width, in_channels] => [batch, height, width, in_channels * 2]
        input = tf.concat([discrim_inputs, discrim_targets], axis=3)

        # layer_1: [batch, 256, 256, in_channels * 2] => [batch, 128, 128, ndf]
        with tf.variable_scope("layer_1"):
            convolved = discrim_conv_sn(input, a.ndf, stride=2)
            rectified = lrelu(convolved, 0.2)
            layers.append(rectified)
            activation.append(rectified)

        # layer_2: [batch, 128, 128, ndf] => [batch, 64, 64, ndf * 2]
        # layer_3: [batch, 64, 64, ndf * 2] => [batch, 32, 32, ndf * 4]
        # layer_4: [batch, 32, 32, ndf * 4] => [batch, 31, 31, ndf * 8]
        for i in range(n_layers):
            with tf.variable_scope("layer_%d" % (len(layers) + 1)):
                out_channels = a.ndf * min(2 ** (i + 1), 8)
                stride = 1 if i == n_layers - 1 else 2  # last layer here has stride 1
                convolved = discrim_conv_sn(layers[-1], out_channels, stride=stride)
                normalized = batchnorm(convolved)
                rectified = lrelu(normalized, 0.2)
                layers.append(rectified)
                activation.append(rectified)

        # layer_5: [batch, 31, 31, ndf * 8] => [batch, 30, 30, 1]
        with tf.variable_scope("layer_%d" % (len(layers) + 1)):
            convolved = discrim_conv_sn(rectified, out_channels=1, stride=1)
            normalized = batchnorm(convolved)
            output = lrelu(normalized, 0.2)
            layers.append(output)
            activation.append(output)

        image_compressed = tf.reshape(layers[-1], [-1, 900])

        with tf.variable_scope("layer_%d" % (len(layers) + 1)):
            output = tf.layers.dense(inputs=image_compressed, units=a.emb_dim, activation=None)
            output = lrelu(output, 0.2)
            layers.append(output)
            activation.append(output)

        with tf.variable_scope("dot_prod"):
            score = tf.reduce_sum(tf.multiply(output, style_embedded), 1, keep_dims=True)

        layer_specs = [
            a.ngf * 8,
            a.ngf * 4,
            a.ngf * 2,
        ]

        for dense_layer, out_chal in enumerate(layer_specs):
            with tf.variable_scope("layer_%d" % (len(layers) + 1)):
                output = tf.layers.dense(inputs=output, units=out_chal, activation=None)
                output = lrelu(output, 0.2)
                layers.append(output)
                activation.append(output)

        with tf.variable_scope("layer_%d" % (len(layers) + 1)):
            output = tf.layers.dense(inputs=layers[-1], units=1, activation=None)
            layers.append(output)

        with tf.variable_scope("combine"):
            combine = score + output
            output = tf.sigmoid(combine)

        layers.append(tf.reshape(output, [-1, 1, 1, 1]))
        return layers[-1], activation

    with tf.variable_scope("embedding") as embedding_scope:
        style_emb_max = 786
        style_embedding_dim = a.emb_dim
        embeding_table = tf.get_variable(
            'style_embedding', [style_emb_max, style_embedding_dim], dtype=tf.float32, trainable=True)

    with tf.variable_scope("embedding_lables"):
        style_embed_labels = tf.stop_gradient(tf.nn.embedding_lookup(embeding_table, labels))
        overall_l2_norm = tf.stop_gradient(tf.reduce_mean(tf.norm(embeding_table, axis=1, ord=2)))

    if external_emb:
        external_emb = tf.placeholder(tf.float32, shape=(1, 1024), name='external_emb')
    else:
        external_emb = None

    with tf.variable_scope("generator"):
        out_channels = int(targets.get_shape()[-1])
        outputs, embed = create_generator(inputs, out_channels, labels, embedding_scope, a, labels2, weight, external_emb)

    with tf.variable_scope("generator", reuse=True):
        test_out_channels = int(test_targets.get_shape()[-1])
        test_outputs, test_embed = create_generator(test_inputs, test_out_channels, test_labels, embedding_scope, a, labels2, weight, external_emb)

    # create two copies of discriminator, one for real pairs and one for fake pairs
    # they share the same underlying variables
    with tf.name_scope("real_discriminator"):
        with tf.variable_scope("discriminator"):
            # 2x [batch, height, width, channels] => [batch, 30, 30, 1]
            predict_real, activation_real = create_discriminator(inputs, targets, labels, embedding_scope, a)

    with tf.name_scope("fake_discriminator"):
        with tf.variable_scope("discriminator", reuse=True):
            # 2x [batch, height, width, channels] => [batch, 30, 30, 1]
            predict_fake, activation_fake = create_discriminator(inputs, outputs, labels, embedding_scope, a)

    with tf.name_scope("real_encoder"):
        with tf.variable_scope("encoder_emb"):
            inf_embed_real = create_encoder(inputs, targets, a)

    with tf.name_scope("fake_encoder"):
        with tf.variable_scope("encoder_emb", reuse=True):
            inf_embed_fake = create_encoder(inputs, outputs, a)

    with tf.name_scope("discriminator_loss"):
        # minimizing -tf.log will try to get inputs to 1
        # predict_real => 1
        # predict_fake => 0
        discrim_loss = tf.reduce_mean(-(tf.log(predict_real + EPS) + tf.log(1 - predict_fake + EPS)))

    with tf.name_scope("feature_matching_loss"):
        loss_fm = tf.reduce_mean(tf.abs(activation_real[0] - activation_fake[0])) + \
                  tf.reduce_mean(tf.abs(activation_real[1] - activation_fake[1])) + \
                  tf.reduce_mean(tf.abs(activation_real[2] - activation_fake[2])) + \
                  tf.reduce_mean(tf.abs(activation_real[3] - activation_fake[3])) + \
                  tf.reduce_mean(tf.abs(activation_real[4] - activation_fake[4])) + \
                  tf.reduce_mean(tf.abs(activation_real[5] - activation_fake[5])) + \
                  tf.reduce_mean(tf.abs(activation_real[6] - activation_fake[6])) + \
                  tf.reduce_mean(tf.abs(activation_real[7] - activation_fake[7])) + \
                  tf.reduce_mean(tf.abs(activation_real[8] - activation_fake[8]))

    activation_num = 0.0
    for style_id in range(5):
        style_b, style_w, style_h, style_c = activation_real[style_id].shape
        activation_num += style_w * style_h * style_c
    with tf.name_scope("style_loss"):
        loss_style = 0.0  # No style loss in training.

    with tf.name_scope("generator_loss"):
        # predict_fake => 1
        # abs(targets - outputs) => 0
        gen_loss_GAN = tf.reduce_mean(-tf.log(predict_fake + EPS))
        gen_loss_L1 = tf.reduce_mean(tf.abs(targets - outputs))
        gen_loss_EMB = a.emb_weight * 0.5 * (tf.norm(inf_embed_real - style_embed_labels) + tf.norm(
            inf_embed_fake - style_embed_labels)) / overall_l2_norm
        gen_loss = gen_loss_GAN * a.gan_weight + gen_loss_L1 * a.l1_weight + gen_loss_EMB + a.fm_weight * loss_fm + a.style_weight * loss_style

    with tf.name_scope("discriminator_train"):
        discrim_tvars = [var for var in tf.trainable_variables() if var.name.startswith("discriminator")]
        discrim_tvars += [var for var in tf.trainable_variables() if var.name.startswith("embedding")]
        discrim_optim = tf.train.AdamOptimizer(a.lr, a.beta1)
        discrim_grads_and_vars = discrim_optim.compute_gradients(discrim_loss, var_list=discrim_tvars)
        discrim_train = discrim_optim.apply_gradients(discrim_grads_and_vars)

    with tf.name_scope("encoder_train"):
        encoder_tvars = [var for var in tf.trainable_variables() if var.name.startswith("encoder_emb")]
        encoder_optim = tf.train.AdamOptimizer(a.lr, a.beta1)
        encoder_grads_and_vars = encoder_optim.compute_gradients(gen_loss_EMB, var_list=encoder_tvars)
        encoder_train = encoder_optim.apply_gradients(encoder_grads_and_vars)

    with tf.name_scope("generator_train"):
        with tf.control_dependencies([discrim_train]):
            with tf.control_dependencies([encoder_train]):
                gen_tvars = [var for var in tf.trainable_variables() if var.name.startswith("generator")]
                gen_tvars += [var for var in tf.trainable_variables() if var.name.startswith("embedding")]
                gen_optim = tf.train.AdamOptimizer(a.lr, a.beta1)
                gen_grads_and_vars = gen_optim.compute_gradients(gen_loss, var_list=gen_tvars)
                gen_train = gen_optim.apply_gradients(gen_grads_and_vars)

    ema = tf.train.ExponentialMovingAverage(decay=0.99)
    update_losses = ema.apply([discrim_loss, gen_loss_GAN, gen_loss_L1, gen_loss_EMB, loss_fm, loss_style])

    global_step = tf.train.get_or_create_global_step()
    incr_global_step = tf.assign(global_step, global_step + 1)

    return Model(
        predict_real=predict_real,
        predict_fake=predict_fake,
        discrim_loss=ema.average(discrim_loss),
        discrim_grads_and_vars=discrim_grads_and_vars,
        gen_loss_GAN=ema.average(gen_loss_GAN),
        gen_loss_L1=ema.average(gen_loss_L1),
        gen_loss_EMB=ema.average(gen_loss_EMB),
        loss_fm=ema.average(loss_fm),
        loss_style=ema.average(loss_style),
        gen_grads_and_vars=gen_grads_and_vars,
        encoder_grads_and_vars=encoder_grads_and_vars,
        outputs=outputs,
        test_outputs=test_outputs,
        train=tf.group(update_losses, incr_global_step, gen_train),
        labels=labels,
        embedding=embed,
        external_emb=external_emb
    )


class Player():
    def __init__(self, first_name, last_name, height_cm, weight_kg):
        self.first_name = first_name
        self.last_name = last_name
        self.height_cm = height_cm
        self.weight_kg = weight_kg

    def weight_to_lbs(self):
        pounds = self.weight_kg * 2.2
        return pounds

    def weight_to_inch(self):
        pounds = self.height_cm / 2.54
        return inches

class FootballPlayer(Player):
    def __init__(self, first_name, last_name, height_cm, weight_kg, goals, yellow_cards, red_cards):
        super().__init__(first_name,last_name,height_cm,weight_kg)
        self.goals = goals
        self.yellow_cards = yellow_cards
        self.red_cards = red_cards

class BasketballPlayer(Player):
    def __init__(self, first_name, last_name, height_cm, weight_kg, points, rebounds, assists):
        super().__init__(first_name,last_name,height_cm,weight_kg)
        self.point = points
        self.rebounds = rebounds
        self.assists = assists

ronaldo = FootballPlayer(first_name="Cristiano", last_name="Ronaldo", height_cm=184, weight_kg=79, goals=678,
                         yellow_cards=95, red_cards=11)
kev_dur = BasketballPlayer(first_name="Kevin", last_name="Durant", height_cm=204, weight_kg=95, points=104,
                         rebounds=152, assists=36)

print(ronaldo.first_name)
print(ronaldo.last_name)
print(ronaldo.goals)
print(ronaldo.weight_kg)
print(ronaldo.weight_to_lbs())
print(ronaldo.first_name + ", " + ronaldo.last_name)
print(ronaldo.first_name + "\n" + ronaldo.last_name)

print(kev_dur.first_name)
print(kev_dur.last_name)
print(kev_dur.weight_kg)