from sklearn import datasets
from sklearn.neural_network import MLPClassifier
import traceback
from submissions.Ban import county_demographics

class DataFrame:
    data = []
    feature_names = []
    target = []
    target_names = []

alumni = DataFrame()
alumni.target = []
alumni.data = []
'''
Extract data from the CORGIS elections, and merge it with the
CORGIS demographics.  Both data sets are organized by county and state.
'''

def alumniTarget(string):
    if (student['Education']["Bachelor's Degree or Higher"] > 50):
        return 1
    return 0

demographics = county_demographics.get_all_counties()
for student in demographics:
    try:
        alumni.target.append(alumniTarget(student['Education']["High School or Higher"]))

        college = float(student['Education']["High School or Higher"])
        poverty = float(student['Income']["Persons Below Poverty Level"])
        ethnicity = float(student['Ethnicities']["White Alone"])

        alumni.data.append([college, poverty, ethnicity])
    except:
        traceback.print_exc()

alumni.feature_names = [
    "High School or Higher",
    "Persons Below Poverty Level",
    "White Alone",
]

alumni.target_names = [
    'Most did not graduate college',
    'Most did graduate college',
    'Ethnicity',
]

'''
Make a customn classifier,
'''
mlpc = MLPClassifier(
    # hidden_layer_sizes = (100,),
    # activation = 'relu',
    solver='sgd', # 'adam',
    # alpha = 0.0001,
    # batch_size='auto',
    learning_rate = 'adaptive', # 'constant',
    # power_t = 0.5,
    max_iter = 1000, # 200,
    # shuffle = True,
    # random_state = None,
    # tol = 1e-4,
    # verbose = False,
    # warm_start = False,
    # momentum = 0.9,
    # nesterovs_momentum = True,
    # early_stopping = False,
    # validation_fraction = 0.1,
    # beta_1 = 0.9,
    # beta_2 = 0.999,
    # epsilon = 1e-8,
)

'''
Try scaling the data.
'''
alumniScaled = DataFrame()

def setupScales(grid):
    global min, max
    min = list(grid[0])
    max = list(grid[0])
    for row in range(1, len(grid)):
        for col in range(len(grid[row])):
            cell = grid[row][col]
            if cell < min[col]:
                min[col] = cell
            if cell > max[col]:
                max[col] = cell

def scaleGrid(grid):
    newGrid = []
    for row in range(len(grid)):
        newRow = []
        for col in range(len(grid[row])):
            try:
                cell = grid[row][col]
                scaled = (cell - min[col]) \
                         / (max[col] - min[col])
                newRow.append(scaled)
            except:
                pass
        newGrid.append(newRow)
    return newGrid

setupScales(alumni.data)
alumniScaled.data = scaleGrid(alumni.data)
alumniScaled.feature_names = alumni.feature_names
alumniScaled.target = alumni.target
alumniScaled.target_names = alumni.target_names

Examples = {
    'AlumniDefault': {
        'Poor with degree': alumni,
    },
    'AlumniSGD': {
        'Poor with degree': alumni,
        'mlpc': mlpc
    },
    'AlumniScaled': {
        'frame': alumniScaled,
    },
}


a = int(input("Enter 1st number:  "))
b = int(input("Enter 2nd number:  "))
c = int(input("Enter 3rd number:  "))

d = int(input("input 1 to obtain max value or 2 to obtain min value: "))

if d == 1 :
    print("maximum value is", max(a,b,c))
if d == 2:
    print("minimum value is", min(a,b,c))

if d != 1 and d != 2:
        print("you put a wrong value")

# Instead of 3 if we could use if, elif, else:
# if d == 1 :
#     print("maximum value is", max(a,b,c))
# elif d == 2:
#     print("minimum value is", min(a,b,c))
#
# else:
#         print("you put a wrong value")


