"""
Functions for numerical approximation
"""

import math
from typing import Callable

import numpy as np

def first_derivative(function: Callable, x_point: float, x_step: float) -> float:
    """
    Numerically estimate the first derivative of the given function.

    :param function: A function for which the derivative is approximated.
    :param x_point: X value where to evaluate derivative
    :param x_step: X step size to use for the evaluation. Smaller value will
    give an estimate with less error.
    :returns: An approximation of the derivative at x_point, as a float
    """

    # The formula for approximating with error O(h^2) is evaluated and returned.
    # The error grows exponentially with step size x_step.
    return (function(x_point + x_step) - function(x_point - x_step)) / (2 * x_step)

def second_derivative(function: Callable, x_point: float, x_step: float):
    """
    Numerically estimate the second derivative of the given function.

    :param function: A function for which the derivative is approximated.
    :param x_point: X value where to evaluate derivative
    :param x_step: X step size to use for the evaluation. Smaller value will
    give an estimate with less error.
    :returns: An approximation of the derivative at x_point, as a float
    """
    return (function(x_point + x_step) + function(x_point - x_step) -
            2*function(x_point)) / x_step**2

def riemann_sum(function: Callable, num_points: int, x_start: float, x_stop: float) -> float:
    """
    Implements Riemann sum formula for approximating an intergral numerically.

    The Riemann sum assumes that the integrated function is (approximately) a
    constant in each small interval. Hence accuracy should improve with
    increasing N (num_points).

    :param function: Function for which the integral is evaluated
    :param num_points: Number of approximation intervals. An integer is expect.
    If a float is given, will truncate to an integer
    :param x_start: X coordinate for beginning of integration interval.
    :param x_stop: X coordinate for ending of integration interval.
    """

    # Make sure an integer amount of approximation points is given
    num_points = int(num_points)

    # Then form an array of evaluation points in uniform grid.
    # This way, we will always use the point at the beginning (left) of an interval.
    points = np.linspace(x_start, x_stop, num_points)
    # We can also easily get delta x form the resulting array
    delta_x = points[1] - points[0]

    # The formula is simple enough to be computed and returned on one line.
    # Use Python's list comprehension to evaluate function at evaluation
    # points in the given range, then sum the points weighted by step size.
    return sum([function(x_i)*delta_x for x_i in points])

def trapezoid_rule(function: Callable, num_points: int, x_start: float, x_stop: float) -> float:
    """
    Implements Trapezoid rule formula for approximating an intergral numerically.

    Accuracy should improve with increasing N (num_points).

    :param function: Function for which the integral is evaluated
    :param num_points: Number of approximation intervals. An integer is expect.
    If a float is given, will truncate to an integer
    :param x_start: X coordinate for beginning of integration interval.
    :param x_stop: X coordinate for ending of integration interval.
    """

    # Make sure an integer amount of approximation points is given
    num_points = int(num_points)

    # Then form an array of evaluation points and find the step size (delta x)
    points = np.linspace(x_start, x_stop, num_points)
    delta_x = points[1] - points[0]

    # Use Python's list comprehension to iterate over evaluation points x_i.
    # At each point, effectively we add the mean of the function in the
    # interval, but division by 2 can be taken out of the summation. Intervals
    # are weighted with step size (delta x).
    return 0.5 * sum([(function(x_i) + function(x_i+delta_x))*delta_x for x_i in points])

def simpson_rule(function: Callable, num_points: int, x_start: float, x_stop: float) -> float:
    """
    Implements Simpson rule formula for approximating an intergral numerically.

    Accuracy should improve with increasing N (num_points).

    :param function: Function for which the integral is evaluated
    :param num_points: Number of approximation intervals. An integer is expect.
    If a float is given, will truncate to an integer
    :param x_start: X coordinate for beginning of integration interval.
    :param x_stop: X coordinate for ending of integration interval.
    """

    # Make sure an integer amount of approximation points is given
    num_points = int(num_points)

    # Then form an array of evaluation points and find the step size (delta x)
    points = np.linspace(x_start, x_stop, num_points)
    delta_x = points[1] - points[0]

    # We need to consider whether there is an even or odd number of intervals.
    # If we divide the number of points in two and truncate to integer, we get a
    # minimum range that we always need to compute anyway.
    half_points = int(num_points / 2)

    # To make the following formulation a bit prettier (shorter) we can evaluate function
    # at every point already.
    values = [function(x) for x in points]

    # Calculate an intermediate result with an even grid. We now iterate only
    # until N/2 - 1 points, and this is accounted for in the range() function.
    # Use the index of current iteration point to access correct coordinates
    # from the value array.
    even_grid_sum = (delta_x / 3) * sum(
        [values[2 * ind] + 4 * values[2 * ind + 1] + values[2 * ind + 2]
         for ind in range(half_points - 1)])
    # This can be checked with the modulus operator
    if num_points % 2 == 0: # Even

        return even_grid_sum

    # Add the last slice, where N is the index of the last point, we subtract 1
    # from the number of points due to zero-based indexing
    N = num_points - 1
    return even_grid_sum + (delta_x / 12) * (
        -1 * function(points[N - 2]) + 8 * function(points[N - 1]) + 5 *
        function(points[N]))

def test_first_derivative(relative_tolerance: float = 0.01) -> bool:
    """
    Test the first_derivative function.

    :param relative_tolerance: Tolerance for testing the accuracy of
    first_derivative function. A relative tolerance is used. Defaults to 0.01 (1%).
    :returns: Boolean True if first_derivative returns a correct approximation,
    else return False
    """

    # First define a function that is used for testing. Let's use something for
    # which the analytical solution of first derivative is available.
    # I'll use the lambda formalism because it is a neat and readable way of
    # defining simple functions, for example here we will use f(x) = x^2 + x.
    test_fun = lambda x: x**2 + x

    # Let's test first_derivative at x = 1 and use a very small step.
    # The first derivative of this function is 2x + 1.
    # At x = 1, the first derivative of our test_fun is 3.
    x_test = 1.
    x_step = 1e-2
    true_result = 3.

    # Get the estimate from our approximation:
    estimate = first_derivative(test_fun, x_test, x_step)

    # Since our approximation cannot be assumed to give a perfect result, we
    # cannot do a simple comparison of numerical values with '=='. Instead we
    # need to use a comparison function that accepts a tolerance. We will return
    # the output of the comparison directly
    return math.isclose(true_result, estimate, rel_tol=relative_tolerance)

def test_second_derivative(relative_tolerance: float = 0.01) -> bool:
    """
    Test the second_derivative function.

    :param relative_tolerance: Tolerance for testing the accuracy of
    second_derivative function. A relative tolerance is used. Defaults to 0.01 (1%).
    :returns: Boolean True if second_derivative returns a correct approximation,
    else return False
    """

    # Define a test function for which analytical solution is known.
    # I'll use f(x) = x^3 + x^2 + x. The first derivative is
    # 3x^2 + 2x + 1 and the second is 6x + 2. At test point x=1 the second
    # derivative should evaluate to 8.
    test_fun = lambda x: x**3 + x**2 + x
    x_test = 1.
    x_step = 1e-2
    true_result = 8.

    # Return the result of comparison with a tolerance
    return math.isclose(true_result,
                        second_derivative(test_fun, x_test, x_step),
                        rel_tol=relative_tolerance)

def test_riemann_sum(relative_tolerance: float = 0.01) -> bool:
    """
    Test the riemann_sum function.

    :param relative_tolerance: Tolerance for testing the accuracy of
    the function. A relative tolerance is used. Defaults to 0.01 (1%).
    :returns: Boolean True if function returns a correct approximation,
    else return False
    """

    # Define a test function, use something for which the analytical result is
    # known. For example integrating sin(x) from zero to pi should give 2.
    num_points = 1000
    x_start = 0
    x_stop = math.pi
    true_result = 2.

    # Return the result of comparison with a tolerance
    return math.isclose(true_result,
                        riemann_sum(math.sin, num_points, x_start, x_stop),
                        rel_tol=relative_tolerance)

def test_trapezoid_rule(relative_tolerance: float = 0.01) -> bool:
    """
    Test the trapezoid_rule function.

    :param relative_tolerance: Tolerance for testing the accuracy of
    the function. A relative tolerance is used. Defaults to 0.01 (1%).
    :returns: Boolean True if function returns a correct approximation,
    else return False
    """

    # Define a test function, use something for which the analytical result is
    # known. For example integrating sin(x) from zero to pi should give 2.
    num_points = 1000
    x_start = 0.
    x_stop = math.pi
    true_result = 2.

    # Return the result of comparison with a tolerance
    return math.isclose(true_result,
                        trapezoid_rule(math.sin, num_points, x_start, x_stop),
                        rel_tol=relative_tolerance)

def test_simpson_rule(relative_tolerance: float = 0.01) -> bool:
    """
    Test the simpson_rule function.

    :param relative_tolerance: Tolerance for testing the accuracy of
    the function. A relative tolerance is used. Defaults to 0.01 (1%).
    :returns: Boolean True if function returns a correct approximation,
    else return False
    """

    # Define a test function, use something for which the analytical result is
    # known. For example integrating sin(x) from zero to pi should give 2.
    num_points = 99
    x_start = 0
    x_stop = math.pi
    true_result = 2.

    # Return the result of comparison with a tolerance
    return math.isclose(true_result,
                        simpson_rule(math.sin, num_points, x_start, x_stop),
                        rel_tol=relative_tolerance)

def main():
    """
    doc
    """
    first_deriv_test_res = test_first_derivative(1e-4)
    print("Test result for function first_derivate() is {}".format(
        first_deriv_test_res))

    second_deriv_test_res = test_second_derivative(1e-4)
    print("Test result for function second_derivate() is {}".format(
        second_deriv_test_res))

    riemann_test_res = test_riemann_sum(1e-4)
    print("Test result for function riemann_sum() is {}".format(
        riemann_test_res))

    trapezoid_test_res = test_trapezoid_rule(1e-4)
    print("Test result for function trapezoid_rule() is {}".format(
        trapezoid_test_res))

    simpson_test_res = test_simpson_rule(1e-4)
    print("Test result for function simpson_rule() is {}".format(
        simpson_test_res))

if __name__ == "__main__":
    main()


from warcaby.board import Board
from warcaby.config import BLACK, WHITE
from random import randint

if __name__ == "__main__":
    game = Board()

    # x = int(input("x: "))
    # y = int(input("y: "))
    x = 5
    y = 5
    my_pawn = game.get_pawn(x, y)
    moves = my_pawn.get_moves()
    for i in range(len(moves)):
        print(f"id: {i} -> {moves[i]}")
    move_id = int(input("option: "))
    my_pawn.move(moves[move_id])

    enemy_pawn = game.get_pawn(7, 3)
    enemy_moves = enemy_pawn.get_moves()
    enemy_move = enemy_moves[randint(0, len(enemy_moves) - 1)]
    enemy_pawn.move(enemy_move)


st = input()
if len(st) == 3:
    print(st[1])
elif len(st) == 2:
    print("")
else:
    li = list(map(int, st[1:len(st)-1].split(',')))
    for i in range(len(li)-2):
        if li[i]<li[i+1]:
            if i == 0:
                print(li[i])
            else:
                if li[i+1]<li[i+2]:
                    print(li[i+1])


