import torch
import torch.nn as nn
from torch.autograd import Variable

from PIL import Image
import example_pb2
from meta import Meta
import lmdb

# Necessary for my KFAC implementation.
class AddBias(nn.Module):
    def __init__(self, bias):
        super(AddBias, self).__init__()
        self._bias = nn.Parameter(bias.unsqueeze(1))

    def forward(self, x):
        if x.dim() == 2:
            bias = self._bias.t().view(1, -1)
        else:
            bias = self._bias.t().view(1, -1, 1, 1)

        return x + bias

def init(module, weight_init, bias_init, gain=1):
    weight_init(module.weight.data, gain=gain)
    bias_init(module.bias.data)
    return module

# https://github.com/openai/baselines/blob/master/baselines/common/tf_util.py#L87
def init_normc_(weight, gain=1):
    weight.normal_(0, 1)
    weight *= gain / torch.sqrt(weight.pow(2).sum(1, keepdim=True))

'''Unwrapped Rewards'''
def convert_to_lmdb(img, rwd, lmdb_path, idx):
    img = Image.fromarray(img, 'RGB')
    img = img.crop((0, 8, 67, 22))  # SpaceInvadersNoFrameskip-v4
    img.save(lmdb_path + '/test/' + str(idx) + '.png')
    img = img.resize([64, 64]).tobytes()

    # reward to digits
    label_of_digits = list(str(int(rwd)))
    length = len(label_of_digits)
    digits = [10, 10, 10, 10, 10, 10, 10, 10, 10, 10]  # digit 10 represents no digit
    for idx, label_of_digit in enumerate(label_of_digits):
        digits[idx] = int(label_of_digit if label_of_digit != 10 else 0)  # label 10 is essentially digit zero

    example = example_pb2.Example()
    example.image = img
    example.length = length
    example.digits.extend(digits)

    str_id = '{:08}'.format(idx)

    env = lmdb.open(lmdb_path + '/test.lmdb', map_size=10*1024*1024*1024)
    with env.begin(write=True) as txn:
        txn.put(str_id.encode(), example.SerializeToString())

def create_lmdb_meta_file(num_test_examples, path_to_lmdb_meta_file):
    print('Saving meta file to %s...' % path_to_lmdb_meta_file)
    meta = Meta()
    # meta.num_train_examples = num_train_examples
    # meta.num_val_examples = num_val_examples
    meta.num_test_examples = num_test_examples
    meta.save(path_to_lmdb_meta_file)

def digit_eval(image, length_labels, digits_labels, model):
    model.eval()
    num_correct = 0
    needs_include_length = False

    for batch_idx, (images, length_labels, digits_labels) in enumerate(self._loader):
        # images, length_labels, digits_labels = (Variable(images.cuda(), volatile=True),
        #                                         Variable(length_labels.cuda()),
        #                                         [Variable(digit_labels.cuda()) for digit_labels in digits_labels])
        length_labels, digits_labels = (Variable(length_labels.cuda()),
                                        [Variable(digit_labels.cuda()) for digit_labels in digits_labels])
        with torch.no_grad():
            images = Variable(images.cuda())
        length_logits, digits_logits = model(images)
        length_predictions = length_logits.data.max(1)[1]
        digits_predictions = [digit_logits.data.max(1)[1] for digit_logits in digits_logits]

        if needs_include_length:
            num_correct += (length_predictions.eq(length_labels.data) &
                            digits_predictions[0].eq(digits_labels[0].data) &
                            digits_predictions[1].eq(digits_labels[1].data) &
                            digits_predictions[2].eq(digits_labels[2].data) &
                            digits_predictions[3].eq(digits_labels[3].data) &
                            digits_predictions[4].eq(digits_labels[4].data) &
                            digits_predictions[5].eq(digits_labels[5].data) &
                            digits_predictions[6].eq(digits_labels[6].data) &
                            digits_predictions[7].eq(digits_labels[7].data) &
                            digits_predictions[8].eq(digits_labels[8].data) &
                            digits_predictions[9].eq(digits_labels[9].data)).cpu().sum()
        else:
            num_correct += (digits_predictions[0].eq(digits_labels[0].data) &
                            digits_predictions[1].eq(digits_labels[1].data) &
                            digits_predictions[2].eq(digits_labels[2].data) &
                            digits_predictions[3].eq(digits_labels[3].data) &
                            digits_predictions[4].eq(digits_labels[4].data) &
                            digits_predictions[5].eq(digits_labels[5].data) &
                            digits_predictions[6].eq(digits_labels[6].data) &
                            digits_predictions[7].eq(digits_labels[7].data) &
                            digits_predictions[8].eq(digits_labels[8].data) &
                            digits_predictions[9].eq(digits_labels[9].data)).cpu().sum()

    accuracy = num_correct.item() / float(len(self._loader.dataset))
    return accuracy


import os
from setuptools import setup, find_packages

__version__ = '0.1.1'
__author__ = 'Takumi Sueda'
__author_email__ = 'puhitaku@gmail.com'
__license__ = 'MIT License'
__classifiers__ = (
    'Development Status :: 3 - Alpha',
    'Environment :: Console',
    'Intended Audience :: Developers',
    'License :: OSI Approved :: MIT License',
    'Operating System :: OS Independent',
    'Programming Language :: Python',
    'Programming Language :: Python :: 3',
    'Programming Language :: Python :: 3.6',
    'Topic :: Software Development :: User Interfaces')

here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.rst')) as f:
    readme = f.read()

setup(
    name='naam',
    version=__version__,
    author=__author__,
    author_email=__author_email__,
    url='https://github.com/puhitaku/naam',
    description='Truly pythonic argument parser.',
    long_description=readme,
    classifiers=__classifiers__,
    packages=find_packages(),
    license=__license__,
    include_package_data=True)


from collections import defaultdict

hooks = defaultdict(list)

_hook_info = {}

import logging
log = logging.getLogger(__name__)

def register_hook(name, description):
    _hook_info[name] = description

def append_to_hook(hook_name, handler):
    hooks[hook_name].append(handler)

def call_hook(hook_name, **kwargs):
    results = []

    for handler in hooks[hook_name]:
        try:
            r = handler(**kwargs)

            if isinstance(r, list):
                results.extend(r)
            elif r is not None:
                results.append(r)

        except Exception:
            log.debug("Tried to run handler of {}".format(str(handler)))
            raise

    return results


from flask_sse import sse
from Simulation.Utils.receiverStates import Receiving, Waiting
from Simulation.Utils.constants import DELIVER_TIME, SEND_TIME
from Simulation.Utils.packet import ACK

class Receiver():
    def __init__(self, env, channel):
        self.env = env
        self.state = Waiting()
        self.states = {'waiting':Waiting(), 'receiving':Receiving()}
        self.channel = channel

    def setState(self, state):
        self.state = self.states[state]
        statement = "{" + str(self.env.now) + "} | " + "Receiver now: " + str(self.state)
        print(statement)
        sse.publish({"message": statement}, type='publish')

    def handle(self, packet, source):
        if type(self.state) is Waiting:
            self.setState('receiving')
            seqnum = packet.seqnum
            statement = "{" + str(self.env.now) + "} | " + "Packet num: " + str(seqnum) + " received"
            print(statement)
            sse.publish({"message": statement}, type='publish')
            self.env.process(self.deliver_data(seqnum))
            yield self.env.process(self.send_ACK(seqnum, source))
        else:
            statement = "{" + str(self.env.now) + "} | " + "Receiver busy please wait"
            print(statement)
            sse.publish({"message": statement}, type='publish')

    def deliver_data(self, seqnum):
        yield self.env.timeout(DELIVER_TIME)
        statement = "{" + str(self.env.now) + "} | " + "Packet num: " + str(seqnum) + " data delivered"
        print(statement)
        sse.publish({"message": statement}, type='publish')

    def send_ACK(self, packet_num, source):
        ack = ACK(packet_num)
        self.setState('waiting')
        sse.publish({"packetNumber": packet_num-1}, type='ACK')
        statement = "{" + str(self.env.now) + "} | " + "Sending ACK for packet num: " + str(packet_num)
        print(statement)
        sse.publish({"message": statement}, type='publish')
        yield self.env.timeout(SEND_TIME)
        self.env.process(self.channel.send(source, ack, self))


import json
import traceback
from io import BytesIO
from slack import WebClient
from slack.errors import SlackApiError

"""
    How to get app token and set scope for app, below is steps for setting app xa-sample-app
        with app id is A052Z4HGNT1

    1. Create your app as normal, go to https://api.slack.com/apps, choose app xa-sample-app or access this link: https://api.slack.com/apps/A052Z4HGNT1
        to go to management page of this app
    2. Go to General, or access this link https://api.slack.com/apps/A052Z4HGNT1/general? to see general config of app
        Choose Install your app to install your app to a slack workspace
        Or you also go here to install your app https://api.slack.com/apps/A052Z4HGNT1/install-on-team?
    3. Go to OAuth & Permissions or access this link https://api.slack.com/apps/A052Z4HGNT1/oauth?
        a. Move to Scopes part,
            Move to User Token Scopes, add scope that you want to add, refer list of scopes: https://api.slack.com/scopes
                To be able to send slack message to a channel, you have to add scope: chat:write
        b. Move to OAuth Tokens for Your Workspace part
            Copy token in Bot User OAuth Token text box, this token will be use by slackclient
"""
credentials = json.loads(open("/home/xuananh/Dropbox/Work/Other/credentials_bk/slack_phungxuananh_workspace.json", "r").read())
SLACK_API_TOKEN = credentials["apps"]["xa-sample-app"]["Bot User OAuth Token"]

def send_slack_alert(channel: str, text: str):
    """Send slack alert"""
    client = WebClient(token=SLACK_API_TOKEN)
    try:
        client.chat_postMessage(channel=channel, text=text)
    except SlackApiError as e:
        traceback.print_exc()

def upload_slack_file(channel: str, file_content_bytes: bytes, initial_comment: str, filename: str):
    """
        Upload slack file to a slack channel
        NOTE: to upload a file to a slack channel, the slack app must be installed to that channel,
            else you will encountered error { "ok": false, "error": "not_in_channel" }
            reference: https://stackoverflow.com/a/68475477/7639845
    """
    client = WebClient(token=SLACK_API_TOKEN)
    try:
        with BytesIO() as b:
            b.write(file_content_bytes)
            b.seek(0)
            client.files_upload(
                channels=channel,
                initial_comment=initial_comment,
                file=b,
                filename=filename,
            )
    except SlackApiError as e:
        traceback.print_exc()

send_slack_alert("#general", "aaaaaaaaaaaaaaaaaaaaaaaaaa, this message sent from slackclient")

