import numpy as np
import cudarray as ca
from ..base import Model, CollectionMixin
from ..expr.base import UnaryElementWise
from ..feed import Feed
from .. import expr

class NegativeGradient(UnaryElementWise):
    def fprop(self):
        self.array = self.x.array

    def bprop(self):
        ca.negative(self.grad_array, self.x.grad_array)

class AdversarialNet(Model, CollectionMixin):
    def __init__(self, generator, discriminator, n_hidden):
        self.generator = generator
        self.discriminator = discriminator
        self.n_hidden = n_hidden
        self.eps = 1e-4
        self.collection = [generator, discriminator]

    def setup(self, x_shape):
        batch_size = x_shape[0]
        self.x_src = expr.Source(x_shape)
        z = expr.random.normal(size=(batch_size, self.n_hidden))
        x_tilde = self.generator(z)
        x_tilde = NegativeGradient()(x_tilde)
        x = expr.Concatenate(axis=0)(self.x_src, x_tilde)
        d = self.discriminator(x)
        d = expr.clip(d, self.eps, 1.0-self.eps)
        sign = np.ones((batch_size*2, 1), dtype=ca.float_)
        sign[batch_size:] = -1.0
        offset = np.zeros_like(sign)
        offset[batch_size:] = 1.0
        self.gan_prob = expr.log(d*sign + offset)
        self.loss = expr.sum(self.gan_prob)
        self._graph = expr.graph.ExprGraph(self.loss)
        self._graph.setup()
        self.loss.grad_array = ca.array(-1.0)

    @property
    def params(self):
        return self.generator.params, self.discriminator.params

    def update(self, x):
        self.x_src.array = x
        self._graph.fprop()
        self._graph.bprop()
        gan_loss = -np.array(self.gan_prob.array)
        batch_size = x.shape[0]
        d_x_loss = np.mean(gan_loss[:batch_size])
        d_z_loss = np.mean(gan_loss[batch_size:])
        return float(d_x_loss), float(d_z_loss)

    def generate(self, hidden):
        self.phase = 'test'
        feed = Feed.from_any(hidden)
        z_src = expr.Source(feed.x_shape)
        sink = self.generator(z_src)
        graph = expr.graph.ExprGraph(sink)
        graph.setup()
        x_tilde = []
        for z, in feed.batches():
            z_src.array = z
            graph.fprop()
            x_tilde.append(np.array(sink.array))
        x_tilde = np.concatenate(x_tilde)[:feed.n_samples]
        return x_tilde


# coding=utf-8
# 本题为考试多行输入输出规范示例，无需提交，不计分。
import sys

def get_fn_add(fnadd, fn):
    return fnadd + fn

if __name__ == "__main__":
    # # 读取第一行的n
    # n = int(sys.stdin.readline().strip())
    # ans = 0
    # for i in range(n):
    #     # 读取每一行
    #     line = sys.stdin.readline().strip()
    #     # 把每一行的数字分隔后转化成int列表
    #     values = list(map(int, line.split()))
    #     for v in values:
    #         ans += v
    # print(ans)
    n = int(sys.stdin.readline().strip())
    # n = int(input())
    list1 = []
    my_dict = {}
    list_total = []
    for i in range(1, n):
        fn = i
        for j in range(1, n):
            fn_add = j
            list1.append(fn)
            list1.append(fn_add)
            while fn_add < n:
                fn_add_add = fn_add + fn
                fn, fn_add = fn_add, fn_add_add
                list1.append(fn_add_add)
            if n in list1:
                index = list1.index(n) + 1
                if index in my_dict.keys():
                    my_dict[index] += 1
                else:
                    my_dict[index] = 1
                list_total.append(list1)
            list1 = []
    print(list_total)
    for k, value in my_dict.items():
        print(k, ' ', value)

给定n查找fb数列满足时候的位置和数量.py

给定n查找fb数列满足时候的位置和数量.py


#P17 (*) Split a list into two parts; the length of the first part is given.

mylist = ['a', 'b', 'c', 'd', 'e', 'f', 'g','h','i','j','k']
num= int(input("enter number to slice = "))
first,second = [],[]
count, length = 0, 0

for item in mylist:             #CALCULATE LENGTH OF LIST
    length +=1

if num <= length:               #CHECK IF INPUT IS VALID
    for item in mylist:
        count += 1              #CREATE A COUNTER TO KEEP CHECK ON THE REQUIRED LIMIT
        if count <= num :       #IF COUNT IS IN RANGE OF THE REQUIRED LIMIT,
            first += item       #ADD THE CURRENT ELEMENT INTO A LIST ONE
        else:
            second += item      #IF NOT, ADD INTO SECOND LIST
    print([first]+[second])     #CONCANATE THE 2 STRINGS TO GET THE SLICED LIST

else:
    print('INVALID INPUT !')    #IF GIVEN INDEX IS LARGER THAN LENGTH OF LIST


import dorm as dm
import pandas as pd
db1=dm.Mysqldb()

table1=dm.MysqlTable(db1,"test",["id","test2","test3"],["int","int","int"])
#table1.create()

rows=[[2,2]]

df=pd.DataFrame(rows,columns=["test2","test3"])

table1.insert_from_df(df)

rows=table1.select_all()
print(rows)

#table1.drop()

db1.close_connection()


from django.conf.urls import url
from mysite import views
from django.urls import path
from django.views.generic import TemplateView

# SET THE NAMESPACE!
app_name = 'mysite'

urlpatterns=[
    url(r'^[a-z]{0,10}/pagination/(?P<start>[0-9]{0,4})/$', views.scroll, name='scroll'),
    url(r'^$', views.homepage, name='homepage'),
    url(r'^clip$', views.clip, name='clip'),
    url(r'^clip/(?P<hash_title>\d+)/$', views.clip_post, name='clip_post'),
    url(r'^favorites$', views.favorites, name='favorites'),
    url(r'^filter/(?P<query>\w+)/$', views.filter_query, name='filter_query'),
    url(r'^filter/(?P<tags>[\-?\w+]*)/(?P<sources>[\-?\w+]+)$', views.filter, name='filter_total'),
    url(r'^filter/(?P<tags>[\-?\w+]*)/(?P<sources>[\-?\w+]+)/pagination/(?P<start>[0-9]{0,4})/$', views.scroll_filter, name='scroll_filter'),
    url(r'^login/\w*$', views.user_login, name='login'),
    url(r'^logout/$', views.user_logout, name='logout'),
    url(r'^registrator/$', views.register, name='registrator'),
    url(r'^search/(?P<query>[\w*\d*\s*]+)/$', views.search, name='search'),
    url(r'^search/(?P<query>[\w*\d*\s*]+)//pagination/(?P<start>\d+)$', views.search_pagination, name='search_pagination'),
]


import logging
import re2 as re
from typing import *

from .bot_request_context import BotRequestContext
from .bot_request_handler import BotRequestHandler
from diffusers_mastodon_bot.diffusion.diffusion_runner import DiffusionRunner
from .proc_args_context import ProcArgsContext
from ..diffusion.pipe_info import PipeInfo

logger = logging.getLogger(__name__)

class DiffuseMeHandler(BotRequestHandler):
    def __init__(self,
                 pipe_info: PipeInfo,
                 tag_name: str = 'diffuse_me',
                 allow_self_request_only: bool = False
                 ):
        self.pipe_info = pipe_info
        self.tag_name = tag_name
        self.allow_self_request_only = allow_self_request_only
        self.re_strip_special_token = re.compile(r'<\|.*?\|>')

    def is_eligible_for(self, ctx: BotRequestContext) -> bool:
        contains_hash = ctx.contains_tag_name(self.tag_name)
        if not contains_hash:
            return False

        return (
                (ctx.mentions_bot() and ctx.not_from_self() and not self.allow_self_request_only)
                or
                not ctx.not_from_self()
        )

    def respond_to(self, ctx: BotRequestContext, args_ctx: ProcArgsContext) -> bool:
        # start
        positive_input_form = args_ctx.prompts['positive']
        negative_input_form = args_ctx.prompts['negative']

        in_progress_status = ctx.reply_to(ctx.status, 'processing...', keep_context=False)

        if 'num_inference_steps' in args_ctx.proc_kwargs \
                and args_ctx.proc_kwargs['num_inference_steps'] is not None:
            args_ctx.proc_kwargs['num_inference_steps'] = int(args_ctx.proc_kwargs['num_inference_steps'])

        diffusion_result: DiffusionRunner.Result = \
            DiffusionRunner.run_diffusion_and_upload(self.pipe_info, ctx, args_ctx)

        logger.info(f'building reply text')

        reply_message, spoiler_text, media_ids = DiffusionRunner.make_reply_message_contents(
            ctx,
            args_ctx,
            diffusion_result,
            detecting_args=['num_inference_steps', 'guidance_scale'],
            positive_input_form=positive_input_form,
            negative_input_form=negative_input_form
        )

        behavior_conf = ctx.bot_ctx.behavior_conf

        reply_target_status = ctx.status if behavior_conf.delete_processing_message else in_progress_status

        replied_status = ctx.reply_to(
            reply_target_status,
            reply_message,
            media_ids=media_ids,
            visibility=ctx.reply_visibility,
            spoiler_text=spoiler_text,
            sensitive=True,
            tag_behind=behavior_conf.tag_behind_on_image_post
        )

        if behavior_conf.tag_behind_on_image_post:
            ctx.mastodon.status_reblog(replied_status['id'])

        if behavior_conf.delete_processing_message:
            ctx.mastodon.status_delete(in_progress_status)

        logger.info(f'sent')

        return True

    def reply_in_progress(self, ctx: BotRequestContext, args_ctx: ProcArgsContext, positive_input_form: str,
                          negative_input_form: Optional[str]):
        processing_body = DiffusionRunner.make_processing_body(args_ctx, positive_input_form, negative_input_form)
        in_progress_status = ctx.reply_to(status=ctx.status,
                                          body=processing_body if len(processing_body) > 0 else 'processing...',
                                          spoiler_text='processing...' if len(processing_body) > 0 else None,
                                          keep_context=True if len(processing_body) > 0 else False
                                          )
        return in_progress_status


from typing import List
from nltk.translate.meteor_score import meteor_score, single_meteor_score
from altilia_text_metrics.metrics.nltk.nltk_utils import nltk_tokenizer
from altilia_text_metrics.utils.environment import set_logger
import nltk
import logging