# -*- coding: utf-8 -*-
from cadnano.assembly import Assembly
from cadnano.proxies.cnproxy import UndoCommand
from cadnano.part import Part
from cadnano.objectinstance import ObjectInstance
from cadnano.proxies.cnobject import CNObject

class RemoveInstanceCommand(UndoCommand):
    """
    Undo ready command for removing an instance.

    Args:
        cnobj:
        obj_instance: Object instance remove
    """

    def __init__(self,  cnobj: CNObject,
                        obj_instance: ObjectInstance):
        super(RemoveInstanceCommand, self).__init__("remove instance")
        self._items = (cnobj, cnobj.document(), obj_instance)
    # end def

    def redo(self):
        cnobj, doc, obji = self._items
        if cnobj._canRemove():
            if isinstance(cnobj, Part):
                cnobj.partRemovedSignal.emit(obji)
            else:
                cnobj.assemblyRemovedSignal.emit(obji)
        cnobj._decrementInstance(obji)
    # end def

    def undo(self):
        cnobj, doc, obji = self._items
        cnobj._incrementInstance(doc, obji)
        if cnobj._canReAdd():
            if isinstance(cnobj, Part):
                doc.documentPartAddedSignal.emit(doc, obji)
            elif isinstance(cnobj, Assembly):
                doc.documentAssemblyAddedSignal.emit(doc, obji)
            else:
                raise NotImplementedError
    # end def
# end class


from starthinker_airflow.factory import DAG_Factory

# Add the following credentials to your Airflow configuration.
USER_CONN_ID = "starthinker_user" # The connection to use for user authentication.
GCP_CONN_ID = "starthinker_service" # The connection to use for service authentication.

INPUTS = {
  'auth_read': 'user',  # Credentials used for reading data.
  'account_ids': [],
  'dataset': '',  # Dataset to be written to in BigQuery.
}

TASKS = [
  {
    'ga_settings_download': {
      'description': 'Will create tables with format ga_* to hold each endpoint via a call to the API list function.',
      'auth': {
        'field': {
          'name': 'auth_read',
          'kind': 'authentication',
          'order': 1,
          'default': 'user',
          'description': 'Credentials used for reading data.'
        }
      },
      'accounts': {
        'field': {
          'name': 'account_ids',
          'kind': 'integer_list',
          'order': 1,
          'default': [
          ]
        }
      },
      'dataset': {
        'field': {
          'name': 'dataset',
          'kind': 'string',
          'order': 2,
          'default': '',
          'description': 'Dataset to be written to in BigQuery.'
        }
      }
    }
  }
]

DAG_FACTORY = DAG_Factory('ga_timeline', { 'tasks':TASKS }, INPUTS)
DAG_FACTORY.apply_credentails(USER_CONN_ID, GCP_CONN_ID)
DAG = DAG_FACTORY.execute()

if __name__ == "__main__":
  DAG_FACTORY.print_commandline()


# Александр LyraX: 11. Дано натуральное число A > 1. Определите, каким по счету числом Фибоначчи
# является, то есть выведите такое число n, что φ(n)=A. Если А не является числом Фибоначчи, выведите число -1.
number = int(input("Введите число: "))
last_number = 1
pre_last_number = 1
current_index = 2
current_number = 1
while current_number <= number:
    current_number = last_number + pre_last_number
    # print(current_number)
    pre_last_number = last_number
    last_number = current_number
    current_index += 1

    if current_number == number:
        print(current_index)
        break
else:
    print(-1)


#! Python 3
# opencv_demo03.py
# 09/07/2018 sample created
#--------------------------
import os
import cv2
import glob

basedir = os.path.abspath(os.path.dirname(__file__))
os.chdir(basedir)

images=glob.glob("*.jpg")

for image in images:
    img=cv2.imread(image,-1)
    #re=cv2.resize(img,(200,100))
    re=cv2.resize(img,(int(img.shape[1]/6),int(img.shape[0]/6)))
    cv2.imshow(image,re)
    cv2.imwrite("resized_"+image,re)

cv2.waitKey(0)
cv2.destroyAllWindows()


import urllib2
import json
import random

def lambda_handler(event, context):
    """ Route the incoming request based on type (LaunchRequest, IntentRequest,
    etc.) The JSON body of the request is provided in the event parameter.
    """
    print("event.session.application.applicationId=" +
          event['session']['application']['applicationId'])

    """
    Uncomment this if statement and populate with your skill's application ID to
    prevent someone else from configuring a skill that sends requests to this
    function.
    """
    # if (event['session']['application']['applicationId'] !=
    #         "amzn1.echo-sdk-ams.app.[unique-value-here]"):
    #     raise ValueError("Invalid Application ID")

    if event['session']['new']:
        on_session_started({'requestId': event['request']['requestId']},
                           event['session'])

    if event['request']['type'] == "LaunchRequest":
        return on_launch(event['request'], event['session'])
    elif event['request']['type'] == "IntentRequest":
        return on_intent(event['request'], event['session'])
    elif event['request']['type'] == "SessionEndedRequest":
        return on_session_ended(event['request'], event['session'])

def on_session_started(session_started_request, session):
    """ Called when the session starts """

    print("on_session_started requestId=" + session_started_request['requestId']
          + ", sessionId=" + session['sessionId'])

def on_launch(launch_request, session):
    """ Called when the user launches the skill without specifying what they
    want
    """

    print("on_launch requestId=" + launch_request['requestId'] +
          ", sessionId=" + session['sessionId'])
    # Dispatch to your skill's launch
    return get_story()

def on_intent(intent_request, session):
    """ Called when the user specifies an intent for this skill """

    print("on_intent requestId=" + intent_request['requestId'] +
          ", sessionId=" + session['sessionId'])

    intent = intent_request['intent']
    intent_name = intent_request['intent']['name']

    # Dispatch to your skill's intent handlers
    if intent_name == "StoryTeller":
        return get_icebreaker_story(intent, session)
    else:
        raise ValueError("Invalid intent")

def on_session_ended(session_ended_request, session):
    """ Called when the user ends the session.

    Is not called when the skill returns should_end_session=true
    """
    print("on_session_ended requestId=" + session_ended_request['requestId'] +
          ", sessionId=" + session['sessionId'])
    # add cleanup logic here

#store mp3 on s3 with a suffix 0-5 to get random samples
def getUrl():
    #return "https://s3.amazon.com/gwc/sample_" + random.randint(0, 5) + ".mp3"
    return "https://s3.amazonaws.com/audible-girls-who-code/dreamhouse.mp3"

def get_icebreaker_story(intent, session):

    url = getUrl()
    output = "<speak> Girls who code welcome to Audible. Here is the story you requested:  <break time=\"1s\"/> <audio src=\""  + url + "\"/>  </speak>"
    card_title = intent['name']
    session_attributes = {}
    should_end_session = True
    reprompt_text = 'Please ask me to tell a story'

    return build_response(session_attributes, build_speechlet_response(
          card_title, output, reprompt_text, should_end_session))

def get_story(intent, session):
    asin = 'B0118CYHCK'   #TODO: get random ASIN

    url = 'https://api.audible.com/1.0/catalog/products/' + asin + '?response_groups=sample'
    response = urllib2.urlopen(url)
    data = json.load(response)
    offset = 10000;
    sample_url = data['product']['sample_url']

    card_title = intent['name']
    session_attributes = {}
    should_end_session = True
    reprompt_text = 'Please ask me to tell a story'

    return build_response(session_attributes, build_audioplayer_speechlet_response(
          card_title, reprompt_text, should_end_session, sample_url, offset))

# --------------- Helpers that build all of the responses ----------------------
# ADD AudioPlayer here

def build_speechlet_response(title, output, reprompt_text, should_end_session):
    return {
        'outputSpeech': {
            'type': 'SSML',
            'ssml': output
        },
        'card': {
            'type': 'Simple',
            'title': 'SessionSpeechlet - ' + title,
            'content': 'SessionSpeechlet - ' + output
        },
        'reprompt': {
            'outputSpeech': {
                'type': 'PlainText',
                'text': reprompt_text
            }
        },
        'shouldEndSession': should_end_session
    }

def build_audioplayer_speechlet_response(title, reprompt_text, should_end_session, audioURL, offset):
    return {
        'directives': [ {
           'type': 'AudioPlayer.Play',
           'playBehavior': 'REPLACE_ALL', #Setting to REPLACE_ALL means that this track will start playing immediately
           'audioItem': {
                'stream': {
                    'url': audioURL,
                    'token': "0", #Unique token for the track - needed when queueing multiple tracks
                    'expectedPreviousToken': None, # The expected previous token - when using queues, ensures safety
                    'offsetInMilliseconds': offset
                }
            }
        }],
        'card': {
            'type': 'Simple',
            'title': 'SessionSpeechlet - ' + title,
            'content': 'SessionSpeechlet - ' + 'Test'
        },
        'reprompt': {
            'outputSpeech': {
                'type': 'PlainText',
                'text': reprompt_text
            }
        },
        'shouldEndSession': should_end_session
    }

def build_response(session_attributes, speechlet_response):
    return {
        'version': '1.0',
        'sessionAttributes': session_attributes,
        'response': speechlet_response
    }


from collections import Counter

def solution(str1, str2):
    # 알파벳 대문자 아스키 코드 값들 리스트
    alpha = [k for k in range(65, 91)]

    # 두글자씩 끊어서 다중집합 생성, 알파벳 이외의 문자가 삽입된 경우 제외(아스키 코드로 알파벳인지 판별)
    strlist = [str1, str2]
    strcombi = [[] for _ in range(2)]
    for i in range(len(strlist)):
        strlist[i] = strlist[i].upper()
        for j in range(len(strlist[i])-1):
            if ord(strlist[i][j]) in alpha and ord(strlist[i][j+1]) in alpha:
                strcombi[i].append((strlist[i][j], strlist[i][j+1]))

    # 다중집합 내의 원소 값들의 갯수 계산(원소(key)-갯수(value) 딕셔너리)
    str1info = Counter(strcombi[0])
    str2info = Counter(strcombi[1])

    # 키 값인 원소 값만 추출 후 교집합, 합집합 처리
    str1key = list(str1info.keys())
    str2key = list(str2info.keys())

    gyolist = list(set(str1key).intersection(set(str2key)))
    haplist = list(set(str1key).union(set(str2key)))

    # 집합 A와 집합 B가 모두 공집합일 경우 J(A, B) = 1로 정의한다는 예외 설정
    if len(str1info)==0 and len(str2info)==0:
        return 65536

    # 자카드 유사도 계산
    gyo = 0
    for x in gyolist:
        gyo += min(str1info[x], str2info[x])

    hap = 0
    for y in haplist:
        if y in str1key and y in str2key:
            hap += max(str1info[y], str2info[y])
        elif y in str1key:
            hap += str1info[y]
        else:
            hap += str2info[y]

    answer = int((gyo / hap) * 65536)

    return answer

str1 = 'FRANCE'
str2 = 'french'
# str1 = 'A+C'
# str2 = 'DEF'
# result: 0
print(solution(str1, str2))


from bs4 import BeautifulSoup
import urllib
import os