upload_slack_file("#general", open("requirements.txt", "rb").read(),
                  initial_comment="this is attachment from XuanAnh",
                  filename="requirements.txt"
                  )


# 导入selenium的浏览器驱动接口
import sys
import os
import json
import requests
import platform

o_path = os.getcwd()  # 返回当前工作目录
sys.path.append(o_path)  # 添加自己指定的搜索路径
sys.path.append('../../')
sys.path.append('./')

from Common.Common import Common
from Project.Resource import mainResource
from Common import Source
from Common.File.FileUtil import FileUtil
from AppInfo.AppInfo import mainAppInfo

# unity c# 代码转成成cocos laya ts
class CSharp2Ts:
    def CodeCSharp2Ts(self):
        self.CSharp2Ts("laya")
        self.CSharp2Ts("cocos")

    def CSharp2Ts(self,name):
        dirCSharp = mainResource.GetRootUnityScriptApp()
        dirTs = mainResource.GetCodeConvert()+"_"+name
        FileUtil.CreateDir2(dirTs)
        listCSharp = []
        FileUtil.GetSubFileList(dirCSharp,"cs",listCSharp)
        for filecs in listCSharp:
            filets = filecs.replace(dirCSharp,dirTs)
            filets = filets.replace(".cs",".ts")
            uiview_ts = mainResource.GetDirProductCommonTS()+"/UIView_"+name+".ts"
            FileUtil.CreateDir2(filets)
            # FileUtil.CreateFile(filets)
            strfile = FileUtil.GetFileString(uiview_ts)
            strfile = strfile.replace("UIViewSampe",FileUtil.GetPathNameWithoutExt(filets))
            FileUtil.SaveString2File(strfile,filets)

# 主函数的实现
if __name__ == "__main__":
    # 设置为utf8编码
    # reload(sys)
    # sys.setdefaultencoding("utf-8")
    is_auto_plus_version = False
    # 入口参数：http://blog.csdn.net/intel80586/article/details/8545572
    cmdPath = Common.cur_file_dir()
    count = len(sys.argv)
    arg3 = ""
    arg4 = ""
    for i in range(1, count):
        print("参数", i, sys.argv[i])
        if i == 1:
            cmdPath = sys.argv[i]
        if i == 3:
            arg3 = sys.argv[i]
        if i == 4:
            arg4 = sys.argv[i]

    mainResource.SetCmdPath(cmdPath)

    p = CSharp2Ts()
    p.CodeCSharp2Ts()

    print("CSharp2Ts sucess")

mainCSharp2Ts = CSharp2Ts()


# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

# Given a Python script and arguments describing the output file, and
# the arguments that can be used to generate the output file, call the
# script's |main| method with appropriate arguments.

import argparse
import importlib.util
import os
import sys
import traceback

import buildconfig
import six

from mozbuild.action.util import log_build_task
from mozbuild.makeutil import Makefile
from mozbuild.pythonutil import iter_modules_in_path
from mozbuild.util import FileAvoidWrite

def main(argv):
    parser = argparse.ArgumentParser(
        "Generate a file from a Python script", add_help=False
    )
    parser.add_argument(
        "--locale", metavar="locale", type=six.text_type, help="The locale in use."
    )
    parser.add_argument(
        "python_script",
        metavar="python-script",
        type=six.text_type,
        help="The Python script to run",
    )
    parser.add_argument(
        "method_name",
        metavar="method-name",
        type=six.text_type,
        help="The method of the script to invoke",
    )
    parser.add_argument(
        "output_file",
        metavar="output-file",
        type=six.text_type,
        help="The file to generate",
    )
    parser.add_argument(
        "dep_file",
        metavar="dep-file",
        type=six.text_type,
        help="File to write any additional make dependencies to",
    )
    parser.add_argument(
        "dep_target",
        metavar="dep-target",
        type=six.text_type,
        help="Make target to use in the dependencies file",
    )
    parser.add_argument(
        "additional_arguments",
        metavar="arg",
        nargs=argparse.REMAINDER,
        help="Additional arguments to the script's main() method",
    )

    args = parser.parse_args(argv)

    kwargs = {}
    if args.locale:
        kwargs["locale"] = args.locale
    script = args.python_script
    # Permit the script to import modules from the same directory in which it
    # resides.  The justification for doing this is that if we were invoking
    # the script as:
    #
    #    python script arg1...
    #
    # then importing modules from the script's directory would come for free.
    # Since we're invoking the script in a roundabout way, we provide this
    # bit of convenience.
    sys.path.append(os.path.dirname(script))
    spec = importlib.util.spec_from_file_location("script", script)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    method = args.method_name
    if not hasattr(module, method):
        print(
            'Error: script "{0}" is missing a {1} method'.format(script, method),
            file=sys.stderr,
        )
        return 1

    ret = 1
    try:
        with FileAvoidWrite(args.output_file, readmode="rb") as output:
            try:
                ret = module.__dict__[method](
                    output, *args.additional_arguments, **kwargs
                )
            except Exception:
                # Ensure that we don't overwrite the file if the script failed.
                output.avoid_writing_to_file()
                raise

            # The following values indicate a statement of success:
            #  - a set() (see below)
            #  - 0
            #  - False
            #  - None
            #
            # Everything else is an error (so scripts can conveniently |return
            # 1| or similar). If a set is returned, the elements of the set
            # indicate additional dependencies that will be listed in the deps
            # file. Python module imports are automatically included as
            # dependencies.
            if isinstance(ret, set):
                deps = set(six.ensure_text(s) for s in ret)
                # The script succeeded, so reset |ret| to indicate that.
                ret = None
            else:
                deps = set()

            # Only write out the dependencies if the script was successful
            if not ret:
                # Add dependencies on any python modules that were imported by
                # the script.
                deps |= set(
                    six.ensure_text(s)
                    for s in iter_modules_in_path(
                        buildconfig.topsrcdir, buildconfig.topobjdir
                    )
                )
                # Add dependencies on any buildconfig items that were accessed
                # by the script.
                deps |= set(six.ensure_text(s) for s in buildconfig.get_dependencies())

                mk = Makefile()
                mk.create_rule([args.dep_target]).add_dependencies(deps)
                with FileAvoidWrite(args.dep_file) as dep_file:
                    mk.dump(dep_file)
            else:
                # Ensure that we don't overwrite the file if the script failed.
                output.avoid_writing_to_file()

    except IOError as e:
        print('Error opening file "{0}"'.format(e.filename), file=sys.stderr)
        traceback.print_exc()
        return 1
    return ret

if __name__ == "__main__":
    sys.exit(log_build_task(main, sys.argv[1:]))


class Solution:
    def orangesRotting(self, grid: List[List[int]]) -> int:
        time, fresh = 0,0
        q = deque()
        for row in range(len(grid)):
            for col in range(len(grid[row])):
                ## getting count of fresh oranges
                if grid[row][col] == 1:
                    fresh +=1
                ## getting locatin of all rotten oranges
                if grid[row][col] == 2:
                    q.append([row,col])
        if fresh == 0:
            return 0
        if len(q) == 0:
            return -1
        neighbour = [(0,1),(0,-1),(1,0),(-1,0)]
        while q and fresh > 0:
            for i in range(len(q)):
                r,c = q.popleft()

                for dr, dc in neighbour:
                    newdr , newdc = r+dr,c+dc
                    if (newdr <0 or newdc <0  or newdr == len(grid) or newdc == len(grid[0]) or grid[newdr][newdc] != 1):
                        continue
                    grid[newdr][newdc] = 2
                    q.append([newdr,newdc])
                    fresh -= 1
            time += 1

        if fresh == 0:
            return time
        return -1


#import sys
import fileinput
import time

#read input continously
# def read_input():
# 	while True:
# 		for line in fileinput.input():
# 			if len(line.split()) > 2 and line.split()[1] == '/muse/acc':
# 				return (line.split())

#get position of head (read size number of data)
def get_buffer(size):
	input_holder = []
	fi = fileinput.input()
	print(input_holder)

	for line in fi:
		if (len(input_holder) > size):
			break
		if len(line.split()) > 2 and line.split()[1] == '/muse/acc':
			#print line.split()
			input_holder.append(float(line.split()[5]))

	fi.close()
	return input_holder

#start game
# while True:
def read_data_from_muse(previous_location, current_location):
	fi = fileinput.input()

	for line in fi:
		if len(line.split()) > 2 and line.split()[1] == '/muse/acc':
			print(line.split())
			previous_location.append(float(line.split()[5]))
			previous_location.pop(0)
			current_location.append(float(line.split()[5]))
			current_location.pop(0)

		if (sum(current_location)/5 - sum(previous_location)/60 > 80):
			fi.close()
			print(1)
			return 1

		elif (sum(current_location)/5 - sum(previous_location)/60 < -100):
			fi.close()
			print(-1)
			return -1

		else:
			fi.close()
			print(0)
			return 0

def go_get_data():
	#get position of head when tilting left
	print("Application Starting...\nCalibrating...\n")
	previous_location = get_buffer(60)
	current_location = get_buffer(5)
	print(previous_location)
	print(current_location)
	while True:
		print(read_data_from_muse(previous_location, current_location))

go_get_data()
# for line in fileinput.input():
# 	print(line)


def solution(n, arr1, arr2):
    answer = []
    wall = '#'
    blank = ' '
    board1 = list ([0] * n for _ in range (n))
    board2 = list ([0] * n for _ in range (n))

    for i in range (len (arr1)):
        count1 = n - 1
        while arr1[i] >= 1:
            board1[i][count1] = int (arr1[i] % 2)
            arr1[i] = (arr1[i] - arr1[i] % 2) / 2
            count1 -= 1

    for i in range (len (arr2)):
        count2 = n - 1
        while arr2[i] >= 1:
            board2[i][count2] = int (arr2[i] % 2)
            arr2[i] = (arr2[i] - arr2[i] % 2) / 2
            count2 -= 1

    for i in range (n):
        temp = ''
        for j in range (n):
            if board1[i][j] == 0 and board2[i][j] == 0:
                temp += blank
            else:
                temp += wall
        answer.append (temp)

    return answer


import yaml
import sys
from os import path

from pylaas_core.interface.core.service_interface import ServiceInterface
from pylaas_core.interface.technical.container_configurable_aware_interface import ContainerConfigurableAwareInterface
from pylaas_core.interface.technical.container_interface import ContainerInterface