logger = logging.getLogger()

nltk.download("wordnet")

def Meteor_nltk(
    hypothesis: List[str],
    references: List[List[str]],
    **kwargs,
):
    """Calculates the Meteor score using the NLTK library.

    Args:
        hypothesis: A list of strings representing the predicted text.
        references: A list of lists of strings representing the reference text.
        **kwargs: Additional keyword arguments to pass to the function.

    Kwrgs:
        return_all_scores: bool: whether to return all scores or just the average.
            True for all scores + average, False for average only.

    Returns:
        A dictionary containing the Meteor score.
    """
    logger = set_logger(kwargs["log_file_path"])
    logger.info("Computing METEOR score...")

    assert len(hypothesis) == len(references), f"{len(hypothesis)} != {len(references)}"

    # Tokenize the sentences
    hypothesis_tok = [nltk_tokenizer(x) for x in hypothesis]
    references_tok = [[nltk_tokenizer(x) for x in ref_list] for ref_list in references]

    meteor_scores = []
    for _hyp, _ref in zip(hypothesis_tok, references_tok):
        if kwargs["method"] == "max":
            meteor_scores.append(max([single_meteor_score(x, _hyp) for x in _ref]))
        elif kwargs["method"] == "avg":
            temp_scores = [single_meteor_score(x, _hyp) for x in _ref]
            meteor_scores.append(sum(temp_scores) / len(temp_scores))

    logger.info("Computing METEOR score... FINISHED!")

    if kwargs["return_all_scores"]:
        return {"scores": meteor_scores, "meteor": sum(meteor_scores) / len(meteor_scores)}
    else:
        return {"meteor": sum(meteor_scores) / len(meteor_scores)}


def divide(var_1, var_2):
    try:
        devide_func = var_1 / var_2
        return devide_func
    except ZeroDivisionError:
        return

var_1 = int(input("Введите первое число: "))
var_2 = int(input("Введите второе число: "))
print(divide(var_1, var_2))


class User: # Create the user class (blueprint)
    def __init__(self,name, email, address): # include the states to create instances of these states later for the individual user
        #instance attributes
        self.name = name
        self.email = email
        self.address  = address
        #instance method
    def display_user_info(self): #create a greeting for the user
        print(f"Hello {self.name} ! Welcome to Los Pollos Hermanos Pizza! The information you have given is: Name: {self.name} Email: {self.email} Address: {self.address}")

    def __str__(self): #create a string for the personal detail summary
        return f'Thank you for your order {self.name}! Your pizza will be handmade and delivered to {self.address} and your receipt will be emailed to {self.email}. Thanks again for supporting Los Pollos Hermanos Pizza, where something delicious is always cooking!'

class Pizza: # create Pizza class (blueprint)
    def __init__(self,size, boxes: int, price: int): # include the states to create instances of these states later for the individual user
        #instance attributes
        self.size = size
        self.boxes = boxes
        self.price = price

        #instance method
        #Getters
    def get_small(self): # Get the initial price of one box of a small size pizza
        if self.size == "Small":
            self.price += 10
            return self.price

    def get_medium(self):
        if self.size == "Medium": # Get the initial price of one box of a medium size pizza
            self.price += 12
            return self.price
    def get_large(self):
        if self.size == "Large": # Get the initial price of one box of a large size pizza
            self.price += 15 # store it in self.price for further operations later on
            return self.price

        #Setters
    def set_price(self,value): # create operation that involves multiplying cost by the number of boxes to set cost without discount
        self.value = value
        self.price = self.price * self.boxes
        print("Cost before promotions and discounts:")
        return self.price

    def set_price_discount(self, discount): # create operation that involves multiplying cost by the number of boxes and by 0.15 to set up cost with discount
        self.discount = discount
        if self.boxes >= 3: # If it is equal to or greater than 3, discount will be applied
            self.discount = (self.price) * 0.15
            self.price = self.price - self.discount
            print("Total with discount:")
            return self.price
        elif self.boxes < 3: # Display message when there is no disount
            print("Discount:")

        #string
    def __str__(self):
        return f'The best deal for {self.boxes} {self.size} pizza boxes, with the consideration of the 15% off your order when you order three or more pizzas deal going on is, ${self.price} CAD. ****So your final total is ${self.price} CAD.**** '

User_name = input("What is your name?")
User_email = input("What is your email?")
User_address = input("What is your address?")
User_info = User(User_name,User_email,User_address)
User_info.display_user_info()

User_size = input("What size pizza would you like: Small - $10 , Medium - $12 , or Large - $15? ")
User_box = float(input("How many pizzas would you like of this size? ***15% off when you buy 3 or more!***"))
User_order = Pizza(User_size, User_box, 0)

if User_size == "Small":
    User_order.get_small()
    print(User_order.set_price(10))
    print(User_order.set_price_discount(10))
    print(User_order.__str__())
elif User_size == "Medium":
    User_order.get_medium()
    print(User_order.set_price(12))
    print(User_order.set_price_discount(12))
    print(User_order.__str__())
elif User_size == "Large":
    User_order.get_large()
    print(User_order.set_price(15))
    print(User_order.set_price_discount(15))
    print(User_order.__str__())

print(User_info.__str__())


import cv2
import numpy as np
from tasks import AlvinsSchatzsuche, Nebel

def main():
    oAlvinsSchatzsuche = AlvinsSchatzsuche()
    oNebel = Nebel()
    possible = oNebel.is_nebel_main()
    print(possible)
    #oAlvinsSchatzsuche.calculate_center()
    #oAlvinsSchatzsuche.recognize_ropes_of_image()

    # ranges = {
    #     "red": ([0, 0, 128], [60, 60, 255]),  # B G R
    #     "yellow": ([30, 100, 140], [70, 200, 220]),  # B G R
    #     "blue": ([90, 0, 0], [255, 50, 50]),  # B G R
    # }
    # image = cv2.imread('assets/alvins-schatzsuche-1.png')

    # for key in ranges.keys():
    #     lowerRange = np.array(ranges[key][0], dtype="uint8")
    #     upperRange = np.array(ranges[key][1], dtype="uint8")

    #     mask = cv2.inRange(image, lowerRange, upperRange)
    #     output = cv2.bitwise_and(image, image, mask=mask)

    #     # show the images
    #     cv2.imshow(key, output)
    #     cv2.waitKey(0)

    # cv2.destroyAllWindows()

    # cv2.imshow('Original Image', image)
    # cv2.waitKey(0)

if __name__ == "__main__":
    main()


from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import status, generics, filters
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from orders.models.order import Order
from orders.models.order_item import OrderItem
from orders.serializers.order_serializer import OrderSerializer
from products.models.product import Product

class StandardResultsSetPagination(PageNumberPagination):
    page_size = 5
    page_size_query_param = 'page_size'
    max_page_size = 1000

class OrderItemView(generics.GenericAPIView):
    permission_classes = (AllowAny,)
    pagination_class = StandardResultsSetPagination
    serializer_class = OrderSerializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    filterset_fields = ['phone_number']
    search_fields = ['phone_number']

    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return Response(data={"error": "User is not login"}, status=status.HTTP_401_UNAUTHORIZED)

        data = request.data

        if not data:
            return Response(data={"error": "Request body is empty"}, status=status.HTTP_400_BAD_REQUEST)

        if not isinstance(data, list):
            return Response(data={"error": "Request body should be a list"}, status=status.HTTP_400_BAD_REQUEST)

        product_obj_list = []
        product_quantity_list = []
        for product in data:
            product_id = product.get("product_id")
            product_quantity = product.get("quantity")

            try:
                product_obj = Product.objects.get(id=product_id)
                product_obj_list.append(product_obj)
                product_quantity_list.append(product_quantity)
            except Product.DoesNotExist:
                return Response(data={"error": f"Product with {product_id} not found "},
                                status=status.HTTP_404_NOT_FOUND)

        total_cost_with_off = 0
        total_cost_without_off = 0

        for product_obj, product_quantity in zip(product_obj_list, product_quantity_list):
            product_price = product_obj.price
            product_off = product_obj.off
            calculate_price_off = product_price - ((product_off / 100) * product_price)  # for one product
            total_cost_with_off += calculate_price_off * product_quantity
            total_cost_without_off += product_price * product_quantity

        total_off = total_cost_without_off - total_cost_with_off

        order_obj = Order.objects.create(
            phone_number=request.user.phone_number,
            first_name=request.user.first_name,
            last_name=request.user.last_name,
            total_cost=total_cost_with_off,
            total_off=total_off
        )

        for product_obj, product_quantity in zip(product_obj_list, product_quantity_list):
            OrderItem.objects.create(
                product=product_obj,
                order=order_obj,
                name=product_obj.name,
                price=product_obj.price,
                off=product_obj.off,
                quantity=product_quantity
            )
        serializer = OrderSerializer(instance=order_obj)
        return Response(data=serializer.data, status=status.HTTP_201_CREATED)

    def get(self, request, *args, **kwargs):

        if not request.user.is_authenticated:
            return Response(data={"error": "User is not login"}, status=status.HTTP_401_UNAUTHORIZED)

        queryset = self.filter_queryset(Order.objects.filter(phone_number=request.user.phone_number))

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
        # serializer = OrderSerializer(instance=Order.objects.all(), many=True)
        # return Response(data=serializer.data, status=status.HTTP_200_OK)

    # def get_object(self, product_id):
    #     try:
    #         return Product.objects.get(id=product_id)
    #     except Product.DoesNotExist:
    #         raise Http404
    #
    # def create_order_item_object(self, product_obj):
    #     obj = OrderItem.objects.create(product=product_obj,
    #                                    # order=order_obj,
    #                                    name=product_obj.name,
    #                                    price=product_obj.price,
    #                                    off=product_obj.off)
    #     return obj
    #
    # def create_order_object(self, user, order_items, total_cost, total_off):
    #     order_obj = Order.objects.create(phone_number=user.phone_number,
    #                                      first_name=user.first_name,
    #                                      last_name=user.last_name,
    #                                      total_off=total_off,
    #                                      total_cost=total_cost)
    #     for order_item in order_items:
    #         order_item.order = order_obj
    #     return order_obj
    #
    # def post(self, request):
    #     serializer = OrderItemSerializer(data=request.data, many=True)
    #     user = request.user
    #     if serializer.is_valid():
    #         basket = request.data
    #         total_cost = 0
    #         total_off = 0
    #         order_items = []
    #         for item in basket:
    #             product_id = item['product_id']
    #             product_obj = self.get_object(product_id)
    #             order_item_obj = self.create_order_item_object(product_obj)
    #             order_items.append(order_item_obj)
    #             total_cost += product_obj.price
    #             total_off += product_obj.off * product_obj.price
    #         object_order = self.create_order_object(user, order_items, total_off, total_cost)
    #         serializer2 = OrderSerializer(instance=object_order)
    #         return Response(serializer2.data, status=201)
    #     return Response(serializer.errors, status=400)