class Solution:
    def nextGreaterElement(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        result = []

        for i in range(len(nums1)):
            num = nums1[i]
            thisResult = -1
            indexOfThisNum = nums2.index(num)
            for j in range(indexOfThisNum, len(nums2)):
                compareNum = nums2[j]
                if num < compareNum:
                    thisResult = compareNum
                    break

            result.append(thisResult)

        return result


# Turn off rendering (faster)
RDK.Render(False)
prog = RDK.AddProgram('AutoProgram')

# Hide program instructions (optional, but faster)
prog.ShowInstructions(False)

# Retrieve the current robot position:
pose_ref = robot.Pose()

# Iterate through a number of points
for i in range(len(POINTS)):
    # add a new target
    ti = RDK.AddTarget('Auto Target %i' % (i+1))

    # use the reference pose and update the XYZ position
    pose_ref.setPos(POINTS[i])
    ti.setPose(pose_ref)

    # force to use the target as a Cartesian target (default)
    ti.setAsCartesianTarget()

    # Add the target as a Linear/Joint move in the new program
    prog.MoveL(ti)

# Hide the target items from the tree: it each movement still keeps its own target.
# Right click the movement instruction and select "Select Target" to see the target in the tree
program.ShowTargets(False)

# Turn rendering ON before starting the simulation (automatic if we are done)
RDK.Render(True)

#--------------------------------------
# Update the program path to display the yellow path in RoboDK.
# Set collision checking ON or OFF
check_collisions = COLLISION_OFF
# Update the path (can take some time if collision checking is active)
update_result = program.Update(check_collisions)
# Retrieve the result
n_insok = update_result[0]
time = update_result[1]
distance = update_result[2]
percent_ok = update_result[3]*100
str_problems = update_result[4]
if percent_ok < 100.0:
    msg_str = "WARNING! Problems with %s (%.1f):
%s" % (program_name, percent_ok, str_problems)
else:
    msg_str = "No problems found for program %s" % program_name

# Notify the user:
print(msg_str)
RDK.ShowMessage(msg_str)


# This file is meant to test different OCR APIs with self made pictures
# Test Pictures have to be stored in 'test_pictures' folder
import Tesseract as ts
import APIs as api
from os import walk
import sys
from pprint import pprint
import json

def analyze_image(img_path):
    results = {}

    # get result from tesseract
    data, tess_text = ts.process_image(img_path)
    results['Tesseract'] = tess_text

    # get result from Google Cloud Vision API
    google_text = api.google_process_image(img_path)
    results['Google'] = google_text

    # get result from Microsoft Cognitive API
    microsoft_text = api.microsoft_process_image(img_path)
    results['Microsoft'] = microsoft_text

    # get result from Microsoft Cognitive API
    abbyy_text = api.abbyy_process_image(img_path)
    results['Abbyy'] = abbyy_text

    # get result from Amazon Textract
    amazon_text = api.amazon_process_image(img_path)
    results['Amazon'] = amazon_text

    return results

def analyze_images(img_folder, **kwargs):
    # possible to pass file='path_to_file' as argument to store result as json file

    files = []
    for (dirpath, dirnames, filenames) in walk(img_folder):
        files.extend(filenames)
        break

    results = {}

    for file in files:
        img_path = 'test_images/' + file

        results[file] = analyze_image(img_path)
    if 'file' in kwargs.keys():
        with open(result_file, 'w') as file:
            json.dump(results, file)

    return results

if __name__ == '__main__':
    folder = sys.argv[1]
    result_file = sys.arg[2]
    result = analyze_images(folder, result_file)
    pprint(result)


import numpy as np
import torch

import GPUtil
# util function

def set_seed(seed=1234):
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    np.random.seed(seed)

def get_device():
    # Select GPUs
    use_cuda = torch.cuda.is_available()
    if use_cuda:
        deviceIDs = GPUtil.getAvailable(order = 'memory', limit = 1, maxLoad = 0.5, maxMemory = 0.5,
                                        includeNan=False, excludeID=[], excludeUUID=[])
        device = torch.device(f"cuda:{deviceIDs[0]}")
    else:
        device = torch.device("cpu")

    return device


"""string

Revision ID: b05922bf5f39
Revises: 2f8eb37dafe1
Create Date: 2022-09-29 15:01:51.873716

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'b05922bf5f39'
down_revision = '2f8eb37dafe1'
branch_labels = None
depends_on = None

def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('register')
    # ### end Alembic commands ###

def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('register',
    sa.Column('username', sa.VARCHAR(), autoincrement=False, nullable=False),
    sa.PrimaryKeyConstraint('username', name='register_pkey')
    )
    # ### end Alembic commands ###


# import random
#
# import data from game_data as followers_list
#
# continue_game = True
# score = 0
# already_used = []
#
# option_1 = random.choice(list(followers_list.keys()))
# key_list = list(followers_list.keys())
#
# while continue_game:
#     already_used.append(option_1)
#
#     option_2 = random.choice(list(followers_list.keys()))
#
#     if followers_list.get(option_1) > followers_list.get(option_2):
#         compare = "l"
#
#     else:
#         compare = "h"
#
#     answer = input(f"Guess if {option_2} has higher or lower instagram followers than {option_1}\n h or l = ")
#
#     if answer == "h" and compare == "h":
#         print(f"You got that right {option_2} has {followers_list.get(option_2)} followers.")
#         score += 1
#         option_1 = option_2
#     elif answer == "l" and compare == "l":
#
#         print(f"You got that right {option_2} has {followers_list.get(option_2)} followers.")
#         score += 1
#         option_1 = option_2
#
#     else:
#         print("Sorry, Your guess was wrong. ")
#         continue_game = False

'''======================================================================='''

import game_data
import random

#display art
print(game_data.logo)

# generate a random account from the game data

#format the account data into printable format

continue_game = True
score = 0
already_used = []

account_a = random.choice(game_data.data)

while continue_game:

    account_b = random.choice(game_data.data)

    if account_a == account_b:
        account_b = random.choice(game_data.data)

    account_a_name = account_a["name"]
    account_b_name = account_b["name"]
    account_a_follower = account_a["follower_count"]
    account_b_follower = account_b["follower_count"]
    account_a_description = account_a["description"]
    account_b_description = account_b["description"]
    account_a_country = account_a["country"]
    account_b_country = account_b["country"]

    if account_a_follower > account_b_follower:
        result = "H"

    else:
        result = "L"

    answer = input(f"Guess if \n A : {account_a_name} a {account_a_description} from {account_a_country}\n has more followers than \n B : {account_b_name} a {account_b_description} from {account_b_country}\n Enter H or L :").upper()

    if answer == "H" and result == "H":
        print(f"You got that right {account_a_name} has {account_a_follower} million followers and {account_b_name} has {account_b_follower} million.")
        score += 1
        account_a = account_b
    elif answer == "L" and result == "L":

        print(f"You got that right {account_b_name} has {account_b_follower} million followers and {account_b_name} has {account_b_follower} million.")
        score += 1
        account_a = account_b

    else:
        print("Sorry, Your guess was wrong. ")
        continue_game = False

    print(f"Your score is {score}")
# Ask the user for a guess

# Check if the user is correct

# Get the followers count of each account

# give user a feedback  on their guess

#keep scores

# make the game repeatable

# making the account at position b to position a

#clear the screen


"""Script to update users analytics data to Elasticsearch."""

import argparse
import datetime
import functools
import json
import logging
import os
import random
import typing

import certifi as _  # Needed to handle SSL in elasticsearch connections, for production use.
import elasticsearch
from google.protobuf import json_format
import requests
import requests_aws4auth

from bob_emploi.frontend.api import geo_pb2
from bob_emploi.frontend.api import job_pb2
from bob_emploi.frontend.api import project_pb2
from bob_emploi.frontend.api import user_pb2
from bob_emploi.frontend.server import mongo
from bob_emploi.frontend.server import now
from bob_emploi.frontend.server import proto
from bob_emploi.frontend.server import scoring
from bob_emploi.frontend.server.asynchronous import report

_DB, _USER_DB, _ = mongo.get_connections_from_env()

def age_group(year_of_birth: int) -> str:
    """Estimate age group from year of birth."""

    if year_of_birth < 1920:
        return 'Unknown'
    precise_age = now.get() - datetime.datetime(year_of_birth, 7, 1)
    age = precise_age.days / 365
    if age < 18:
        return '-18'
    if age < 25:
        return '18-24'
    if age < 35:
        return '25-34'
    if age < 45:
        return '35-44'
    if age < 55:
        return '45-54'
    if age < 65:
        return '55-64'
    return '65+'

def nps_love_score(nps_score: int) -> typing.Optional[int]:
    """Convert NPS scode to lovers/detractors values.

    Returns -1 for detractors, meaning NPS score is between 1 and 5.
    Returns 0 for passive, meaning NPS score is 6 or 7.
    Returns 1 for lovers, meaning NPS score is 8, 9, 10.
    Returns None otherwise."""

    if nps_score <= 5:
        return -1
    if nps_score <= 7:
        return 0
    if nps_score <= 10:
        return 1
    logging.warning('Cannot convert nps_score %s', nps_score)
    return None

def bob_has_helped_love_score(answer: str) -> typing.Optional[int]:
    """Convert 'Bob has helped ?' answers to lovers/detractors values.

    Return -1 if answer is 'NO'
    Return 1 if answer is 'YES' or 'YES_A_LOT'
    Return None otherwise."""

    if answer in ('NO', 'NOT_AT_ALL'):
        return -1
    if answer in ('YES', 'YES_A_LOT'):
        return 1
    logging.warning('bobHasHelped field has unknown answer "%s"', answer)
    return None

def feedback_love_score(feedback_score: int) -> typing.Optional[int]:
    """Convert online feedback score to lovers/detractors values.

    Returns -1 if score is 1 or 2.
    Returns 0 if score 3.
    Returns 1 if score is 4 or 5.
    Returns None otherwise."""

    if feedback_score in (1, 2):
        return -1
    if feedback_score == 3:
        return 0
    if feedback_score in (4, 5):
        return 1
    logging.warning('Cannot convert feedback_score %s', feedback_score)
    return None

def _get_employment_status(user: user_pb2.User) -> typing.Optional[user_pb2.EmploymentStatus]:
    """Get the last employmentStatus for which we have an answer to bobHasHelped question, or get
    the last employmentStatus."""

    last_status = None
    for status in reversed(user.employment_status):
        if status.bob_has_helped:
            return status
        if not last_status:
            last_status = status
    return last_status

def _get_last_complete_project(user: user_pb2.User) -> typing.Optional[project_pb2.Project]:
    """Get last project which is not is_incomplete."""

    return next(
        (project for project in reversed(user.projects)
         if not project.is_incomplete),
        None)

_T = typing.TypeVar('_T')
_U = typing.TypeVar('_U')

def _remove_null_fields(mydict: typing.Dict[_T, typing.Optional[_U]]) -> typing.Dict[_T, _U]:
    out: typing.Dict[_T, _U] = {}
    for key, value in mydict.items():
        clean_value: typing.Optional[_U]
        if isinstance(value, dict):
            clean_value = typing.cast(_U, _remove_null_fields(value)) or None
        else:
            clean_value = value
        if clean_value is not None:
            out[key] = clean_value
    return out

# Cache (from MongoDB) of known cities.
@functools.lru_cache(maxsize=256, typed=False)
def _get_urban_context(city_id: str) -> typing.Optional[str]:
    target_city = _DB.cities.find_one({'_id': city_id})
    if target_city:
        target_city_proto = typing.cast(
            geo_pb2.FrenchCity, proto.create_from_mongo(target_city, geo_pb2.FrenchCity))
        return geo_pb2.UrbanContext.Name(target_city_proto.urban_context)
    return None

def _user_to_analytics_data(user: user_pb2.User) -> typing.Dict[str, typing.Any]:
    """Gather analytics data to insert into elasticsearch."""

    data: typing.Dict[str, typing.Any] = {
        'registeredAt': user.registered_at.ToJsonString(),
        'randomGroup': random.randint(0, 100) / 100,
        'profile': {
            'ageGroup': age_group(user.profile.year_of_birth),
            'canTutoie': user.profile.can_tutoie,
            'coachingEmailFrequency': user_pb2.EmailFrequency.Name(
                user.profile.coaching_email_frequency),
            'frustrations': [user_pb2.Frustration.Name(f) for f in user.profile.frustrations],
            'gender': user_pb2.Gender.Name(user.profile.gender),
            'hasHandicap': user.profile.has_handicap,
            'highestDegree': job_pb2.DegreeLevel.Name(user.profile.highest_degree),
            'origin': user_pb2.UserOrigin.Name(user.profile.origin),
        },
        'featuresEnabled': json_format.MessageToDict(user.features_enabled),
        'origin': {
            'medium': user.origin.medium,
            'source': user.origin.source,
        },
    }
    if user.net_promoter_score_survey_response.HasField('responded_at'):
        data['nps_response'] = {
            'loveScore': nps_love_score(user.net_promoter_score_survey_response.score),
            'score': user.net_promoter_score_survey_response.score,
            'time': user.net_promoter_score_survey_response.responded_at.ToJsonString(),
        }
    last_project = _get_last_complete_project(user)
    if last_project:
        scoring_project = scoring.ScoringProject(
            last_project, user.profile, user.features_enabled, _DB)
        data['project'] = {
            'targetJob': {
                'name': last_project.target_job.name,
                'job_group': {
                    'name': last_project.target_job.job_group.name,
                },
            },
            'areaType': geo_pb2.AreaType.Name(last_project.area_type),
            'city': {
                'regionName': last_project.city.region_name,
                'urbanScore': last_project.city.urban_score,
            },
            'job_search_length_months': round(scoring_project.get_search_length_at_creation()),
            'advices': [a.advice_id for a in last_project.advices if a.num_stars >= 2],
            'numAdvicesRead': sum(
                1 for a in last_project.advices if a.status == project_pb2.ADVICE_READ),
            'isComplete': not last_project.is_incomplete,
        }
        if last_project.kind:
            data['project']['kind'] = project_pb2.ProjectKind.Name(last_project.kind)
        if last_project.feedback.score:
            data['project']['feedbackScore'] = last_project.feedback.score
            data['project']['feedbackLoveScore'] = feedback_love_score(last_project.feedback.score)
        if last_project.min_salary and last_project.min_salary < 1000000000:
            data['project']['minSalary'] = last_project.min_salary
        urban_context = _get_urban_context(last_project.city.city_id)
        if urban_context:
            data['project']['city']['urbanContext'] = urban_context
    last_status = _get_employment_status(user)
    if last_status:
        data['employmentStatus'] = json_format.MessageToDict(last_status)
        data['employmentStatus']['daysSinceRegistration'] = \
            (last_status.created_at.ToDatetime() - user.registered_at.ToDatetime()).days
        if last_status.bob_has_helped:
            data['employmentStatus']['bobHasHelpedScore'] = bob_has_helped_love_score(
                last_status.bob_has_helped)
        if last_status.other_coaches_used:
            data['employmentStatus']['otherCoachesUsed'] = [
                user_pb2.OtherCoach.Name(c) for c in last_status.other_coaches_used
            ]
        if last_status.bob_relative_personalization:
            data['employmentStatus']['bobRelativePersonalization'] = \
                last_status.bob_relative_personalization

    if user.emails_sent:
        data['emailsSent'] = {
            # This will keep only the last email sent for each campaign.
            email.campaign_id: user_pb2.EmailSentStatus.Name(email.status)
            for email in sorted(user.emails_sent, key=lambda email: email.sent_at.ToDatetime())
        }

    if user.client_metrics.first_session_duration_seconds:
        data['clientMetrics'] = {
            'firstSessionDurationSeconds': user.client_metrics.first_session_duration_seconds,
        }
    if user.client_metrics.is_first_session_mobile:
        data['clientMetrics'] = data.get('clientMetrics', {})
        data['clientMetrics']['isFirstSessionMobile'] = \
            user_pb2.OptionalBool.Name(user.client_metrics.is_first_session_mobile)

    return _remove_null_fields(data)

def export_user_to_elasticsearch(
        es_client: elasticsearch.Elasticsearch, index: str, registered_from: str,
        dry_run: bool = True) -> None:
    """Synchronize users to elasticsearch for analytics purpose."""

    if not dry_run:
        if es_client.indices.exists(index=index):
            logging.info('Removing old bobusers index ...')
            es_client.indices.delete(index=index)
        logging.info('Creating bobusers index ...')
        es_client.indices.create(index=index)

    nb_users = 0
    nb_docs = 0
    cursor = _USER_DB.user.find({
        'registeredAt': {'$gt': registered_from},
        'featuresEnabled.excludeFromAnalytics': {'$ne': True},
    })
    for row in cursor:

        nb_users += 1
        user_id = str(row.pop('_id'))
        user = typing.cast(user_pb2.User, proto.create_from_mongo(row, user_pb2.User))
        data = _user_to_analytics_data(user)

        logging.debug(data)

        if not dry_run:
            es_client.create(index=index, doc_type='user', id=user_id, body=json.dumps(data))
            nb_docs += 1
            if nb_docs % 1000 == 0:
                logging.info('%i users processed', nb_docs)

    if not dry_run:
        es_client.indices.flush(index=index)

def main(
        es_client: elasticsearch.Elasticsearch,
        string_args: typing.Optional[typing.List[str]] = None) -> None:
    """Parse command line arguments and trigger sync_employment_status function."""

    parser = argparse.ArgumentParser(
        description='Synchronize mongodb employement status fields retrieving typeform data.')
    parser.add_argument(
        '-r', '--registered-from', default='2017-06-01',
        help='Process users registered from the given date')
    parser.add_argument(
        '--no-dry-run', dest='dry_run', action='store_false',
        help='No dry run really store in elasticsearch.')
    parser.add_argument('--index', default='bobusers', help='Elasticsearch index to write to')
    parser.add_argument('--verbose', '-v', action='store_true', help='More detailed output.')
    parser.add_argument(
        '--disable-sentry', action='store_true', help='Disable logging to Sentry.')
    args = parser.parse_args(string_args)

    logging.basicConfig(level='DEBUG' if args.verbose else 'INFO')
    if not args.dry_run and not args.disable_sentry:
        try:
            report.setup_sentry_logging(os.getenv('SENTRY_DSN'))
        except ValueError:
            logging.error(
                'Please set SENTRY_DSN to enable logging to Sentry, or use --disable-sentry option')
            return

    export_user_to_elasticsearch(es_client, args.index, args.registered_from, dry_run=args.dry_run)

def _get_auth_from_env(
        env: typing.Mapping[str, str]) -> typing.Optional[requests_aws4auth.AWS4Auth]:
    aws_in_docker = env.get('AWS_CONTAINER_CREDENTIALS_RELATIVE_URI')
    if aws_in_docker:
        # https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html
        response = requests.get('http://169.254.170.2{}'.format(aws_in_docker))
        response.raise_for_status()
        credentials = response.json()
        access_key_id = credentials.get('AccessKeyId')
        secret_access_key = credentials.get('SecretAccessKey')
        session_token = credentials.get('Token')
    else:
        access_key_id = env.get('AWS_ACCESS_KEY_ID')
        secret_access_key = env.get('AWS_SECRET_ACCESS_KEY')
        session_token = None
    if not access_key_id:
        return None
    return requests_aws4auth.AWS4Auth(
        access_key_id, secret_access_key, 'eu-central-1', 'es', session_token=session_token)

def get_es_client_from_env() -> elasticsearch.Elasticsearch:
    """Get an Elasticsearch client configured from environment variables."""

    env = os.environ
    return elasticsearch.Elasticsearch(
        env.get('ELASTICSEARCH_URL', 'http://elastic:changeme@elastic-dev:9200').split(','),
        http_auth=_get_auth_from_env(env),
        connection_class=elasticsearch.RequestsHttpConnection)

if __name__ == '__main__':
    main(get_es_client_from_env())


import socket
def Respon_send(new_socket):
    #这里注意window系统换行符是\r\n，不是正斜杠
    response='HTTP/1.1 200 OK \r\n'
    response+='\r\n'
    response+='
大型考试——考试发布
'
    print(new_socket.send(response.encode('gbk')))

def main():
    tcp_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    tcp_socket.bind(('127.0.0.1',8895))
    #128参数制定了内核为此套接口排队的最大连接个数,对于高并发的服务这里这样设置显然是不够的，会比这个大很多。
    tcp_socket.listen(128)
    #链接多个客户端
    new_tcp_socket,addr = tcp_socket.accept()
        #判断客户端请求是否发送完成,这里可以设置程序的内存
    new_tcp_socket.recv(1024*1024).decode('gbk')
    Respon_send(new_tcp_socket)

    new_tcp_socket.close()
    tcp_socket.close()

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
"""
Created on Wed Nov 18 14:56:59 2020

@author: Ankit Parashar
"""
#! selectionSort.py

def findSmallest(arr):
    size = len(arr)
    smallest = arr[0]
    smallest_index = 0
    for i in range(1, size):
        if arr[i] < smallest:
            smallest = arr[i]
            smallest_index = i

    return smallest_index

def selectionSort(arr):
    newArr = []
    size = len(arr)
    for i in range(size):
        smallest = findSmallest(arr)
        newArr.append(arr.pop(smallest))
    return newArr

print(selectionSort([5, 3, 6, 2, 10]))


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

# 引数を受け取る
import sys

# 引数を変数に格納
args = sys.argv

# 引数があるかどうか
if len(args) != 2 or not args[1] or not args[1].isdigit():
  print("引数が存在しないか、数字ではないため処理を終了します")
  sys.exit()
else:
  print(args)
  print(args[1])

# 引数の値を調べる
num = int(args[1])
if num > 20:
  print("引数は20より大きいです")
elif num < 10:
  print("引数は10より小さいです")
else:
  print("引数は20以下で10以上です")


from os.path import join, exists
from os import mkdir, makedirs
from config import debug, local
from IPython import display
import numpy as np
import itertools
from matplotlib import pyplot as plt
from matplotlib_inline import backend_inline
from sklearn import metrics

def use_svg_display():
    """Use the svg format to display a plot."""

    backend_inline.set_matplotlib_formats('svg')

def set_axes(axes, x_label, y_label, x_lim, y_lim, x_scale, y_scale, legend):
    """Set the axes for matplotlib.

    Defined in :numref:`sec_calculus`"""
    if x_label is not None:
        axes.set_xlabel(x_label)
    if y_label is not None:
        axes.set_ylabel(y_label)
    if x_scale is not None:
        axes.set_xscale(x_scale)
    if y_scale is not None:
        axes.set_yscale(y_scale)
    axes.set_xlim(x_lim)
    axes.set_ylim(y_lim)
    if legend:
        axes.legend(legend)
    axes.grid()

class Animator:
    """For plotting data_access in animation."""

    def __init__(self, x_label=None, y_label=None, legend=None, x_lim=None,
                 y_lim=None, x_scale='linear', y_scale='linear',
                 fmts=('-', 'm--', 'g-.', 'r:'), num_rows=1, num_cols=1,
                 fig_size=(5., 3.5)):
        """init parameter for plot."""

        # Incrementally plot multiple lines
        if legend is None:
            legend = []
        use_svg_display()
        self.fig, self.axes = plt.subplots(num_rows, num_cols, figsize=fig_size)
        if num_rows * num_cols == 1:
            self.axes = [self.axes, ]
        # Use a lambda function to capture arguments
        self.config_axes = lambda: set_axes(
            self.axes[0], x_label, y_label, x_lim, y_lim, x_scale, y_scale, legend)
        self.X, self.Y, self.fmts = None, None, fmts

    def add(self, x, y):
        # Add multiple data_access points into the figure
        if not hasattr(y, "__len__"):
            y = [y]
        n = len(y)
        if not hasattr(x, "__len__"):
            x = [x] * n
        if not self.X:
            self.X = [[] for _ in range(n)]
        if not self.Y:
            self.Y = [[] for _ in range(n)]
        for i, (a, b) in enumerate(zip(x, y)):
            if a is not None and b is not None:
                self.X[i].append(a)
                self.Y[i].append(b)
        if debug is True and local is True:
            self.axes[0].cla()
            for x, y, fmt in zip(self.X, self.Y, self.fmts):
                self.axes[0].plot(x, y, fmt)
            self.config_axes()
            display.display(self.fig)
            display.clear_output(wait=True)
            plt.pause(0.01)

    def show(self):
        # Show picture
        self.axes[0].cla()
        for x, y, fmt in zip(self.X, self.Y, self.fmts):
            self.axes[0].plot(x, y, fmt)
        self.config_axes()

    @staticmethod
    def plot_confusion_matrix(cm, classes,
                              normalize=False,
                              title='Confusion matrix',
                              cmap=plt.cm.Blues):
        """This function prints and plots the confusion matrix. Normalization
        can be applied by setting `normalize=True`.
        """
        if normalize:
            cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
            print("Normalized confusion matrix")
        else:
            print('Confusion matrix, without normalization')

        print(cm)

        plt.imshow(cm, interpolation='nearest', cmap=cmap)
        plt.title(title)
        plt.colorbar()
        tick_marks = np.arange(len(classes))
        plt.xticks(tick_marks, classes, rotation=45)
        plt.yticks(tick_marks, classes)

        fmt = '.2f' if normalize else 'd'
        thresh = cm.max() / 2.
        for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
            plt.text(j, i, format(cm[i, j], fmt),
                     horizontalalignment="center",
                     color="white" if cm[i, j] > thresh else "black")

        plt.tight_layout()
        plt.ylabel('True label')
        plt.xlabel('Predicted label')
        plt.gcf().subplots_adjust(bottom=0.25)

    @staticmethod
    def get_confusion_matrix(cnf_matrix,
                             saving_dir: str = None,
                             model_name: str = ''):
        plt.figure()
        Animator.plot_confusion_matrix(cnf_matrix,
                                       classes=[0, 1],
                                       title='Confusion matrix, without normalization')
        plt.show()
        if saving_dir is not None:
            if not exists(saving_dir):
                makedirs(saving_dir)
            file_name = join(saving_dir, f'{model_name}_' + 'confusion')
            plt.savefig(file_name)

        plt.figure()
        Animator.plot_confusion_matrix(cnf_matrix, normalize=True, classes=[0, 1],
                                   title='Normalized confusion matrix')
        plt.show()
        if saving_dir is not None:
            if not exists(saving_dir):
                makedirs(saving_dir)
            file_name = join(saving_dir, f'{model_name}_' +  'confusion_normalized')
            plt.savefig(file_name)

    @staticmethod
    def get_metrics(effect,
                    saving_dir: str = None,
                    model_name: str = ''):
        plt.figure()
        if type(effect).__name__ == 'dict':
            ax = list(effect.keys())
            ay = list(effect.values())
            plt.ylim([0.0, 1.05])
            plt.tick_params(axis='x', labelsize=12)
            plt.bar(ax, ay)
            for a, b, i in zip(ax, ay, range(len(ax))):  # zip 函数
                plt.text(a, b + 0.01, "%.2f" % ay[i], ha='center', fontsize=12)
            plt.show()
            if saving_dir is not None:
                if not exists(saving_dir):
                    makedirs(saving_dir)
                plt.savefig(join(saving_dir, f'{model_name}_' + "metrics"))

    @staticmethod
    def get_auc(y_prob, y_true,
                saving_dir: str = None,
                model_name: str = ''):
        auc_fig = plt.figure()
        fpr, tpr, thresholds = metrics.roc_curve(y_true, y_prob, pos_label=1)
        roc_auc = metrics.auc(fpr, tpr)
        plt.figure(auc_fig.number)
        plt.plot(fpr, tpr, label=model_name + ' (area = %0.2f)' % roc_auc)
        plt.plot([0, 1], [0, 1], 'k--')
        plt.xlim([0.0, 1.0])
        plt.ylim([0.0, 1.05])
        plt.xlabel('False Positive Rate', fontsize=12)
        plt.ylabel('True Positive Rate', fontsize=12)
        plt.title('Receiver operating characteristic (ROC)', fontsize=12)
        plt.legend(loc="lower right")
        auc_fig.show()
        if saving_dir is not None:
            if not exists(saving_dir):
                makedirs(saving_dir)
            auc_fig.savefig(join(saving_dir, f'{model_name}_' + 'auc_curves'))

    @staticmethod
    def get_auprc(y_prob, y_true,
                 saving_dir: str = None,
                 model_name: str = ''):
        prc_fig = plt.figure()
        prc_fig.set_size_inches((10, 6))
        precision, recall, thresholds = metrics.precision_recall_curve(y_true, y_prob, pos_label=1)
        roc_auc = metrics.average_precision_score(y_true, y_prob)
        plt.figure(prc_fig.number)
        plt.plot(recall, precision, label=model_name + ' (area under precision recall curve = %0.2f)' % roc_auc)

        plt.xlim([0.0, 1.0])
        plt.ylim([0.0, 1.05])
        plt.xlabel('Recall', fontsize=12)
        plt.ylabel('precision', fontsize=12)
        plt.title('Precision Recall Curve (PRC)', fontsize=12)
        plt.legend(loc="lower right")
        prc_fig.show()
        if saving_dir is not None:
            if not exists(saving_dir):
                makedirs(saving_dir)
            prc_fig.savefig(join(saving_dir, f'{model_name}_' + 'auprc_curves'))


import os

from allauth.socialaccount import providers
from allauth.socialaccount.models import SocialApp
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    help = 'Automatically create default SocialApp for each provider'

    def handle(self, *args, **options):
        sites = Site.objects.all()

        available_providers = providers.registry.get_list()
        for provider in available_providers:
            client_id = os.environ.get('SOCIALACCOUNT_{}_CLIENT_ID'.format(provider.id.upper()))
            secret = os.environ.get('SOCIALACCOUNT_{}_SECRET'.format(provider.id.upper()))

            if client_id and secret:
                socialapp, created = SocialApp.objects.get_or_create(provider=provider.id, defaults={
                    'name': 'Default {}'.format(provider.name),
                    'client_id': client_id,
                    'secret': secret,
                })

                if created:
                    socialapp.sites.add(*sites)


import argparse
import numpy as np
import cv2

def mse(imageA, imageB):
    prediction = cv2.imread(imageA,0)
    actual = cv2.imread(imageB,0)

    err = np.sum((prediction.astype("float") - actual.astype("float")) ** 2)
    err /= float(prediction.shape[0] * prediction.shape[1])
    print("RMSE = ", err)

    cv2.imshow('prediction',prediction)
    cv2.imshow('actual',actual)

    cv2.waitKey(10000)
    cv2.destroyAllWindows()

    return err

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Simple testing funtion for Monodepthv2 models.')

    parser.add_argument('--imageA', type=str,
                        help='path to a test image or folder of images', required=True)
    parser.add_argument('--imageB', type=str,
                        help='path to a test image or folder of images', required=True)

    args = parser.parse_args()
    val = mse(args.imageA,args.imageB)
    # print(val)


from django import template
import geoip2.database
from geoip2.errors import AddressNotFoundError

register = template.Library()

@register.simple_tag(takes_context=True)
def location_geoip(context):
    """Геолокация - определение города по ip"""
    x_forwarded_for = context['request'].META.get('HTTP_X_FORWARDED_FOR')

    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = context['request'].META.get('REMOTE_ADDR')
    # print(ip)
    # g = GeoIP2()
    # location = g.city(ip)
    # location_city = location["city"]
    reader = geoip2.database.Reader('service/geoip/GeoLite2-City.mmdb')
    try:
        response = reader.city(ip)
        location_city = response.city.names['ru']
        print(location_city)
        reader.close()
        return location_city
    except AddressNotFoundError:
        return "не определен"
    except:
        return "no city"


from flask import Flask, jsonify, request
from business_logic import checkout

app = Flask(__name__)

@app.route('/checkout', methods=['POST'])
def checkout():
    data = request.get_json()
    total_price = checkout.calculate_total(data)

    if total_price is None:
        return jsonify({'error': 'checkout-0001',
                        'message': 'There was an error calculating total price',
                        'detail': 'Check request was formatted correctly with valid IDs'
                        }), 400
    else:
        return jsonify({'price': total_price}), 200

if __name__ == '__main__':
    app.run()


import pandas as pd
import os
import numpy as np

if __name__ == "__main__":
    lidar_df = pd.read_csv('lidar_with_cluster_angle.csv')
    # df = df[df['Centroid_X'] > 0]
    # df.to_csv('lidar_distinct.csv', index=False)
    image_data = []
    with open("camera.csv", 'r') as cameri:
        lines = cameri.readlines()
        for folder in os.listdir(r"C:\Users\julia\fusion_data\new-raw-data\raw-data\camera-data\2023-05-30"):
            file = os.listdir(os.path.join(r"C:\Users\julia\fusion_data\new-raw-data\raw-data\camera-data\2023-05-30"
                                           , folder))[0]
            for line in lines:
                # print(line, end="")
                print(file, end="")
                if file.split(".")[0] in line:
                    values = [val.strip() for val in line.split(",")]
                    image_data.append([values[5], values[6], values[8]])
            # 5 6 8
    data = np.array(image_data)
    print(data)
    image_df = pd.DataFrame(data=data, columns=['center_x', 'center_y', 'bounding_box_angle'])
    merged = lidar_df.merge(image_df, left_index=True, right_index=True, how='inner')\
        .to_csv("training_data.csv", index=False)


from flask import Flask, render_template, redirect, request
from uuid import uuid4
from datetime import date

from db import createTransacao
from db import totalReceitas, totalDespesas, saldo, extrato, obterTransacao
from db import excluirTransacao
from db import editarTransacao

app = Flask(__name__)

@app.route('/')
def index():
  return render_template(
    'index.html',
    saldo = saldo(),
    receita=totalReceitas(),
    despesa = totalDespesas(),
    extrato = extrato(),
  )

@app.route('/cadastrar/<tipo>', methods=['GET', 'POST'])
def cadastrar(tipo):
  if request.method == 'GET':
    return render_template('cadastrar.html', tipo=tipo)

  data = request.form['data']
  if(not request.form['data']):
    data = str(date.today())

  dados = {
    'id': str(uuid4()),
    'descricao':request.form['descricao'],
    'valor':float(request.form['valor']),
    'data':data,
    'tipo': tipo,
  }

  createTransacao(dados)

  return redirect('/')

@app.route('/deletar/<id>')
def deletar(id):
  excluirTransacao(id)

  return redirect("/")

@app.route('/editar/<id>', methods=['GET', 'POST'])
def editar(id):
  if request.method == 'GET':
    transacao = obterTransacao(id)
    return render_template('editar.html', transacao=transacao)

  newDados = {
    'descricao':request.form['descricao'],
    'valor':float(request.form['valor']),
    'data':request.form['data'],
  }

  editarTransacao(newDados, id)

  return redirect('/')

app.run(debug=True)


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

# OpenGL example code - Geometry Shader and Blending
# Uses a geometry shader to expand points to billboard quads.
# The billboards are then blended while drawing to create a galaxy
# made of particles.

import math
from random import random as rand
import ctypes

import numpy as np
from OpenGL.GL import *
from OpenGL.GL import shaders

from glfw import *
import glm

class Window(object):

    def __init__(self, width=640, height=480, title='GLFW opengl window'):
        self.width = width
        self.height = height
        self.title = title
        self.window = None

        self.__vertexShader = './shaders/%s.vert' % self.title
        self.__geomShader = './shaders/%s.geom' % self.title
        self.__fragmentShader = './shaders/%s.frag' % self.title
        self.__shaderProgram = None
        self.__vao = None

        self.__viewLocation = None
        self.__projLocation = None

        self.__particles = 128 * 1024

    def shaderFromFile(self, shaderType, shaderFile):
        """read shader from file and compile it"""
        shaderSrc = ''
        with open(shaderFile) as sf:
            shaderSrc = sf.read()

        return shaders.compileShader(shaderSrc, shaderType)

    def initGL(self):
        """opengl initialization"""
        # load shaders
        vertexShader = self.shaderFromFile(GL_VERTEX_SHADER, self.__vertexShader)
        geomShader = self.shaderFromFile(GL_GEOMETRY_SHADER, self.__geomShader)
        fragmentShader = self.shaderFromFile(GL_FRAGMENT_SHADER, self.__fragmentShader)
        self.__shaderProgram = shaders.compileProgram(vertexShader, geomShader, fragmentShader)
        if not self.__shaderProgram:
            self.close()

        # obtain location of projection uniform
        self.__viewLocation = glGetUniformLocation(self.__shaderProgram, 'View')
        self.__projLocation = glGetUniformLocation(self.__shaderProgram, 'Projection')

        # generate and bind the vao
        self.__vao = glGenVertexArrays(1)
        glBindVertexArray(self.__vao)

        # generate and bind the buffer object
        vbo = glGenBuffers(1)
        glBindBuffer(GL_ARRAY_BUFFER, vbo)

        # create a galaxy like distribution of points
        vertexData = []
        for i in xrange(self.__particles):
            arm = 3 * rand()
            alpha = 1 / (.1 + math.pow(rand(), .7)) - 1/1.1
            r = 4.0 * alpha
            alpha += arm * 2.0 * 3.1416 / 3.0

            x = r * math.sin(alpha)
            y = 0
            z = r * math.cos(alpha)

            x += (4.0 - .2 * alpha) * (2 - rand() + rand() + rand() + rand())
            y += (2.0 - .1 * alpha) * (2 - rand() + rand() + rand() + rand())
            z += (4.0 - .2 * alpha) * (2 - rand() + rand() + rand() + rand())
            vertexData.append((x, y, z))
        vertexData = np.array(vertexData, dtype=np.float32)

        # fill with data
        glBufferData(GL_ARRAY_BUFFER, vertexData.nbytes, vertexData, GL_STATIC_DRAW)

        # set up generic attrib pointers
        glEnableVertexAttribArray(0)
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * 4, None)

        glBindVertexArray(0)

        # we are blending so no depth testing
        glDisable(GL_DEPTH_TEST)

        # enable blending
        glEnable(GL_BLEND)
        # and set the blend function to result = 1 * source + 1 * destination
        glBlendFunc(GL_ONE, GL_ONE)

    def renderGL(self):
        """opengl render method"""
        # get the time in seconds
        t = glfwGetTime()

        # clear first
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        # use the shader program
        glUseProgram(self.__shaderProgram)

        # calculate ViewProjection matrix
        projection = glm.perspective(90.0, 4.0 / 3.0, .1, 100.0)
        projection = np.array(projection, dtype=np.float32)

        # translate the world/view position
        view = glm.translate(glm.mat4(1.0), glm.vec3(0.0, 0.0, -50.0))

        # make the camera rotate around the origin
        view = glm.rotate(view, 30.0 * math.sin(t * 0.1), glm.vec3(1.0, 0.0, 0.0))
        view = glm.rotate(view, -22.5 * t, glm.vec3(0.0, 1.0, 0.0))
        view = np.array(view, dtype=np.float32)

        # set the uniform
        glUniformMatrix4fv(self.__viewLocation, 1, GL_FALSE, view)
        glUniformMatrix4fv(self.__projLocation, 1, GL_FALSE, projection)

        # bind the vao
        glBindVertexArray(self.__vao)

        # draw
        glDrawArrays(GL_POINTS, 0, self.__particles)

        glBindVertexArray(0)
        glUseProgram(0)

    def initWindow(self):
        """setup window options. etc, opengl version"""
        # select opengl version
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE)
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3)
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3)

    def show(self):
        """create the window and show it"""
        self.initWindow()

        self.window = glfwCreateWindow(self.width, self.height, self.title, 0, 0)
        if self.window == 0:
            glfwTerminate()
            raise Exception('failed to open window')

        glfwMakeContextCurrent(self.window)

        # initialize opengl
        self.initGL()

        while not glfwWindowShouldClose(self.window):
            glfwPollEvents()

            self.renderGL()

            # check for errors
            error = glGetError()
            if error != GL_NO_ERROR:
                raise Exception(error)

            # finally swap buffers
            glfwSwapBuffers(self.window)

        self.close()

    def close(self):
        glfwDestroyWindow(self.window)
        glfwTerminate()

if __name__ == '__main__':
    import os.path

    if glfwInit() == GL_FALSE:
        raise Exception('failed to init GLFW')

    title = os.path.basename(__file__)
    win = Window(title=title[:-3])
    win.show()


#  对请求返回值做处理，加"ThisIdYellowBegin" ，"ThisIdYellowEnd"
#  注意对最后一层的修改如果是不可变类型（string，int）返回上一级是不会修改的，除非有修改的返回值
#  对list，dict的修改返回上一层也是修改的结果

import json
#  有返回值的修改
def test2(temp):
    if isinstance(temp, dict):
        for key in temp.keys():
            temp[key] = test2(temp[key])
    elif isinstance(temp, (list, tuple)):
        for i in range(0, len(temp)):
            temp[i] = test2(temp[i])
    elif isinstance(temp, str):
        if temp[0] in ['{', '[']:
            temp = json.loads(temp)
            temp = test2(temp)
        else:
            temp = "ThisIdYellowBegin" + temp + "ThisIdYellowEnd"
    elif isinstance(temp, int):
        temp  = "ThisIdYellowBegin" + str(temp) + "ThisIdYellowEnd"
    else:
        pass
    return temp  # 注意递归的每次都有return返回上层

# 原因解释：最底层的修改，没有返回上一层；是不是因为底层是不可变数据类型,可变类型是适用的
def test3(temp):
    if isinstance(temp, dict):
        for key in temp.keys():
            res = test3(temp[key])
    elif isinstance(temp, (list,tuple)):
        for i in range(0, len(temp)):
            res = test3(temp[i])
    elif isinstance(temp, str):
        if temp[0] in ['{' ,'[']: # 加判断
            res =json.loads(temp)
            test3(temp)
        else:
            temp="ThisIdYellowBegin" + temp + "ThisIdYellowEnd"
    elif isinstance(temp, int):
        temp="ThisIdYellowBegin" + str(temp) + "ThisIdYellowEnd"
    else:
        pass

    return False

if __name__=='__main__':
    # temp = {'cur_filter': 123}
    temp = {'cur_filter': '123'}
    # temp = {'cur_filter': '{"department_5":"4339","department_6":"43399"}'}
    # temp = {'cur_filter': {"department_5":"4339","department_6":"43399"}}
    # temp = {'cur_filter': [{"department_5":"4339","department_6":"43399"}]}
    # temp = {'cur_filter': '[{"department_1":"1726","department":"2785","department_3":"3626","department_4":"4338","department_5":"4339","department_erp":"abc"}]'}
    # temp={'cur_filter': {"department_6":"43399","department_5":"4339"}}
    # ans = test(temp)
    # print(ans)
    test3(temp)
    print(temp)


from utils import verify_request
from webob import MultiDict

import webapp2
import cgi
import unittest
import hashlib
import binascii
import urllib
import hmac
import ndb_tests

from google.appengine.ext.ndb import model

class TestVerifier(ndb_tests.NDBTest):

    def setUp(self):
        super(TestVerifier, self).setUp()

        class AppAccess(model.Model):
            secret = model.StringProperty(required=True)

        self.eins_zwo = AppAccess(secret="meine weihnacht").put()
        self.other_key = AppAccess(secret="secret souce").put()

    def test_no_key(self):
        self.assertRaises(webapp2.HTTPException,
                verify_request, "GET", "http://example.com", {})

    def test_no_signature(self):
        self.assertRaises(webapp2.HTTPException,
                verify_request, "GET", "http://example.com", {"_key": ""})

    def test_unknown_key(self):
        self.assertRaises(webapp2.HTTPException,
                verify_request, "GET", "http://example.com",
                {"_key": self.other_key.urlsafe()[:4] + "blaa",
                        "_signature": "faulty"})

    def test_faulty_signature(self):
        self.assertRaises(webapp2.HTTPException, verify_request,
            "GET", "http://example.com",
            {"_key": self.eins_zwo.urlsafe(), "_signature": "faulty"})

    def test_simple(self):
        key = self.eins_zwo.urlsafe()
        secret = "meine weihnacht"
        params = {"yay": "other", "second": "yes", "_key": key}
        query = '&'.join(("GET", "http://www.example.com",
                    urllib.urlencode(params)))
        params["_signature"] = binascii.b2a_base64(
            hmac.new(secret, query, hashlib.sha256).digest())

        self.assertEquals(self.eins_zwo.get(), verify_request("GET",
                    "http://www.example.com", params))

    def test_lists(self):
        key = self.eins_zwo.urlsafe()
        secret = "meine weihnacht"
        params = {"yay": ["other", "peter", "michael"],
                "second": "yes", "_key": key}
        query = '&'.join(("GET", "http://www.example.com",
                    urllib.urlencode(params)))
        params["_signature"] = binascii.b2a_base64(
            hmac.new(secret, query, hashlib.sha256).digest())

        self.assertEquals(self.eins_zwo.get(), verify_request("GET",
                    "http://www.example.com", params))

    def test_unsorted_params(self):
        key = self.eins_zwo.urlsafe()
        secret = "meine weihnacht"
        done_params = "c=b&a=b&_key=" + key
        query = '&'.join(("GET", "http://www.example.com",
                    done_params))
        params = MultiDict(cgi.parse_qsl(
                done_params, keep_blank_values=True,
                strict_parsing=False))
        params["_signature"] = binascii.b2a_base64(
            hmac.new(secret, query, hashlib.sha256).digest())

        self.assertEquals(self.eins_zwo.get(), verify_request("GET",
                    "http://www.example.com", params))

    def test_post(self):
        key = self.other_key.urlsafe()
        secret = "secret souce"
        params = {"yay": "other", "second": "yes", "_key": key}
        query = '&'.join(("POST", "http://www.example.com",
                    urllib.urlencode(params)))
        params["_signature"] = binascii.b2a_base64(
            hmac.new(secret, query, hashlib.sha256).digest())

        self.assertEquals(self.other_key.get(), verify_request("POST",
                    "http://www.example.com", params))

    def test_changed_params(self):
        key = self.eins_zwo.urlsafe()
        secret = "meine weihnacht"
        params = {"yay": "other", "second": "yes", "_key": key}
        query = '&'.join(("GET", "http://www.example.com",
                    urllib.urlencode(params)))
        params["_signature"] = binascii.b2a_base64(
            hmac.new(secret, query, hashlib.sha256).digest())

        # let's play with the params
        params["yay"] = "oupsi"

        self.assertRaises(webapp2.HTTPException,
                verify_request, "GET", "http://www.example.com", params)

if __name__ == "__main__":
    unittest.main()


import pandas
import numpy
import csv
import sys
import event

theory_fname = sys.argv[1]
opt_event_fname = sys.argv[2]
plot_fname = sys.argv[3]
current_fname = sys.argv[4]

df = pandas.read_csv(theory_fname, header=None)
theory_data = df.to_numpy()
theory_spec = event.Event(0, theory_data[0,:])
print("theo mean", theory_spec.mean, "theo var", theory_spec.variance)

df = pandas.read_csv(opt_event_fname, header=None)
opt_data = df.to_numpy()
opt_spec = event.Event(0, opt_data[0,:])

# order is important
[opt_align, dist] = event.alignment2(theory_spec.data, opt_spec.data)

#for i in range(50):
#    print(i, opt_align[i], theory_spec.data[i])

from matplotlib import pyplot as plt
plt.plot(theory_spec.data, label="Theoretical")
plt.plot(opt_align, label="Experimental")
plt.legend()
plt.savefig(plot_fname);

norm_opt_align = opt_spec.de_norm_intensity(opt_align)

seq_len = 42
data_len = len(norm_opt_align)
print("data len", data_len)
bin_size = (data_len - 1) / (seq_len + 1)
wing = 1
print("bin size", bin_size, "wing size", wing)

min_pos = numpy.argmin(norm_opt_align)
min_val = norm_opt_align[min_pos]
print("min", min_val)

current = []

for i in range(seq_len):
    pos = round(bin_size * (i+1))
    sample = norm_opt_align[pos-wing: pos+wing+1]
    mean = numpy.mean(sample)
    #print(i, pos, opt_align[pos])
    current.append(mean - min_val)

with open(current_fname, mode='w') as current_file:
    current_writer = csv.writer(current_file, delimiter=',')
    current_writer.writerow(current)


import cv2
import imageio
import numpy as np

images = []
while True:
    img = np.random.random((250,350))*255
    img = np.array(img , dtype=np.uint8)
    images.append(img)
    cv2.imshow('',img)
    if cv2.waitKey(25) & 0xFF == ord('q'):
        break

imageio.mimsave('Output/tv.gif',images)


from random import randint, seed
INVALID_POSITION = 0
EMPTY_POSITION = 1
ROUND_OVER = 2
PLAY_AGAIN = 3
pos = 0
seed(69)
## @B
## + rozumně sledovatelný kód
## + místy využívá pěkné, efektivní konstrukce
## - míst využívá nepěkné nebo neefektivní konstrukce
## - několik nevhodně pojmenovaných proměnných

def init(size, start):

    return ([start for i in range(size)]+[0],
            [start for i in range(size)]+[0])
## ~ pozor, + vynucuje kopii obou svých argumentů, efektivnější by bylo
## použít append

def play(our, their, position):

    if position not in range(0, len(our) - 1):
        return INVALID_POSITION
## zbytečně neefektivní; Python je hloupý a pokud je position mimo uvedené
## hranice, stejně por každou hodnotu z rozsahu zkontroluje, jestli
## se jí position náhodou nerovná -- obyčejná dvě porovnání by zde byla
## nesrovnatelně efektivnější
## EDIT: ještě mi to vrtalo hlavou -- a zjistila jsem, že pro celá čísla python
## _je_ dostatečně chytrý, aby nezkoušel všechny hodnoty, ale došel k závěru
## na základě několika matematických operací -- uvedený řádek tedy není zásadně
## méně efektivní než obyčejné porovnání -- nicméně porovnání není méně
## efektivní než toto a zároveň je výrazně srozumitelnější -- už jenom proto
## že je na první pohled zřejmé, co se děje a že opravdu jde o efektivní
## řešení; zároveň porovnání funguje efektivně i třeba s desetinnými čísly,
## se kterými už si range chytře neporadí

    if our[position] == 0:
        return EMPTY_POSITION

    shift = our[position]
    our[position] = 0
    length = 2 * len(our) - 1
## výstižnější by bylo pojmenovat tuto proměnnou třeba moves a název shift
## (nebo offset) si nechat místo i v následujícím kódu

    for i in range(position + 1, shift + 1 + position):
## efektivní indexování bez nutnosti kopírovat hrací plochu, výborně! :)

        last_number = (i % length) if i % length < len(our) else (i % length - len(our))
## number v názvu zní spíš, jako by šlo o hodnotu, nicméně proměnná představuje
## index do příslušné hrací plochy -- bylo by vhodné, aby název odrážel, že jde
## o index současného důlku

## bylo by pěkné zarovnat else pod =

        (our if i % length < len(our) else their)[last_number] += 1

    i = (shift + position) % length
## zde už jde (téměř) o index posledního důlku; název by to měl odrážet

    length_their = len(their)
    if i == len(our) - 1:
        return PLAY_AGAIN
## název proměnné je delší a o nic méně popisný než přímo len(their), navíc
## délku seznamu v Pythonu získáme efektivně okamžitě

    elif (i < len(our) and our[last_number] == 1)\
            and (their[length_their - 2 - last_number] != 0):
        our[last_number] = 0
## zbytečný else (elif) po return, stačí přímo if
## navíc zbytečné závorky

        our[-1] += 1 + ((their[length_their - 2 - i]))
        their[length_their - 2 - i] = 0
## zbytečné závorky (dvakrát)

    return ROUND_OVER

def random_choice(our):
    nonzero = [num for num in our[:-1] if num != 0]
    if not nonzero:
## pozor, slice vytváří kopii

        return
## raději explicitně return None -- to, že v Pythonu je None "defaultní"
## vrácená hodnota, není něco, čeho bys chtěl využívat

    random = randint(1, len(nonzero))
    numbers = 0
    position = 0
    while numbers < random:
## elegantnější by bylo si v nonzero pamatovat indexy, ne hodnoty
## a jenom vrátit index na pozici dané random

        if our[position] != 0:
            numbers += 1
        position += 1

    return position - 1

def run_random_game(size, start):
    our, their = init(size, start)

    theirbank = 0
## zbytečná proměnná, stačilo by v podmínce používat čistě their[-1],
## nemusel bys hodnotu pak nastavovat a v cyklu udržovat

    changes = False
## nevypovídající název -- měl by odrážet, že hodnota vyjadřuje, jestli
## na tahu právě je nebo není hráč, který hru začínal

    while sum(our) != theirbank:
        position = random_choice(our)
## ~ výstižnější by bylo nonzero_position

        while position is not None and play(our, their, position) == 3:
            position = random_choice(our)
        if position is None:
            break
        theirbank = their[-1]
        changes = not changes
        our, their = their, our
## místo 3 bys měl rozhodně použít definovanou globální konstantu!
## je žádoucí, aby program nebyl závislý na konkrétních hodnotách konstant,
## když v tomto případě samy o sobě nemají žádný význam (jiný než odlišit se
## od ostatních globálních konstant)

    if changes:
        our, their = their, our
## pěkné :)
    return sum(our), sum(their)

def main():
    # --- init ---
    assert init(6, 3) \
        == ([3, 3, 3, 3, 3, 3, 0], [3, 3, 3, 3, 3, 3, 0])

    assert init(9, 7) \
        == ([7, 7, 7, 7, 7, 7, 7, 7, 7, 0], [7, 7, 7, 7, 7, 7, 7, 7, 7, 0])

    # --- play ---

    our = [3, 0, 6, 0]
    their = [3, 3, 3, 0]
    assert play(our, their, -1) == INVALID_POSITION
    assert our == [3, 0, 6, 0]
    assert their == [3, 3, 3, 0]

    our = [3, 0, 6, 0]
    their = [3, 3, 3, 0]
    assert play(our, their, 0) == PLAY_AGAIN
    assert our == [0, 1, 7, 1]
    assert their == [3, 3, 3, 0]

    our = [3, 0, 6, 0]
    their = [3, 3, 3, 0]
    assert play(our, their, 1) == EMPTY_POSITION
    assert our == [3, 0, 6, 0]
    assert their == [3, 3, 3, 0]

    our = [3, 0, 6, 0]
    their = [3, 3, 3, 0]
    assert play(our, their, 2) == ROUND_OVER
    assert our == [4, 0, 0, 6]
    assert their == [4, 0, 4, 0]

    our = [3, 0, 6, 0]
    their = [3, 3, 3, 0]
    assert play(our, their, 3) == INVALID_POSITION
    assert our == [3, 0, 6, 0]
    assert their == [3, 3, 3, 0]

    # --- random_choice ---

    assert random_choice([1, 2, 3, 4, 0]) in [0, 1, 2, 3]

    assert random_choice([3, 3, 0, 3, 3, 7]) in [0, 1, 3, 4]

    assert random_choice([0, 0, 0, 1]) is None
    for i in range(10):
        for j in range (10):
            print(run_random_game(i,j))

if __name__ == '__main__':
    main()


# string 안에서의 숫자 제거 후 string만 남은 리스트를 출력

# 구현하고 싶은 코드: string을 처음부터 탐색한 다음
# 숫자가 나오면 끊은 다음 리스트 요소로 만들고 싶어요

inputs = "cat32dog16cow5"

def find_string(inputs):
    for i in inputs:
        if i.isdigit():
            print(i)

string_list = find_string(inputs)
print(string_list)

#결과: ['cat', 'dog', 'cow']


import life_of_block
import random

blockchain = [life_of_block.create_genesis_block()]
previous_block = blockchain[0]

num_of_blocks_until_the_end_of_the_world = random.randint(3,20)

for generation in range(0, num_of_blocks_until_the_end_of_the_world):
    new_block = life_of_block.next_block(previous_block)
    blockchain.append(new_block)
    previous_block = new_block

    print(f"New block #{format(new_block.index)} " +
          "has been added to the blockchain.")
    print(f"Hash: {format(new_block.hash)}\n")


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

from odoo import models, fields, api, _
from odoo.exceptions import Warning, UserError

class CreateSingleSource(models.TransientModel):
    _name = 'wiz.create.single.source'
    _description = 'Create Single Source'

    # relations
    requisition_id = fields.Many2one('material.purchase.requisition', string="Requisition")
    vendor_id = fields.Many2one('res.partner', string='Proposed Vendor Name', required=True)

    def create_single_source(self):
        """
        This method Creates Single Source.
        """
        single_source_id = self.env['single.source.configuration'].create({
            'pr_id': self.requisition_id.id,
            'department_id': self.requisition_id.department_id.id,
            'vendor_id': self.vendor_id.id,
        })
        self.requisition_id.single_source_id = single_source_id
        for line in self.requisition_id.requisition_line_ids:
            self.env['single.source.line'].create({
                'source_id':single_source_id.id,
                'product_id': line.product_id.id,
                'description': line.description,
                'qty': line.qty,
                'uom': line.uom.id,
                'unit_price': line.unit_price,
                'sub_total': line.sub_total,
            })
        return True


import json
import random
import re
from collections import defaultdict
from typing import List

import morfeusz2

morf = morfeusz2.Morfeusz()

tags_to_delete = set(
    [
        "burk",
        "conj",
        "comp",
        "num",
        "ppron12",
        "ppron3",
        "pred",
        "prep",
        "siebie",
        "brev",
        "qub",
        "wulg",
        "interj",
    ]
)

def sieve_popularity_dict(popularity_file: str) -> None:
    """ "Sieve popularity dict to get rid of tags_to_delete."""
    with open(popularity_file, "r", encoding="utf-8") as popularity:
        dicti = json.load(popularity)
        words_to_del = set()
        for word in dicti:
            word_tags_set = set()
            for tup in morf.analyse(word):
                further_analysis = (tup[2])[2].split(":")
                for e in further_analysis:
                    word_tags_set.add(e)
            if len(word_tags_set) == 1:
                words_to_del.add(word)
            if len(word_tags_set.intersection(tags_to_delete)) != 0:
                words_to_del.add(word)
        for word in words_to_del:
            del dicti[word]
        with open("sieved_popularity.json", "w", encoding="utf-8") as save:
            json.dump(dicti, save, ensure_ascii=False)

def reverse_popularity_dict(popularity_file: str) -> None:
    """Find the less popular words by reversing the popularity dict"""
    with open(popularity_file, "r", encoding="utf-8") as popularity:
        dicti = json.load(popularity)
        desc_ord = dict(sorted(dicti.items(), key=lambda item: item[1], reverse=True))
        with open("reverse_pop.json", "w", encoding="utf-8") as save:
            json.dump(desc_ord, save, ensure_ascii=False)

def cut_to_n_keys(popularity_file: str, n: int) -> None:
    """Cut the popularity dict only to n chosen keys."""
    with open(popularity_file, "r", encoding="utf-8") as popularity:
        dicti = json.load(popularity)
        n_items = {k: dicti[k] for k in list(dicti.keys())[:n]}
        with open(str(n) + "_popularity_items.json", "w", encoding="utf-8") as save:
            json.dump(n_items, save, ensure_ascii=False)

def sieve_corpus_to_leave_populars(corpus: str, pop_dict: str) -> None:
    """Sieve corpora with popular dict to leave only the popular words."""
    with open(corpus, "r", encoding="utf-8") as corp:
        with open(pop_dict, "r", encoding="utf-8") as popul:
            with open("corpus_with_populars.txt", "w", encoding="utf-8") as f:
                pop_dic = json.load(popul)
                keys_set = set(pop_dic.keys())
                for line in corp:
                    line = line.rstrip()
                    guard = 1
                    for word in tokenize(line):
                        word = word.strip()
                        if word not in keys_set:
                            guard = 0
                            continue
                    if guard == 1:
                        f.write(line + "\n")

def tokenize(line: str) -> List[str]:
    """Tokenize line of text to have just words."""
    text = line.lower()
    pattern = r"\s*\w*\s*"
    return list(filter(None, re.findall(pattern, text)))

def create_indexes_dict() -> None:
    """Create a dict that remembers indexes of chosen words."""
    with open("corpus_with_populars.txt", "r", encoding="utf-8") as corp:
        with open("sieved_popularity.json", "r", encoding="utf-8") as pops:
            pops_dict = json.load(pops)
            keys_set = set(pops_dict.keys())
            indexes = defaultdict(list)
            for index, line in enumerate(corp):
                line = line.strip()
                for word in tokenize(line):
                    word = word.strip()
                    if word in keys_set:
                        indexes[word].append(index)

            for word in indexes:
                val = indexes[word]
                random.shuffle(val)
                indexes[word] = val[:1000]
    with open("index_dict.json", "w", encoding="utf-8") as save:
        json.dump(indexes, save, ensure_ascii=False)

def see_indexes() -> None:
    """Check indexes to see if they're correct."""
    with open("index_dict.json", "r", encoding="utf-8") as save:
        index_dict = json.load(save)
        i = 0
        for j, indexes in index_dict.items():
            print(j, indexes)
            print()
            i += 1
            if i > 5:
                break

def cut_indexes_lists() -> None:
    """Cut the lists of indexes to 1000 places."""
    with open("index_dict.json", "r", encoding="utf-8") as dicti:
        index_dict = json.load(dicti)
        for key in index_dict:
            if len(index_dict[key]) > 1000:
                val = index_dict[key]
                random.shuffle(val)
                index_dict[key] = val[:1000]
    with open("indexes_narrowed.json", "w", encoding="utf-8") as save:
        json.dump(index_dict, save, ensure_ascii=False)


import argparse
import os
import shutil

import mindspore
from mindspore import CheckpointConfig
from tensorboardX import SummaryWriter

from mindediting import create_trainer_by_name
from mindediting.dataset.create_loaders import create_data_loader
from mindediting.deploy.utils.config import Config, merge, parse_cli_to_yaml, parse_yaml
from mindediting.loss import create_loss
from mindediting.models import create_model_by_name
from mindediting.optim import create_optimizer
from mindediting.scheduler import create_scheduler_by_name
from mindediting.utils.callbacks import EvalAsInValPyCallBack, ProfileCallback, TrainingMonitor
from mindediting.utils.device_adapter import get_device_id, get_device_num
from mindediting.utils.init_utils import init_env

def train(cfg, profile):
    init_env(cfg)
    # create dataset
    rank_id = get_device_id()
    group_size = get_device_num()

    # create train data loader
    loader_train = create_data_loader(
        cfg.model.name,
        cfg.dataset,
        cfg.train_pipeline,
        "train",
        cfg.dataset.batch_size,
    )

    # create model
    cfg.mode = "train"
    net, eval_network = create_model_by_name(model_name=cfg.model.name, cfg=cfg)
    cfg.net, cfg.steps_per_epoch = net, loader_train.get_dataset_size()

    # create loss
    loss = create_loss(loss_name=cfg.loss.name, **cfg.loss.cfg_dict)

    # create learning rate schedule
    optimizer_params, learning_rate = create_scheduler_by_name(model_name=cfg.model.name, cfg=cfg)

    # create optimizer
    loss_scale = 1.0 if cfg.loss.amp_level == "O0" else cfg.loss.loss_scale
    optimizer = create_optimizer(
        params=optimizer_params,
        lr=learning_rate,
        opt=cfg.optimizer.name,
        loss_scale=loss_scale,
        **{"beta1": cfg.optimizer.beta1, "beta2": cfg.optimizer.beta2}
    )

    # define callbacks
    save_checkpoint_steps = cfg.train_params.save_epoch_frq * loader_train.get_dataset_size()
    config_ck = CheckpointConfig(
        save_checkpoint_steps=save_checkpoint_steps, keep_checkpoint_max=cfg.train_params.keep_checkpoint_max
    )
    summary_writer = None
    if rank_id == 0:
        summary_writer = SummaryWriter(os.path.join(cfg.train_params.ckpt_save_dir, "summary"))
    callbacks = [mindspore.TimeMonitor()]
    if cfg.train_params.need_val:
        callbacks.append(EvalAsInValPyCallBack(cfg, net, eval_network, summary_writer=summary_writer))
    if profile:
        callbacks.append(ProfileCallback(**cfg.train_params.profile.cfg_dict))
    if rank_id == 0:
        callbacks.append(
            TrainingMonitor(
                cfg.train_params.epoch_size,
                cfg.steps_per_epoch,
                print_frequency=cfg.train_params.print_frequency,
                summary_writer=summary_writer,
            )
        )
        callbacks.append(
            mindspore.ModelCheckpoint(
                prefix=cfg.model.name + "_" + cfg.dataset.dataset_name,
                directory=cfg.train_params.ckpt_save_dir,
                config=config_ck,
            )
        )

    # define trainer
    trainer = create_trainer_by_name(cfg.model.name, net, loss, optimizer, cfg)
    initial_epoch = cfg.train_params.get("initial_epoch", 0)
    print(" training...")
    trainer.train(
        cfg.train_params.epoch_size,
        loader_train,
        dataset_sink_mode=cfg.dataset.dataset_sink_mode,
        callbacks=callbacks,
        initial_epoch=initial_epoch,
    )

    if summary_writer:
        summary_writer.close()

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="default name", add_help=False)
    parser.add_argument("--config_path", type=str, help="Config file path", required=True)
    parser.add_argument("--profile", action="store_true", help="Enables profile callback.")
    known_args, _ = parser.parse_known_args()
    default, helper, choices = parse_yaml(known_args.config_path)
    args = parse_cli_to_yaml(
        parser=parser, cfg=default, helper=helper, choices=choices, cfg_path=known_args.config_path
    )
    final_config = merge(args, default)
    final_config = Config(final_config)
    if get_device_id() == 0:
        os.makedirs(final_config.train_params.ckpt_save_dir, exist_ok=True)
        try:
            shutil.copy(known_args.config_path, final_config.train_params.ckpt_save_dir)
        except shutil.SameFileError:
            pass
    train(final_config, known_args.profile)