class Container(ContainerInterface):
    """Container to handle DI

    Attributes:
        _definitions (dict) : list of container definitions
        _singletons (dict) : list of class singletons
    """

    def __init__(self) -> None:
        self._definitions = {'configurations': {}, 'services': {}}
        self._singletons = {}

    def add_definitions(self, definitions):
        """Add definition to container
        Args:
            definitions (dict|string): list of definitions

        Returns:
            ContainerInterface
        """
        if type(definitions) is not dict:
            if path.exists(definitions):
                with open(definitions, 'r') as f:
                    definitions = yaml.load(f)
            else:
                raise FileExistsError("Container definitions file '{}' does not exits".format(definitions))

        if 'configurations' in definitions and definitions.get('configurations') is not None:
            self._definitions['configurations'].update(definitions['configurations'])
        if 'services' in definitions and definitions.get('services') is not None:
            self._definitions['services'].update(definitions['services'])

        return self

    def get_definitions(self):
        """Get container definitions

        Returns:
            definitions (dict): list of definitions
        """
        return self._definitions

    def has(self, def_id):
        """Returns true if the container can return an entry for the given identifier.

        Args:
            def_id: Identifier of the entry to look for

        Returns:
            bool
        """
        return def_id in self._definitions['services']

    def get(self, def_id):
        """Finds an entry of the container by its identifier and returns it.

        Args:
            def_id: Identifier of the entry to look for.

        Returns:
            ServiceInterface: singleton services
        """
        if not self.has(def_id):
            raise RuntimeError("service id '{}' does not exists".format(def_id))

        # check if service has been already created as a singleton
        if def_id not in self._singletons:
            parts = self._definitions['services'][def_id].split(".")
            module_name = ".".join(parts[:-1])
            class_name = parts[-1]
            __import__(module_name)
            service = getattr(sys.modules[module_name], class_name)
            service = service()
            if isinstance(service, ContainerConfigurableAwareInterface):
                service.set_configs(self._definitions['configurations'][def_id])
            self._singletons[def_id] = service

        return self._singletons[def_id]

    def clear(self, def_id) -> None:
        """Clear an entry of the container by its identifier

        Args:
            def_id: Identifier of the entry to look for.

        Returns:
            None
        """
        if def_id not in self._singletons:
            return
        del self._singletons[def_id]


import os
import shutil
import subprocess
import sys
import tempfile

import docopt

def main():
    arguments = docopt.docopt(__doc__)
    repo = arguments['REPO_URL']
    repo_branch = arguments['--repo-branch']
    cleanbuild = arguments['--cleanbuild']
    keep_dir = arguments['--keep-dir']
    if _is_git(repo):
        if shutil.which('git'):
            path = _git_clone(repo, repo_branch)
        else:
            sys.exit('Please install git.')
    elif _is_bzr(repo):
        if shutil.which('bzr'):
            path = _bzr_branch(repo)
        else:
            sys.exit('Please install bzr.')
    else:
        sys.exit('Unsupported repository.')

    _build_snaps(path, cleanbuild, keep_dir)

def _is_git(repo):
    return (repo.startswith('https://github.com/') or
            repo.startswith('git://') or
            repo.startswith('https://git.launchpad.net/'))

def _git_clone(url, repo_branch=None):
    temp_dir = tempfile.mkdtemp(prefix='snapcraft-')
    command = ['git', 'clone', '--progress', url, temp_dir]
    print(' '.join(command))
    subprocess.check_call(command)
    if repo_branch:
        subprocess.check_call(['git', 'checkout', repo_branch], cwd=temp_dir)
    return temp_dir

def _is_bzr(repo):
    return repo.startswith('lp:')

def _bzr_branch(url):
    temp_dir = tempfile.mkdtemp(prefix='snapcraft-')
    repo_dir = os.path.join(temp_dir, 'repo')
    command = ['bzr', 'branch', '-v', url, repo_dir]
    print(' '.join(command))
    subprocess.check_call(command)
    return repo_dir

def _build_snaps(path, cleanbuild=False, keep_dir=False):
    try:
        for dirpath, dirnames, filenames in os.walk(path, topdown=True):
            if _is_snapcraft_dir(dirpath, dirnames, filenames):
                _build_snap(dirpath, cleanbuild, keep_dir)
                # Do not recurse in any directory.
                del dirnames[:]
    except subprocess.CalledProcessError as e:
        sys.exit(e.returncode)
    finally:
        if keep_dir:
            print(
                'You can inspect the built project repository in {}'.format(
                    path))
        else:
            shutil.rmtree(path)

def _is_snapcraft_dir(dirpath, dirnames, filenames):
    return (('snap' in dirnames and
             'snapcraft.yaml' in os.listdir(os.path.join(dirpath, 'snap'))) or
            'snapcraft.yaml' in filenames or
            '.snapcraft.yaml' in filenames)

def _build_snap(path, cleanbuild=False, keep_dir=False):
    snapcraft = os.path.abspath(os.path.join('bin', 'snapcraft'))
    print('Updating the parts cache...')
    subprocess.check_call([snapcraft, 'update'])
    print('Snapping {}'.format(path))
    command = [snapcraft, '-d']
    if cleanbuild:
        command.append('cleanbuild')
    print(' '.join(command))
    subprocess.check_call(command, cwd=path)

if __name__ == '__main__':
    main()


from django.shortcuts import render,redirect
from datetime import datetime
from collections import Counter
from django.core.mail import send_mail
import smtplib
from cle.models import Espece, Caractere, Etat_caracteres, Espece_caractere, Cle

def accueil(request):
	date_du_jour = datetime.now()
	date_du_jour_txt = date_du_jour.strftime("%H:%M:%S %d/%m/%Y")
	return render(request,'cle/index.html', {'date_jour':date_du_jour_txt})

def affiche_contact(request):

	if request.method=='POST':
		try :
			send_mail(request.POST['Nomdefamille'] + " " + request.POST['Prenom'] + ' [Mustélidés]', # Objet mail
			request.POST['textarea'] + "\n\nenvoyé par : " + request.POST['Mail'], # Contenu mail
			'adressemustilidae@gmail.com', # Destinataire mail
			['adressemustilidae@gmail.com'], # Destinataire
			fail_silently=False)
		except smtplib.SMTPDataError as e:
			print('Exception : ' + 'SMTPDataError' + ' Probablement trop de connections journalieres sur le serveur smtp')
		else :
			print('Tout va bien')
	return render(request, 'cle/page_contact.html', {})

def affiche_liste(request):
	# on cree une liste des Cles mais sans la cle europe pour
	# pouvoir les afficher sur la page web
	liste_cle = []
	for element in Cle.objects.all():
		if (element.id != 1):
			liste_cle.append(element)
	return render(request, 'cle/page_liste.html', {'liste_cle': liste_cle})

def affiche_ajouter(request):
	print('Hello world')
	# Espece.objects.create(nom='vache')
	# Cle.objects.create(nom='hi')
	if request.method=='POST':
		print('Request Data :' + str(request.POST))
		print('Cle Region :' + request.POST['cleRegion'])
		print('Nom espece :' + request.POST['espName'])

		print('Nom latin :' + request.POST['latinName'])
		print('Description :' + request.POST['description'])
		print('Post members :' + str(len(request.POST)))

		# Si la cle de region existe on la stocke dans une variable pour plus tard
		# sinon on la cree et on la stocke dans une variable (pour plus tard)
		if (not Cle.objects.filter(nom=request.POST['cleRegion']).exists()):
			cleRegion = Cle.objects.create(nom=request.POST['cleRegion'])
		else :
			cleRegion = Cle.objects.filter(nom=request.POST['cleRegion'])[0]
		print('La cle de region id : ' + str(cleRegion.id))

		# On regarde si l'espece existe deja, si elle existe,
		# on ne rempli pas la base de donnees
		if (Espece.objects.filter(nom=request.POST['espName']).exists()):
			print('L\'espece est deja repertoriee')
			return render(request, 'cle/page_ajouter.html', {})

		# On cree une nouvelle espece dans la BD avec son nom,
		# son nom latin et sa description, et l'id de la cle de region
		cleEspece = Espece.objects.create(nom=request.POST['espName'], \
		nom_latin=request.POST['latinName'], description=request.POST['description'], cle_name_id=cleRegion.id)

		# On etabli combien de caracteres sont presents dans le formulaire
		# en se basant sur la taille du formulaire
		# 4 champs d'input + 1 token = 5, du coup on enleve 5
		# 2 champs par caractere du coup on divise par 2 le reste pour avoir le nombre de caracteres
		caracteresRestants = (len(request.POST) - 5) / 2
		print('Remaining caracteres :' + str(caracteresRestants))

		i = 0
		# On tourne tant qu'on a pas trouvé tous les caracteres
		while (caracteresRestants > 0):
			print('search ', caracteresRestants)
			# On cherche le premier caractere on iterant les numeros
			# pcq on peut avoir par exemple caractere 3, 5 et pas
			# le reste si on a supprimé des caracteres sur la page Web
			while not str('caractere' + str(i)) in request.POST:
				i += 1
			print('found at :', str(i))
			print('Nom caractere ' + str(i) + ' :', request.POST['caractere' + str(i)] )
			print('etat ' + str(i) + ' :', request.POST['etat' + str(i)] )

			# Si le caractere existe pas, on le crée et on le stocke dans une variable,
			# sinon on le recupere dans une variable
			if (not Caractere.objects.filter(nom=request.POST['caractere' + str(i)]).exists()):
				cleCaractere = Caractere.objects.create(nom=request.POST['caractere' + str(i)])
			else :
				cleCaractere = Caractere.objects.filter(nom=request.POST['caractere' + str(i)])[0]

			# Si le l'etat du caractere existe pas, on le crée et on le stocke dans une variable,
			# sinon on le recupere dans une variable
			if (not Etat_caracteres.objects.filter(etat=request.POST['etat' + str(i)]).exists()):
				cleEtat= Etat_caracteres.objects.create(etat=request.POST['etat' + str(i)], caractere_id=cleCaractere.id)
			else :
				cleEtat = Etat_caracteres.objects.filter(etat=request.POST['etat' + str(i)])[0]

			# On cree le caractere dans la BD avec l'etat, l'id du caractere, et l'id de l'espece
			Espece_caractere.objects.create(etat=request.POST['etat' + str(i)],
														caractere_id=cleCaractere.id,
														espece_id=cleEspece.id)

			i += 1
			caracteresRestants -= 1

	return render(request, 'cle/page_ajouter.html', {})

def affiche_specialiste(request):
	return render(request, 'cle/page_specialiste.html', {})

def affiche_amerique(request):
	return render(request, 'cle/page_amerique.html', {})

def affiche_europe(request):
	liste_caractere=Caractere.objects.all()
	return render (request, 'cle/page_europe.html', {'liste_caractere': liste_caractere})

def caractere(request, id_caractere):
	if Caractere.objects.filter(id=id_caractere).exists():
		caractere=Caractere.objects.get(id=id_caractere)
		etat=Etat_caracteres.objects.filter(caractere=id_caractere)
	else:
		return render(request, 'cle/page_erreur.html', {'id':id_caractere})

	return render(request, 'cle/caractere.html', {'ca':caractere,'l_etat':etat})