from flask_sqlalchemy import SQLAlchemy
from flask import Flask, jsonify, request,render_template,send_file
from app import app, db
from models import mediapp_patient, mediapp_userinfo, post, mediapp_problems
import datetime,os

# get imgs in the project
@app.route('/sys_img/<pic_path>',methods=['GET','POST'])
def returnPic(pic_path):
    fileDir = os.path.join(os.path.dirname(os.path.realpath('__file__')),'static')
    targetPath=os.path.join(fileDir,pic_path)

    return send_file(targetPath, mimetype='image/png') #, video/mp4

# return webpage
@app.route('/createUser',methods=['GET','POST'])
def showAddUserPage():
    #fileDir = os.path.join(os.path.dirname(os.path.realpath('__file__')),'static')
    #targetPath=os.path.join(fileDir,'index.html')
    #print(targetPath)
    #return render_template("index.html")
    return render_template("test.html")

'''routes connect to db and fetch data'''

@app.route('/test')
def index():

    sql_cmd = """
        select *
        from disease
        """
    query_data = db.engine.execute(sql_cmd)
    for row in query_data:
        print("id:", row)
    print(query_data)
    print("OK")
    return 'OK'

@app.route('/getPatientInfo/<patient_id>',methods=['POST'])
def getPatientInfo(patient_id):
    patient=mediapp_patient.query.filter_by(id=int(patient_id)).first()
    if patient:
        patientInfo={}
        patientInfo["name"]=patient.Name
        patientInfo["line_id"]=patient.lineID
        return jsonify(patientInfo),200
    else:
        return 'no such patient',500

@app.route('/getLineStatus',methods=['POST'])
def getLineStatus():
    print(request.get_json())
    line_id=request.get_json()["line_id"]
    linePatient=mediapp_patient.query.filter_by(lineID=line_id).all()
    lineStatus='0'
    if linePatient:
        for patient in linePatient:
            if patient.Certified=='1':
                lineStatus='1'
            elif patient.Certified=='2':
                lineStatus='2'
                break
    else:
        lineStatus='3'
        #0 patient has no line account
        #1 patient applied account, not certidfied
        #2 patient line account certified
        #3 lineid not found in db
    print('test\ntest\ntest\n')
    print(lineStatus)
    return lineStatus

@app.route('/getLinePending',methods=['POST'])
def getLinePending():
    line_id=request.get_json()["line_id"]
    linePatient=mediapp_patient.query.filter_by(lineID=line_id).all()
    pendings=[]
    if linePatient:
        for patient in linePatient:
            pendingInfo={}
            if patient.Certified=='1':
                pendingInfo["name"]=patient.Name
            pendings.append(pendingInfo)
        #0 patient has no line account
        #1 patient applied account, not certidfied
        #2 patient line account certified
        #3 lineid not found in db
    return jsonify(pendings),200

@app.route('/user/<lineID>',methods=['GET'])
def users(lineID):
    lineID = "'"+lineID+"'"
    sql_cmd = """
        select *
        from mediapp_patient
        where lineID =
        """+lineID

    data = []

    query_data = db.engine.execute(sql_cmd)
    for row in query_data:
        diction = {}
        phID = row['PharmacyID']
        print("user:", row['Name'],row['Sex'],row['PharmacyID'])
        diction['name'] = row['Name']
        diction['gender'] = row['Sex']
        userName = row['Name']
        userGender = row['Sex']

        sql_cmd2 = """
            select *
            from mediapp_userinfo
            where id =
            """ + phID

        query_data2 = db.engine.execute(sql_cmd2)

        for row2 in query_data2:
            # phID = row['PharmacyID']
            print("user:", row2['PhName'])
            diction['phName'] = row2['PhName']
            phName = row2['PhName']

        data.append(diction)
    print(data)
    print(query_data2)
    print('ok')

    return jsonify(data), 200

@app.route('/phInfo/<lineID>', methods=['GET'])
def phInfo(lineID):
    # lineID = "'"+lineID+"'"

    data = []

    # sql_cmd = """
    #     select *
    #     from mediapp_patient
    #     where lineID =
    # """ + lineID

    # query_data = db.engine.execute(sql_cmd)

    # for row in query_data:

    #     print("user:", row)
    #     phId = row['PharmacyID']

    # sql_cmd2 = """
    #     select *
    #     from mediapp_userinfo
    #     where id =
    # """ + phId

    # query_data2 = db.engine.execute(sql_cmd2)

    # for row in query_data2:
    #     diction = {}
    #     print("phInfo:", row)
    #     diction['phName'] = row['PhName']
    #     diction['phTel'] = row['Telephone']
    #     diction['phAdd'] = row['Address']
    #     diction['LineID'] = row['LineID']
    #     diction['WebURL'] = row['WebURL']
    #     data.append(diction)

    query = mediapp_patient.query.filter_by(lineID=lineID).all()
    if query:
        for num in query:
            query2 = mediapp_userinfo.query.filter_by(id=num.PharmacyID).first()
            if query2 != None:

                diction = {}
                print("phInfo:", query2)
                diction['phName'] = query2.PhName
                diction['phTel'] = query2.Telephone
                diction['phAdd'] = query2.Address
                diction['LineID'] = query2.LineID
                diction['WebURL'] = query2.WebURL
                data.append(diction)

            else:
                dictionErr = {}
                # dictionErr['result'] = 'Not Found'
                # dictionErr['userName'] = num.Name
                # data.append(dictionErr)

    else:
        dictionErr = {}
        # dictionErr['lineID'] = lineID
        # dictionErr['result'] = 'Not Found'
        # data.append(dictionErr)

    return jsonify(data) , 200

@app.route('/addUser', methods=['POST'])
def addUser():
    # , cardNumber, lineID, photo
    print('test1')
    print(request.form)
    print('test2')
    print('test3')
    req_data = request.form
    cardID = req_data['cardID']
    cardNumber = req_data['cardNumber']
    # celePhone = req_data['celePhone']
    lineID = req_data['lineID']
    lineName = req_data['lineName']

    check = mediapp_patient.query.filter_by(lineID = lineID).first()

    if check == None:
        query = mediapp_patient.query.filter_by(cardID=cardID).first()

        query.cardNumber = cardNumber
        # query.Celephone = celePhone
        query.lineID = lineID
        query.lineName = lineName
        query.Certified = 2
        db.session.commit()

    else:
        query = mediapp_patient.query.filter_by(cardID=cardID).first()

        query.cardNumber = cardNumber
        # query.Celephone = celePhone
        query.lineID = lineID
        query.lineName = lineName
        query.Certified = 1
        db.session.commit()

    return 'ok', 200

@app.route('/checkUser/<cardID>', methods=['GET'])
def checkUser(cardID):

    res = ''

    query = mediapp_patient.query.filter_by(cardID=cardID).first()
    if query == None:
        print('Not Found')
        res = 'Not Found'
    else:
        print(query.id)
        res = 'Found'

    return res, 200

@app.route('/checkTime/<lineID>',methods=['GET'])
def checkMul(lineID):
    # data = []
    # lineID = "'"+lineID+"'"
    # sql_cmd = """
    #     select *
    #     from mediapp_patient
    #     where lineID = """+lineID

    # query_data = db.engine.execute(sql_cmd)

    # for row in query_data:
    #     print("info: ",row['id'])
    #     sql_cmd2 = """
    #         select TakeMedDate
    #         from post
    #         where PatientID_id ={id}
    #     """.format(id=row['id'])
    #     query_data2 = db.engine.execute(sql_cmd2)
    #     for row2 in query_data2:
    #         diction = {}
    #         print("time: ",row2['TakeMedDate'])
    #         diction['dayStart'] = row2['TakeMedDate']
    #         d = datetime.datetime.strptime(row2['TakeMedDate'],'%Y-%m-%d')
    #         delta = datetime.timedelta(days=10)
    #         n_days = d + delta
    #         print (n_days.strftime('%Y-%m-%d'))
    #         diction['dayEnd'] = n_days.strftime('%Y-%m-%d')
    #         data.append(diction)

    #     # query_data = db.engine.execute(sql_cmd2)
    data=[]
    query = mediapp_patient.query.filter_by(lineID=lineID).all()
    if query:
        for num in query:
            query2 = post.query.filter_by(PatientID_id=num.id).all()
            if query2:
                for row2 in query2:
                    if row2:
                        diction = {}
                        diction['userName'] = num.Name
                        diction['dayStart'] = row2.TakeMedDate_start
                        d = datetime.datetime.strptime(row2.TakeMedDate_start,'%Y-%m-%d')
                        diction['weekDayStart'] = d.weekday()
                        delta = datetime.timedelta(days=10)
                        n_days = d + delta
                        diction['dayEnd'] = n_days.strftime('%Y-%m-%d')
                        diction['weekDayEnd'] = n_days.weekday()
                        diction['symptom']=row2.symptom
                        data.append(diction)
                        # print(data)
                    else:
                        diction2 = {}
                        diction2['userName'] = num.Name
                        diction2['result'] = 'Not Found'
                        data.append(diction2)
            else:
                diction2 = {}
                # diction2['userName'] = num.Name
                # diction2['result'] = 'Not Found'
                # data.append(diction2)
    else:
        diction3 = {}
        # diction3['lineID'] = lineID
        # diction3['result'] = 'Not Found'
        # data.append(diction3)

    return jsonify(data), 200