class Solution:
    def countCompleteSubarrays(self, nums: List[int]) -> int:
        length = len(set(nums))
        left = 0
        res = 0
        my_dict = defaultdict(int)

        for index,num in enumerate(nums):
            my_dict[num] += 1
            while len(my_dict) == length and left < len(nums):
                res += len(nums)- index
                if nums[left] in my_dict:
                    my_dict[nums[left]] -= 1
                    if my_dict[nums[left]] == 0:
                        del my_dict[nums[left]]
                left += 1

        return res


import sys

# n 개 중에서 m 개를 뽑는 것.
n,m = map(int, input().split())
c = [False]*(n+1) # 사용했는지 안했는지에 대한 표식
a = [0] * m

def go(index, n, m) :
    if index == m :
        sys.stdout.write(' '.join(map(str,a))+ '\n')
        return

    for i in range(1, n+1):
        if c[i] :
            continue

        c[i] = True
        a[index] = i
        go(index+1, n, m)
        c[i] = False

go(0,n,m)


class Solution:
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # soln 1, O(n)
        # 1. adding "val" to the "set" if "val" is not in the "set" => A^0 = A
        # 2. removing "val" from the "set" if "val" is already in the "set" => A^A = 0
        one, two = 0, 0
        for num in nums:
            one = (one ^ num) & ~two
            two = (two ^ num) & ~one
        return one

        # soln 2, O(32n)
        # Iterate over all possible 32 bits and for each num check if this num has non-zero bit on position i with num & (1<<i) == (1<<i) formula.
        # We evaluate this sum modulo 3. Note, that in the end for each bit we can have either 0 or 1 and never 2.
        # Next, update our answer single with evaluated bit.
        # Finally, we need to deal with overflow cases in python: maximum value for int32 is 2^31 - 1, so if we get number more than this value we have negative answer in fact.
        single = 0
        for i in range(32):
            count = 0
            for num in nums:
                if (num >> i) & 1: # count 1 for all num at current bit
                    count += 1
            single |= (count % 3) << i

        return single if single < (1<<31) else single - (1<<32)