def cle_en_cours(request, id_etat):
	caractere_test = Etat_caracteres.objects.get(id=id_etat)
	liste_espece_cara = Espece_caractere.objects.all()
	esp_possible = Espece_caractere.objects.filter(etat=caractere_test.etat) #Recupère toutes les espèces qui présentent l'état de caractère choisi.
	cara_restant = Espece_caractere.objects.exclude(caractere=caractere_test.caractere) #exclue le caractère venant d'être évalué

	etat_restant = [] #Variable pour récupérer tous les état de caractères encore à évaluer.
	nb = 0
	etat_cara_restant = [] #Même que etat_restant mais exclue en plus l'etat de caractere qui vient d'etre validé
	Liste_cara_restant = []

	for esp in esp_possible : #compte le nombre d'espèces restantes
		nb += 1

	if nb == 1:

		espece = esp_possible[0]
		eid = espece.espece
		print(espece)
		caid = 1
		return redirect('affiche_espece', id_espece=espece.espece.id )

	else:
		for esp in liste_espece_cara : # fonction pour récupérer tous les état de caractères encore à évaluer.
			if esp_possible.filter(espece=esp.espece).exists():
				etat_restant.append(esp)

		for esp in etat_restant :
			if cara_restant.filter(caractere=esp.caractere).exists():
				etat_cara_restant.append(esp)
				Liste_cara_restant.append(esp.caractere)

		compte_cara = Counter(Liste_cara_restant)

		i = -1 #compteur pour retrouver le nom du caractère dans la liste
		for cpte in compte_cara.values(): #Verifie quel caractère apparaît pour toutes les espèces encore présentes > pour trouver le caractère suivant.
			i += 1
			if cpte == nb:
				print("yay")
				value = cpte
				break

		liste_caracteres = []
		for cpte in compte_cara.keys():
			liste_caracteres.append(cpte)

		while i < 100 :
			nm_cara = liste_caracteres[i]
			cara_suiv = Caractere.objects.filter(nom=nm_cara)

			cara = cara_suiv[0] #objet caractère
			cara_pres = Espece_caractere.objects.filter(caractere=cara.id)#Recupère toutes les apparition de ce caractère dans la table complete des Etat par Especes.
			liste_apparition = []
			for esp in cara_pres:
				liste_apparition.append(esp.caractere)

			compte_ap = Counter(liste_apparition)
			for cpte in compte_ap.values():
				value_ap = cpte

			if value_ap > value:
				i += 1
				print(value_ap)
				print(value)
			else:
				break

		caid = cara.id #id du prochain caractère à évaluer.

	#print(cara)
	#print(caid)
	#print(compte_cara)
	#print(i)
	#print(liste_caracteres[i])
	#print(nb)

	return render(request, 'cle/cle_en_cours.html', {'l_esp':esp_possible,'c_test':caractere_test,'caid':caid})

def espece (request, id_espece):
    if Espece.objects.filter(id=id_espece).exists():
        espece=Espece.objects.get(id=id_espece)
    else:
        return render(request, 'cle/page_erreur.html', {'id':id_espece})

    return render(request, 'cle/espece.html', {'es':espece})


import pandas as pd
import sys

df = pd.read_csv(sys.stdin, dtype=str)
df['dt'] = df.dt.astype(int)
df = df[df.temp != '+9999']

hourly = df.sort_values('dt').groupby('date_hour').temp.first().reset_index()

hourly['year'] = hourly.date_hour.str[:4]
hourly['hour'] = hourly.date_hour.str[8:10]

hourly[['year','hour','temp']].to_csv(sys.stdout, index=False)


# https://blog.shahinrostami.com/2018/09/jupyter-notebook-and-updating-plots/
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import clear_output

df = pd.read_csv("bosch_numeric_1_30.gz")

for n in np.r_[1:df.shape[1]]:
    df[df.columns[n]].hist(bins = 50, xlabelsize = 5)
    plt.title(df.columns[n])
    plt.xlabel("x axis")
    plt.ylabel("y axis", size = 20)
    plt.show()
    plt.pause(2)
    clear_output()


import re
import random
import asyncio
import datetime
import pandas as pd
from playwright.async_api import async_playwright

async def perform_request_with_retry(page, link):
    MAX_RETRIES = 5
    retry_count = 0
    while retry_count < MAX_RETRIES:
        try:
            await page.goto(link, timeout=60000)
            break
        except:
            retry_count += 1
            if retry_count == MAX_RETRIES:
                raise Exception("Request timed out")
            await asyncio.sleep(random.uniform(1, 5))

async def extract_product_links(browser, page, num_products=0, num_clicks=0):
    all_items = await page.query_selector_all(
        '.a-link-normal.s-underline-text.s-underline-link-text.s-link-style.a-text-normal')
    product_links = set()
    for item in all_items:
        link = await item.get_attribute('href')
        full_link = 'https://www.amazon.in' + link
        product_links.add(full_link)
    num_products += len(product_links)
    print(f"Scraped {num_products} products.")

    next_button = await page.query_selector(
        "a.s-pagination-item.s-pagination-next.s-pagination-button.s-pagination-separator")
    if next_button:
        num_clicks += 1
        await next_button.click()
        await page.wait_for_selector('.a-link-normal.s-underline-text.s-underline-link-text.s-link-style.a-text-normal')
        product_links.update(
            await extract_product_links(browser, page, num_products,
                                        num_clicks))
    print(f"Finished scraping {num_products} products after {num_clicks} clicks.")
    return list(product_links)

async def get_product_name(page):
    try:
        product_name = await (await page.query_selector("#productTitle")).text_content()
    except:
        product_name = "Not Available"
    return product_name

async def get_brand(page):
    try:
        brand = await (await page.query_selector("tr:has-text('Brand') td.a-size-base")).inner_text()
        brand = re.sub('\u200e', '', brand)
    except:
        brand = "Not Available"
    return brand

async def get_star_rating(page):
    try:
        star_rating = await (await page.query_selector(".a-icon-row .a-icon-alt")).inner_text()
        star_rating = star_rating.split(" ")[0]
    except:
        star_rating = "Not Available"
    return star_rating

async def get_num_ratings(page):
    try:
        num_ratings_elem = await page.query_selector("#acrCustomerReviewLink #acrCustomerReviewText")
        num_ratings = await num_ratings_elem.inner_text()
        num_ratings = num_ratings.split(" ")[0]
    except:
        num_ratings = "Not Available"
    return num_ratings

async def get_original_price(page):
    try:
        original_price = await (await page.query_selector(".a-price.a-text-price")).text_content()
        original_price = original_price.split("₹")[1]
    except:
        original_price = "Not Available"
    return original_price

async def get_offer_price(page):
    try:
        offer_price = await (await page.query_selector(".a-price-whole")).text_content()
    except:
        offer_price = "Not Available"
    return offer_price

async def extract_technical_details(page):
    try:
        table_element = await page.query_selector("#productDetails_techSpec_section_1")
        rows = await table_element.query_selector_all("tr")
        technical_details = {}
        for row in rows:
            key_element = await row.query_selector("th")
            value_element = await row.query_selector("td")
            key = await page.evaluate('(element) => element.textContent', key_element)
            value = await page.evaluate('(element) => element.textContent', value_element)
            value = value.strip().replace('\u200e', '')
            technical_details[key.strip()] = value
        return technical_details
    except:
        return {}

async def get_best_sellers_rank(page):
    try:
        best_sellers_rank = await (
            await page.query_selector("tr th:has-text('Best Sellers Rank') + td span:nth-child(1)")).text_content()
    except:
        best_sellers_rank = "Not Available"
    return best_sellers_rank

async def get_bullet_points(page):
    bullet_points = []
    try:
        ul_element = await page.query_selector('#feature-bullets ul.a-vertical')
        li_elements = await ul_element.query_selector_all('li')
        for li in li_elements:
            bullet_points.append(await li.inner_text())
    except:
        bullet_points = []
    return bullet_points

async def main():
    async with async_playwright() as pw:
        browser = await pw.chromium.launch()
        page = await browser.new_page()
        await perform_request_with_retry(page,
                                         'https://www.amazon.in/s?k=air+fryer&crid=3EWKFR0AZLVMY&sprefix=air+fryer%2Caps%2C3150&ref=nb_sb_noss_1')
        product_links = await extract_product_links(browser, page)

        data = []
        for i, link in enumerate(product_links):
            await perform_request_with_retry(page, link)

            product_name = await get_product_name(page)
            brand = await get_brand(page)
            star_rating = await get_star_rating(page)
            num_ratings = await get_num_ratings(page)
            original_price = await get_original_price(page)
            offer_price = await get_offer_price(page)
            best_sellers_rank = await get_best_sellers_rank(page)
            technical_details = await extract_technical_details(page)
            bullet_points = await get_bullet_points(page)

            if i % 10 == 0 and i > 0:
                print(f"Processed {i} links.")
            if i == len(product_links) - 1:
                print(f"All information for link {i} has been scraped.")

            today = datetime.datetime.now().strftime("%Y-%m-%d")
            data.append((today, link, product_name, brand, star_rating, num_ratings, original_price, offer_price,
                         best_sellers_rank, technical_details, bullet_points))

        df = pd.DataFrame(data,
                          columns=['Date', 'Product Link', 'Product Name', 'Brand', 'Star Rating', 'Number of Ratings',
                                   'Original Price', 'Offer Price', 'Best Sellers Rank', 'Technical Details',
                                   'Description'])

        df.to_csv('product_details_new_day_4.1.csv', index=False)
        print('CSV file has been written successfully.')
        await browser.close()

if __name__ == '__main__':
    asyncio.run(main())


# 전력망을 둘로 나누기

# 문제 설명

# n개의 송전탑이 전선을 통해 하나의 트리 형태로 연결되어 있습니다. 당신은 이 전선들 중 하나를 끊어서 현재의 전력망 네트워크를 2개로 분할하려고 합니다.
# 이때, 두 전력망이 갖게 되는 송전탑의 개수를 최대한 비슷하게 맞추고자 합니다.
# 송전탑의 개수 n, 그리고 전선 정보 wires가 매개변수로 주어집니다.
# 전선들 중 하나를 끊어서 송전탑 개수가 가능한 비슷하도록 두 전력망으로 나누었을 때, 두 전력망이 가지고 있는 송전탑 개수의 차이(절대값)를 return 하도록 solution 함수를 완성해주세요.

# 제한사항
# n은 2 이상 100 이하인 자연수입니다.
# wires는 길이가 n-1인 정수형 2차원 배열입니다.
# wires의 각 원소는 [v1, v2] 2개의 자연수로 이루어져 있으며, 이는 전력망의 v1번 송전탑과 v2번 송전탑이 전선으로 연결되어 있다는 것을 의미합니다.
# 1 ≤ v1 < v2 ≤ n 입니다.
# 전력망 네트워크가 하나의 트리 형태가 아닌 경우는 입력으로 주어지지 않습니다.