'''
@app.route('/notify/<postID>',methods=['GET'])
def notify(postID):
    sql_cmd = """
        update post
        set RemindStatus = 2
        where id = {id}""".format(id=postID)

    db.engine.execute(sql_cmd)

    return 'ok', 200

'''
@app.route('/problem',methods=['POST'])
def problem():
    req_data = request.form
    Type = req_data['Type']
    LineID = req_data['LineID']

    query = mediapp_patient.query.filter_by(lineID=LineID).first()
    if query is None:
        return 'Not Found', 400

    else:
        problemAns = mediapp_problems(Type=Type,LineID=LineID)
        db.session.add(problemAns)
        db.session.commit()

    return 'ok', 200

@app.route('/notify/<postID>',methods=['GET'])
def notify(postID):
    # sql_cmd = """
    #     update post
    #     set RemindStatus = 2
    #     where id = {id}""".format(id=postID)

    # db.engine.execute(sql_cmd)

    query = post.query.filter_by(id=postID).first()

    if query is None:
        return 'Not Found', 400
    else:
        query.RemindStatus = 2
        db.session.commit()

    return 'ok', 200

@app.route('/postPh/<PhName>',methods=['GET'])
def postUser(PhName):
    data = []
    query = mediapp_userinfo.query.filter_by(PhName=PhName).first()
    if query == None:
        return 'Not Found', 200
    else:
        diction = {}
        # print("phInfo:", query)
        diction['phName'] = query.PhName
        diction['phTel'] = query.Telephone
        diction['phAdd'] = query.Address
        diction['LineID'] = query.LineID
        diction['WebURL'] = query.WebURL
        data.append(diction)

    return jsonify(data), 200

@app.route('/postInfo/<int:id>',methods=['GET'])
def postInfo(id):
    data = []
    diction = {}
    diction['postID'] = id
    query = post.query.filter_by(id=id).first()
    if query == None:
        return 'Post not exist', 200
    else:
        query2 = mediapp_patient.query.filter_by(id=query.PatientID_id).first()
        if query2 == None:
            return 'Patient not exist', 200
        else:
            diction['Gender'] = query2.Sex
            diction['Name'] = query2.Name
            diction['lineID'] = query2.lineID

        query3 = mediapp_userinfo.query.filter_by(id=query.PharmacyID).first()

        if query3 == None:
            return 'Pharmacy null', 200
        else:
            diction['PhName'] = query3.PhName

        diction['dayStart'] = query.TakeMedDate_start
        d = datetime.datetime.strptime(query.TakeMedDate_start,'%Y-%m-%d')
        diction['weekDayStart'] = d.weekday()
        delta = datetime.timedelta(days=10)
        n_days = d + delta
        diction['dayEnd'] = n_days.strftime('%Y-%m-%d')
        diction['weekDayEnd'] = n_days.weekday()
        diction['symptom']=query.symptom
        data.append(diction)
        return jsonify(data),200


import openpyxl

# 1) 엑셀 만들기
wb = openpyxl.Workbook()

# 2) 엑셀 워크시트 만들기
ws = wb.create_sheet('오징어 게임')

# 3) 데이터 추가하기
ws['A1'] = '참가번호'
ws['B1'] = '성명'

ws['A2'] = 1
ws['B2'] = '오일남'

wb.save(r'C:\Users\kwons\Desktop\study\git_project\python_crawling\basic_crawling_1\Chapter05\참가자_data.xlsx')


import numpy as np
import scipy.stats as stats
import BayesianQuantitation as bqvd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import pickle
import math
import numpy
import seaborn as sns

def plotBarGraph(data,filename, colors, labels, xticks, xlabel, ylabel, legend = True):
	plt.close()

	f, ax1 = plt.subplots(1, figsize=(5,5))
	bar_width = 0.5
	bar_l = [i+1 for i in range(len(data[0]))]
	tick_pos = [i for i in bar_l]
	print(len(data))
	for i in range(len(data)):
		if(i==0):
			ax1.bar(bar_l, data[i],width=bar_width,label=labels[i],alpha=0.5,color=colors[i])
		elif(i==1):
			ax1.bar(bar_l, data[i],width=bar_width,bottom=data[i-1],label=labels[i],alpha=0.5,color=colors[i])
		elif(i==2):
			ax1.bar(bar_l, data[i],width=bar_width,bottom=[i+j for i,j in zip(data[i-1],data[i-2])],label=labels[i],alpha=0.5,color=colors[i])
		else:
			ax1.bar(bar_l, data[i],width=bar_width,bottom=[i+j+k for i,j,k in zip(data[i-1],data[i-2], data[i-3])],label=labels[i],alpha=0.5,color=colors[i])

	if(legend):
		plt.legend(frameon=True)
	plt.tight_layout()
	plt.savefig(filename)

functions = [r'$x$',r'$e^{x}$',r'$x^{2}$',r'$\frac{1}{x}$',r'$sin(x)$']
with open('results_nonLinearity_2.pickle','rb') as f:
	listsAssoc,probsAssoc, pearsonCorrelation, MI = pickle.load(f)

plt.close()
plt.style.use('ggplot')
plt.rcParams['axes.facecolor']='white'
plt.rcParams['grid.color']='gainsboro'

fig = plt.figure(figsize = (6,3), dpi = 300)
gs = gridspec.GridSpec(1,3, width_ratios = [1,0.05,1])
cbar_ax = fig.add_axes([.46, .28, .022, .5])

hMap = plt.subplot(gs[0,0])

sns.heatmap(probsAssoc, vmin = 0, vmax = 1, ax = hMap, cbar = True, square = True, xticklabels = functions, yticklabels = functions, cbar_ax = cbar_ax)
hMap.tick_params(labelsize = 8)
hMap.set_xlabel('Estimated Relationship Function',fontsize = 7)
hMap.set_ylabel('Actual Relationship Function',fontsize = 7)

cbar_ax.tick_params(labelsize = 7)

ax1 = plt.subplot(gs[0,2])
bar_width = 0.2
bar_Pearson = [1.1,2.1,3.1,4.1,5.1]
bar_MI = [1.1 + 0.2,2.1 + 0.2,3.1 + 0.2,4.1 + 0.2,5.1 + 0.2]
bar_Bayesian = [1.1 + 0.2 + 0.2,2.1 + 0.2 + 0.2,3.1 + 0.2 + 0.2,4.1 + 0.2 + 0.2,5.1 + 0.2 + 0.2]
data_ph1 = [probsAssoc[i][i] for i in range(5)]
tick_pos = [1.25,2.25,3.25,4.25,5.25]
ax1.bar(bar_Pearson, pearsonCorrelation,width=bar_width,label='Pearson Correlation Coefficient',alpha=0.5,color='silver')
ax1.bar(bar_MI, MI,width=bar_width,label=r'Mutual Information Content',alpha=0.5,color='dimgray')
ax1.bar(bar_Bayesian, data_ph1,width=bar_width,label=r'$P(H_1)$',alpha=0.5,color='black')
plt.xticks([1.3,2.3,3.3,4.3,5.3], functions, ha = 'center')
ax1.set_yticks([0,0.5,1])
ax1.set_xlabel('Choice of function', fontsize = 7)
ax1.set_ylabel('Results', fontsize = 7)
ax1.set_xlim([min(tick_pos)-2.5*bar_width, max(tick_pos)+2*bar_width])
ax1.legend(frameon = True, fontsize = 7, loc = 'upper right')
ax1.set_ylim([0,1.3])
ax1.tick_params(labelsize = 7)
fig.text(0.03,0.93,'a',fontsize = 7, fontweight = 'bold')
fig.text(0.55,0.93,'b',fontsize = 7, fontweight = 'bold')
plt.tight_layout()
plt.savefig('Figure6.png', dpi = 300)


from django.conf.urls import url
from django.contrib import admin

from .views import (
	blogue_list,
	blogue_details,
	)

urlpatterns = [
	url(r'^$', blogue_list, name='liste'),
	url(r'^article$', blogue_details, name='details'),
]


from django.urls import path

from datahub.company.views import (
    CompanyAuditViewSet,
    CompanyViewSet,
    ExportWinsForCompanyView,
    OneListGroupCoreTeamViewSet,
    PublicCompanyViewSet,
)

company_collection = CompanyViewSet.as_view({
    'get': 'list',
    'post': 'create',
})

company_item = CompanyViewSet.as_view({
    'get': 'retrieve',
    'patch': 'partial_update',
})

company_audit = CompanyAuditViewSet.as_view({
    'get': 'list',
})

company_archive = CompanyViewSet.as_action_view('archive')

company_unarchive = CompanyViewSet.as_action_view('unarchive')

company_assign_regional_account_manager = CompanyViewSet.as_action_view(
    'assign_regional_account_manager',
)

company_self_assign_account_manager = CompanyViewSet.as_action_view(
    'self_assign_account_manager',
)

company_remove_account_manager = CompanyViewSet.as_action_view(
    'remove_account_manager',
)

company_assign_one_list_tier_and_global_account_manager = CompanyViewSet.as_action_view(
    'assign_one_list_tier_and_global_account_manager',
)

company_remove_from_one_list = CompanyViewSet.as_action_view('remove_from_one_list')

update_export_detail = CompanyViewSet.as_action_view(
    'update_export_detail',
)

one_list_group_core_team = OneListGroupCoreTeamViewSet.as_view({
    'get': 'list',
})

update_one_list_core_team = CompanyViewSet.as_action_view(
    'update_one_list_core_team',
)

public_company_item = PublicCompanyViewSet.as_view({
    'get': 'retrieve',
})

urls = [
    path('company', company_collection, name='collection'),
    path('company/<uuid:pk>', company_item, name='item'),
    path('company/<uuid:pk>/archive', company_archive, name='archive'),
    path('company/<uuid:pk>/unarchive', company_unarchive, name='unarchive'),
    path('company/<uuid:pk>/audit', company_audit, name='audit-item'),
    path(
        'company/<uuid:pk>/assign-regional-account-manager',
        company_assign_regional_account_manager,
        name='assign-regional-account-manager',
    ),
    path(
        'company/<uuid:pk>/self-assign-account-manager',
        company_self_assign_account_manager,
        name='self-assign-account-manager',
    ),
    path(
        'company/<uuid:pk>/remove-account-manager',
        company_remove_account_manager,
        name='remove-account-manager',
    ),
    path(
        'company/<uuid:pk>/assign-one-list-tier-and-global-account-manager',
        company_assign_one_list_tier_and_global_account_manager,
        name='assign-one-list-tier-and-global-account-manager',
    ),
    path(
        'company/<uuid:pk>/remove-from-one-list',
        company_remove_from_one_list,
        name='remove-from-one-list',
    ),
    path(
        'company/<uuid:pk>/one-list-group-core-team',
        one_list_group_core_team,
        name='one-list-group-core-team',
    ),
    path(
        'company/<uuid:pk>/update-one-list-core-team',
        update_one_list_core_team,
        name='update-one-list-core-team',
    ),
    path(
        'company/<uuid:pk>/export-detail',
        update_export_detail,
        name='update-export-detail',
    ),
    path(
        'company/<uuid:pk>/export-win',
        ExportWinsForCompanyView.as_view(),
        name='export-win',
    ),
    path('public/company/<uuid:pk>', public_company_item, name='public-item'),
]