from typing import List
from collections import defaultdict
from copy import deepcopy
import heapq

final_pos = {
    1: (0, 0),
    2: (0, 1),
    3: (0, 2),
    4: (1, 0),
    5: (1, 1),
    0: (1, 2),
}

dirs = (
    (0, -1),
    (0, 1),
    (-1, 0),
    (1, 0),
)

class Solution:
    def slidingPuzzle(self, board: List[List[int]]) -> int:

        visited = defaultdict(bool)
        m, n = len(board), len(board[0])
        q = [(self.heuristic_dist(board) + 0, 0, board)]
        target = [
            [1, 2, 3],
            [4, 5, 0],
        ]
        while q:
            heu, cur_dist, board = heapq.heappop(q)
            visited[self.ser(board)] = True
            if board == target:
                return cur_dist

            cur_dist += 1
            i, j = self.zero_pos(board)
            for di, dj in dirs:
                I = i + di
                J = j + dj
                if 0 <= I < m and 0 <= J < n:
                    B = deepcopy(board)
                    B[I][J], B[i][j] = B[i][j], B[I][J]
                    if not visited[self.ser(B)]:
                        heapq.heappush(q, (self.heuristic_dist(B) + cur_dist, cur_dist, B))
        return -1

    def zero_pos(self, board):
        for i, row in enumerate(board):
            for j, v in enumerate(row):
                if v == 0:
                    return i, j
        raise

    def heuristic_dist(self, board):

        ret = 0
        for i, row in enumerate(board):
            for j, v in enumerate(row):
                if v != 0:
                    I, J = final_pos[v]
                    ret += abs(i - I) + abs(j - J)
        return ret

    def ser(self, board):
        return tuple(
            tuple(row)
            for row in board
        )