from collections import deque

def bfs(start, visited, graph):
    queue = deque([start])
    result = 1
    visited[start] = True
    while queue:
        now = queue.popleft()

        for i in graph[now]:
            if visited[i] == False:
                result += 1
                queue.append(i)
                visited[i] = True

    return result

def solution(n, wires):
    answer = n
    graph = [[] for i in range(n+1)]

    for v1,v2 in wires:
        graph[v1].append(v2)
        graph[v2].append(v1)

    for start,not_visit in wires:
        visitied = [False]*(n+1)
        visitied[not_visit] = True
        result = bfs(start,visitied,graph)
        if abs(result - (n-result)) < answer:
            answer = abs(result - (n-result))

    return answer

# set을 활용한 다른 풀이
def solution(n, wires):
    answer = n
    for sub in (wires[i+1:] + wires[:i] for i in range(len(wires))):
        s = set(sub[0])
        [s.update(v) for _ in sub for v in sub if set(v) & s]
        answer = min(answer, abs(2 * len(s) - n))
    return answer


import cv2
import os
import numpy as np

file_dir ='.\\source\\'
obj_dir='.\\result\\'

i=0

##对比度和亮度调整
def Contrast_and_Brightness(alpha, beta, img):
    blank = np.zeros(img.shape, img.dtype)
    # dst = alpha * img + beta * blank
    dst = cv2.addWeighted(img, alpha, blank, 1-alpha, beta)
    return dst

##旋转调整
def rotate(img,angle):
    height = img.shape[0]
    width = img.shape[1]

    if angle%180 == 0:
        scale = 1
    elif angle%90 == 0:
        scale = float(max(height, width))/min(height, width)
    else:
        scale = math.sqrt(pow(height,2)+pow(width,2))/min(height, width)
    rotateMat = cv2.getRotationMatrix2D((width/2, height/2), angle, scale)
    rotateImg = cv2.warpAffine(img, rotateMat, (width, height))
    return rotateImg

def  cv_imread(filePath):
     cv_img=cv2.imdecode(np.fromfile(filePath,dtype=np.uint8),-1)
     return cv_img

for img_name in os.listdir(file_dir):
    img_name=img_name
    img_path = file_dir+img_name#读取每一个图片路径
    image = cv_imread(img_path)
    #rotate_image=rotate(image,180)
    image_brightened=Contrast_and_Brightness(1.020, 1.5, image)
    cv2.imwrite(obj_dir+'zd949Contrast_{:<d}.jpg'.format(i),image_brightened)
    i+=1

print("图像处理完毕！")


def plurals(string):
    wordlist = string.split()       # get all the word(s) from the string
    vowelslist = ('ay', 'ey', 'iy', 'oy', 'uy')
    endswithYlist = ('y')
    endswithElselist = ('o', 'ch', 's', 'sh', 'x', 'z')
    pluralstring = ''                # store the response in a string
    for words in wordlist:

        if words.endswith(vowelslist):             #use endwith() to check if words are end in vowelist

            pluralstring += words + 's' + ' '

        elif words.endswith(endswithYlist):       # end in endswithYlist

            pluralstring += words[:-1] + 'ies' + ' '

        elif words.endswith(endswithElselist):   #end in endwithElselist

            pluralstring += words + 'es' + ' '

        else:

            pluralstring += words + 's' + ' '       #the normal end just add 's

        if words == wordlist[-1]:
            pluralstring = pluralstring[:-1]
    return pluralstring                                 #return the string after confirm the words in it are plural

def getuserstring():
    username = input("Hello and welcome! What's your name? : ")
    userline = input('Hello! ' + username + ', please enter any statement or line : ')
    print('Prural of the line is : ', plurals(userline))

getuserstring()


import json
import matplotlib.pyplot as plt
import os
from scipy import integrate
import scipy.interpolate
import scipy.optimize
import numpy as np
from glob import glob
import pathlib
import math as m

mc_lib_dir = pathlib.Path(__file__).parent.resolve()

def find(lst, a):
    """Finds the index of an element that matches a specified value.
    Args:
        a(float): The value to search for
    Returns:
        match_list[0](int): The index that a match occurrs, assuming there is only one match.
    """
    tolerance = 1e-14
    match_list = [
        i for i, x in enumerate(lst) if np.isclose([x], [a], rtol=tolerance)[0]
    ]
    if len(match_list) == 1:
        return match_list[0]
    elif len(match_list) > 1:
        print("Found more than one match. This is not expected.")
    elif len(match_list) == 0:
        print(
            "\nWARNING: Search value does not match any value in the provided list.\n"
        )

def read_mc_results_file(results_file_path):
    """Function to parse mc results.json files.
    Args;
        results_file_path(str): Path to the results.json file for the given monte carlo simulation.
    Returns:
        x(ndarray): Vector of compostitions
        b(ndarray): Vector of beta values
        temperature(ndarray): Vecor of temperature values (K)
        potential_energy(ndarray): Vector of potential energy values (E-mu*x)
    """
    with open(results_file_path) as f:
        results = json.load(f)

    mu = np.array(results["param_chem_pot(a)"])
    x = np.array(results["<comp(a)>"])
    b = np.array(results["Beta"])
    temperature = np.array(results["T"])
    potential_energy = np.array(results["<potential_energy>"])
    return (mu, x, b, temperature, potential_energy)

def read_lte_results(results_file_path):
    """
    Takes a lte results.json file and returns outputs from the simulation.

    Args:
        results_file_path(str): Path to the results.json file.
    Returns:
        tuple(
            mu(ndarray): Vector of chemical potentials (species "a")
            b(ndarray): Vector of Beta values.
            t(ndarray): Vector of temperatures.
            x(ndarray): Vector of compositions.
            pot_eng(ndarray): Vector of phi values (grand canonical potential energy)
        )
    """
    with open(results_file_path) as f:
        results = json.load(f)

    mu = np.array(results["param_chem_pot(a)"])
    b = np.array(results["Beta"])
    t = np.array(results["T"])
    x = np.array(results["gs_comp(a)"])
    pot_eng = np.array(results["phi_LTE"])

    return (mu, b, t, x, pot_eng)

def read_mc_settings(settings_file):
    """
    Function to read chemical potential and temperature values from a mc_settings.json file.

    Args:
        settings_file(str): Path to a mc_settings.json file.
    Returns:
        tuple(
            mu_values,      (ndarray): Vector of chemical potential values.
            t_values        (ndarray): Vector of temperature values.
        )
    """
    with open(settings_file) as f:
        settings = json.load(f)

    mu_start = settings["driver"]["initial_conditions"]["param_chem_pot"]["a"]
    mu_stop = settings["driver"]["final_conditions"]["param_chem_pot"]["a"]
    mu_increment = settings["driver"]["incremental_conditions"]["param_chem_pot"]["a"]
    t_start = settings["driver"]["initial_conditions"]["temperature"]
    t_stop = settings["driver"]["final_conditions"]["temperature"]
    t_increment = settings["driver"]["incremental_conditions"]["temperature"]

    if mu_increment != 0:
        mu_length = int(np.abs((mu_start - mu_stop) / mu_increment))
    else:
        mu_length = 1
    if t_increment != 0:
        t_length = int(np.abs((t_start - t_stop) / t_increment))
    else:
        t_length = 1

    if mu_length == 1:
        mu_values = np.ones(t_length) * mu_start
    elif mu_length > 1:
        mu_values = np.linspace(mu_start, mu_stop, mu_length)
    if t_length == 1:
        t_values = np.ones(mu_length) * t_start
    elif t_length > 1:
        t_values = np.linspace(t_start, t_stop, t_length)

    return (mu_values, t_values)

def read_superdupercell(mc_settings_file):
    """Function to read mu / temperature values as well as superdupercell from a monte carlo settings.json file.
    Args:
        mc_settings_file(str): Path to mc_settings.json file.
    Returns:
        superdupercell(list): Matrix (list of 3 lists) that describes a supercell for the monte carlo simulation
    """
    with open(mc_settings_file) as f:
        settings = json.load(f)
    superdupercell = settings["supercell"]
    return superdupercell

class lte_run:
    def __init__(self, lte_dir):
        self.path = lte_dir
        self.read_lte_results()

    def read_lte_results(self):
        results_file = os.path.join(self.path, "results.json")
        with open(results_file) as f:
            results = json.load(f)
        self.mu = results["param_chem_pot(a)"]
        self.b = results["Beta"]
        self.t = results["T"]
        self.x = results["gs_comp(a)"]
        self.pot_eng = results["phi_LTE"]
        self.superdupercell = read_superdupercell(
            os.path.join(self.path, "mc_settings.json")
        )

class constant_t_run:
    def __init__(self, const_t_dir):
        self.path = const_t_dir
        results_file_path = os.path.join(self.path, "results.json")
        self.mu, self.x, self.b, self.t, self.pot_eng = read_mc_results_file(
            results_file_path
        )
        self.integrate_constant_temp_grand_canonical()
        self.superdupercell = read_superdupercell(
            os.path.join(self.path, "mc_settings.json")
        )

    def integrate_constant_temp_grand_canonical(self):
        """Function to integrate across mu values at a constant temperature
        Args:
            x(list): Vector of compostitions
            b(list): Vector of beta values
            potential_energy(list): Vector of potential energy values (E-mu*x)
            mu(list): Vector of mu values

        Returns:
            integrated_potential(list): List of grand canonical free energy values corresponding to a fixed temperature / beta value.
        """
        free_energy_reference = self.pot_eng[0]
        integrated_potential = []
        for index, value in enumerate(self.mu):
            index = index + 1
            if index > 0:
                current_mu = self.mu[0:index]
                current_b = self.b[0:index]
                current_x = self.x[0:index]
                integrated_potential.append(
                    (1 / current_b[-1])
                    * (
                        self.b[0] * free_energy_reference
                        + integrate.simpson((-1 * current_b * current_x), current_mu)
                    )
                )
        self.integ_grand_canonical = np.asarray(integrated_potential)