# Browser
BROWSER = 'ChromiumDesktop'
BROWSER_HEIGHT = 1080
BROWSER_LIB='chromium'
BROWSER_LIB_HEADLESS=False
BROWSER_LIB_IS_MOBILE=False
BROWSER_LIB_LOCALE='de-DE'
BROWSER_OPTIONS = ''
BROWSER_WIDTH = 1920
INNER_WINDOW_SIZE = "0x0"
MAIN_CONTEXT = ""
USER_AGENT = ""
WINDOW_SIZE= "0x0"

# URLS
LOGIN_URL = ""
MY_ACCOUNT_URL = ""


class Environment:
    def __init__(self, globalRecipe, globalIngredient, globalPurchasable, agent, initialState, rawIngredients):
        self.globalRecipe = globalRecipe
        self.globalIngredient = globalIngredient
        self.globalPurchasable = globalPurchasable
        self.rawIngredients = rawIngredients
        self.agent = agent
        self.initialState = initialState
        self.visitedCombinations = {}

    def __Generate_Basket(self, recipe, basket, purchasedList):
        clonedBasket = basket.copy()
        for purchasedItem in purchasedList:
            if purchasedItem not in clonedBasket:
                clonedBasket[purchasedItem] =  purchasedList[purchasedItem]
            else:
                clonedBasket[purchasedItem] = clonedBasket[purchasedItem] + purchasedList[purchasedItem]
        for ingredient in recipe["ingredients"]:
            if ingredient in clonedBasket:
                clonedBasket[ingredient] = clonedBasket[ingredient] - 1
                if clonedBasket[ingredient] <= 0:
                    clonedBasket.pop(ingredient)
        return clonedBasket

    def __Generate_Purchased_Item(self, recipe, basket):
        purchaseList = {}
        for ingredient in recipe["ingredients"]:
            if ingredient not in basket:
                purchaseList[ingredient] = self.globalPurchasable[ingredient]
        return purchaseList

    def __Calculate_Cost(self, recipe, purchaseList):
        cost = sum([self.globalIngredient[ingredient]["cost"]*self.globalPurchasable[ingredient] for ingredient in purchaseList])
        calories = sum([self.globalIngredient[ingredient]["calories"] for ingredient in recipe["ingredients"]])
        return self.agent.caloriesPreference*calories + self.agent.costPreference*cost

    def __Is_Visited_Already(self, cookedMeal):
        clonedVisitedCombinations = self.visitedCombinations.copy()
        cookedSet = set(cookedMeal)
        if len(cookedMeal) in clonedVisitedCombinations:
            shouldAddToCombination = True
            for combinations in clonedVisitedCombinations[len(cookedMeal)]:
                if len(cookedSet.intersection(combinations)) == len(cookedMeal):
                    shouldAddToCombination = False
                    break
            if shouldAddToCombination:
                clonedVisitedCombinations[len(cookedMeal)].append(cookedSet)
                self.visitedCombinations = clonedVisitedCombinations
                return False
            return  True
        self.visitedCombinations[len(cookedMeal)] = [cookedSet]
        return False

    def __Generate_Nodes(self, currentNode):
        for_sort_nodes = []
        if currentNode["mealNumber"] < self.agent.numberOfMeal:
            for recipe in self.globalRecipe:
                if recipe not in currentNode["cookedMeal"]:
                    selectedRecipe = self.globalRecipe[recipe]
                    cookedMeal =  currentNode["cookedMeal"] + [recipe]
                    isVisitedCombination = self.__Is_Visited_Already(cookedMeal)
                    if not isVisitedCombination:
                        purchasedList = self.__Generate_Purchased_Item(
                            selectedRecipe,
                            currentNode["basket"]
                        )
                        basket = self.__Generate_Basket(
                            selectedRecipe,
                            currentNode["basket"],
                            purchasedList
                        )
                        cost = self.__Calculate_Cost(
                            selectedRecipe,
                            purchasedList
                        )
                        heuristic = self.__Calculate_Heuristic(basket, currentNode["mealNumber"], cookedMeal)
                        if heuristic is not None:
                            for_sort_nodes.append({
                                "basket": basket,
                                "cost": currentNode["previousGrocceryCost"] + cost + heuristic,
                                "previousGrocceryCost": currentNode["previousGrocceryCost"] + cost,
                                "cookedMeal": cookedMeal,
                                "mealNumber": currentNode["mealNumber"] + 1,
                            })
            self.agent.fringe = self.agent.fringe + for_sort_nodes
            self.agent.fringe.sort(key = lambda x: x["cost"], reverse = False)

    def __Unrestrainded_Generate_Purchased_Item(self, recipe, basket):
        purchaseList = {}
        for ingredient in recipe["ingredients"]:
            if ingredient not in basket:
                purchaseList[ingredient] = 1
        return purchaseList

    def __Find_Cheapest_Recipe_With_Ingredient(self, ingredient, basket, cookedMeal):
        minCost = None
        cheapestRecipe = None
        cheapestPurchaseList = None
        for recipe in self.globalRecipe:
            selectedRecipe = self.globalRecipe[recipe]
            if ingredient in selectedRecipe["ingredients"] and selectedRecipe["id"] not in cookedMeal:
                purchaseList = self.__Unrestrainded_Generate_Purchased_Item(selectedRecipe, basket)
                cost = self.__Calculate_Cost(selectedRecipe, purchaseList)
                if minCost == None or cost < minCost:
                    minCost = cost
                    cheapestRecipe = recipe
                    cheapestPurchaseList = purchaseList
        if minCost == None:
            return (None, None, None)
        return (minCost, cheapestRecipe, cheapestPurchaseList)

    def __Calculate_Recipe_Cost(self, recipe):
        costList = []
        caloriesList = []
        for ingredient in recipe["ingredients"]:
            selectedIngredient = self.globalIngredient[ingredient]
            costList.append(selectedIngredient["cost"])
            caloriesList.append(selectedIngredient["calories"])
        return (self.agent.costPreference*sum(costList))+(self.agent.caloriesPreference*sum(caloriesList))

    def __Sequential_Cheapest_Recipe_Cost_For(self, cookedMeal, mealLeft):
        result = []
        for recipe in self.globalRecipe:
            selectedRecipe = self.globalRecipe[recipe]
            if selectedRecipe["id"] not in cookedMeal:
                result.append(self.__Calculate_Recipe_Cost(selectedRecipe))
        result.sort(reverse=False)
        return sum(result[:mealLeft])

    def __Calculate_Heuristic(self, basket, mealNumber, cookedMeal):
        clonedBasket = basket.copy()
        heuristic = 0
        counter = mealNumber + 1
        while True:
            if len(clonedBasket) == 0:
                break
            counter += 1
            if counter > self.agent.numberOfMeal:
                return None
            ingredient = list(clonedBasket.items())[0][0]
            costRecipeTuple = self.__Find_Cheapest_Recipe_With_Ingredient(ingredient, clonedBasket, cookedMeal)
            if costRecipeTuple[0] == None:
                return None
            clonedBasket = self.__Generate_Basket(self.globalRecipe[costRecipeTuple[1]], clonedBasket, costRecipeTuple[2])
            heuristic += costRecipeTuple[0]

        mealLeft = self.agent.numberOfMeal - counter
        if mealLeft != 0:
            heuristic += self.__Sequential_Cheapest_Recipe_Cost_For(cookedMeal, mealLeft)
        return heuristic

    def __To_MealPlan(self, node):
        menu = []
        basket = self.initialState["basket"]
        for recipe in node["cookedMeal"]:
            selectedRecipe = self.globalRecipe[recipe]
            purchasedList = self.__Generate_Purchased_Item(selectedRecipe, basket)
            basket =  self.__Generate_Basket(selectedRecipe, basket, purchasedList)
            ingredients = []
            for ingredient in purchasedList:
                selectedIngredient = self.rawIngredients[ingredient]
                ingredients.append({
                    "id": ingredient,
                    "name": selectedIngredient["name"],
                    "url": selectedIngredient["url"],
                    "calories": round(selectedIngredient["calories"],2),
                    "cost": round(selectedIngredient["cost"],2),
                    "quantity": round(purchasedList[ingredient],2)
                })
            menu.append(
                {
                    "id": recipe,
                    "name": selectedRecipe["recipe"],
                    "url": selectedRecipe["url"],
                    "calories": round(sum([ self.rawIngredients[ingredient]["calories"] for ingredient in selectedRecipe["ingredients"]]),2),
                    "cost": sum([ingredient["cost"] * ingredient["quantity"] for ingredient in ingredients]),
                    "shoppingList": ingredients
                }
            )
        return menu

    def Simulate(self, goalState):
        currentNode = {
            "cost": 0,
            "basket": self.initialState["basket"],
            "cookedMeal": [],
            "mealNumber": 0,
            "previousGrocceryCost": 0
        }
        self.__Generate_Nodes(currentNode)
        while len(self.agent.fringe) > 0:
            lowestCostNode = self.agent.fringe.pop(0)
            if lowestCostNode["basket"] == goalState["basket"] and lowestCostNode["mealNumber"] == goalState["numberOfMeal"]:
                return self.__To_MealPlan(lowestCostNode)
            self.__Generate_Nodes(lowestCostNode)
        return None

def BuildEnvironment(globalRecipe, globalIngredient, globalPurchasable, agent, initialState, rawIngredients):
    return Environment(globalRecipe, globalIngredient, globalPurchasable, agent, initialState, rawIngredients)