if __name__ == "__main__":
    assert Solution().slidingPuzzle([[1,2,3],[4,0,5]]) == 1
    assert Solution().slidingPuzzle([[1,2,3],[5,4,0]]) == -1


def solve():
    # Creates a dictionary object to store phonebook.
    phonebook = dict()

    # Iterates through the number of contacts to be stored.
    for _ in range(int(input())):
        name, phone = input().split()
        phonebook[name] = phone

    # Since there is no actual number of queries, i decided to check the end of the queries with a while loop.
    while True:
        try:
            # Takes the query name.
            query_name = input()

            # Searches phonebook for the query name.
            if query_name in phonebook:
                print(f"{query_name}={phonebook[query_name]}")
            else:
                print("Not found")
        except:
            break

if __name__ == "__main__":
    solve()


'''Get Google Chrome bookmark entries.
'''

import csv
import getpass
import json
import sys
from typing import Callable

config = {
    # macOS:
    'chrome_bookmark_path': (
        '/Users/{username}/Library/Application Support/'
        'Google/Chrome/Default/Bookmarks'
    ).format(username=getpass.getuser())
}

def main():
    data = get_chrome_bookmark_data()

    # printer = Printer(RawPrintStrategy())
    # printer = Printer(SimplePrintStrategy())
    printer = Printer(CsvPrintStrategy())

    printer.walk(data)