class heating_run:
    def __init__(self, heating_dir, lte_run):
        self.path = heating_dir
        results_file_path = os.path.join(self.path, "results.json")
        self.mu, self.x, self.b, self.t, self.pot_eng = read_mc_results_file(
            results_file_path
        )
        self.get_lte_reference_energy(lte_run)
        self.integrate_heating_grand_canonical_from_lte()
        self.superdupercell = read_superdupercell(
            os.path.join(self.path, "mc_settings.json")
        )

    def get_lte_reference_energy(self, lte_run):
        mu_index = find(lte_run.mu, self.mu[0])
        self.energy_reference = lte_run.pot_eng[mu_index]

    def integrate_heating_grand_canonical_from_lte(self):
        """Function to integrate the grand canonical free energy from monte carlo heating run results.
        Args:
            x(list): Vector of compostitions
            b(list): Vector of beta values
            potential_energy(list): Vector of potential energy values (E-mu*x)
            mu(list): Vector of mu values

        Returns:
            integrated_potential(list): List of grand canonical free energy values corresponding to a fixed mu value.
        """

        self.pot_eng[0] = self.energy_reference

        integrated_potential = []
        for index in range(len(self.b)):
            index = index + 1
            if index > 0:
                current_b = self.b[0:index]
                current_potential_energy = self.pot_eng[0:index]
                integrated_potential.append(
                    (1 / current_b[-1])
                    * (
                        self.b[0] * self.energy_reference
                        + integrate.simpson(current_potential_energy, current_b)
                    )
                )
        self.integ_grand_canonical = np.asarray(integrated_potential)

class cooling_run:
    def __init__(self, cooling_dir, constant_t_run):
        self.path = cooling_dir
        results_file_path = os.path.join(self.path, "results.json")
        self.mu, self.x, self.b, self.t, self.pot_eng = read_mc_results_file(
            results_file_path
        )
        self.get_constant_t_reference_energy(constant_t_run)
        self.integrate_cooling_from_const_t_run()
        self.superdupercell = read_superdupercell(
            os.path.join(self.path, "mc_settings.json")
        )

    def get_constant_t_reference_energy(self, constant_t_run):
        mu_index = find(constant_t_run.mu, self.mu[0])
        self.energy_reference = constant_t_run.integ_grand_canonical[mu_index]

    def integrate_cooling_from_const_t_run(self):
        free_energy_reference = self.energy_reference
        integrated_potential = []
        for index, value in enumerate(self.b):
            index = index + 1
            if index > 0:
                current_b = self.b[0:index]
                current_potential_energy = self.pot_eng[0:index]
                integrated_potential.append(
                    (1 / current_b[-1])
                    * (
                        self.b[0] * free_energy_reference
                        + integrate.simpson(current_potential_energy, current_b)
                    )
                )
        self.integ_grand_canonical = np.asarray(integrated_potential)

def format_mc_settings(
    superdupercell,
    mu_init,
    mu_final,
    mu_increment,
    temp_init,
    temp_final,
    temp_increment,
    output_file,
    start_config_path,
):

    templates_path = os.path.join(mc_lib_dir, "../templates")
    # Read template
    with open(os.path.join(templates_path, "mc_grand_canonical_template.json")) as f:
        mc_settings = json.load(f)

    # Write settings
    mc_settings["supercell"] = superdupercell
    mc_settings["driver"]["initial_conditions"]["param_chem_pot"]["a"] = mu_init
    mc_settings["driver"]["initial_conditions"]["temperature"] = temp_init
    mc_settings["driver"]["final_conditions"]["param_chem_pot"]["a"] = mu_final
    mc_settings["driver"]["final_conditions"]["temperature"] = temp_final
    mc_settings["driver"]["incremental_conditions"]["param_chem_pot"][
        "a"
    ] = mu_increment
    mc_settings["driver"]["incremental_conditions"]["temperature"] = temp_increment

    if (start_config_path != False) and (start_config_path != None):
        mc_settings["driver"]["motif"]["configdof"] = start_config_path

    # write settings file
    with open(output_file, "w") as f:
        json.dump(mc_settings, f, indent="")

def run_cooling_from_const_temperature(
    mu_values,
    mc_cooling_dir,
    const_temp_run_dir,
    temp_final=20,
    temperature_increment=-5,
    job_scheduler="slurm",
):

    # read mu values, temperature information from the existing settings file
    (const_t_mu, x, b, temperature_values, potential_energy) = read_mc_results_file(
        os.path.join(const_temp_run_dir, "results.json")
    )
    superdupercell = read_superdupercell(
        os.path.join(const_temp_run_dir, "mc_settings.json")
    )
    # for each mu value, start a cooling run with the condition.# final state as the initial state (condition indexing starts at 0)
    for mu in mu_values:

        # Set up run directory
        run_name = "mu_%.4f_%.4f_T_%d_%d" % (mu, mu, temperature_values[0], temp_final)
        current_dir = os.path.join(mc_cooling_dir, run_name)
        if os.path.isfile(os.path.join(current_dir, "results.json")) == False:

            os.makedirs(current_dir)
            os.chdir(current_dir)

            # get const_t_mu index that matches mu
            mu_index = find(const_t_mu, mu)
            # Write settings file
            settings_file = os.path.join(current_dir, "mc_settings.json")
            start_config_path = os.path.join(
                const_temp_run_dir, "conditions.%d" % mu_index, "final_state.json"
            )

            format_mc_settings(
                superdupercell,
                mu,
                mu,
                0,
                temperature_values[0],
                temp_final,
                temperature_increment,
                settings_file,
                start_config_path,
            )

            # Run MC cooling
            if job_scheduler == "slurm":
                user_command = "casm monte -s mc_settings.json > mc_results.out"
                format_slurm_job(
                    jobname="cool_" + run_name,
                    hours=20,
                    user_command=user_command,
                    output_dir=current_dir,
                    delete_submit_script=False,
                )
                submit_slurm_job(current_dir)
            elif job_scheduler == "braid":
                user_command = "casm monte -s mc_settings.json > mc_results.out"
                format_pbs_job(
                    jobname=run_name,
                    hours=20,
                    user_command=user_command,
                    output_dir=current_dir,
                    delete_submit_script=False,
                )
                submit_pbs_job(current_dir)
            elif job_scheduler == "pod":
                print("In the works")
            """
            print("Submitting: ", end="")
            print(current_dir)
            os.system("casm monte -s mc_settings.json > mc_results.out &")
            """

def run_heating(
    mc_heating_dir,
    mu_values,
    superdupercell,
    temp_init=20,
    temp_final=2000,
    temp_increment=5,
    scheduler="slurm",
):

    for mu_value in mu_values:

        run_name = "mu_%.4f_%.4f_T_%d_%d" % (mu_value, mu_value, temp_init, temp_final)
        current_dir = os.path.join(mc_heating_dir, run_name)

        if os.path.isfile(os.path.join(current_dir, "results.json")) == False:
            os.makedirs(current_dir)
            os.chdir(current_dir)

            # Format settings file for this heating run
            settings_file = os.path.join(current_dir, "mc_settings.json")
            format_mc_settings(
                superdupercell,
                mu_value,
                mu_value,
                0,
                temp_init,
                temp_final,
                temp_increment,
                settings_file,
                start_config_path=False,
            )

            # Run MC heating
            user_command = "casm monte -s mc_settings.json > mc_results.out"
            if scheduler == "slurm":
                format_slurm_job(
                    jobname="heat_" + run_name,
                    hours=20,
                    user_command=user_command,
                    output_dir=current_dir,
                    delete_submit_script=False,
                )
                submit_slurm_job(current_dir)
            elif scheduler == "pbs":
                format_pbs_job(
                    jobname=run_name,
                    hours=20,
                    user_command=user_command,
                    output_dir=current_dir,
                    delete_submit_script=False,
                )
                submit_pbs_job(current_dir)
            """
            print("Submitting: ", end="")
            print(current_dir)
            os.system("casm monte -s mc_settings.json > mc_results.out &")
            """

def plot_const_t_x_vs_mu(const_t_left, const_t_right):

    full_mu = np.concatenate((const_t_left.mu, const_t_right.mu))
    full_x = np.concatenate((const_t_left.x, const_t_right.x))

    plt.scatter(full_x, full_mu, color="xkcd:crimson")
    plt.xlabel("Composition (a)", fontsize=18)
    plt.ylabel("Chemical Potential (a)", fontsize=18)
    fig = plt.gcf()
    fig.set_size_inches(15, 19)

    return fig

def plot_heating_and_cooling(heating_run, cooling_run):
    bullet_size = 3
    if heating_run.mu[0] != cooling_run.mu[0]:
        print(
            "WARNING: Chemical potentials do not match between the heating and cooling runs"
        )
    plt.title("Constant Mu: %.4f" % heating_run.mu[0])
    plt.xlabel("Temperature (K)", fontsize=18)
    plt.ylabel("Grand Canonical Free Energy", fontsize=18)
    plt.scatter(cooling_run.t, cooling_run.integ_grand_canonical, s=bullet_size)
    plt.scatter(heating_run.t, heating_run.integ_grand_canonical, s=bullet_size)
    plt.legend(["Cooling", "Heating"])
    fig = plt.gcf()
    fig.set_size_inches(15, 19)
    return fig

# TODO: Function to check that a free energy crossing

def predict_free_energy_crossing(heating_run, cooling_run):
    """Function to find crossing point between two (energy vs T) curves.
    Args:
        heating_run(djlib.mc.heating_run):  Heating run object defined in djlib.mc
        cooling_run(djlib.mc.cooling_run): Cooling run object defined in djlib.mc
    Returns:
        tuple(
            t_intersect_predict,
            energy_intersect_predict, composition_intersect_predict
        )

    """
    # Check that lengths of all vectors match and that temp_heating == temp_cooling (i.e., they're not the reverse of each other)
    if (
        heating_run.integ_grand_canonical.shape[0]
        == heating_run.t.shape[0]
        == cooling_run.integ_grand_canonical.shape[0]
        == cooling_run.t.shape[0]
        == heating_run.x.shape[0]
        == cooling_run.x.shape[0]
    ):

        find_intersection = False
        if np.allclose(heating_run.t, cooling_run.t):
            find_intersection = True
        else:
            # If the temperature axes arent the same, try swapping the order of temp_cooling and cooling_integrated_free_energy.
            cooling_run.t = np.flip(cooling_run.t)
            cooling_run.integ_grand_canonical = np.flip(
                cooling_run.integ_grand_canonical
            )
            cooling_run.x = np.flip(cooling_run.x)

            # If the temperature axes still aren't the same, cancel the function.
            if np.allclose(heating_run.t, cooling_run.t):
                find_intersection = True
            else:
                print(
                    "Heating and cooling run temperature vectors are the same length but do not match. See printout below:\ntemp_heating  temp_cooling"
                )
                for idx, value in enumerate(heating_run.t):
                    print("%.3f  %.3f" % heating_run.t[idx], cooling_run.t[idx])

        if find_intersection:
            # TODO: Check that there isn't more than one intersection (complete overlap) or no intersection.

            # fit spline to each dataset, calculate intersection
            interp_heating = scipy.interpolate.InterpolatedUnivariateSpline(
                heating_run.t, heating_run.integ_grand_canonical
            )
            interp_heating_comp = scipy.interpolate.InterpolatedUnivariateSpline(
                heating_run.t, heating_run.x
            )
            interp_cooling = scipy.interpolate.InterpolatedUnivariateSpline(
                cooling_run.t, cooling_run.integ_grand_canonical
            )
            interp_cooling_comp = scipy.interpolate.InterpolatedUnivariateSpline(
                cooling_run.t, cooling_run.x
            )

            # define a difference function to calculate the root
            def difference(t):
                return np.abs(interp_heating(t) - interp_cooling(t))

            # Provide a composition x0 as a guess for the root finder
            # This will break if there are multiple identical minimum values
            t0_index = np.argmin(
                abs(
                    heating_run.integ_grand_canonical
                    - cooling_run.integ_grand_canonical
                )
            )
            t0_guess = heating_run.t[t0_index]

            # Calculate the intersection point
            t_intersect_predict = scipy.optimize.fsolve(difference, x0=t0_guess)
            energy_intersect_predict = interp_heating(t_intersect_predict)
            composition_intersect_predict = interp_heating_comp(t_intersect_predict)

            return (
                t_intersect_predict,
                energy_intersect_predict,
                composition_intersect_predict,
            )

    else:
        print(
            "The free energies and composition vectors do not have the same lengths.\nCurrent lengths are:"
        )
        print("length of temp_heating: %d" % len(temp_heating))
        print(
            "length of heating_integrated_free_energy: %d"
            % len(heating_integrated_free_energy)
        )
        print("length of temp_cooling: %d" % len(temp_cooling))
        print(
            "length of cooling_integrated_free_energy: %d"
            % len(cooling_integrated_free_energy)
        )