import sys
sys.stdin = open("data/in6.txt", "rt")
N = int(sys.stdin.readline())

#내 풀이 (강의 풀이가 훨씬 효율적이다.)
num_max = -2400000 #최대 점수
for i in range(N) :
    arr = list(map(int, sys.stdin.readline().split())) #[3, 3, 6] [0, 0, 0] [0, 0, 0] ...
    cnt = 0 # 같은 수가 몇 개인지 저장 됨
    num = 0 #점수 계산
    for j, x in enumerate(arr) : #3 3 6 따로 출력
        cnt_check = 0 # cnt 저장 전 카운팅
        for k, y in enumerate(arr) :
            if arr[j] == arr[k] : #[0] == [1][2][3] ...
                cnt_check += 1
        if cnt < cnt_check : # cnt _check 중에서 가장 큰 값을 저장
            cnt = cnt_check
    if cnt == 3 :
        num = 10000 + (arr[0] * 1000)

    if cnt == 2 :
        for q, a in enumerate(arr) :
            cnt_check = 0
            for k, y in enumerate(arr) :
                if arr[q] == arr[k] :
                    cnt_check += 1
            if cnt_check == 2 :
                num = 1000 + (a * 100)
                break ##cnt_check 가 2가 될 때의 a 값은 중복 값이기 때문에 사용

    if cnt == 1 :
        arr.sort(reverse = True)
        num = arr[0] * 100

    if num_max < num :
        num_max = num

print(num_max)

# 강의 풀이
res = 0
for i in range(N) :
    tmp = list(sys.stdin.readline().split())
    tmp.sort() # 미리 정렬을 해둔다
    a, b, c = map(int, tmp) #list를 a, b ,c 각각 변수에 저장
    if a == b and b ==c : # abc가 모두 같을 때
        money = 10000 + (a * 1000)
    elif a == b or a == c : #abc 중 2개만 같은 때
        money = 1000 + (a * 100)
    elif b == c : #abc 중 2개만 같은 때
        money = 1000 + (b * 100)
    else :
        money = c * 100
    if money > res :
        res = money
print(res)

inflearn/section2 코드 구현력 기르기/9. 주사위 게임/AA.py


import base64
import json
import re
import yaml
from pathlib import Path
from . import errors

file_suffix = "#file"
max_value_size_bytes = 5 * 1024
max_content_size_bytes = 64 * 1024

def create_secret_data(args):
    """CreateSecretData creates a secret data bag from a list of arguments.
    If a key has the #base64 suffix, then the value is already base64 encoded,otherwise the value is base64 encoded as it is added to the data bag.

    If a key has the '#file' suffix, the value is read from the corresponding file.

    :return []str: bag of key value pairs for a secret
    """
    data = {}
    for val in args:
        # Remove any base64 padding ("=") before splitting the key=value.
        stripped = val.rstrip(base64.b64encode(b'=').decode('utf-8'))
        idx = stripped.find("=")
        if idx < 1:
            raise ValueError(f"Invalid key value {val}")

        key = stripped[0:idx]
        value = stripped[idx + 1:]

        # If the key doesn't have the #file suffix, then add it to the bag and continue.
        if not key.endswith(file_suffix):
            data[key] = value
            continue

        key = key.rstrip(file_suffix)
        path = Path(value).resolve()
        try:
            fs = path.stat()
            if fs.st_size > max_value_size_bytes:
                raise ValueError(f"Secret content in file {path} too large: {fs.st_size} bytes")
            content = path.read_text()
            data[key] = content
        except Exception as e:
            raise ValueError(f"Error processing key {key}: {e}")

    return encode_values_base64(data)

def read_secret_data(file):
    """ReadSecretData reads secret data from a YAML or JSON file as key value pairs.

    :param file str: Path to a YAML or JSON file to read values from.

    :return []str: bag of key value pairs for a secret
    """
    data = {}
    path = Path(file).resolve()

    try:
        fs = path.stat()
        if fs.st_size > max_content_size_bytes:
            raise ValueError(f"Secret content in file {path} too large: {fs.st_size} bytes")
    except FileNotFoundError:
        raise FileNotFoundError(f"The file {path} does not exist.")
    except OSError:
        raise

    try:
        with open(path, 'r', encoding='utf-8') as file:
            data = file.read()
    except Exception:
        raise

    try:
        data = json.loads(data)
    except json.JSONDecodeError:
        try:
            data = yaml.safe_load(data)
        except yaml.YAMLError:
            raise errors.JujuNotValid(f"Invalid data file at: {file}")

    return encode_values_base64(data)

base64_suffix = "#base64"
key_reg_exp = re.compile("^([a-z](?:-?[a-z0-9]){2,})$")

def encode_values_base64(data):
    """Encodes the values in the given data bag for a secret

    If a key has the #base64 suffix, then the value is already base64 encoded,otherwise the value is base64 encoded as it is added to the data bag.
    """

    out = {}
    content_size = 0
    for k, v in data.items():
        if len(v) > max_value_size_bytes:
            raise ValueError(f"secret content for key {k} too large: {len(v)} bytes")
        content_size += len(v)
        if k.endswith(base64_suffix):
            k = k[:-7]
            if not key_reg_exp.match(k):
                raise ValueError(f"Not valid key: {k}")
            out[k] = v
            continue
        if not key_reg_exp.match(k):
            raise ValueError(f"Not valid key: {k}")
        out[k] = base64.b64encode(str(v).encode()).decode()
    if content_size > max_content_size_bytes:
        raise ValueError(f"secret content too large: {content_size} bytes")
    return out


import os
import json
import csv
data_dict = {}
data_dict['intents'] = []

with open('./Datasets/Mental_Health_FAQ.csv', encoding = 'utf-8') as csv_file_handler:
    csv_reader = csv.DictReader(csv_file_handler)
    for row in csv_reader:
        row['tag'] = row['Question_ID']
        del(row['Question_ID'])
        row['patterns'] = row['Questions']
        del(row['Questions'])
        row['responses'] = row['Answers']
        del(row['Answers'])
        data_dict['intents'].append(row)

with open('./JSON/faq.json', 'w', encoding = 'utf-8') as json_file_handler:
    json_file_handler.write(json.dumps(data_dict, indent = 4))


import sys
input = sys.stdin.readline

def input_list_numbers():
    return(list(map(int, input().split())))

t = int(input())
tests = [None] * t

for i in range(t):
    tests[i] = input_list_numbers()

for test in tests:
    small_side = min(test)
    big_side = max(test)

    if 2 * small_side >= big_side:
        print((2*small_side)**2)
    else:
        print(big_side**2)


import pygame.font

class Info_Screen():
    def __init__(self, screen):
        #Hyun_ 화면의 크기, 위치, 색상, 폰트, 폰트 색상 등 설정
        self.screen = screen
        self.screen_rect = screen.get_rect()
        self.width, self.height = 600, 600
        self.rect_color = (0, 255, 0)
        self.text_color = (0, 0, 0)
        self.font = pygame.font.SysFont(None, 30)
        self.title_font = pygame.font.SysFont(None, 100)
        self.rect = pygame.Rect(0, 0, self.width, self.height)
        self.rect.center = self.screen_rect.center

        #Hyun_ 출력할 텍스트, 이미지 설정 및 렌더 메소드 실행
        self.title = 'Alien Invasion'
        self.msgs_page_1 = ['Defeat the Aliens and earn points by shooting them',
                   'Use" <-  -> " arrow keys to move horizontally',
                   'Press SPACEBAR to shoot aliens',
                    ' --------Alien Speed-------- ',
                    'EASY: 0.5, NORMAL = 1.0, HARD = 1.5'
        ]
        self.msgs_page_1_rect_y = [-50, 0, 50, 100, 150]
        self.aliens = [pygame.image.load('assets/redalien.png'),
                        pygame.image.load('assets/blue.png'),
                        pygame.image.load('assets/black.png')]
        self.msgs_page_2 = ['_______________Bonuses_______________',
                            'Alien Speed Up',
                            'Alien Speed Down',
                            'Ship Shooting Speed Up']
        self.msgs_page_2_rect_y = [-100, 20, 80, 140]

        self.prep_msgs(self.msgs_page_1, self.msgs_page_2)

        #Hyun_ 화면 출력중인지 저장
        self.status = False
        #Hyun_ 현재 페이지 저장
        self.currentPage = 1

    # Hyun_ 텍스트 렌더 및 배치 메소드
    def prep_msgs(self, msgs_page_1, msgs_page_2):
        #Hyun_ 타이틀
        self.title_image = self.title_font.render(self.title, True, self.text_color, self.rect_color)
        self.title_image_rect = self.title_image.get_rect()
        self.title_image_rect.centerx = self.rect.centerx
        self.title_image_rect.top = self.rect.top + 20

        #Hyun_ 1페이지에서 쓰일 텍스트
        msg_page_1_images = [self.font.render(msg, True, self.text_color, self.rect_color) for msg in msgs_page_1]
        msg_page_1_image_rects = [img.get_rect() for img in msg_page_1_images]
        for rect, y in zip(msg_page_1_image_rects, self.msgs_page_1_rect_y):
            rect.centerx = self.rect.centerx
            rect.centery = self.rect.centery + y

        #Hyun_ 2페이지에서 쓰일 이미지 및 텍스트
        alien_image_rects = [img.get_rect() for img in self.aliens]
        msg_page_2_images = [self.font.render(msg, True, self.text_color, self.rect_color) for msg in msgs_page_2]
        msg_page_2_image_rects = [img.get_rect() for img in msg_page_2_images]
        for rect, y in zip(msg_page_2_image_rects, self.msgs_page_2_rect_y):
            if y < 0:
                rect.centerx = self.rect.centerx
            else:
                rect.left = self.rect.right - 300
            rect.centery = self.rect.centery + y
        for rect, y in zip(alien_image_rects, self.msgs_page_2_rect_y[1:]):
            rect.right = self.rect.left + 200
            rect.centery = self.rect.centery + y

        #Hyun_ self.page에 각 페이지별 출력할 텍스트들, 이미지들을 딕셔너리로 저장
        self.page = {1: [[msg_page_1_images, msg_page_1_image_rects]],
                    2: [[msg_page_2_images, msg_page_2_image_rects], [self.aliens, alien_image_rects]]}

    #Hyun_ 출력 메소드
    def draw_screen(self):
        self.screen.fill(self.rect_color, self.rect)
        self.screen.blit(self.title_image, self.title_image_rect)

        #Hyun_ 현재 페이지에 맞는 텍스트, 이미지를 출력함
        for items in self.page[self.currentPage]:
            for img, rect in zip(items[0], items[1]):
                self.screen.blit(img, rect)