def get_chrome_bookmark_data() -> dict:
    '''Get the json of user's Chrome bookmark.'''
    with open(config['chrome_bookmark_path']) as f:
        return json.load(f)

def walk_bookmark(entry: dict, callback: Callable) -> None:
    '''Walk through bookmark entry tree.

    Execute a callback function for bookmark entries.
    '''
    if isinstance(entry, list):
        for child in entry:
            walk_bookmark(child, callback)

    if isinstance(entry, dict):
        if 'type' in entry:
            if entry['type'] == 'folder':
                walk_bookmark(entry['children'], callback)
            elif entry['type'] == 'url':
                callback(entry)

class Printer:
    '''Base Printer class for a bookmark entry.

    Includes the following functions.
    - Prints a boomark entry.
    - Stores the count of times the method is invoked.
    '''

    def __init__(self, print_strategy):
        self.print_strategy = print_strategy
        self.count = 0

    def walk(self, data):
        walk_bookmark(data['roots']['bookmark_bar'], self.print)
        walk_bookmark(data['roots']['other'], self.print)
        print('Total: {}'.format(self.count))

    def print(self, entry) -> None:
        self.print_strategy.print(entry)
        self.count += 1

class RawPrintStrategy:
    def print(self, entry) -> None:
        print(entry)