def find_crossing_composition(
    temperature, integrated_energies, t_intersect_predict, energy_intersect_predict
):
    """Given an interpolated point in (energy vs temperature) space, find the closest existing (energy, temperature) and return the corresponding composition x and corresponding temperature.
    Args:
        integrated_energies(ndarray): Vector of integrated energy values.
        temperature(ndarray): Vector of temperature values (K).
        x(ndarray): Vector of composition values.
        t_intersect_predict(float): Interpolated prediction of the free energy crossing temperature between a heating and cooling grand canonical monte carlo simulation.
        energy_intersect_predict(float): Interpolated prediction of the free energy at the crossing temperature between a heating and cooling grand canonical monte carlo simulation.

    Returns:
        tuple(
            x_at_crossing(float): Composition at the actual coordinates closest to the predicted
            t_at_crossing(float): Temperature (K) at the actual coordinates closest to the predicted
        )
    """

    temperature_and_energy = np.zeros((len(temperature), 2))
    temperature_and_energy[:, 0] = temperature
    temperature_and_energy[:, 1] = integrated_energies

    prediction_point = np.array([t_intersect_predict, energy_intersect_predict])

    difference = temperature_and_energy - prediction_point

    distance = np.sum(np.abs(difference) ** 2, axis=-1) ** (1 / 2)
    closest_point_index = np.argmin(distance)

    x_at_crossing = x[closest_point_index]
    t_at_crossing = temperature[closest_point_index]
    return (x_at_crossing, t_at_crossing)

def simulation_is_complete(mc_run_dir):
    """Check that a grand canonical monte carlo simulation has finished
    Args:
        mc_run_dir(str): Path to a monte carlo simulation directory.

    Returns:
        simulation_status(bool): simulation is complete (True) or simulation is not complete (False)
    """
    # Check the number of conditions (mu, temp) that should be completed
    # TODO: read the results.json file instead of the number of conditions directories to see if a simulaiton is complete.
    mc_settings_file = os.path.join(mc_run_dir, "mc_settings.json")
    mu_values, temperature_values = read_mc_settings(mc_settings_file)

    target_t_length = temperature_values.shape[0]

    if os.path.isfile(os.path.join(mc_run_dir, "results.json")):
        mu, x, b, temperature, potential_energy = read_mc_results_file(
            os.path.join(mc_run_dir, "results.json")
        )
        if temperature.shape[0] == target_t_length.shape:
            simulation_status = True
        else:
            simulation_status = False
    else:
        print("Cannot find %s" % os.path.join(mc_run_dir, "results.json"))
        simulation_status = False
    return simulation_status

def plot_t_vs_x_rainplot(mc_runs_directory, save_image=False, show_labels=False):
    """plot_rain_plots(mc_runs_directory, save_image_path=False, show_labels=False)

    Generate a single (T vs composition) plot using all monte carlo runs in mc_runs_directory.
    Args:
        mc_runs_directory(str): Path to the directory containing all grand canonical monte carlo runs.
        same_image(bool): Whether the image will be saved to the run directory or not.
        show_labels(bool): Whether or not the plot legend displays.

    Returns:
        fig(matplotlib.pyplot figure object): 2D plot object. Can do fig.show() to display the plot.
    """
    labels = []
    run_list = glob(os.path.join(mc_runs_directory, "mu*"))
    for run in run_list:
        results_file = os.path.join(run, "results.json")
        if os.path.isfile(results_file):
            with open(results_file) as f:
                data = json.load(f)
                f.close()
                current_mc = run.split("/")[-1]
                labels.append(current_mc)
                composition = data["<comp(a)>"]
                temperature = data["T"]
                plt.scatter(composition, temperature)

    if show_labels:
        plt.legend(labels)
    plt.xlabel("Composition", fontsize=18)
    plt.ylabel("Temperature (K)", fontsize=18)
    title = (
        "Chemical Potential and Temperature Sweep Rain Plot: %s"
        % mc_runs_directory.split("/")[-1]
    )
    plt.title("Chemical Potential and Temperature Sweep Rain Plot", fontsize=30)
    fig = plt.gcf()
    fig.set_size_inches(18.5, 10)
    if save_image:
        fig.savefig(os.path.join(mc_runs_directory, title + ".png"), dpi=100)
        print("Saving image to file: ", end="")
        print(os.path.join(mc_runs_directory, title + ".png"))
    return fig

def submit_pbs_job(run_dir):
    submit_file = os.path.join(run_dir, "submit_pbs.sh")
    os.system("qsub %s" % submit_file)

def format_pbs_job(
    jobname, hours, user_command, output_dir, delete_submit_script=False
):
    """
    Formats a pbs (TORQUE) submit file.
    Args:
        jobname(str): Name of the slurm job.
        hours(int): number of hours to run the job. Only accepts integer values.
        user_command(str): command line command submitted by the user as a string.
        output_dir(str): Path to the directory that will contain the submit file. Assumes that submit file will be named "submit.sh"
        delete_submit_script(bool): Whether the submission script should delete itself upon completion.
    Returns:
        None.
    """
    submit_file_path = os.path.join(output_dir, "submit_pbs.sh")
    templates_path = os.path.join(mc_lib_dir, "../templates")
    with open(os.path.join(templates_path, "single_task_pbs_template.sh")) as f:
        template = f.read()

        if delete_submit_script:
            delete_submit_script = "rm %s" % submit_file_path
        else:
            delete_submit_script = ""

        hours = int(m.ceil(hours))
        s = template.format(
            jobname=jobname,
            rundir=output_dir,
            hours=hours,
            user_command=user_command,
            delete_submit_script=delete_submit_script,
        )
    with open(submit_file_path, "w") as f:
        f.write(s)
    os.system("chmod +x %s " % submit_file_path)

def submit_slurm_job(run_dir):
    submit_file = os.path.join(run_dir, "submit_slurm.sh")
    os.system("sbatch %s" % submit_file)

def format_slurm_job(
    jobname, hours, user_command, output_dir, delete_submit_script=False
):
    """
    Formats a slurm job sumbission script. Assumes that the task only needs one thread.
    Args:
        jobname(str): Name of the slurm job.
        hours(int): number of hours to run the job. Only accepts integer values.
        user_command(str): command line command submitted by the user as a string.
        output_dir(str): Path to the directory that will contain the submit file. Assumes that submit file will be named "submit.sh"
        delete_submit_script(bool): Whether the submission script should delete itself upon completion.
    Returns:
        None.
    """
    submit_file_path = os.path.join(output_dir, "submit_slurm.sh")
    templates_path = os.path.join(mc_lib_dir, "../templates")
    with open(os.path.join(templates_path, "single_task_slurm_template.sh")) as f:
        template = f.read()

        if delete_submit_script:
            delete_submit_script = "rm %s" % submit_file_path
        else:
            delete_submit_script = ""

        hours = int(m.ceil(hours))
        s = template.format(
            jobname=jobname,
            rundir=output_dir,
            hours=hours,
            user_command=user_command,
            delete_submit_script=delete_submit_script,
        )
    with open(submit_file_path, "w") as f:
        f.write(s)
    os.system("chmod 755 %s " % submit_file_path)


import numpy as np

def feed_training_data(input,filename):
    i=0
    file = open(filename, 'r')
    for line in file.readlines():
        input[i] = [int(x) for x in line.split()]
        i=i+1

def test_item_based_similarity(input,file,num):
    testdata = open(file, 'r').read().strip().split('\n')
    testmatrix = [data.split() for data in testdata]
    testmatrix = [[int(e) for e in data] for data in testmatrix]
    current_user_id = testmatrix[0][0]-1
    current_user_data={}
    movie_ids = []
    ratings=[]
    outputfile = "result"+str(num)+".txt"

    for i in range(len(testmatrix)):
        user_id = testmatrix[i][0]-1
        movie_id = testmatrix[i][1]-1
        rating = testmatrix[i][2]

        if user_id== current_user_id:
            if rating == 0 :
                movie_ids.append(movie_id)
            else:
                current_user_data [movie_id] = rating
        else:
            get_results_using_adjusted_cosine(
                input,
                current_user_data,
                current_user_id,
                movie_ids,
                ratings,
                outputfile
            )
            current_user_id = user_id
            current_user_data = {}
            movie_ids = []
            if rating == 0 :
                movie_ids.append(movie_id)
            else:
                current_user_data [movie_id] = rating

    get_results_using_adjusted_cosine(input,current_user_data,current_user_id,movie_ids,ratings,outputfile)
    return ratings

def get_results_using_adjusted_cosine(input,current_user_data,current_user_id,movie_ids,ratings,outputfile):

     #Creating movie-user matrix by taking transpose of inpur matrix
     movie__user_matrix = np.array(input).T

     #Calculating average rating for every user
     users_avg = [np.average([r for r in u if r > 0]) for u in input]

     #Creating output file
     file = open(outputfile, "a")

     for movie in movie_ids:
         sum=0
         weight_sum=0
         rating =0
         weights ={}

         for key in current_user_data:
             weights[key]=(get_cosine_similarity(movie__user_matrix[key], movie__user_matrix[movie],users_avg))

         for key_movie in current_user_data:

             weight_sum+=weights[key_movie]
             sum+=weights[key_movie]*current_user_data[key_movie]

         if weight_sum != 0:
             rating = sum/weight_sum
         else:
         # If no neighbors were found guessing rating as 3
             rating = 3

         rating = scale_rating(rating)

         #Appending to output file
         file.write("%i %i %i\n" % (current_user_id+1, movie+1,rating))
         ratings.append(rating)

     file.close()
     return