from django.conf.urls import patterns, url

from app_store import views

urlpatterns = patterns(
	'',
	url(r'^$', views.index, name='index'),
	url(r'^app/(?P<app_id>\d+)/$', views.detail, name='detail'),
	url(r'^category/(?P<category_id>\d+)/$', views.category, name='category'),
	url(r'^categories$', views.categories, name='categories'),
	url(r'^search$', views.search, name='search'),
	url(r'^app_lists$', views.app_lists, name='app_lists'),
	url(r'app_list/(?P<list_id>\d+)/$', views.app_list, name='app_list'),
	url(r'review/(?P<app_id>\d+)/$', views.new_review, name='new_review'),
	url(r'new_app$', views.new_application, name='new_app'),
	url(r'review_apps$', views.review_applications, name='review_apps'),
	url(r'review_app/(?P<app_id>\d+)/(?P<choice>\d+)/$', views.review_application, name='review_app'),
	url(r'about$', views.about, name='about'),
	url(r'app_list_entry/(?P<app_id>\d+)/$', views.new_app_list_entry, name='new_app_list_entry'),
)


#!/usr/bin/env python
# encoding: utf-8

import my_stack
s=my_stack.Stack(10)
for i in range(9):
    s.push(i)
s.show()
s.push(9)
s.show()
s.push(10)
s.pop()
s.show()
print(s.length())
print(s.get_top())
for i in range(9):
    s.pop()
s.pop()
print(s.get_top())


"""
The main file, which exposes the robustness command-line tool, detailed in
:doc:`this walkthrough <../example_usage/cli_usage>`.
"""

from argparse import ArgumentParser
import os, random
import torch as ch
ch.backends.cudnn.deterministic = True
import numpy as np
import helper as hp

try:
    from .model_utils import make_and_restore_model
    from .datasets import DATASETS
    from .train import train_model, eval_model
    from .tools import constants, helpers
    from . import defaults, __version__
    from .defaults import check_and_fill_args
except:
    raise ValueError("Make sure to run with python -m (see README.md)")

parser = ArgumentParser()
parser = defaults.add_args_to_parser(defaults.CONFIG_ARGS, parser)
parser = defaults.add_args_to_parser(defaults.MODEL_LOADER_ARGS, parser)
parser = defaults.add_args_to_parser(defaults.TRAINING_ARGS, parser)
parser = defaults.add_args_to_parser(defaults.PGD_ARGS, parser)
parser.add_argument('--devices', '-dev', nargs='+', type=int,
    required=False, default=[0], help='Visible GPUs')

def main(args, store=None):
    '''Given arguments from `setup_args` and a store from `setup_store`,
    trains as a model. Check out the argparse object in this file for
    argument options.
    '''
    # MAKE DATASET AND LOADERS
    data_path = os.path.expandvars(args.data)
    dataset = DATASETS[args.dataset](data_path)

    model_type = f'robust/l{args.constraint}/eps{args.eps}/iters{args.attack_steps}' if args.adv_train else 'nonrobust'
    model_type += f'da_{bool(args.data_aug)}'
    args.out_dir += f'/{args.dataset}/{args.arch}/{model_type}'
    hp.recursive_create_dir(args.out_dir)

    train_loader, val_loader = dataset.make_loaders(args.workers,
                    args.batch_size, data_aug=bool(args.data_aug))

    train_loader = helpers.DataPrefetcher(train_loader, device=ch.device(f'cuda:{args.devices[0]}'))
    val_loader = helpers.DataPrefetcher(val_loader, device=ch.device(f'cuda:{args.devices[0]}'))
    loaders = (train_loader, val_loader)

    # SET RANDOM SEED
    ch.manual_seed(args.random_seed)
    np.random.seed(args.random_seed)
    random.seed(args.random_seed)
    # MAKE MODEL
    model, checkpoint = make_and_restore_model(arch=args.arch,
            dataset=dataset, resume_path=args.resume,
            parallel=len(args.devices)>1, devices=args.devices)

    print(args)
    if args.eval_only:
        return eval_model(args, model, val_loader, store=store)

    if not args.resume_optimizer: checkpoint = None
    model = train_model(args, model, loaders, dp_device_ids=args.devices,
        store=store, checkpoint=checkpoint)

    return model

def setup_args(args):
    '''
    Fill the args object with reasonable defaults from
    :mod:`robustness.defaults`, and also perform a sanity check to make sure no
    args are missing.
    '''
    ds_class = DATASETS[args.dataset]
    args = check_and_fill_args(args, defaults.CONFIG_ARGS, ds_class)

    if not args.eval_only:
        args = check_and_fill_args(args, defaults.TRAINING_ARGS, ds_class)

    if args.adv_train or args.adv_eval:
        args = check_and_fill_args(args, defaults.PGD_ARGS, ds_class)

    args = check_and_fill_args(args, defaults.MODEL_LOADER_ARGS, ds_class)
    if args.eval_only: assert args.resume is not None, \
            "Must provide a resume path if only evaluating"
    return args

if __name__ == "__main__":
    args = parser.parse_args()
    args = setup_args(args)
    main(args)


import cv2

import numpy as np

# Create a black image
img = np.zeros((512,512,3), np.uint8)

# Draw a diagonal blue line with thickness of 5 px
img = cv2.line(img, (0,0), (511,511), (255, 0, 0), 5)

# Draw a rectangle green line with thickness of 3 px
img= cv2.rectangle(img, ( 384 , 0 ),( 510 , 128 ),( 0 , 255 , 0 ), 3)

# Draw a circele red line with thickness of 1 px inside
img = cv2.circle(img,(447,63), 63, (0,0,255), -1)

#Draw an ellipse with center: 256 256 axis lenght 100 50 rotation ellipse 0 rotation of ellipse from to 0 180 and cthickness 1 px inside
img = cv2.ellipse( img ,( 256 , 256 ),( 100 , 50 ), 0 , 0 , 180 , 255 , - 1)

cv2.imshow("image", img )
cv2.waitKeyEx()

# we can drawing poligon
#            and write text
#https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_drawing_functions/py_drawing_functions.html


from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.auth.models import User
from player.models.img import Img

class ReceiveView(APIView):

    def post(self, request):
        data =  request.POST
        user = User.objects.get(id=data['userId'])
        img = Img.objects.create(user=user, filename=data['filename'], randomname=data['randomname'], size=data['size'],
                mimetype=data['mimeType'], height=data['height'], width=data['width'], url='https://img.zzqahm.top/%s' %
                data['randomname'])
        img.save()
        return Response({
            'result': "success",
            'imgId': img.id,
            'imgName': img.filename,
            'imgUrl': img.url
        })


def swap(lst, a, b):
    tmp = lst[a]
    lst[a] = lst[b]
    lst[b] = tmp

def insertionSort(lst):
    i = 1
    while i < len(lst):
        insertionItem = lst[i]
        j = i - 1
        while j >= 0:
            if insertionItem < lst[j]:
                lst[j+1] = lst[j]
            else:
                break
            j -= 1
        lst[j+1] = insertionItem
        print(lst)
        i += 1

lst = [2,5,1,4,3]
insertionSort(lst)


from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.parsers import JSONParser
from .models import *
from .serializers import *
from rest_framework.views import APIView
from django.http import Http404
from rest_framework import mixins
from rest_framework import generics
from django.contrib.auth.models import User
from Login.verifications import wxlogin,create_jwt_token
from utils.default_value import default_response
from utils.decorator import new_login_check

# Create your views here.

# 获取用户列表
class user_list(generics.ListCreateAPIView):
    queryset = Userinfo.objects.all()
    serializer_class = UserInfoSerializer

# 针对特定用户操作
class user_detail(APIView):
    def get_objects(self,pk):
        try:
            return Userinfo.objects.get(pk=pk)
        except Userinfo.DoesNotExist:
            raise Http404
    def get(self,request,pk,format=None):
        user = self.get_objects(pk)
        serializer = UserInfoSerializer(user)
        result = default_response()
        result['data'] = serializer.data
        return Response(result)
    def put(self,request,pk,format=None):
        user = self.get_objects(pk)
        serializer = UserInfoSerializer(user,data=request.data)
        print(request.data)
        if serializer.is_valid():
            serializer.save()
            result = default_response()
            result['data'] = serializer.data
            return Response(result)
        return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
    def delete(self,request,pk,format=None):
        user = self.get_objects(pk)
        user.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