class SimplePrintStrategy:
    def print(self, entry) -> None:
        print('{}: {}'.format(entry['name'], entry['url']))

class CsvPrintStrategy:
    def __init__(self):
        self.writer = csv.writer(sys.stdout)

    def print(self, entry) -> None:
        self.writer.writerow(
            [entry['id'], entry['name'], entry['date_added'], entry['url']]
        )

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
__author__ = 'essepuntato'

import re

class RewriteRuleHandler(object):
    def __init__(self, class_name, r_list=None, urls=()):
        self.urls = urls
        self.class_name = class_name
        self.rr = []
        if r_list is not None:
            self.add_rules(r_list)

    def add_rule(self, p, r, is_last=False):
        self.rr += [(p, r, is_last)]

    def add_rules(self, r_list):
        for r in r_list:
            if len(r) > 2:
                self.add_rule(r[0], r[1], r[2])
            else:
                self.add_rule(r[0], r[1])
            self.urls += ("(" + r[0] + ")", self.class_name)

    def rewrite(self, u):
        res = u
        for p, r, is_last in self.rr:
            if re.search(p, res) is not None:
                res = re.sub(p, r, res)
                if is_last:
                    break
        return res

    def get_urls(self):
        return self.urls


class Solution(object):
    def trap(self, height):
        n = len(height)
        s1, s2 = 0, 0
        max1, max2 = 0, 0
        for i in range(n):
            if height[i] > max1:
                max1 = height[i]
            if height[n - i - 1] > max2:
                max2 = height[n - i - 1]
            s1 += max1
            s2 += max2
        res = s1 + s2 - max1 * len(height) - sum(height)
        return res


from volttron.platform.vip.agent import BasicAgent, Core
from volttron.platform.agent import utils
import logging
import random
import gevent
import traceback
from volttron.platform.messaging import headers as headers_mod
from volttron.platform.messaging.topics import (DRIVER_TOPIC_BASE,
                                                DRIVER_TOPIC_ALL,
                                                DEVICES_VALUE,
                                                DEVICES_PATH)

from volttron.platform.vip.agent.errors import VIPError, Again
from .driver_locks import publish_lock
import datetime

utils.setup_logging()
_log = logging.getLogger(__name__)