def scale_rating(rating):
    rating = int(np.rint(rating))
    if rating > 5:
        rating = 5
    elif rating < 1:
        rating = 1

    return rating
def get_common_values(v1, v2, users_avg):
    """
    Returns new vectors (a, b) after filtering any
    indices where an element in a or b <= 0.
    """
    v1_new = []
    v2_new = []
    for i, x in enumerate(v1):
        y = v2[i]
        if y > 0 and x > 0:
            v1_new.append(x-users_avg[i])
            v2_new.append(y-users_avg[i])
    return np.array(v1_new), np.array(v2_new)

def get_cosine_similarity(movie1,movie2,users_avg):
    """
        Cosine similarity between two vectors.
        Returns a float in [-1, 1].
    """

    vector_v1, vector_v2 = get_common_values(movie1, movie2, users_avg)

    sim = np.dot((vector_v1), vector_v2)

    lenght_v1 = get_length(vector_v1)
    length_v2 = get_length(vector_v2)

    if lenght_v1 != 0 and length_v2 != 0:
        sim /= (lenght_v1 * length_v2)
    else:
        sim = 0

    if sim > 1:
        sim = 1
    elif sim < -1:
        sim = -1

    return sim

def get_length(v):
    return np.sqrt(np.sum(np.square(v)))
def sortSecond(val):
    return val[1]
def main():
    # Declaring rows
    N = 200
    # Declaring columns
    M = 1000

    #Intializing input matrix
    input = [[0 for i in range(M)] for j in range(N)]
    feed_training_data(input,'train.txt')

    print("processing test file 5")
    test_item_based_similarity(input,"test5.txt",5)
    print("predictions done for file 5")
    print("processing test file 10")
    test_item_based_similarity(input,"test10.txt",10)
    print("predictions done for file 10")
    print("processing test file 20")
    test_item_based_similarity(input, "test20.txt",20)
    print("predictions done for file 20")

main()


#☆𝒐𝒎𝒂𝒋𝒊𝒏𝒂𝒊☆#
import sys
import math
from math import ceil, floor, atan2, degrees
import itertools
from functools import lru_cache
from collections import deque
import cmath
inf=10**20
tau=2*cmath.pi
sys.setrecursionlimit(10000000)
input=sys.stdin.readline
'''''✂'''''''''''''''''''''''''''''''''''''''''''''''''''''''''

def kaku(a,b):
    return abs(a-b) if abs(a-b)<=180 else 360-abs(a-b)

def main():
    n=int(input())
    d=[tuple(map(int,input().split())) for i in range(n)]
    mx=0

    for i in range(n):
        x0,y0=d[i]
        dg=[]
        for j in range(n):
            if i==j:
                continue
            tmp=degrees(atan2(d[j][1]-y0,d[j][0]-x0))
            dg.append(tmp if tmp>=0 else 360+tmp)
        dg=sorted(dg)
        for k in range(n-1):
            l,r=0,n-1
            tmp=dg[k]+180 if dg[k]+180<360 else dg[k]-180
            while l+1<r:
                mid=(l+r)//2
                if dg[mid]<=tmp:
                    l=mid
                else:
                    r=mid
            if r<n-1:
                mx=max(mx,kaku(dg[k],dg[l]),kaku(dg[k],dg[r]))
            else:
                mx=max(mx,kaku(dg[k],dg[l]))
    print(mx)
main()


# review/serializers.py
from rest_framework import serializers

from review.models import Project, Review, Asset, Media, Feedback

from user.serializers import UserViewSerializer

class ReviewField(serializers.RelatedField):
    """Custom RelatedField Serializer for representation of a review"""

    def to_representation(self, value):
        collaborators = value.collaborators.all()
        serializer = UserViewSerializer(data=collaborators, many=True)
        serializer.is_valid()

        fields = {
            'id': value.id,
            'review_name': value.review_name,
            'image_url': value.image_url,
            'is_open': value.is_open,
            'number_of_media': value.number_of_media,
            'number_of_collaborator': value.number_of_collaborator,
            'user': {'id': value.user.id, 'username': value.user.username},
            'collaborators': serializer.data
        }
        return fields

class ProjectField(serializers.RelatedField):
    """Custom ProjectField Serializer for representation of a project"""

    def to_representation(self, value):
        fields = {
            'id': value.id,
            'project_name': value.project_name,
            'user': {'id': value.user.id, 'username': value.user.username}
        }
        return fields

class MediaField(serializers.RelatedField):
    """Media field representation"""

    def to_representation(self, value):
        fields = {
            'id': value.id,
            'media_name': value.media_name,
            'version': value.version,
            'parent': value.parent.id if value.parent else value.parent,
            'asset': {
                'id': value.asset.id,
                'name': value.asset.asset_name,
                'url': value.asset.url,
                'image_url': value.asset.image_url,
            },
            'user': {'id': value.user.id, 'username': value.user.username}
        }
        return fields

class ProjectSerializer(serializers.ModelSerializer):
    """Serializer for Project Model"""
    user = UserViewSerializer(read_only=True)
    reviews = ReviewField(read_only=True, many=True)

    class Meta:
        model = Project
        fields = ('id', 'project_name', 'image_url', 'color', 'user',
                  'reviews', 'created_at', 'updated_at', )
        read_only_fields = ('id', 'user',
                            'updated_at', 'created_at', 'reviews', 'color')

class ProjectListSerializer(serializers.ModelSerializer):
    """Serializer for Project Model"""
    user = UserViewSerializer(read_only=True)

    class Meta:
        model = Project
        fields = ('id', 'project_name', 'image_url', 'color', 'user',
                  'created_at', 'updated_at', )
        read_only_fields = ('id', 'user',
                            'updated_at', 'created_at', 'color')

class ReviewSerializer(serializers.ModelSerializer):
    """Serializer for Review Model"""
    user = UserViewSerializer(read_only=True)
    collaborators = UserViewSerializer(many=True, read_only=True)

    # Using a project serializer seems slow down the retrieve
    # review list process
    # project = ProjectSerializer(read_only=True)
    project = ProjectField(read_only=True)
    media = MediaField(read_only=True, many=True)

    class Meta:
        model = Review
        fields = ('id', 'review_name', 'description', 'project', 'is_open',
                  'number_of_media', 'number_of_collaborator', 'user',
                  'collaborators', 'media', 'image_url',
                  'created_at', 'updated_at')
        read_only_fields = ('id', 'updated_at', 'created_at',
                            'user', 'media', 'image_url',
                            'number_of_media', 'number_of_collaborator')

    # Need to override create and update because of collaborators and project
    # fiedls are customized above also check the view.py part of this for
    # more detail(perform_create, perform_update)
    def create(self, validated_data):
        review_name = validated_data.get('review_name')
        description = validated_data.get('description')
        collaborators = validated_data.get('collaborators')
        project = validated_data.get('project')
        user = validated_data.get('user')
        review = Review.objects.create(user=user, review_name=review_name,
                                       description=description,
                                       project=project)
        review.collaborators.set(collaborators)
        review.number_of_collaborator = len(review.collaborators.all())
        review.save()

        return review

    def update(self, instance, validated_data):
        instance.review_name = validated_data.get(
            'review_name', instance.review_name)
        instance.description = validated_data.get(
            'description', instance.description)
        collaborators = validated_data.get(
            'collaborators', instance.collaborators.all())
        instance.collaborators.set(collaborators)
        instance.project = validated_data.get('project', instance.project)
        instance.user = validated_data.get('user', instance.user)
        instance.is_open = validated_data.get('is_open', instance.is_open)

        instance.number_of_collaborator = len(instance.collaborators.all())

        instance.save()

        return instance

class AssetSerializer(serializers.ModelSerializer):
    """Serializer for Asset Model"""
    user = UserViewSerializer(read_only=True)

    class Meta:
        model = Asset
        fields = ('id', 'asset_name', 'url', 'height', 'width',
                  'asset_format', 'duration', 'frame_rate', 'resource_type',
                  'image_url', 'user', 'created_at', 'updated_at')
        read_only_fields = ('id', 'created_at', 'updated_at', 'user')

class MediaSerializer(serializers.ModelSerializer):
    """Serializer for Media Model"""
    user = UserViewSerializer(read_only=True)

    class Meta:
        model = Media
        fields = ('id', 'media_name', 'version', 'media_type', 'asset',
                  'user', 'review', 'parent',
                  'created_at', 'updated_at')
        read_only_fields = ('id', 'created_at', 'updated_at', 'user')

        # Depth will unfold asset and review field, so it shows details
        # on asset and review insted of number, because of this we have to
        # manually add asset and review for this serializer check out view.py
        # for more detail(perform_create)
        depth = 1

class FeedbackSerializer(serializers.ModelSerializer):
    """Serializer for Feedback Model"""
    user = UserViewSerializer(read_only=True)

    class Meta:
        model = Feedback
        fields = ('id', 'content', 'media_time', 'annotation_url',
                  'user', 'media', 'parent', 'created_at', 'updated_at')
        read_only_fields = ('id', 'created_at', 'updated_at', 'user')

        depth = 1


# 1차 풀이 - 성공
import itertools
def solution(genres, plays):
    cnt = {}
    for g, p in zip(genres, plays):
        if g not in cnt:
            cnt[g] = p
        else:
            cnt[g] += p
    cnt = dict(sorted(cnt.items(), key=lambda x: x[1], reverse=True))

    playIdx = {}
    for c in list(cnt.keys()):
        playIdx[c] = {}
    for i, p in enumerate(plays):
        playIdx[genres[i]][i] = p

    play = []
    for p in playIdx.values():
        play.append(dict(sorted(p.items(), key=lambda x: (-x[1], x[0]))))

    answer = []
    for p in play:
        if len(p) == 1:
            answer.append(p.keys())
        else:
            answer.append(list(p.keys())[:2])

    return list(itertools.chain(*answer))

# 다른 사람 풀이
def solution(genres, plays):
    answer = []
    d = {e:[] for e in set(genres)}
    for e in zip(genres, plays, range(len(plays))):
        d[e[0]].append([e[1] , e[2]])
    genreSort =sorted(list(d.keys()), key= lambda x: sum( map(lambda y: y[0],d[x])), reverse = True)
    for g in genreSort:
        temp = [e[1] for e in sorted(d[g],key= lambda x: (x[0], -x[1]), reverse = True)]
        answer += temp[:min(len(temp),2)]
    return answer