def page_exists(url):
    local_filename, headers = urllib.request.urlretrieve(url)
    html = open(local_filename)
    soup = BeautifulSoup(html, "html.parser")
    next = soup.find_all("a", class_="pagInfo-page-numbers-next empty")
    html.close()
    os.remove(local_filename)

    if len(next) == 0:
        return True
    else:
        return False

def get_num_dished(cuisine):
    url = "https://www.bbc.com/food/recipes/search?cuisines[]=" + cuisine
    local_filename, headers = urllib.request.urlretrieve(url)
    html = open(local_filename)
    soup = BeautifulSoup(html, "html.parser")
    text = str(soup.find_all("div", id="queryBox"))
    text = text.split("
")[1].split(" ")[0]
    return int(text)

def det_add_dishes_dict(cuisine):
    dict_add_dish = {}
    with open("/home/umberto/Desktop/NoLinkIngr/" + cuisine + ".txt") as file:
        for line in file:
            line = line.replace("\n", "")
            name = line.split("| ")[0]
            new_name = line.split("| ")[1]
            dict_add_dish[name.replace(" ", "")] = new_name

    return dict_add_dish

#
cuisines = [#"african", "american", "british", "caribbean",
            #"chinese", "east_european", "french", "greek",
           #"indian", "irish", "italian", "japanese",
           #"korean",
            "mexican", "nordic", "north_african",
           "pakistani", "portuguese", "south_american",
           "spanish", "thai_and_south-east_asian",
           "turkish_and_middle_eastern"]

recepies_dataset = "/home/umberto/Desktop/data/DetasetRecepies/"
#images_dataset = "/home/umberto/Desktop/DatasetImages/"

file_url = open("/home/umberto/Desktop/data/urls.csv", "a")

for cuisine in cuisines:
    num_of_dishes_for_page = 15
    num_dished = get_num_dished(cuisine)
    print("Current letter: ", cuisine, "  --  num of dishes: ", num_dished)

    dataset_name = recepies_dataset + cuisine + ".csv"
    dataset = open(dataset_name, "w")

    upp = int(num_dished/num_of_dishes_for_page)
    if num_dished % num_of_dishes_for_page != 0:
        upp += 1

    dict_add_dish = det_add_dishes_dict(cuisine)

    for i in range(1, upp+1):
        url = "https://www.bbc.com/food/recipes/search?page=" + str(i) +"&cuisines%5B0%5D=" + cuisine + "&sortBy=lastModified"
        local_filename, headers = urllib.request.urlretrieve(url)
        html = open(local_filename)
        soup = BeautifulSoup(html, "html.parser")

        for dish in soup.find_all("div", class_="left with-image"):
            domain = "https://www.bbc.com"
            link = str(dish).split("href=")[1].split("\"")[1]
            name = str(dish).split("")[0].split(">")[-1]

            url2 = domain + link
            file, h = urllib.request.urlretrieve(url2)
            html2 = open(file)
            soup2 = BeautifulSoup(html2, "html.parser")
            list_ingr = ""

            for ingr in soup2.find_all("a", class_="recipe-ingredients__link"):
                list_ingr += str(ingr).split(">")[1][:-3] + ";"

            for ingr in soup2.find_all("li", class_="recipe-ingredients__list-item"):
                if "" not in str(ingr):
                    name_ing = str(ingr).split("<")[1].split(">")[-1]
                    if name_ing != "":
                        dict_value = dict_add_dish[name_ing.replace(" ", "")]
                        if dict_value != " ":
                            list_ingr += dict_value + ";"

            dataset.write(name + ";" + list_ingr + "\n")
            file_url.write(name + ";" + url2 + "\n")

            #imm = soup2.find_all("div", class_="responsive-image-container__16/9")[0]
            #link_imm = str(imm).split("src=")[1].split("\"")[1]

            #if not os.path.exists(images_dataset + cuisine):
            #    os.makedirs(images_dataset + cuisine)

            #urllib.request.urlretrieve(link_imm, images_dataset + cuisine + "/" + name + ".jpg")

            html2.close()
            os.remove(file)

        file_url.flush()

        html.close()
        os.remove(local_filename)
    dataset.close()
file_url.close()


#!/usr/bin/env python3
import rospy
import math
from geometry_msgs.msg import Twist
from ackermann_msgs.msg import AckermannDriveStamped

class TwistToAckermann:
    def __init__(self):
        # Init node
        rospy.init_node('twist_converter_node', anonymous=False)

        # Get node name
        self.node_name = rospy.get_name()

        self._remote = False
        self._v = 0.0
        self._steer = 0.0

        # Get ros params
        self.get_ros_params()

        self.sub_twist_cmd = rospy.Subscriber(self.twist_cmd_topic, Twist, self.twist_callback, queue_size=1)
        self.sub_twist_man = rospy.Subscriber('tab_vel', Twist, self.twist_tab_callback, queue_size=1)
        self.pub_acker_cmd = rospy.Publisher(self.ackermann_cmd_topic, AckermannDriveStamped, queue_size=1)

    def tiwst_convert_to_steering(self, v, omega):
        if omega == 0 or v == 0:
            return 0
        radius = v / omega
        return math.atan(self.wheelbase / radius)

    def sending(self, v, steering):
        msg = AckermannDriveStamped()
        msg.header.stamp = rospy.Time.now()
        msg.header.frame_id = self.frame_id
        msg.drive.steering_angle = steering
        msg.drive.speed = v
        self.pub_acker_cmd.publish(msg)

    def twist_callback(self, twist_msg):
        # reference https://github.com/rst-tu-dortmund/teb_local_planner/blob/melodic-devel/scripts/cmd_vel_to_ackermann_drive.py
        v = twist_msg.linear.x
        if self.cmd_angle_instead_rotvel:
            if v < 0 and twist_msg.angular.z != 0:
                steering = self.tiwst_convert_to_steering(v, (twist_msg.angular.z * -1))
            else:
                steering = self.tiwst_convert_to_steering(v, twist_msg.angular.z)
        else:
            steering = twist_msg.angular.z
        if self._remote is False:
            self.sending(v, steering)

    def twist_tab_callback(self, twist_msg):
        v = twist_msg.linear.x
        steering = twist_msg.angular.z
        if steering != 0 or v != 0:
            self._remote = True
            self.sending(v, steering)
        else:
            self._remote = False

    def get_ros_params(self):
        self.twist_cmd_topic = rospy.get_param(self.node_name + '/twist_cmd_topic', 'cmd_vel')
        self.ackermann_cmd_topic = rospy.get_param(self.node_name + '/ackermann_cmd_topic', 'ackermann_cmd')
        self.wheelbase = rospy.get_param(self.node_name + '/wheelbase', 1.0)
        self.frame_id = rospy.get_param(self.node_name + '/frame_id', 'odom')
        self.cmd_angle_instead_rotvel = rospy.get_param('/move_base/TebLocalPlannerROS/cmd_angle_instead_rotvel', True)

    def run(self):
        rospy.spin()

if __name__ == '__main__':
    twist_to_ack = TwistToAckermann()
    try:
      twist_to_ack.run()
    except rospy.ROSInterruptException:
        rospy.loginfo('TwistToAckermann_node exit.')


import sys
sys.stdin = open('input.txt')

def solution(N, alien_list):
    def translator(number):
        # 외계어로 번역
        if type(number) == int:
            if number == 0:
                return 'ZRO'
            elif number == 1:
                return 'ONE'

        # 사람말로 번
        elif type(number) == str:
            if number == 'ZRO':
                return 0

        # translator 함수 하나를 두번 map하면 끝!
        return ' '.join(map(translator(sorted(list(map(translator, alien_list))))))

        # 근데 보기 너무 숭하니까 나눠서 적자
        human_list = list(map(translator, alien_list))
        human_list.sort()
        sorted_alien_list = map(translator, human_list)
        return ' '.join(sorted_alien_list)

    aliens = ["ZRO", "ONE", "TWO", "THR", "FOR", "FIV", "SIX", "SVN", "EGT", "NIN"]

T = int(input())
for tc in range(1, T+1):
    N= int(input().split()[1])

    print('#{}\n{}'.format(tc, solution(N, input().split())))


lst = list()
sortlst = list()

fname = input("Enter file name: ")
fh = open(fname)

for line in fh :
  line = line.rstrip()
  lst = line.split()
  for w in lst :
    if w not in sortlst :
      sortlst.append(w)
      continue

sortlst.sort()
print(sortlst)


from machine import Pin
from time import sleep
import utime

red = Pin(19, Pin.OUT)
grn = Pin(20, Pin.OUT)
blu = Pin(21, Pin.OUT)
led = Pin(25, Pin.OUT)

red.off()
grn.off()
blu.off()
epoch = 1671790536
while True:
    epoch = epoch + 1
    print("[From Pico-W-Go] Toggle at " + str(utime.gmtime(epoch)))
    led.toggle()
    red.off()
    blu.toggle()
    sleep(0.5)
    led.toggle()
    blu.off()
    red.toggle()
    sleep(0.5)


from fer import FER2013
from torch.autograd import Variable
from models import *
import torch
import torch.nn as nn
import transforms
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
import utils

cut_size = 44
bs = 1
model_path = 'FER2013_Resnet18/PublicTest_model.t7'

epls = [0.001 * i for i in range(11)]

transform_train = transforms.Compose([
    transforms.RandomCrop(44),
    transforms.RandomHorizontalFlip(),
    transforms.ToTensor(),
])

transform_test = transforms.Compose([
    transforms.CenterCrop(cut_size),
    transforms.ToTensor(),
])

transform_eval = transforms.Compose([
    transforms.TenCrop(cut_size),
    transforms.Lambda(lambda crops: torch.stack([transforms.ToTensor()(crop) for crop in crops])),
])
tbs = 32
trainset = FER2013(split='Training', transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=tbs, shuffle=True, num_workers=1)
PublicTestset = FER2013(split='PublicTest', transform=transform_eval)
PublicTestloader = torch.utils.data.DataLoader(PublicTestset, batch_size=tbs, shuffle=False, num_workers=1)
PrivateTestset = FER2013(split='PrivateTest', transform=transform_eval)
PrivateTestloader = torch.utils.data.DataLoader(PrivateTestset, batch_size=tbs, shuffle=False, num_workers=1)
criterion = nn.CrossEntropyLoss()
best_PublicTest_acc = 0  # best PublicTest accuracy
best_PublicTest_acc_epoch = 0
best_PrivateTest_acc = 0  # best PrivateTest accuracy
best_PrivateTest_acc_epoch = 0

def fgsm_attack(img, eps, data_grad):
    sign_data_grad = data_grad.sign()
    perturbed_img = img + eps * sign_data_grad
    perturbed_img = torch.clamp(perturbed_img, 0, 1)
    return perturbed_img

def test(model, device, test_loader, eps):
    correct = 0
    adv_egs = []
    for data, target in test_loader:
        # batch_size, ncrops, c, h , w = np.shape(data)
        # data = data.view(-1, c, h, w)

        data, target = data.to(device), target.to(device)
        data.requires_grad = True
        output = model(data)
        init_pred = output.max(1, keepdim=True)[1]
        if init_pred.item() != target.item():
            continue

        loss = F.nll_loss(output, target)
        model.zero_grad()
        loss.backward()

        data_grad = data.grad.data
        perturbed_data = fgsm_attack(data, eps, data_grad)
        output = model(perturbed_data)
        final_pred = output.max(1, keepdim=True)[1]
        if final_pred.item() == target.item():
            correct += 1
            if (eps == 0) and (len(adv_egs) < 5):
                adv_eg = perturbed_data.squeeze().detach().cpu().numpy()
                adv_egs.append((init_pred.item(), final_pred.item(), adv_eg))
        else:
            if len(adv_egs) < 5:
                adv_eg = perturbed_data.squeeze().detach().cpu().numpy()
                adv_egs.append((init_pred.item(), final_pred.item(), adv_eg))

    final_acc = correct / float(len(test_loader))
    print('Epsilon: %.4f Test Accuracy； %d / %d = %.3f' % (eps, correct, len(test_loader), final_acc))
    return final_acc, adv_egs

def PublicTest(epoch, net):
    global PublicTest_acc
    global best_PublicTest_acc
    global best_PublicTest_acc_epoch
    net.eval()
    PublicTest_loss = 0
    correct = 0
    total = 0
    for batch_idx, (inputs, targets) in enumerate(PublicTestloader):
        bs, ncrops, c, h, w = np.shape(inputs)
        inputs = inputs.view(-1, c, h, w)
        inputs, targets = inputs.to(device), targets.to(device)

        outputs = net(inputs)
        outputs_avg = outputs.view(bs, ncrops, -1).mean(1)  # avg over crops
        loss = criterion(outputs_avg, targets)
        PublicTest_loss += loss.item()
        _, predicted = torch.max(outputs_avg.data, 1)
        total += targets.size(0)

        correct += (predicted == targets).sum().item()
        utils.progress_bar(batch_idx, len(PublicTestloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'
                           % (PublicTest_loss / (batch_idx + 1), 100. * correct / total, correct, total))

    # Save checkpoint.
    PublicTest_acc = 100.*correct/total
    # writer.add_scalars('Loss', {'PublicTest': PublicTest_loss / len(PublicTestloader)}, epoch)
    # writer.add_scalars('Accuracy', {'PublicTest': PublicTest_acc}, epoch)
    if PublicTest_acc > best_PublicTest_acc:
        print('Saving..')
        print("best_PublicTest_acc: %0.3f" % PublicTest_acc)
        best_PublicTest_acc = PublicTest_acc
        best_PublicTest_acc_epoch = epoch

def PrivateTest(epoch, net):
    global PrivateTest_acc
    global best_PrivateTest_acc
    global best_PrivateTest_acc_epoch
    net.eval()
    PrivateTest_loss = 0
    correct = 0
    total = 0
    for batch_idx, (inputs, targets) in enumerate(PrivateTestloader):
        bs, ncrops, c, h, w = np.shape(inputs)
        inputs = inputs.view(-1, c, h, w)
        inputs, targets = inputs.to(device), targets.to(device)

        outputs = net(inputs)
        outputs_avg = outputs.view(bs, ncrops, -1).mean(1)  # avg over crops
        loss = criterion(outputs_avg, targets)
        PrivateTest_loss += loss.item()
        _, predicted = torch.max(outputs_avg.data, 1)
        total += targets.size(0)

        correct += (predicted == targets).sum().item()
        utils.progress_bar(batch_idx, len(PublicTestloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'
            % (PrivateTest_loss / (batch_idx + 1), 100. * correct / total, correct, total))
    # Save checkpoint.
    PrivateTest_acc = 100.*correct/total
    # writer.add_scalars('Loss', {'PrivateTest': PrivateTest_loss / len(PrivateTestloader)}, epoch)
    # writer.add_scalars('Accuracy', {'PrivateTest': PrivateTest_acc}, epoch)

    if PrivateTest_acc > best_PrivateTest_acc:
        print('Saving..')
        print("best_PrivateTest_acc: %0.3f" % PrivateTest_acc)
        best_PrivateTest_acc = PrivateTest_acc
        best_PrivateTest_acc_epoch = epoch

def aecurve(eps, accs):
    plt.figure(figsize=(5, 5))
    plt.plot(eps, accs, '*-')
    plt.xticks(np.arange(0, 0.012, step=0.001))
    plt.yticks(np.arange(0, 1.1, step=0.1))
    plt.title('Accuracy & Epsilon')
    plt.xlabel('Epsilon')
    plt.ylabel('Accuracy')
    plt.show()

if __name__ == '__main__':
    mode = 'test'

    PublicTestset1 = FER2013(split='PublicTest', transform=transform_test)
    PublicTestloader1 = torch.utils.data.DataLoader(PublicTestset1, batch_size=bs, shuffle=False, num_workers=1)
    PrivateTestset1 = FER2013(split='PrivateTest', transform=transform_test)
    PrivateTestloader1 = torch.utils.data.DataLoader(PrivateTestset1, batch_size=bs, shuffle=False, num_workers=1)
    device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
    # device = torch.device('cpu')
    print('Device: ', device)
    model = ResNet18()
    checkpoint = torch.load(model_path)
    print('Loading model from %s' % model_path)
    model.load_state_dict(checkpoint['net'])

    # best_PublicTest_acc = checkpoint['best_PublicTest_acc']
    # best_PrivateTest_acc = checkpoint['best_PrivateTest_acc']
    # best_PublicTest_acc_epoch = checkpoint['best_PublicTest_acc_epoch']
    # best_PrivateTest_acc_epoch = checkpoint['best_PrivateTest_acc_epoch']

    model.to(device)
    model.eval()

    if mode == 'test':
        PublicTest(1, model)
        PrivateTest(1, model)
        exit()

    accs = []
    egs = []
    for e in epls:
        acc, eg = test(model, device, PrivateTestloader1, e)
        accs.append(acc)
        egs.append(eg)
    aecurve(eps=epls, accs=accs)
    print(epls, accs)

    cnt = 0
    plt.figure(figsize=(8, 10))
    for i in range(len(epls)):
        for j in range(len(egs[i])):
            cnt += 1
            plt.subplot(len(epls), len(egs[0]), cnt)
            plt.xticks([], [])
            plt.yticks([], [])
            if j == 0:
                plt.ylabel("Eps: {}".format(epls[i]), fontsize=14)
            orig, adv, ex = egs[i][j]
            plt.title("{} -> {}".format(orig, adv))
            plt.imshow(ex)
    plt.tight_layout()
    plt.show()


word = input().upper()
myword = list(set(word))
cnt = []
for i in myword:
   x = word.count(i)
   cnt.append(x)
if cnt.count(max(cnt)) > 1:
    print("?")
else:
    cntmax = cnt.index(max(cnt))
    print(myword[cntmax])


import unittest
from appium import webdriver
from time import sleep
import HTMLTestRunner
import time
import my_testRunner

class MyTestCase(unittest.TestCase):

    @classmethod
    def setUpClass(self):
        desired_caps = {'platformName': 'Android',
                        'platformVersion': '6.0',
                        'deviceName': '192.168.163.101:5555',
                        'app': 'C:\\Users\\admin\\Desktop\\selendroid-test-app-0.17.0.apk',
                        'appPackage': 'io.selendroid.testapp',
                        'appActivity': '.HomeScreenActivity',
                        'unicodeKeyboard': True,
                        'resetKeyboard': True,
                        'automationName': 'Selendroid',
                        'noReset': True}
        self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)
        self.driver.implicitly_wait(5)

    @classmethod
    def tearDownClass(self):
        self.driver.quit()

    def test_1(self):
        driver = self.driver
        driver.find_element_by_id('buttonStartWebview').click()
        driver.find_element_by_id('spinner_webdriver_test_data').click()
        driver.find_element_by_link_text('xhtmlTestPage').click()
        sleep(2)
        # 此时验证的信息在WEBVIEW_0的context中，所以需要切换到web app
        driver.switch_to.context('WEBVIEW_0')
        self.assertTrue(driver.page_source.__contains__('XHTML Might Be The Future'))
        # print(driver.contexts)  # 打印当前界面中的所有上下

    def test_2(self):
        driver = self.driver
        driver.find_elements_by_link_text('click me')[0].click()
        sleep(2)
        self.assertTrue(driver.page_source.__contains__('List of stuff'))
        driver.switch_to.context('NATIVE_APP')
        driver.find_element_by_id('goBack').click()
        sleep(1)
        self.assertTrue(driver.find_element_by_id('buttonTest').is_displayed())

if __name__ == '__main__':
    cases_MyTestCase = unittest.TestLoader().loadTestsFromTestCase(MyTestCase)
    cases_my_testRunner = unittest.TestLoader().loadTestsFromTestCase(my_testRunner.TestOne)
    suite = unittest.TestSuite([cases_MyTestCase, cases_my_testRunner])
    suite.addTest(my_testRunner.TestOne('test_2'))
    now = time.strftime('%Y-%m-%d_%H-%M-%S', time.localtime(time.time()))
    fp = open(now + 'Result.html', 'wb')
    runner = HTMLTestRunner.HTMLTestRunner(stream=fp, verbosity=2, title='Test Report', description=u'Result:')
    runner.run(suite)
    print(now)
    fp.close()


import requests
import json

class Dingding_Robot_new():
    def __init__(self, dingding_cfg=None):
        self.appkey = dingding_cfg.appkey
        self.appsecret = dingding_cfg.appsecret
        self.chatid = dingding_cfg.chatid

    def getAccess_token(self):
        appkey = self.appkey  # 管理员账号登录开发者平台，应用开发-创建应用-查看详情-appkey
        appsecret = self.appsecret  # 应用里的appsecret
        # https://oapi.dingtalk.com/gettoken?appkey=key&appsecret=secret
        url = 'https://oapi.dingtalk.com/gettoken'
        headers = {
            'Content-Type': "application/x-www-form-urlencoded"
        }
        data = {'appkey': appkey,
                'appsecret': appsecret}
        r = requests.get(url=url, params=data, headers=headers)
        # print(r.text)
        access_token = r.json()["access_token"]

        print(access_token)
        return access_token

    def getMedia_id(self):
        access_token = self.getAccess_token()  # 拿到接口凭证
        path = 'C:/Users/Long/Desktop/123.txt'  # 文件路径
        url = 'https://oapi.dingtalk.com/media/upload?access_token=' + access_token + '&type=file'
        files = {'media': open(path, 'rb')}
        data = {'access_token': access_token,
                'type': 'file'}
        response = requests.post(url, files=files, data=data)
        json = response.json()
        print(json)
        return json["media_id"]

    def SendFile(self):
        access_token = self.getAccess_token()
        media_id = self.getMedia_id()
        chatid = self.chatid  # 通过jsapi工具获取的群聊id
        url = 'https://oapi.dingtalk.com/chat/send?access_token=' + access_token
        header = {
            'Content-Type': 'application/json'
        }
        data = {'access_token': access_token,
                'chatid': chatid,
                'msg': {
                    'msgtype': 'file',
                    'file': {'media_id': media_id}
                }}
        r = requests.request('POST', url, data=json.dumps(data), headers=header)
        print(r.json())

if __name__ == "__main__":
    run = Dingding_Robot_new()
    run.SendFile()


import datetime
import logging

from flask import Blueprint, request

from app.constants import REBOOKINGS_SPREADSHEET_ID, SheetHeaderIndex
from app.services.google_sheets_client import google_sheets

logger = logging.getLogger(__name__)

blueprint = Blueprint("blvd_appointment_created", __name__, url_prefix="/blvd")

@blueprint.route("/appointment_created", methods=["POST"])
def appointment_created():
    request_json = request.get_json()

    if request_json.get("event") == "ping":
        logger.info(
            f"Received ping for {request_json.get('url')}. "
            f"ID: {request_json.get('webhookId')}"
        )
        return request_json

    client_data = request_json.get("data", {}).get("node")
    appt_client_id = client_data.get("clientId")

    sheet_client_ids = google_sheets.get_values_from_sheet(
        REBOOKINGS_SPREADSHEET_ID, "rebookings!A2:A", major_dimension="COLUMNS"
    )[0]

    try:
        # Checking if value exists - if it does not, a ValueError is raised
        row_number = sheet_client_ids.index(appt_client_id) + 2

        row_data = google_sheets.get_values_from_sheet(
            REBOOKINGS_SPREADSHEET_ID, f"rebookings!{row_number}:{row_number}"
        )[0]
        current_time = datetime.datetime.now()
        sheet_input_datetime = datetime.datetime.fromisoformat(
            row_data[SheetHeaderIndex.INPUT_TIME.value]
        )

        if row_data[SheetHeaderIndex.INITIAL_APPT_BOOKED.value] == "FALSE":
            row_data[SheetHeaderIndex.INITIAL_APPT_BOOKED.value] = "TRUE"
        elif (
            sheet_input_datetime
            <= current_time
            <= (sheet_input_datetime + datetime.timedelta(seconds=15))
        ):
            logger.info(f"Initial appt already booked: {row_data}")
            return {"row_data": row_data}
        elif row_data[SheetHeaderIndex.REBOOKED.value] == "FALSE":
            row_data[SheetHeaderIndex.REBOOKED.value] = "TRUE"
        else:
            return {"row_data": row_data}

        row_data[SheetHeaderIndex.ROW_LAST_UPDATED_TIME.value] = str(current_time)

        body_data = [
            [
                appt_client_id,
                str(current_time),
                str(client_data),
            ]
        ]

        rebookings_update_response = google_sheets.update_sheet(
            REBOOKINGS_SPREADSHEET_ID,
            f"rebookings!{row_number}:{row_number}",
            [row_data],
        )
        google_sheets.append_to_sheet(
            REBOOKINGS_SPREADSHEET_ID,
            "new_client_appointments!A:A",
            body_data,
        )

        logger.info(
            f"Updated sheet with new Boulevard Appointment: "
            f"{rebookings_update_response}"
        )

        return rebookings_update_response

    except ValueError:
        logger.info(
            f"NOT FOUND: Attempted to find client_id {appt_client_id} in google sheet."
        )
        return request_json


##Codigo para probar los motores a pasos con una rampa
##Steve Mena Navarro PFG
##Tiene dos modos, uno para que funciones el concentrado y otro los steppers.

import RPi.GPIO as GPIO
import time
import sys

def cleanAndExit():
	print("Cleaning...")
	GPIO.cleanup()
	print("Bye...")
	sys.exit()

isStepper = True
maxSpeed 	= 2667*2

try:
	GPIO.setmode(GPIO.BCM)
	GPIO.setwarnings(False)
	if(isStepper):
		Giro = 21
		Velocidad = 20
	else:
		Giro = 7
		Velocidad = 8
	GPIO.setup(Velocidad,GPIO.OUT)
	GPIO.setup(Giro,GPIO.OUT)

	#CW+: Sentido de giro
	#CLK+: Velocidad del stepper
	GPIO.output(Giro,GPIO.HIGH)

	stepper = GPIO.PWM(Velocidad,40)
	stepper.start(0)
	print("Motor Arrancado")
	stepper.ChangeDutyCycle(33)
	while True:
		"""for i in range(20,100,5):
			stepper.ChangeDutyCycle(i)
			time.sleep(0.5)
		i = 0
		for i in range(100,20,-5):
			stepper.ChangeDutyCycle(i)
			time.sleep(0.5)
		"""
		pass

except(KeyboardInterrupt,SystemExit):
	stepper.stop()
	cleanAndExit()
finally:
	GPIO.cleanup()


import os
import threading

import rospy

from sound_play.msg import SoundRequest

try:
    import gi
    gi.require_version('Gst', '1.0')
    from gi.repository import Gst as Gst
except Exception:
    str = """
**************************************************************
Error opening pygst. Is gstreamer installed?
**************************************************************
"""
    rospy.logfatal(str)
    # print str
    exit(1)

class SoundType(object):
    STOPPED = 0
    LOOPING = 1
    COUNTING = 2

    def __init__(self, file, device, volume=1.0):
        self.lock = threading.RLock()
        self.state = self.STOPPED
        self.sound = Gst.ElementFactory.make("playbin", None)
        if self.sound is None:
            raise Exception("Could not create sound player")

        if device:
            self.sink = Gst.ElementFactory.make("alsasink", "sink")
            self.sink.set_property("device", device)
            self.sound.set_property("audio-sink", self.sink)

        if (":" in file):
            uri = file
        elif os.path.isfile(file):
            uri = "file://" + os.path.abspath(file)
        else:
            rospy.logerr('Error: URI is invalid: %s' % file)

        self.uri = uri
        self.volume = volume
        self.sound.set_property('uri', uri)
        self.sound.set_property("volume", volume)
        self.staleness = 1
        self.file = file

        self.bus = self.sound.get_bus()
        self.bus.add_signal_watch()
        self.bus_conn_id = self.bus.connect("message", self.on_stream_end)

    def on_stream_end(self, bus, message):
        if message.type == Gst.MessageType.EOS:
            if (self.state == self.LOOPING):
                self.sound.seek_simple(Gst.Format.TIME, Gst.SeekFlags.FLUSH, 0)
            else:
                self.stop()

    def __del__(self):
        # stop our GST object so that it gets garbage-collected
        self.dispose()

    def update(self):
        if self.bus is not None:
            self.bus.poll(Gst.MessageType.ERROR, 10)

    def loop(self):
        self.lock.acquire()
        try:
            self.staleness = 0
            if self.state == self.COUNTING:
                self.stop()

            if self.state == self.STOPPED:
                self.sound.seek_simple(Gst.Format.TIME, Gst.SeekFlags.FLUSH, 0)
                self.sound.set_state(Gst.State.PLAYING)
            self.state = self.LOOPING
        finally:
            self.lock.release()

    def dispose(self):
        self.lock.acquire()
        try:
            if self.bus is not None:
                self.sound.set_state(Gst.State.NULL)
                self.bus.disconnect(self.bus_conn_id)
                self.bus.remove_signal_watch()
                self.bus = None
                self.sound = None
                self.sink = None
                self.state = self.STOPPED
        except Exception as e:
            rospy.logerr('Exception in dispose: %s' % str(e))
        finally:
            self.lock.release()

    def stop(self):
        if self.state != self.STOPPED:
            self.lock.acquire()
            try:
                self.sound.set_state(Gst.State.NULL)
                self.state = self.STOPPED
            finally:
                self.lock.release()

    def single(self):
        self.lock.acquire()
        try:
            rospy.logdebug("Playing %s" % self.uri)
            self.staleness = 0
            if self.state == self.LOOPING:
                self.stop()

            self.sound.seek_simple(Gst.Format.TIME, Gst.SeekFlags.FLUSH, 0)
            self.sound.set_state(Gst.State.PLAYING)
            self.state = self.COUNTING
        finally:
            self.lock.release()

    def command(self, cmd):
        if cmd == SoundRequest.PLAY_STOP:
            self.stop()
        elif cmd == SoundRequest.PLAY_ONCE:
            self.single()
        elif cmd == SoundRequest.PLAY_START:
            self.loop()

    def get_staleness(self):
        self.lock.acquire()
        position = 0
        duration = 0
        try:
            position = self.sound.query_position(Gst.Format.TIME)[1]
            duration = self.sound.query_duration(Gst.Format.TIME)[1]
        except Exception:
            position = 0
            duration = 0
        finally:
            self.lock.release()

        if position != duration:
            self.staleness = 0
        else:
            self.staleness = self.staleness + 1
        return self.staleness

    def get_playing(self):
        return self.state == self.COUNTING


from rivr.views import View
from rivr.http import ResponseRedirect

try:
    from rivr_jinja import JinjaView
except ImportError:
    raise ImportError('rivr-peewee views are missing an optional ' \
                      'dependency of rivr-jinja')

class QueryMixin(object):
    model = None
    query = None

    def get_model(self):
        if self.model:
            return self.model

        return self.query.model_class

    def get_query(self):
        if self.query:
            return query

        if self.model:
            return self.model.select()

        raise Exception('QueryMixin requires either a definition of'
                        '`model` or `query`, or an implementation of'
                        '`get_query()`')

    def get_model_name(self):
        return self.get_model().__name__.lower()

class SingleObjectMixin(QueryMixin):
    def get_object(self):
        pk = self.kwargs['pk']
        return self.get_query().filter(id=pk).get()

    def get_template_names(self):
        return [
            '{}_detail.html'.format(self.get_model_name()),
        ]

    def get_context_data(self, **kwargs):
        kwargs[self.get_model_name()] = self.get_object()
        return kwargs

class DetailView(SingleObjectMixin, JinjaView):
    pass

class MultipleObjectMixin(QueryMixin):
    def get_objects(self):
        return self.get_query()

    def get_template_names(self):
        return [
            '{}_list.html'.format(self.get_model_name()),
        ]

    def get_context_data(self, **kwargs):
        context_name = '{}_list'.format(self.get_model_name())
        kwargs[context_name] = self.get_objects()
        return kwargs

class ListView(MultipleObjectMixin, JinjaView):
    pass


class Chapter:
    def __init__(self, Subject: str, Name: str, Pages: int, Marks: int):
        self.Subject = Subject
        self.Name = Name
        self.Pages = Pages
        self.Marks = Marks

    def __repr__(self):
        return self.Subject + " with " + self.Name

class Exam:
    def __init__(self, examName: str, chapterList: list):
        self.examName = examName
        self.chapterList = chapterList

    def __str__(self) -> str:
        return self.examName + " " + str(self.chapterList)

    def marksList(self):
        MarksofChapters = []
        for chapter in self.chapterList:
            MarksofChapters.append(chapter.Marks)
        return MarksofChapters

    def findMaximumChapterByPage(self):
        PagesofChapters = []
        for chapter in self.chapterList:
            PagesofChapters.append(chapter.Pages)
        index = PagesofChapters.index(max(PagesofChapters))
        return self.chapterList[index]

    def sortChapterByMarks(self):
        chapterList = self.chapterList
        finalChapters = []
        MarksofChapters = self.marksList()
        sortedMarksofChapters = sorted(self.marksList())
        indexes = []
        for number in sortedMarksofChapters:
            indexes.append(MarksofChapters.index(number))
        # return indexes
        for i in indexes:
            finalChapters.append(chapterList[i])
        return finalChapters

if __name__ == "__main__":
    # n = int(input("Enter the number of Chapters : "))
    # listOfChapters = []
    # for i in range(n):
    #     print("Enter record no. "+str(i+1))
    #     chapterSubject = input("Enter the Subject : ")
    #     chapterName = input("Enter the Name : ")
    #     chapterPages = int(input("Enter the pages : "))
    #     chapterMarks = int(input("Enter the marks : "))
    #     listOfChapters.append(
    #         Chapter(chapterSubject, chapterName, chapterPages, chapterMarks))
    # print(listOfChapters)

    listOfChapters = [Chapter('Science', 'Bio', 34, 90), Chapter(
        'Maths', 'Geometry', 20, 71), Chapter('English', 'Jofra', 12, 89)]
    print(listOfChapters)

    # ExamName = input("Enter exam name : ")

    ExamName = "Final"
    exam1 = Exam(ExamName, listOfChapters)
    print(exam1)
    print(exam1.marksList())
    print(exam1.findMaximumChapterByPage())
    print(exam1.sortChapterByMarks())


from tkinter import *
import tkinter as tk
from typing import List
from tkinter import messagebox

ogr_bilgileri = {"23122860048" : " 192803050 , Ahmet Can ÖZTÜRKMEN , Gaziantep , 2001 , Yazılım Mühendisliği "}

ogr_data= open('ogr_sifre.txt', 'r')
ogr_parola = ogr_data.read()
ogr_parola = ogr_parola.replace("/n","")
ogr_data.close()

ogr_parola = ogr_parola.split()

sorumlu_data= open('sorumlu_sifre.txt', 'r')
sorumlu_parola = sorumlu_data.read()
sorumlu_parola = sorumlu_parola.replace("/n","")
sorumlu_data.close()

sorumlu_parola = sorumlu_parola.split()

admin_data= open('admin_sifre.txt', 'r')
admin_parola = admin_data.read()
admin_parola = admin_parola.replace("/n","")
admin_data.close()

admin_parola = admin_parola.split()

def ogr_islem():
    ogr_pencere = Tk()

    ogr_pencere.title("Öğrenci İşlemleri")
    ogr_pencere.geometry("600x600")

    uygulama2 = Frame(ogr_pencere)
    uygulama2.grid()
    var = messagebox.showinfo("Uyarı" , "Öğrenci İşlemerine Hoşgeldiniz Yapmak İstediğiniz işlemi Seçiniz")
    button5 = Button(uygulama2, text = " Test çöz  " , width=40,height=5, command=exit)
    button5.grid(padx=165, pady=45)

    button6 = Button(uygulama2, text = " Öğrenci Bilgileri  " , width=40,height=5, command=bilgi_sorgu)
    button6.grid(padx=165, pady=45)

    button7 = Button(uygulama2, text = " Öğrenci Sınav Raporu   " , width=40,height=5, command=exit)
    button7.grid(padx=165, pady=45)
    ogr_pencere.mainloop()

def sorumlu_islem():
    sorumlu_pencere = Tk()

    sorumlu_pencere.title("Sınav Sorumlusu İşlemleri")
    sorumlu_pencere.geometry("600x600")

    uygulama2 = Frame(sorumlu_pencere)
    uygulama2.grid()
    var = messagebox.showinfo("Uyarı" , "Sınav Sorumlusu İşlemerine Hoşgeldiniz Yapmak İstediğiniz işlemi Seçiniz")
    button5 = Button(uygulama2, text = " Test Hazırla  " , width=40,height=5, command=exit)
    button5.grid(padx=165, pady=45)

    button6 = Button(uygulama2, text = " Sorumlu Bilgileri  " , width=40,height=5, command=exit)
    button6.grid(padx=165, pady=45)
    button7 = Button(uygulama2, text = " Öğrenci Bilgileri Sorgula   " , width=40,height=5, command=exit)
    button7.grid(padx=165, pady=45)

    sorumlu_pencere.mainloop()

def admin_islem():
    admin_pencere = Tk()

    admin_pencere.title("admin İşlemleri")
    admin_pencere.geometry("600x600")

    uygulama2 = Frame(admin_pencere)
    uygulama2.grid()
    var = messagebox.showinfo("Uyarı" , "Admin İşlemerine Hoşgeldiniz Yapmak İstediğiniz işlemi Seçiniz")
    button5 = Button(uygulama2, text = " Sınav Sorumlusu Ekle  " , width=40,height=5, command=exit)
    button5.grid(padx=165, pady=45)

    button6 = Button(uygulama2, text = " Sınav Sorumlusu Çıkar  " , width=40,height=5, command=exit)
    button6.grid(padx=165, pady=45)

    button7 = Button(uygulama2, text = " Öğrenci Bilgileri Sorgula   " , width=40,height=5, command=exit)
    button7.grid(padx=165, pady=45)

    admin_pencere.mainloop()

def ögrenci_giris():
    giris_ekranı = Tk()

    giris_ekranı.title("Öğrenci Arayüzü ")
    giris_ekranı.geometry("400x300")

    uygulama2 = Frame(giris_ekranı)
    uygulama2.grid()

    L1 = Label(uygulama2 , text = "Tcnizi girin ")
    L1.grid(padx=140 , pady=10)

    E1 = Entry(uygulama2 , bd=2)
    E1.grid(padx=140 , pady=3)

    def deger_al():
        TC=E1.get()
        print(TC)
        for i in range(len(ogr_parola)):
            if (TC == ogr_parola[i]):
                print("Başarılı")
                ogr_islem()
                break

            else:
                pass

    button4 = Button(uygulama2, text = " Onayla " , width=15,height=2, command=deger_al)
    button4.grid()

    giris_ekranı.mainloop()

def sorumlu_giris():
    giris_ekranı = Tk()

    giris_ekranı.title("Sorumlu Arayüzü ")
    giris_ekranı.geometry("400x300")

    uygulama2 = Frame(giris_ekranı)
    uygulama2.grid()

    L1 = Label(uygulama2 , text = "Tcnizi girin ")
    L1.grid(padx=140 , pady=10)

    E1 = Entry(uygulama2 , bd=2)
    E1.grid(padx=140 , pady=3)

    def deger_al():
        TC=E1.get()
        print(TC)
        for i in range(len(sorumlu_parola)):
            if (TC == sorumlu_parola[i]):
                print("Başarılı")
                sorumlu_islem()
                break

            else:
                pass

    button4 = Button(uygulama2, text = " Onayla " , width=15,height=2, command=deger_al)
    button4.grid()

    giris_ekranı.mainloop()

def admin_giris():
    giris_ekranı = Tk()

    giris_ekranı.title("Admin Arayüzü ")
    giris_ekranı.geometry("400x300")

    uygulama2 = Frame(giris_ekranı)
    uygulama2.grid()

    L1 = Label(uygulama2 , text = "Tcnizi girin ")
    L1.grid(padx=140 , pady=10)

    E1 = Entry(uygulama2 , bd=2)
    E1.grid(padx=140 , pady=3)

    def deger_al():
        TC=E1.get()
        print(TC)
        for i in range(len(admin_parola)):
            if (TC == admin_parola[i]):
                print("Başarılı")
                admin_islem()
                break

            else:
                pass

    button4 = Button(uygulama2, text = " Onayla " , width=15,height=2, command=deger_al)
    button4.grid()

    giris_ekranı.mainloop()

def ana_menu():
    pencere = Tk()

    pencere.title("Ana Menü ")
    pencere.geometry("600x600")

    uygulama = Frame(pencere)
    uygulama.grid()

    button1 = Button(uygulama, text = " Öğrenci İşlemleri  " , width=40,height=5, command=ögrenci_giris)
    button1.grid(padx=165, pady=45)

    button2 = Button(uygulama, text = " Sınav Sorumlusu İşlemleri  " , width=40,height=5, command=sorumlu_giris)
    button2.grid(padx=165, pady=45)

    button3 = Button(uygulama, text = " Admin İşlemleri  " , width=40,height=5, command=admin_giris)
    button3.grid(padx=165, pady=45)
    pencere.mainloop()

def bilgi_sorgu():
    giris_ekranı = Tk()

    giris_ekranı.title("Öğrenci Bilgi  Arayüzü ")
    giris_ekranı.geometry("400x300")

    uygulama2 = Frame(giris_ekranı)
    uygulama2.grid()

    L1 = Label(uygulama2 , text = "Tcnizi girin ")
    L1.grid(padx=140 , pady=10)

    E1 = Entry(uygulama2 , bd=2)
    E1.grid(padx=140 , pady=3)

    def bilgi_sorgu():
        TC=E1.get()
        print(TC)
        for i in range(len(ogr_bilgileri)):
            if (TC == ogr_bilgileri[i]):
                print(ogr_bilgileri[i])
                break

            else:
                pass

    button4 = Button(uygulama2, text = " Onayla " , width=15,height=2, command=bilgi_sorgu)
    button4.grid()

    giris_ekranı.mainloop()

ana_menu()


'''
Program 2: Write a Program that accepts a number from user and prints the
values at following places from that number. {Value at one’s place, ten’s place,
hundreds’ place & thousand’s place if the values exists}
Input: 123
Output:
Value at ones place: 3
Value at ten’s place: 2
Value at hundreds’’ place: 1
'''

#num: type(int) - to take the integer value from user
#
num = int(input("Enter num: "))

#list to take places
place = ['One', 'Ten', 'Hundreds', 'Thousand','Lakh', 'crore']
#for indexing
lc=0
while num and lc < len(place):
    print('Value  at ', place[lc], ':', num%10)
    num //=10       #decrese the num by one place
    lc +=1          #increment the lc


"""
给定一个数组，任务是将其分为两组S1和S2，以使它们的和之间的绝对差最小
"""

def ad(l):
    number=0
    for i in l:
        number=number+i
    return number

n=int(input())
string_list = []

for i in range(n*2):
    string_list.append(str(input()))

i=0
while i<len(string_list):
    N=string_list[i]
    arr=[int(k) for k in string_list[i+1].split(" ")]
    arr.sort()

    Min=max(arr)
    ad_of_all=ad(arr)

    for m in range(len(arr)):
        k=m+1
        while k<=len(arr):
            num1=ad(arr[m:k])
            num2=ad_of_all-num1
            if num1>=num2:
                num=num1-num2
            else:
                num=num2-num1
            if Min>num:
                Min=num
            k=k+1

    print(Min)

    i=i+2


import streamlit as st
import datetime
import json

st.markdown("# Bestellen ðŸ›’")
st.sidebar.markdown("# Bestellen ðŸ›’")
#test
# Datenbank-Datei fÃ¼r Werkzeugnisinformationen im JSON-Format
database_filename = "bestellungen_database.json"

# Laden der bestehenden Werkzeugnisdaten aus der JSON-Datei
def load_existing_data(filename):
    try:
        with open(filename, "r") as file:
            data = [json.loads(line) for line in file]
        return data
    except (FileNotFoundError, json.JSONDecodeError):
        return []

existing_data = load_existing_data(database_filename)

# Seitentitel
#st.title("Bestellung aufgeben")

# Kunde
kunde = st.text_input("Kundenname")

# Automatisches EinfÃ¼gen des aktuellen Datums und der Uhrzeit
current_datetime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

# Generiere die Auftragsnummer aus den ersten Buchstaben des Kunden und dem Datum
if kunde:
    auftragsnummer = kunde[:3].upper() + current_datetime.replace("-", "").replace(" ", "").replace(":", "")
    st.write(f"Auftragsnummer: {auftragsnummer}")

st.write(f"Bestellung vom: {current_datetime}")
# Auswahl der Bestellvarianten
st.write("WÃ¤hlen Sie Ihre Farben aus:")

varianten_farben = {
    "FÃ¼hrerhaus": ["Blau", "Rot", "Gelb"],
    "Sidepipes": ["Rot", "Blau"],
    "Container 1": ["GrÃ¼n", "Gelb", "Blau"],
    "Container 2": ["GrÃ¼n", "Gelb", "Blau"],
    "Container 3": ["GrÃ¼n", "Gelb", "Blau"],
    "Container 4": ["GrÃ¼n", "Gelb", "Blau"]

}

selected_variants = {}

# Erstelle 6 Spalten
columns = st.columns(6)

for variante, farben in varianten_farben.items():
    #with columns[0]:
      #  st.write(variante)
    with columns[1]:
        selected_color = st.radio(f"Auswahl {variante}", farben)
        if selected_color:
            selected_variants[variante] = selected_color

# Sonderwunsch
sonderwunsch = st.text_input("Sonderwunsch", "")

# Kundentakt
Kundentakt = st.text_input("Kundentakt", "")

# SchaltflÃ¤che, um Bestellung abzuschicken
if st.button("Bestellung abschicken"):

    # Speichern der Bestellinformationen in der Datenbank als separates JSON-Objekt pro Zeile
    bestellungen_info = {
        "Bestelldatum und Uhrzeit": current_datetime,
        "Kunde": kunde,
        "Auftragsnummer": auftragsnummer,
        "Sonderwunsch": sonderwunsch,
        "Variante nach Bestellung": selected_variants,
        "Kundentakt": Kundentakt,
    }
    existing_data.append(bestellungen_info)  # HinzufÃ¼gen der neuen Daten zu den vorhandenen Daten

    with open(database_filename, "w") as db:
        for entry in existing_data:
            db.write(json.dumps(entry) + "\n")

    st.write("Die Bestellung wurde abgeschickt")
    # Laden der bestehenden Werkzeugnisdaten aus der JSON-Datei
    st.experimental_rerun()


import docx
import time
from src.common import defines as dv
from src.common import configVars as cv
from src.common import stringHelpers as strHlprs
from src.cmdInterface import cmdProgressBar

class DocxExporter:
    """Class to generate the output acronym document"""
    def __init__(self, acro_dict_handler):
        self.acro_dict_handler = acro_dict_handler
        self.document = None
        self.obj_normal_style = None
        self.obj_header_style = None
        self.time_paragraph = 0

    def generate_output_docx(self, time_begin_acronymate):
        """Generates a docx document with the user accepted acronyms

        :param time_begin_acronymate: time.monotonic() of the program start. Used in the stats print
        :return: python-docx document object
        """
        # --- Initialize ---
        print(_("Generando Word con tabla de acrónimos"))
        obj_progress_bar = cmdProgressBar.CmdProgressBar(len(self.acro_dict_handler.acros_output.keys()), _("Acrónimos"))

        self.document = docx.Document()

        # --- Define styles ---
        self._define_styles()

        # --- Footer ---
        self._add_footer()

        # --- Text before table (Statistics) ---
        self._add_summary_paragraphs()

        # --- Acronym Table ---
        self._add_acronym_table(obj_progress_bar)

        # --- Fill elapsed time to statistics ---
        self._complete_time_paragraph(time_begin_acronymate)

        return self.document

    def _define_styles(self):
        """Defines the styles used in the document"""
        self.obj_normal_style = self.document.styles['Normal']
        font = self.obj_normal_style.font
        font.name = cv.config_output_font
        font.size = docx.shared.Pt(cv.config_output_font_size)
        paragraph_format = self.obj_normal_style.paragraph_format
        paragraph_format.space_after = docx.shared.Pt(2)
        paragraph_format.space_before = docx.shared.Pt(2)

        self.obj_header_style = self.document.styles.add_style('HeaderStyle', docx.enum.style.WD_STYLE_TYPE.PARAGRAPH)
        hdr_font = self.obj_header_style.font
        hdr_font.size = docx.shared.Pt(cv.config_output_font_size_header)
        hdr_font.name = cv.config_output_font
        paragraph_format = self.obj_header_style.paragraph_format
        paragraph_format.space_after = docx.shared.Pt(2)
        paragraph_format.space_before = docx.shared.Pt(2)

    def _add_footer(self):
        """Adds the footer of the document"""
        # Only one section in document
        section_footer = self.document.sections[0].footer
        section_footer.paragraphs[0].text = "ACRONYMATE " + dv.define_acronymate_version + " - SAHR Projects 2023"
        section_footer.paragraphs[0].alignment = docx.enum.text.WD_ALIGN_PARAGRAPH.RIGHT

    def _add_summary_paragraphs(self):
        """Adds a brief summary before the acronyms table"""
        self.document.add_paragraph(_('Archivo procesado: %s') % self.acro_dict_handler.str_file)
        self.document.add_paragraph(_('Acrónimos extraídos: %d') % len(self.acro_dict_handler.acros_output.keys()))
        self.document.add_paragraph('Tiempo')
        self.time_paragraph = len(self.document.paragraphs) - 1  # Save paragraph to fill later with a precise time
        self.document.add_paragraph('')  # Spacer

    def _complete_time_paragraph(self, time_begin_acronymate):
        """Completes the elapsed time paragraph with hours minutes and seconds since the beginning of the program"""
        elapsed_f_sec = time.monotonic() - time_begin_acronymate
        hours, minutes = 0, 0
        while elapsed_f_sec >= 3600:
            elapsed_f_sec -= 3600
            hours += 1
        while elapsed_f_sec >= 60:
            elapsed_f_sec -= 60
            minutes += 1
        seconds = int(elapsed_f_sec)
        msec = int((elapsed_f_sec - seconds)*100)

        self.document.paragraphs[self.time_paragraph].text = \
            _('Tiempo transcurrido: %s:%s:%s.%d') % \
            (str(hours).zfill(2), str(minutes).zfill(2), str(seconds).zfill(2), msec)

    def _add_acronym_table(self, obj_progress_bar):
        """Adds the acronym table"""
        table = self.document.add_table(rows=1, cols=2)
        # In case we would like to use some styling: table.obj_normal_style = 'LightShading-Accent1'
        table.autofit = True
        hdr_cells = table.rows[0].cells
        hdr_cells[0].text = _('Acrónimo')
        hdr_cells[1].text = _('Definición')
        for i in range(len(hdr_cells)):
            hdr_cells[i].paragraphs[0].runs[0].font.bold = True
            hdr_cells[i].paragraphs[0].style = self.obj_header_style
        # Set parameter in cells for auto width
        for cell in table.rows[0].cells:
            cell._tc.tcPr.tcW.type = 'auto'

        for n_acro, acro in enumerate(sorted(self.acro_dict_handler.acros_output.keys(), key=strHlprs.acro_ordering)):
            row_cells = table.add_row().cells
            row_cells[0].text = acro
            row_cells[0].paragraphs[0].runs[0].font.bold = True
            for i in range(len(self.acro_dict_handler.acros_output[acro]['Def'])):
                if i > 0:
                    row_cells[1].add_paragraph()
                run_main_def = row_cells[1].paragraphs[i].add_run(
                    self.acro_dict_handler.acros_output[acro]['Def'][i]['Main'])
                if 'Translation' in self.acro_dict_handler.acros_output[acro]['Def'][i]:
                    run_main_def.italic = True
                    row_cells[1].paragraphs[i].add_run(
                        " (" + self.acro_dict_handler.acros_output[acro]['Def'][i]['Translation'] + ")")
            # Set parameter in cells for auto width
            for cell in row_cells:
                cell._tc.tcPr.tcW.type = 'auto'

            obj_progress_bar.update(n_acro+1)

def save_document(filepath_output, document):
    """Static function that saves an python-docx object

    :param filepath_output: Desired path
    :param document: python-docx document object
    """
    document.save(filepath_output)


arr1 = eval(input())
arr2 = eval(input())
ans = []
for n in arr2:
    count = arr1.count(n)
    for c in range(count):
        ans.append(n)
        arr1.remove(n)
ans.extend(sorted(arr1))
print(ans)


# -*- coding: utf-8 -*-
"""
Created on Fri Jan 24 15:31:13 2020

@author: jessi
"""

import numpy as np

class MakeData():

    def make_data(n_samples=100, noise=0.1, random_state=None):

        n_samples_outer = n_samples // 2
        n_samples_inner = n_samples - n_samples_outer

        outer_circ_x = np.linspace(0, np.pi, n_samples_outer) + np.random.normal(0, noise, n_samples_outer)
        outer_circ_y = np.sin(outer_circ_x) + np.random.normal(0, noise, n_samples_outer)
        outer_freqs = np.linspace(100, 10000, n_samples_outer)

        inner_circ_x = np.linspace(0, 2*np.pi, n_samples_inner) + np.random.normal(0, noise, n_samples_inner)
        inner_circ_y = 2*np.sin(1/2* inner_circ_x) + np.random.normal(0, noise, n_samples_inner)
        inner_freqs = np.linspace(100, 10000, n_samples_inner)

        X = np.hstack([np.vstack([np.append(outer_circ_x, inner_circ_x),
                       np.append(outer_circ_y, inner_circ_y)]).T,
                        np.vstack(np.append(outer_freqs, inner_freqs))])

        y = np.hstack([np.zeros(n_samples_outer, dtype=np.intp),
                       np.ones(n_samples_inner, dtype=np.intp)])

        return X, y


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

def linear_regression(x, y):
    x = np.array(x)
    y = np.array(y)
    slope, intercept, r_value, p_value, std_err = linregress(x, y)
    return slope, intercept, r_value

table = pandas.read_csv("./data.csv")
x_data = table["Assault"]
y_data = table["Murder"]

slope, intercept, correlation_coefficient = linear_regression(x_data, y_data)

print("Slope (m):", slope)
print("Intercept (c):", intercept)
print("Correlation Coefficient (r):", correlation_coefficient)

plt.figure(figsize=(16, 10))

regression_line = x_data*slope + intercept
plt.scatter(x_data, y_data.where(y_data > regression_line), color='red')
plt.scatter(x_data, y_data.where(y_data < regression_line), color='green')
plt.plot(x_data, regression_line, color='red', label='Linear Regression Line')
plt.title(label="Murder / Assault", fontsize=40, color="green")
plt.savefig("output.jpg")


from gamegrid import *
import math

# ------------------- class animGif -----------------------
class AnimGif(Actor):
    def __init__(self):
        Actor.__init__(self, True, "anim/fireworks.png", 24)

# ------ End of class definitions --------------------

def keyCallback(e):
    code = e.getKeyCode()
    if code == KeyEvent.VK_SPACE:
        for m in range(1000):
            id = animGif.getIdVisible()
            if id != 23: # Wait until crossbow is loaded
                id = id + 1
                animGif.show(id)
            else:
                animGif.show(0) # crossbow is released
            delay(50)

screenWidth = 600
screenHeight = 400

makeGameGrid(screenWidth, screenHeight, 1, False, keyPressed = keyCallback)
animGif = AnimGif()
addActor(animGif, Location(int(screenWidth/2), int(screenHeight/2)))

doRun()
show()


# 백준 문제들을 vscode에서 풀기 위해 만들어둔 tool

import sys

sys.stdin = open('input.txt')

input = sys.stdin.readline

# 여기부터 백준 코드 입력

n = int(sys.stdin.readline())

queue=[]
for i in range(n):
    command = sys.stdin.readline().split()

    if command[0]=='push':
        queue.append(command[1])
    elif command[0]=='pop':
        if len(queue)==0:
            print(-1)
        else:
            print(queue[0])
            del queue[0]
    elif command[0] == 'size':
        print(len(queue))
    elif command[0] == 'empty':
        if len(queue)==0:
            print(1)
        else:
            print(0)
    elif command[0] == 'front':
        if len(queue)==0:
            print(-1)
        else:
            print(queue[0])
    elif command[0] == 'back':
        if len(queue)==0:
            print(-1)
        else:
            print(queue[-1])


import random
from typing import Callable, Any

def validate_args(func: Callable) -> Callable:

    def wrapped_func(*args) -> Any:
        if len(args) < 1:
            print('Not enough arguments')
            return

        if len(args) > 1:
            print('Too many arguments')
            return

        inp = args[0]
        if not isinstance(inp, int):
            print('Wrong types')
            return

        if inp < 0:
            print('Negative argument')
            return
        else:
            return func(inp)

    return wrapped_func

# @validate_args
# def somefunc(number):
#     result = number + random.randint(-number, 100)
#     return 'Ваш психологический возраст: {} лет!'.format(result)
#
#
# ans = somefunc(24)
# print(ans)


import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.autograd as autograd
import torch.optim as optim
import numpy as np
from torch.autograd import Variable

from hybrid_model import VAEDualEncoder
from data import UDCv2
from evaluation import recall_at_k, eval_model_hybrid_v1
from util import save_model

import argparse
from tqdm import tqdm

parser = argparse.ArgumentParser(
    description='UDC Experiment Runner'
)

parser.add_argument('--gpu', default=False, action='store_true',
                    help='whether to run in the GPU')
parser.add_argument('--emb_dim', type=int, default=100, metavar='',
                    help='embedding dimension (default: 100)')
parser.add_argument('--h_dim', type=int, default=100, metavar='',
                    help='hidden dimension (default: 100)')
parser.add_argument('--z_dim', type=int, default=100, metavar='',
                    help='latent dimension (default: 100)')
parser.add_argument('--lr', type=float, default=1e-3, metavar='',
                    help='learning rate (default: 1e-3)')
parser.add_argument('--mb_size', type=int, default=128, metavar='',
                    help='size of minibatch (default: 128)')
parser.add_argument('--n_epoch', type=int, default=500, metavar='',
                    help='number of iterations (default: 500)')
parser.add_argument('--randseed', type=int, default=123, metavar='',
                    help='random seed (default: 123)')

args = parser.parse_args()

max_seq_len = 160

# Set random seed
np.random.seed(args.randseed)
torch.manual_seed(args.randseed)

if args.gpu:
    torch.cuda.manual_seed(args.randseed)

udc = UDCv2('/home/DebanjanChaudhuri/UDC/ubuntu_data', batch_size=args.mb_size, use_mask=True,
            max_seq_len=max_seq_len, gpu=args.gpu, use_fasttext=True)

eos_idx = 63346
pad_idx = 0
model = VAEDualEncoder(udc.emb_dim, udc.vocab_size, args.h_dim, args.z_dim, udc.vectors, eos_idx, pad_idx, 0.5, args.gpu)

solver = optim.Adam(model.parameters(), lr=1e-3)

for epoch in range(args.n_epoch):
    print('\n\n-------------------------------------------')
    print('Epoch-{}'.format(epoch))
    print('-------------------------------------------')

    train_iter = enumerate(udc.get_iter('train'))
    train_iter = tqdm(train_iter)
    train_iter.set_description_str('Training')
    train_iter.total = udc.n_train // udc.batch_size

    for it, mb in train_iter:
        context, response, y, _, _ = mb

        outputs_retrieval, recon_loss_c, kl_loss_c, recon_loss_r, kl_loss_r = model(context, response)

        loss_ret = F.binary_cross_entropy_with_logits(outputs_retrieval, y)
        loss_vae_c = recon_loss_c + kl_loss_c
        loss_vae_r = recon_loss_r + kl_loss_r

        loss = loss_ret + loss_vae_c + loss_vae_r

        loss.backward()
        grad_norm = nn.utils.clip_grad_norm(model.parameters(), 10)
        solver.step()
        solver.zero_grad()

        if it != 0 and it % 2000 == 0:
            # Validation
            recall_at_ks = eval_model_hybrid_v1(model, udc, 'valid', gpu=args.gpu)

            print('\nLoss: {:.3f}; recall@1: {:.3f}; recall@2: {:.3f}; recall@5: {:.3f}'
                .format(loss.data[0], recall_at_ks[0], recall_at_ks[1], recall_at_ks[4]))

    save_model(model, 'hybrid_variational')


from collections import defaultdict
import json
import time
import threading
import tempfile
import os

from webob.dec import wsgify
from webob import exc

from webtestplus.recorder import get_record

__all__ = ['ClientTesterMiddleware']

DISABLED = 'disabled'
RECORD = 'recording'
REPLAY = 'playing'

def _int2status(status):
    if status == 200:
        return '200 OK'
    if status == 400:
        return '400 Bad Request'
    if status == '401':
        return '400 Unauthorized'

    return '%d Explanation' % status

class ClientTesterMiddleware(object):
    """Middleware that let a client drive failures for testing purposes.
    """
    def __init__(self, app, mock_path='/__testing__',
                 filter_path='/__filter__',
                 rec_path='/__record__',
                 secret='CHANGEME',
                 requires_secret=True,
                 rec_file=None):
        self.custom_paths = mock_path, filter_path, rec_path
        self.app = app
        self.mock_path = mock_path
        self.filter_path = filter_path
        self.rec_path = rec_path
        self.replays = defaultdict(list)
        self.filters = defaultdict(dict)
        self.is_recording = defaultdict(lambda: DISABLED)
        self.lock = threading.RLock()
        if rec_file is None:
            fd, rec_file = tempfile.mkstemp()
            os.close(fd)

        self.rec_file = rec_file
        self.secret = secret
        self.requires_secret = requires_secret

    def _auth(self, request):
        if not self.requires_secret:
            return
        provided = request.headers.get('X-Secret')
        if provided != self.secret:
            raise exc.HTTPUnauthorized()

    def _get_client_ip(self, environ):
        if 'HTTP_X_FORWARDED_FOR' in environ:
            return environ['HTTP_X_FORWARDED_FOR'].split(',')[0].strip()

        if 'REMOTE_ADDR' in environ:
            return environ['REMOTE_ADDR']

        return None

    def _resp(self, req, status='200 OK', body='', headers=None):
        resp = req.response
        resp.status = status
        resp.body = body
        resp.content_type = 'application/json'

        if headers is not None:
            resp.headers.update(dict(headers))

        return resp

    def _apply_filters(self, resp, filters):
        status = resp.status
        intst = int(status.split()[0])
        if intst in filters:
            time.sleep(filters[intst])
        elif '*' in filters:
            time.sleep(filters['*'])

        # XXX maybe we will have filters that change the resp
        return resp

    @wsgify
    def __call__(self, request):
        if request.path_info in self.custom_paths:
            self._auth(request)

        environ = request.environ
        path = request.path_info

        environ['_ip'] = ip = self._get_client_ip(environ)
        environ['_replays'] = replays = self.replays[ip]
        environ['_filters'] = filters = self.filters[ip]
        environ['_is_recording'] = rec = self.is_recording[ip]

        # routing
        if path.startswith(self.mock_path):
            return self._mock(request)
        elif path.startswith(self.filter_path):
            return self._filter(request)
        elif path.startswith(self.rec_path):
            return self._rec_state(request)

        # classical call, do we have something to replay ?
        if len(replays) > 0:
            # yes
            replay = replays.pop()
            status = _int2status(replay.get('status', 0))
            body = replay.get('body', u'').encode('utf8')
            headers = replay.get('headers')
            delay = replay.get('delay', 0)
            passthrough = replay.get('passthrough', False)

            # repeat it, always
            if replay.get('repeat') == -1:
                replays.insert(0, replay)

            # build the response
            if not passthrough:
                resp = request.response
            else:
                resp = request.get_response(self.app)
            if status:
                resp.status = status
            if body:
                resp.body = body
            if headers:
                resp.headers.update(dict(headers))

            # apply filters
            resp = self._apply_filters(resp, filters)

            # extra delay
            time.sleep(delay)

            return resp
        else:
            # no, regular app
            # do we record or play or just call the app ?
            if rec in (DISABLED, RECORD):
                resp = request.get_response(self.app)
                if rec == RECORD:
                    self._record(request, resp)
            else:  # REPLAY:
                resp = self._replay(request)

            return self._apply_filters(resp, filters)

    def _checkmeth(self, method, allowed=None):
        if allowed is None:
            allowed = ('POST', 'DELETE')

        if method not in allowed:
            raise exc.HTTPMethodNotAllowed(
                              allow=','.join(allowed))

    def _rec_state(self, request):
        ip = request.environ['_ip']
        method = request.method
        self._checkmeth(method, ('POST', 'GET'))

        if method == 'POST':
            # define the toggle
            try:
                st = json.loads(request.body)
            except ValueError:
                raise exc.HTTPBadRequest()

            self.is_recording[ip] = st
            return self._resp(request)

        status = json.dumps(self.is_recording[ip])
        return self._resp(request, body=status)

    def _mock(self, request):
        # what's the method ?
        method = request.method
        self._checkmeth(method)
        replays = request.environ['_replays']

        if method == 'DELETE':
            # wipe out
            replays[:] = []
            return self._resp(request)

        # that's something to add to the pile
        try:
            resp = json.loads(request.body)
        except ValueError:
            raise exc.HTTPBadRequest()

        repeat = resp.get('repeat', 1)
        if repeat == -1:
            # will repeat indefinitely
            replays.insert(0, resp)
        else:
            for i in range(repeat):
                replays.insert(0, resp)

        return self._resp(request)

    def _filter(self, request):
        # what's the method ?
        method = request.method
        self._checkmeth(method)
        filters = request.environ['_filters']

        if method == 'DELETE':
            # wipe out
            filters.clear()
            return self._resp(request)

        # that's something to set
        try:
            new = json.loads(request.body)
        except ValueError:
            raise exc.HTTPBadRequest()

        filters.clear()

        for status, delay in new.items():
            if status != '*':
                status = int(status)
            filters[status] = delay

        return self._resp(request)

    def _replay(self, request):
        ip = request.environ['_ip']
        resp = get_record(self.rec_file, request)
        if resp is None:
            # failed to find a matching record
            # by-passing
            return request.get_response(self.app)

        return resp

    def _record(self, request, resp):
        data = []

        data.append('--Request:\n')
        data.append(str(request))
        if not request.content_length:
            data.append('\n')

        data.append('\n--Response:\n')
        data.append(str(resp))
        if not resp.body:
            data.append('\n')
        data.append('\n')

        self.lock.acquire()
        try:
            with open(self.rec_file, 'a+') as f:
                f.write(''.join(data))
        finally:
            self.lock.release()