class DriverAgent(BasicAgent):
    def __init__(self, parent, config, time_slot, driver_scrape_interval, device_path,
                 group, group_offset_interval,
                 default_publish_depth_first_all=True,
                 default_publish_breadth_first_all=True,
                 default_publish_depth_first=True,
                 default_publish_breadth_first=True,
                 **kwargs):
        super(DriverAgent, self).__init__(**kwargs)
        self.heart_beat_value = 0
        self.device_name = ''
        #Use the parent's vip connection
        self.parent = parent
        self.vip = parent.vip
        self.config = config
        self.device_path = device_path

        self.update_publish_types(default_publish_depth_first_all ,
                                 default_publish_breadth_first_all,
                                 default_publish_depth_first,
                                 default_publish_breadth_first)

        try:
            interval = int(config.get("interval", 60))
            if interval < 1.0:
                raise ValueError
        except ValueError:
            _log.warning("Invalid device scrape interval {}. Defaulting to 60 seconds.".format(config.get("interval")))
            interval = 60

        self.interval = interval
        self.periodic_read_event = None

        self.update_scrape_schedule(time_slot, driver_scrape_interval, group, group_offset_interval)

    def update_publish_types(self, publish_depth_first_all,
                                   publish_breadth_first_all,
                                   publish_depth_first,
                                   publish_breadth_first):
        """Setup which publish types happen for a scrape.
           Values passed in are overridden by settings in the specific device configuration."""
        self.publish_depth_first_all = bool(self.config.get("publish_depth_first_all", publish_depth_first_all))
        self.publish_breadth_first_all = bool(self.config.get("publish_breadth_first_all", publish_breadth_first_all))
        self.publish_depth_first = bool(self.config.get("publish_depth_first", publish_depth_first))
        self.publish_breadth_first = bool(self.config.get("publish_breadth_first", publish_breadth_first))

    def update_scrape_schedule(self, time_slot, driver_scrape_interval, group, group_offset_interval):
        self.time_slot_offset = (time_slot * driver_scrape_interval) + (group * group_offset_interval)
        self.time_slot = time_slot
        self.group = group

        _log.debug("{} group: {}, time_slot: {}, offset: {}".format(self.device_path, group,
                                                                    time_slot, self.time_slot_offset))

        if self.time_slot_offset >= self.interval:
            _log.warning(
                "Scrape offset exceeds interval. Required adjustment will cause scrapes to double up with other devices.")
            while self.time_slot_offset >= self.interval:
                self.time_slot_offset -= self.interval

        #check weather or not we have run our starting method.
        if not self.periodic_read_event:
            return

        self.periodic_read_event.cancel()

        next_periodic_read = self.find_starting_datetime(utils.get_aware_utc_now())

        self.periodic_read_event = self.core.schedule(next_periodic_read, self.periodic_read, next_periodic_read)

    def find_starting_datetime(self, now):
        midnight = now.replace(hour=0, minute=0, second=0, microsecond=0)
        seconds_from_midnight = (now - midnight).total_seconds()
        interval = self.interval

        offset = seconds_from_midnight % interval

        if not offset:
            return now

        previous_in_seconds = seconds_from_midnight - offset
        next_in_seconds = previous_in_seconds + interval

        from_midnight = datetime.timedelta(seconds=next_in_seconds)
        return midnight + from_midnight + datetime.timedelta(seconds=self.time_slot_offset)

    def get_interface(self, driver_type, config_dict, config_string):
        """Returns an instance of the interface"""
        module_name = "platform_driver.interfaces." + driver_type
        module = __import__(module_name,globals(),locals(),[], 0)
        interfaces = module.interfaces
        sub_module = getattr(interfaces, driver_type)
        klass = getattr(sub_module, "Interface")
        interface = klass(vip=self.vip, core=self.core, device_path=self.device_path)
        interface.configure(config_dict, config_string)
        return interface

    @Core.receiver('onstart')
    def starting(self, sender, **kwargs):
        self.setup_device()

        # interval = self.config.get("interval", 60)
        # self.core.periodic(interval, self.periodic_read, wait=None)

        next_periodic_read = self.find_starting_datetime(utils.get_aware_utc_now())

        self.periodic_read_event = self.core.schedule(next_periodic_read, self.periodic_read, next_periodic_read)

        self.all_path_depth, self.all_path_breadth = self.get_paths_for_point(DRIVER_TOPIC_ALL)

    def setup_device(self):

        config = self.config
        driver_config = config["driver_config"]
        driver_type = config["driver_type"]
        registry_config = config.get("registry_config")

        self.heart_beat_point = config.get("heart_beat_point")

        self.interface = self.get_interface(driver_type, driver_config, registry_config)
        self.meta_data = {}

        for point in self.interface.get_register_names():
            register = self.interface.get_register_by_name(point)
            if register.register_type == 'bit':
                ts_type = 'boolean'
            else:
                if register.python_type is int:
                    ts_type = 'integer'
                elif register.python_type is float:
                    ts_type = 'float'
                elif register.python_type is str:
                    ts_type = 'string'

            self.meta_data[point] = {'units': register.get_units(),
                                     'type': ts_type,
                                     'tz': config.get('timezone', '')}

        self.base_topic = DEVICES_VALUE(campus='',
                                        building='',
                                        unit='',
                                        path=self.device_path,
                                        point=None)

        self.device_name = DEVICES_PATH(base='',
                                        node='',
                                        campus='',
                                        building='',
                                        unit='',
                                        path=self.device_path,
                                        point='')

        # self.parent.device_startup_callback(self.device_name, self)

    def periodic_read(self, now):
        #we not use self.core.schedule to prevent drift.
        next_scrape_time = now + datetime.timedelta(seconds=self.interval)
        # Sanity check now.
        # This is specifically for when this is running in a VM that gets
        # suspended and then resumed.
        # If we don't make this check a resumed VM will publish one event
        # per minute of
        # time the VM was suspended for.
        test_now = utils.get_aware_utc_now()
        if test_now - next_scrape_time > datetime.timedelta(seconds=self.interval):
            next_scrape_time = self.find_starting_datetime(test_now)

        _log.debug("{} next scrape scheduled: {}".format(self.device_path, next_scrape_time))

        self.periodic_read_event = self.core.schedule(next_scrape_time, self.periodic_read, next_scrape_time)

        _log.debug("scraping device: " + self.device_name)

        self.parent.scrape_starting(self.device_name)

        try:
            results = self.interface.scrape_all()
            register_names = self.interface.get_register_names_view()
            for point in (register_names - results.keys()):
                depth_first_topic = self.base_topic(point=point)
                _log.error("Failed to scrape point: "+depth_first_topic)
        except (Exception, gevent.Timeout) as ex:
            tb = traceback.format_exc()
            _log.error('Failed to scrape ' + self.device_name + ':\n' + tb)
            return

        # XXX: Does a warning need to be printed?
        if not results:
            return

        utcnow = utils.get_aware_utc_now()
        utcnow_string = utils.format_timestamp(utcnow)
        sync_timestamp = utils.format_timestamp(now - datetime.timedelta(seconds=self.time_slot_offset))

        headers = {
            headers_mod.DATE: utcnow_string,
            headers_mod.TIMESTAMP: utcnow_string,
            headers_mod.SYNC_TIMESTAMP: sync_timestamp
        }

        if self.publish_depth_first or self.publish_breadth_first:
            for point, value in results.items():
                depth_first_topic, breadth_first_topic = self.get_paths_for_point(point)
                message = [value, self.meta_data[point]]

                if self.publish_depth_first:
                    self._publish_wrapper(depth_first_topic,
                                          headers=headers,
                                          message=message)

                if self.publish_breadth_first:
                    self._publish_wrapper(breadth_first_topic,
                                          headers=headers,
                                          message=message)

        message = [results, self.meta_data]
        if self.publish_depth_first_all:
            self._publish_wrapper(self.all_path_depth,
                                  headers=headers,
                                  message=message)

        if self.publish_breadth_first_all:
            self._publish_wrapper(self.all_path_breadth,
                                  headers=headers,
                                  message=message)

        self.parent.scrape_ending(self.device_name)

    def _publish_wrapper(self, topic, headers, message):
        while True:
            try:
                with publish_lock():
                    _log.debug("publishing: " + topic)
                    self.vip.pubsub.publish('pubsub',
                                            topic,
                                            headers=headers,
                                            message=message).get(timeout=10.0)

                    _log.debug("finish publishing: " + topic)
            except gevent.Timeout:
                _log.warning("Did not receive confirmation of publish to "+topic)
                break
            except Again:
                _log.warning("publish delayed: " + topic + " pubsub is busy")
                gevent.sleep(random.random())
            except VIPError as ex:
                _log.warning("driver failed to publish " + topic + ": " + str(ex))
                break
            else:
                break

    def heart_beat(self):
        if self.heart_beat_point is None:
            return

        self.heart_beat_value = int(not bool(self.heart_beat_value))

        _log.debug("sending heartbeat: " + self.device_name + ' ' + str(self.heart_beat_value))

        self.set_point(self.heart_beat_point, self.heart_beat_value)

    def get_paths_for_point(self, point):
        depth_first = self.base_topic(point=point)

        parts = depth_first.split('/')
        breadth_first_parts = parts[1:]
        breadth_first_parts.reverse()
        breadth_first_parts = [DRIVER_TOPIC_BASE] + breadth_first_parts
        breadth_first = '/'.join(breadth_first_parts)

        return depth_first, breadth_first

    def get_point(self, point_name, **kwargs):
        return self.interface.get_point(point_name, **kwargs)

    def set_point(self, point_name, value, **kwargs):
        return self.interface.set_point(point_name, value, **kwargs)

    def scrape_all(self):
        return self.interface.scrape_all()

    def get_multiple_points(self, point_names, **kwargs):
        return self.interface.get_multiple_points(self.device_name,
                                                  point_names,
                                                  **kwargs)

    def set_multiple_points(self, point_names_values, **kwargs):
        return self.interface.set_multiple_points(self.device_name,
                                                  point_names_values,
                                                  **kwargs)

    def revert_point(self, point_name, **kwargs):
        self.interface.revert_point(point_name, **kwargs)

    def revert_all(self, **kwargs):
        self.interface.revert_all(**kwargs)

    def publish_cov_value(self, point_name, point_values):
        """
        Called in the platform driver agent to publish a cov from a point
        :param point_name: point which sent COV notifications
        :param point_values: COV point values
        """
        utcnow = utils.get_aware_utc_now()
        utcnow_string = utils.format_timestamp(utcnow)
        headers = {
            headers_mod.DATE: utcnow_string,
            headers_mod.TIMESTAMP: utcnow_string,
        }
        for point, value in point_values.items():
            results = {point_name: value}
            meta = {point_name: self.meta_data[point_name]}
            all_message = [results, meta]
            individual_point_message = [value, self.meta_data[point_name]]

            depth_first_topic, breadth_first_topic = self.get_paths_for_point(
                point_name)

            if self.publish_depth_first:
                self._publish_wrapper(depth_first_topic,
                                      headers=headers,
                                      message=individual_point_message)
            #
            if self.publish_breadth_first:
                self._publish_wrapper(breadth_first_topic,
                                      headers=headers,
                                      message=individual_point_message)

            if self.publish_depth_first_all:
                self._publish_wrapper(self.all_path_depth,
                                      headers=headers,
                                      message=all_message)

            if self.publish_breadth_first_all:
                self._publish_wrapper(self.all_path_breadth,
                                      headers=headers,
                                      message=all_message)


import json
from textwrap import indent
from task1 import*
from task5 import*
tsk_a=open("task5.json","r+")
tsk_b=json.load(tsk_a)

dict={}
def analys_movie_ganer():
    for i in tsk_b:
        if "Genare" in i:
            a=i["Genare"]
            for j in a:
                if j in dict:
                    dict[j]+=1
                else:
                    dict[j]=1

        print(dict)

    with open("task11.json","w+")as file:
        json.load(dict,file,indent=4)

analys_movie_ganer()