class user_message(mixins.ListModelMixin,generics.GenericAPIView,mixins.CreateModelMixin):
    queryset = Usermassage.objects.all()
    serializer_class = UsermassageSerializer

    def post(self,request,*args,**kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            serializer.save()
        result = default_response()
        result['data'] = serializer.data
        return Response(result)

class user_collect(mixins.ListModelMixin,generics.GenericAPIView,mixins.CreateModelMixin):
    queryset = UserCollection.objects.all()
    serializer_class = CollectSerializer
    def get_objects(self,pk):
        try:
            return UserCollection.objects.get(pk=pk)
        except UserCollection.DoesNotExist:
            raise Http404

    def post(self,request,*args,**kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            serializer.save()
        result = default_response()
        result['data'] = serializer.data
        return Response(result)

    def delete(self, request, pk, format=None):
        collect = self.get_objects(pk)
        collect.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

@api_view(['POST'])
def wxlogin_view(request, format=None):
    """
    小程序端微信登录
    """
    print(request.data)
    result = default_response()
    instance = wxlogin(request)
    if instance is None:
        result['data']['reseaion'] = "登录失败"
        return Response(result)
    jwt_token = create_jwt_token(instance.open_id)
    result['data']['JWT'] = jwt_token
    result['data']['user_id'] = instance.id
    return Response(result)


import pandas as pd  # For data handling
from gensim.models import Word2Vec
import operator
from numpy import take
from snowballstemmer import TurkishStemmer
import itertools

####   Migros ürün açıklamaları ve productstxt kullanılarak eğitilmiş modeli kullanarak search engine

model = Word2Vec.load('C:/Users/Lenovo/Desktop/Bitirme/Word2Vec.v3/models/trained_data.model.bin')
df = pd.read_csv('C:/Users/Lenovo/Desktop/Bitirme/Word2Vec.v3/files/product_catalog.v2.csv')
df_clean = df.drop_duplicates(subset=['ProductName', 'ManufacturerName'])
abbrev = ['lı', 'li', 'lu', 'lü', 'kg', 'gr', 'lt', 'ml', 'cm', 'migros']
f = open('files/stopwords.txt', 'r', encoding='utf8')
stopwords = f.read()

# For Turkish Character
translationTable = str.maketrans("ğĞıİöÖüÜşŞçÇ", "gGiIoOuUsScC")
from itertools import islice

def take(n, iterable):
    "Return first n items of the iterable as a list"
    return list(islice(iterable, n))

def lowerForTurkish(str):
    rep = [('I', 'ı'), ('İ', 'i')]
    for search, replace in rep:
        str = str.replace(search, replace)
    return str.lower()
def check_corpus(context):
    context = lowerForTurkish(context)
    valid_harf = ["a", "b", "c", "ç", "d", "e", "f", "g", "ğ", "h", "ı", "i", "j", "k", "l"
        , "m", "n", "o", "ö", "p", "r", "s", "ş", "t", "u", "ü", "v", "y", "z","w","q", "w",' ' ]

    ncontext = ""
    for i in range(len(context)):
        if context[i] in valid_harf:
            ncontext += context[i]
        else:
            ncontext += ' '
    return ncontext

def controlProduct(product):

    product = check_corpus(product)
    splitted = product.split()

    for i in splitted.copy():
        if (len(i) < 2) or (i in stopwords) or (i in abbrev) :
            splitted.remove(i)
        elif i not in model.wv.vocab:
            splitted.remove(i)
            #print(i)
    return splitted

def searchEngine(keys):
    #wp = open('files/productNames.txt', 'a', encoding='utf8')
    keyWords = keys.split()
    keyWords = [lowerForTurkish(x) for x in keyWords]
    #stemmer = TurkishStemmer()
    """
    for i in keyWords:
        newWord = stemmer.stemWord(i)
        if newWord not in keyWords and newWord in model.wv.vocab:
            keyWords.append(newWord)
    """
    transed = [x.translate(translationTable) for x in keyWords]

    # keyWords = list(set(keyWords))
    for a in keyWords:
        if a not in model.wv.vocab:
            keyWords.remove(a)
            keyWords.append(a.translate(translationTable))

    puanlanmis = dict()
    compareCount=0

    for product in df_clean['ProductName']:
        #wr = product + '\n'
        #wp.write(wr)
        puanlanmis[product]=0
        controlled= controlProduct(product)
        for word in controlled:
            for key in keyWords:
                puanlanmis[product] += model.wv.similarity(word, key)
                compareCount+=1
        if len(controlled)>0:
            puanlanmis[product] = puanlanmis[product] / compareCount
            compareCount=0
            for i in keyWords:
                if i in controlled:
                    puanlanmis[product]+=1

    puanlanmis = dict(sorted(puanlanmis.items(),reverse=True, key=operator.itemgetter(1)),)
    print("KEYWORDS",keyWords)
    print("most similar: ", model.wv.most_similar(positive=keyWords,topn=100))
    j = 1
    for i in take(20,puanlanmis.items()):
        #if puanlanmis[i]>0:
        print(j,i)
        j+=1
searchEngine("")


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

import pytest, sys

from elasticImporter import *
from argparse import Namespace

class objectview(object):
    def __init__(self, d):
        self.__dict__ = d

class Test_elasticImporter(object):
	def test_nan_or_inf(self):
		values  = ['+inf', '-inf', 'inf', 0, 0.2, 2e2, 5**2, 'nan', 'NaN', float("inf")-float("inf")]
		results = [True, True, True, False, False, False, False, True, True, True]
		ops = zip(values, results)
		for value, result in ops:
			assert is_nan_or_inf(float(value)) == result

	def test_parse_property(self):
		args = {}
		args['dates_in_seconds'] = True
		args = objectview(args)
		values = [('', 'float', None),
		('+inf', 'float', None),
		('inf', 'integer', None),
		('1.1', 'float', 1.1),
		('1', "long", long(1)),
		('1', 'integer', int(1)),
		('1', 'string', '1'),
		('1519995883.3099031', 'date', 1519995883309)]
		for v, t, r in values:
			assert parse_property(v, t, args) == r

	def test_no_all_no_source_args(self):
		cfg = {u'order_in_file': [u'person', u'size', u'city'], u'meta': {u'index': u'example', u'type': u'my_doc'}, u'properties': {u'person': u'keyword', u'city': u'keyword', u'size': u'float'}}
		doc = 'my_doc'
		args = Namespace(bulk=2000, cfg='example.cfg', date_fields=[], dates_in_seconds=False, debug=False, deflate_compression=False, delete=True, extra_data=None, geo_column_country_code=None, geo_column_country_name=None, geo_column_ip=None, geo_column_place_name=None, geo_column_region_name=None, geo_column_zip_code=None, geo_fields={}, geo_int_ip=False, geo_precission=None, geodb=None, index=None, input='example.csv', md5_exclude=[], md5_id=False, no_all=True, no_source=True, node='localhost', noprogress=False, password='', port=9200, queue=6, raise_on_error=False, raise_on_exception=False, refresh=True, refresh_interval='60s', regenerate_databases=[], replicas=0, separator=',', shards=2, show_elastic_logger=False, skip_first_line=False, test_processing_speed=False, threads=5, timeout=600, tor_info=None, tor_info_from=False, tor_int_ip=False, type=None, typed_iterator=False, user=None, utf8=False)
		doc_class = create_doc_class(cfg, doc, args)
		assert doc_class.__dict__[doc] == {'_all': {'enabled': False}, '_source': {'enabled': False}}


import sys
sys.stdin = open('요리사.txt','r')

def ncr(n, k, cnt):
    global minV, c, case

    if c == case//2+2:
        return

    if cnt == N//2:
        c += 1
        s_man = list(nums-set(f_man))
        FV, SV = 0, 0
        for i in range(N//2):
            for j in range(i+1, N//2):
                FV += arr[f_man[i]][f_man[j]]+arr[f_man[j]][f_man[i]]
                SV += arr[s_man[i]][s_man[j]]+arr[s_man[j]][s_man[i]]
        minV = min(minV, abs(FV-SV))
        return

    if n == k:
        return

    else:
        f_man[cnt] = n
        ncr(n+1, k, cnt+1)
        ncr(n+1, k, cnt)

for t in range(int(input())):
    N = int(input())
    arr = [list(map(int, input().split())) for _ in range(N)]
    nums = set(i for i in range(N))
    f_man = [0]*(N//2)
    minV = float('INF')
    case = 1
    for i in range(N, N//2, -1):
        case = case*i//(i-(N//2))
    c = 0
    ncr(0, N, 0)

    print('#{} {}'.format(t+1, minV))


#!/usr/bin/env python

import sys
import os
import logbook
from logbook import Logger, StreamHandler, RotatingFileHandler
logbook.set_datetime_format("local")

from conf import DB, DEBUG

PATH_PROYECT = os.path.dirname(__file__)

DB = DB
#~ Establece la ruta al archivo LOG de registros
LOG_PATH = 'cfdi.log'
LOG_NAME = 'CFDI'
LOG_LEVEL = 'INFO'

format_string = '[{record.time:%d-%b-%Y %H:%M:%S}] ' \
    '{record.level_name}: ' \
    '{record.channel}: ' \
    '{record.message}'
RotatingFileHandler(
    LOG_PATH,
    backup_count=10,
    max_size=1073741824,
    level=LOG_LEVEL,
    format_string=format_string).push_application()

if DEBUG:
    LOG_LEVEL = 'DEBUG'

StreamHandler(
    sys.stdout,
    level=LOG_LEVEL,
    format_string=format_string).push_application()

log = Logger(LOG_NAME)

#~ Aumenta el tiempo (segundos) de espera, solo si tienes una conexión muy lenta o inestable
TIMEOUT = 120

#~ Cantidad de veces que se intenta en:
#~ - Identificarse en el SAT
#~ - Descargar un CFDI si hay timeout
#~ - Descargar faltantes de la lista obtenida al buscar
TRY_COUNT = 3

#~ Ruta al ejecutable pdftotext, necesario para extraer la fecha de cancelación
#~ de los documentos emitidos
PDF_TO_TEXT = 'pdftotext'

WEBSITE = 'http://rlsistemas.com.mx'
W_DONATE = ''
W_FORUM = ''

HEADERS = {'Auth-Token': '', 'content-type': 'application/json'}
base = ''
if DEBUG:
    base = 'http://localhost:8000/{}'
URL = {
    'RESOLVE': base.format('resolveCaptcha'),
}

# Pon en False si tienes problemas con los certificados de la página del SAT
VERIFY_CERT = True

# Es el nombre como se buscará la FIEL en el directorio pasado, argumento -df
NAME_CER = 'fiel.{}'

OS = sys.platform
PATH_OPENSSL = 'openssl'
if 'win' in OS:
    PDF_TO_TEXT = 'pdftotext.exe'
    PATH_OPENSSL = os.path.join(PATH_PROYECT, 'bin', 'openssl.exe')


from api.database.database_base import Session
from api.module.company.company_model import CompanyModel

class CompanyRepository:
    def list(self):
        session = Session()
        return session.query(CompanyModel).all()
    def create(self, company_name):
        print(company_name)
        session = Session()
        company = CompanyModel(company_name=company_name, logo_url='')
        session.add(company)
        session.commit()
        session.refresh(company)
        return company


import math

def main():
    a, b = map(float, input().split())

    # bは1増やした時の経過時間
    g = 1
    count = 0

    min_clock = b * count + a / math.sqrt(g)

    while True:
        g = g + 1
        count = count + 1

        time = b * count + a / math.sqrt(g)

        # print(time)

        if min_clock < time:
            break
        else:
            min_clock = time

    print(min_clock)

main()


# While Loop

i = 1
while i <= 10:
    print("Uzzal")
    i = i+1
print("End")

j = 1
add = 0
while j <= 10:
    add = add+j
    j = j+1
print("Sum is: ", add)