import collections
def orangesRotting(grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        m = len(grid)
        n = len(grid[0])
        queue = []
        def turnRotten(row, col):
            if row >= 0 and row < m and col >= 0 and col < n and grid[row][col] == 1:
                grid[row][col] = 2
                queue.append((row,col))
            return

        minutes = 0
        for row in range(m):
            for column in range(n):
                if grid[row][column] == 2:
                    queue.append((row,column))
        while queue:
            temp = queue
            queue = [] # Prep for next queue iteration/ minute
            for (r,c) in temp:
                turnRotten(r+1, c)
                turnRotten(r, c+1)
                turnRotten(r-1, c)
                turnRotten(r, c-1)
            if queue:
                minutes += 1

        # See if any fresh oranges remain
        for row in range(m):
            for column in range(n):
                if grid[row][column] == 1:
                    return -1
        return minutes

grid = [[2,1,2],
        [1,0,1],
        [0,0,0]]
print(orangesRotting(grid))


# 1. На улице встретились N друзей.
# Каждый пожал руку всем остальным друзьям (по одному разу).
# Сколько рукопожатий было?

from collections import deque

n = int(input('сколько друзей: '))

graph = []
graph.append([1]*n)
for i in range(n-1):
    graph.append([1] + [0] * (n - 1))

#print(*graph, sep='\n')

def bfs(grp, start, finish):
    parent = [None for i in range(len(grp))]
    is_visited = [False for i in range(len(grp))]

    deq = deque([start])
    is_visited[start] = True

    while len(deq) > 0:
        current = deq.pop()
        if current == finish:
            return parent
            break
        for i, vertex in enumerate(grp[current]):
            if vertex == 1 and not is_visited[i]:
                is_visited[i] = True
                parent[i] = current
                deq.appendleft(i)
    else:
        return 'невозможно!'

print(len(bfs(graph, 0, n-1)) - 1)


# Morris H. 12/10

from vpython import *

# perimeter

earth_r = 6.371E6

earth_m =  5.9724E24

theta = radians(60)

v0 = 3E3

T = 86400

G = 6.67408E-11

omg = 2*pi/T

# scene setting

scene = canvas(title='Coriolis Effect\n',
               width=1600, height=1300, align='left', range=200)

scene.range = earth_r*1.5

# display earth

earth = sphere(radius=earth_r, texture=textures.earth, up=vec(0, 1, 0), pos=vec(0, 0, 0))

# ball

ball1 = sphere(radius=earth_r/50, pos=vec(0, 0, earth_r+earth_r/100), make_trail=True,

              v=vec(0, v0*cos(theta), v0*sin(theta)), a=vec(0, 0, 0), color=color.red)

ball2 = sphere(radius=earth_r/50, pos=vec(0, 0, earth_r+earth_r/100), make_trail=True,

              v=vec(0, -v0*cos(theta), v0*sin(theta)), a=vec(0, 0, 0), color=color.blue)

ball3 = sphere(radius=earth_r/50, pos=vec(0, 0, earth_r+earth_r/100), make_trail=True,

              v=vec(0, v0*cos(theta), v0*sin(theta)), a=vec(0, 0, 0))

ball4 = sphere(radius=earth_r/50, pos=vec(0, 0, earth_r+earth_r/100), make_trail=True,

              v=vec(0, -v0*cos(theta), v0*sin(theta)), a=vec(0, 0, 0))

ball = [ball1, ball2, ball3, ball4]

# plot

g1 = graph(title='horizontal motion', align='right', xtitle='X(km)', ytitle='Y(km)',
           width=1400, height=600)

x1 = gdots(graph=g1, color=color.red)

x2 = gdots(graph=g1, color=color.blue)

# calculate force

def acc():
    return -G*earth_m*(ball[i].pos)/mag(ball[i].pos)**3 + 2*cross(vec(0, omg, 0), ball[i].v)

def cmp_acc():
    return -G*earth_m*(ball[i].pos)/mag(ball[i].pos)**3

# sim

t, dt = 0, 1

while True:

    rate(100)

    # earth rotate

    # earth.rotate(angle=2*pi/T*dt, axis=vec(0, 1, 0))

    # ball motion

    if mag(ball[0].pos) >= (earth_r + ball[0].radius*0.5):

        i = 0

        ball[0].a = acc()

        ball[0].v += ball[0].a*dt

        ball[0].pos += ball[0].v*dt

        x1.plot(pos=(ball[0].pos.x/1000, ball[0].pos.y/1000))

    if mag(ball[1].pos) >= (earth_r + ball[1].radius*0.5):

        i = 1

        ball[1].a = acc()

        ball[1].v += ball[1].a*dt

        ball[1].pos += ball[1].v*dt

        x2.plot(pos=(ball[1].pos.x/1000, ball[1].pos.y/1000))

    for i in range(2,4):

        if mag(ball[i].pos) >= (earth_r + ball[i].radius*0.5):

            ball[i].a = cmp_acc()

            ball[i].v += ball[i].a*dt

            ball[i].pos += ball[i].v*dt

    t += dt


import tensorflow as tf
from tensorflow.keras import layers
from layer import reduce, inceptionblock, auxiliary

class inceptionv1(tf.keras.Model):
    def __init__(self, channels=10):
        super(inceptionv1, self).__init__()

        self.con7 = layers.Conv2D(
            64, kernel_size=7, strides=2, padding="same", activation="relu"
        )
        self.max3_2 = layers.MaxPooling2D(3, strides=2)
        self.lrn1 = layers.Lambda(tf.nn.local_response_normalization)
        self.con3 = reduce(64, 3, 192)
        self.lrn2 = layers.Lambda(tf.nn.local_response_normalization)
        self.in3a = inceptionblock(64, [96, 3, 128], [16, 5, 32], 32)
        self.in3b = inceptionblock(128, [128, 3, 192], [32, 5, 96], 64)

        self.in4a = inceptionblock(192, [96, 3, 208], [16, 5, 48], 64)
        self.aux1 = auxiliary(channels)
        self.in4b = inceptionblock(160, [112, 3, 224], [24, 5, 64], 64)
        self.in4c = inceptionblock(128, [128, 3, 256], [24, 5, 64], 64)
        self.in4d = inceptionblock(112, [144, 3, 288], [32, 5, 64], 64)
        self.aux2 = auxiliary(channels)
        self.in4e = inceptionblock(256, [160, 3, 320], [32, 5, 128], 128)

        self.in5a = inceptionblock(256, [160, 3, 320], [32, 5, 128], 128)
        self.in5b = inceptionblock(384, [192, 3, 384], [48, 5, 128], 128)
        self.avgp = layers.AveragePooling2D(pool_size=7, strides=1)
        self.drop = layers.Dropout(0.4)
        self.flat = layers.Flatten()
        self.full = layers.Dense(channels, activation="softmax")

    def call(self, inp):
        x = self.con7(inp)
        x = self.max3_2(x)
        x = self.lrn1(x)
        x = self.con3(x)
        x = self.lrn2(x)
        # x = self.max3_2(x)
        x = self.in3a(x)
        x = self.in3b(x)
        # x = self.max3_2(x)
        x = self.in4a(x)
        a1 = self.aux1(x)
        x = self.in4b(x)
        x = self.in4c(x)
        x = self.in4d(x)
        a2 = self.aux2(x)
        x = self.in4e(x)
        # x = self.max3_2(x)
        x = self.in5a(x)
        x = self.in5b(x)
        x = self.avgp(x)
        x = self.drop(x)
        x = self.flat(x)
        x = self.full(x)
        return [x, a1, a2]

    def model(self, inp):
        x = layers.Input(shape=inp[0].shape)
        return tf.keras.Model(inputs=x, outputs=self.call(x))


class MyHashTable:
    def __init__(self, size):
        self.data = [None] * size

    def _hash(self, key):
        hash = 0
        for i in range(len(key)):
            hash = (hash + ord(key[i]) * i) % len(self.data)
        return hash

    def set(self, key, value):
        address = self._hash(key)
        if self.data[address] == None:
            self.data[address] = []
        self.data[address].append([key, value])

    def get(self, key):
        address = self._hash(key)
        currentBucket = self.data[address]
        if currentBucket != None:
            for i in range(len(currentBucket)):
                if currentBucket[i][0] == key:
                    return currentBucket[i][1]
        return None

    def keys(self):
        keysArray = []
        for i in range(len(self.data)):
            if self.data[i] != None:
                keysArray.append(self.data[i][0][0])
        return keysArray

    def myFirstRecurringCharacter(self, array):

        aux = []

        for i in array:
            if aux.__contains__(i):
                return i
            aux.append(i)

        return "There's no recurring character!"

    def lessonFirstRecurringCharacter(self, array):

        for i in array:
            if self.get(chr(i)):
                return i
            self.set(chr(i), True)

        return "There's no recurring character!"
if __name__ == '__main__':
    myArray = [2, 5, 1, 2, 3, 5, 1, 2, 4]
    ##myArray = [2, 1, 1, 2, 3, 5, 1, 2, 4]
    ##myArray = [2, 3, 4, 5]

    myHashTable = MyHashTable(len(myArray))

    print(myHashTable.lessonFirstRecurringCharacter(myArray))


from fabric.api import local, settings, abort, run, cd, env

env.hosts = ['52.10.173.250']
env.user = 'ec2-user'
env.key_filename = '/Users/anirudh/Documents/Python-Projects/Results/key.pem'

def prepare_deploy(message='fab push'):
    local('git add . && git commit'+" -m '"+message+"'")
    local('git push')

def deploy():
    code_dir = '/var/www/html/MSRIT-Results/'
    with cd(code_dir):
        run('sudo git pull')
        with cd(code_dir+'results'):
            run('sudo touch wsgi.py')


from collections import Counter
import string
import math

def array_int():

    return [int(i) for i in input().split()]
def vary(number_of_variables):
    if number_of_variables==1:
        return int(input())
    if number_of_variables>=2:
        return map(int,input().split())
def makedict(var):
    return dict(Counter(var))
mod=1000000007
m,n=vary(2)
mat=[]
for i in range(m):
    mat.append(array_int())
pat=[]
for i in range(m):
    pat.append([int(-2) for j in range(n)])
for i in range(m):
    for j in range(n):
        if mat[i][j]==0:
            for k in range(n):
                pat[i][k]=0
            for k in range(m):
                pat[k][j]=0
for i in range(m):
    for j in range(n):
        if pat[i][j]==-2:
            pat[i][j]=1

""" for i in range(m):
    print(*pat[i]) """
cat=[]
for i in range(m):
    cat.append([0 for j in range(n)])
for i in range(m):
    for j in range(n):
        for k in range(n):
            if pat[i][k]==1:
                cat[i][j]=1

        for k in range(m):
            if pat[k][j]==1:
                cat[i][j]=1
""" print(cat)
print(mat)
print(pat) """
if cat==mat:
    print('YES')
    for i in range(m):
        print(*pat[i])
else:
    print('NO')


from flask import Flask, render_template, request, redirect, url_for
from sklearn.externals import joblib

app = Flask(__name__)

flo = joblib.load("/home/analizer/mysite/flower.pkl" , mmap_mode ='r')

@app.route('/',methods=["POST","GET"])

def pred():
    if request.method=="POST":
        f1=request.form["fname"]
        print(f1)
        f0=list(f1.split(','))
        f01= [f0]
        predict=flo.predict_proba(f01)
        for i in predict:
            if i[0]==1:
                result= 'setosa'
            if i[1]==1:
                result= 'versicolor'
            if i[2]==1:
                result= 'virginica'
        print(result)
        return redirect(url_for("user",usr=result))
    else:
        return render_template("pred.html")

@app.errorhandler(500) # Server error
def error1(error):
   return render_template('500.html'), 500

@app.route("/<usr>")
def user(usr):
    return f"<h1>{usr}</h1>"


c = int(input())
p = 0

while c > 0:
    m, n, x, y = map(int, input().split())
    x -= 1
    y -= 1

    mat = [None] * m
    for i in range(m):
        mat[i] = [int(k) for k in input().split()]

    for i in range(m):
        for j in range(n):
            distancia = max(abs(i-x),abs(j-y))
            if distancia > 8:
                mat[i][j] += 1
            else:
                mat[i][j] += (10-distancia)

    p += 1
    print("Parede {}:".format(p))
    for i in range(m):
        print("%d" % (mat[i][0]), end='')
        for j in range(1, n):
            print(" %d" % mat[i][j], end='')
        print()

    c -= 1


#coding=utf-8
import json
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
obj = {'content':"测试内容",'stars':5}
array = []
for i in range(5):
	temp = obj.copy()
	temp['content'] = "测试内容" + str(i)
	temp['stars'] = i;
	array.append(temp.copy())
filecontent = {'name':"jwkuang",'date':20150825,'content':array}
encodedjson = json.dumps(filecontent)
filename = "20150825jwkuang.json"
fileobj = open(filename,"w+")
fileobj.write(encodedjson)


import csv
import json
import requests
import pandas as pd
import random

from firebase_admin import credentials, firestore, initialize_app

cred = credentials.Certificate('./firebase-private.json')
default_app = initialize_app(cred)
db = firestore.client()
itemService = db.collection('items')

# Specify the path to your CSV file
csv_file = '/Users/sarthakrawat/PythonProjects/hackathon/gpt-jam-backend/DataLoadScript/FoodNames.csv'

index = 0

df = pd.read_csv(csv_file)

id = 1

for index, row in df.iterrows():
    # Read the values from the DataFrame row
    food_item = row['FoodItem']
    food_category = row['FoodCategory']
    image_url = row['Image']

    # Create a dictionary for the JSON object
    json_obj = {
        "itemId": "itm"+str(id).zfill(6),
        "name": food_item,
        "description": food_item + " - " + food_category,
        "tags": [food_item.lower(),food_category.lower()],
        "rating": random.randint(3, 5),
        "price": random.randint(3, 8)+0.99,
        "image": image_url
    }
    item_id = json_obj["itemId"]
    # json_string = json.dumps(json_obj)
    itemService.document(item_id).set(json_obj)
    id += 1


"""
Proctor (Audit) System.

A stand-alone library that provides a pluggable framework to simplify
coding functions that detect/fix data conditions.  The objective
is to abstract the boilerplate code necessary to expose such functions
to the front-end and re-use them throughout the application.

Sometimes when we find an issue, we write a function that will
tell us the extent of the issue. And we keep running that function
over time until that condition goes away.  That functions serves as a 'detector'
for us to see if we are solving the issue.

The Proctor system attempts to put some structure around that workflow,
to allow us to specify functions that can be added/removed without impact
to the core code base.

At some point we could slap a GUI on the Proctor to code a condition on
the fly so that we can add custom reporting without a deployment.
"""
import sys
import copy
import hashlib
import logging
import warnings
from mapping import Mapping
from .registry import ConditionRegistry
from .exceptions import NotRegistered, BadProctorCondition
import plugin_support as plugins

log = logging.getLogger("proctor")
ilog = logging.getLogger('proctor.meta')
clog = logging.getLogger('proctor.condition')

def warnFormatter(message, category, filename, lineno, line=None):
    return "{}: {}".format(category.__name__, message)
warnings.formatwarning = warnFormatter

def get_property(obj, key):
    """Get the value of a related property - however deep"""
    _keys = key.split(".")

    # dotted keys "x.y.z"
    if len(_keys) > 1:
        # Could raise KeyError
        return get_property(getattr(obj, _keys[0]), _keys[1])
    else:
        return getattr(obj, _keys[0])

class ProctorSingleton(type):
    """
    The first instance created will load the plugins, if
    provided some paths.  see Proctor.__init__
    """

    _instances = {}

    def __call__(self, *args, **kwargs):
        if self not in self._instances:
            inst = super(ProctorSingleton, self).__call__(*args, **kwargs)
            self._instances[self] = inst
            inst.load_plugins()
        return self._instances[self]

class Proctor(object):
    """Manages conditions, detectors, and rectifiers collected as a registry"""

    __metaclass__ = ProctorSingleton

    def __init__(self, extpaths=None):
        self._conditions = ConditionRegistry()
        self.plugin_dirs = extpaths if extpaths else []

    """
    Methods that deal with loading conditions, detectors, and
    rectifiers.
    """

    def load_plugins(self):
        """Load all the directories"""
        for path in self.plugin_dirs:
            self.load_plugins_from(path)

    def load_plugins_from(self, dirname):
        """Loads plugins from a directory"""
        try:
            if plugins.load(dirname):
                log.info(u"Successfully loaded plugins from {}".format(dirname))
        except Exception as e:
            log.exception(u"Failed to load extensions at {}. {}".format(dirname, e.message))

    def add_module(self, name):
        """Load a module that contains conditions and detectors"""
        log.debug(u"Adding module {}".format(name))
        plugins.load_module(name)

    def add_paths(self, paths):
        """Appends the plugin path after loading"""
        for path in paths:
            if path not in self.plugin_dirs:
                self.load_plugins_from(path)
            self.plugin_dirs.append(path)

    @property
    def condition_list(self):
        """Get a listing of condition names"""
        return self._conditions.condition_list()

    def register(self, cls):
        """Registers both Conditions and ProctorObjects"""
        log.debug("Registering {}".format(cls.__name__))
        logging.captureWarnings(True)
        self._conditions.register(cls)
        logging.captureWarnings(False)

    def get_registry(self):
        """Returns the registry (a copy)"""
        return self._conditions.get_registry()

    def show_registry(self):
        """Shows the content of the registry"""
        return self._conditions.show()

    def __get_conditions(self, context):
        """
        Get the conditions registered to the context,
        where context is class object
        """
        return self._conditions.get_registered_conditions(context)

    def find_condition(self, condition, klass):
        """
        Find a specific (registered) condition - will contain all associated detectors and rectifiers

        condition(str or condition instance) text for look up for
        klass(class) to find the conditions for
        """
        name = condition if isinstance(condition, basestring) else condition.name
        for _condition in self.__get_conditions(klass):
            if _condition.name == name:
                return _condition
        return None

    def conditions(self, obj, min_level=1, exposed=None):
        """
        Get contextual condition objects - aka conditions that can be called to detect and
        rectify on the given object
        """
        conditions = []
        for cond in self._conditions.get_registered_conditions(obj.__class__):
            if cond.condition.level >= min_level:
                if exposed is None:
                    conditions.append(ContextualCondition(obj, cond))
                else:
                    if exposed == cond.condition.exposed:
                        conditions.append(ContextualCondition(obj, cond))
        return conditions

    def detect_conditions(self, obj, min_level=1, exposed=None):
        """Executes the detector on contextualConditions"""
        for condition in self.conditions(obj, min_level, exposed):
            condition.detect()
            yield condition

    def get_rectifier(self, condition, obj):
        """Gets a condition rectifier for an obj"""
        try:
            return self.find_condition(condition, obj.__class__).get_rectifier(obj)
        except Exception:
            return None

    def get_contextual_condition(self, condition, obj):
        """Get the contextualCondition for this object"""
        try:
            return ContextualCondition(obj, self.find_condition(condition, obj.__class__))
        except Exception:
            return None

    def detect_condition(self, condition, obj):
        _condition = self.get_contextual_condition(condition, obj)
        if _condition:
            _condition.detect()
        return _condition

    def clear_registry(self):
        log.critical("Clearing condition registry")
        self._conditions.reset()
        self.plugin_dirs = []

class ProctorObjectMeta(type):
    """Handles the registration and checking ProctorObjects"""

    def __init__(cls, name, bases, attrs):
        """
        Called when a derived class is imported.
        Classifies the ProctorObject as a detector, rectifier or condition.
        """
        rectifier = False
        detector = False

        _cls = {}
        ilog.debug("Building class {} {} {} {}".format(cls, name, bases, attrs))

        # Check methods for a rectifier and a detector,
        # as determined (see: decorators)
        for _name, method in cls.__dict__.iteritems():
            ilog.debug("Checking {} {}".format(_name, method))

            # Has a decorated rectifier?
            if hasattr(method, "is_rectifier"):
                _cls["_is_rectifier"] = True
                _cls["_rectify"] = method
                rectifier = True

            # Has a decorated detector?
            if hasattr(method, "is_detector"):
                _cls["_is_detector"] = True
                _cls["_detector"] = method
                detector = True

            # Has a decorated filter method?
            # If a method is specified as a filter,
            # it takes prescendence over 'applies_to'
            # and 'excludes' properties.
            if hasattr(method, "is_filter"):
                ilog.debug("{} has prefilter".format(name))
                _cls['_has_filter'] = True
                _cls['_filter'] = method
                # Make it the hightest priority
                _cls['_filter_priority'] = sys.maxint

        # Inject the things we set above into the class
        for k, v in _cls.items():
            setattr(cls, k, v)

        # If there is no filter in this class - make one that will
        # understand about 'applies_to' and 'exclude' class properties of
        # - NOTE: This purposley breaks inheritence of the _filter property.
        if not hasattr(cls.__dict__, "_filter") and "_filter" not in _cls:

            # Declare the filter method that will honor 'applied_to' and 'excludes'.
            def _filter(self, obj):
                ilog.debug("Checking {}.filter()".format(cls.__name__))

                for k, v in cls.applies_to.items():
                    # try to get the value for the key
                    try:
                        value = get_property(obj, k)
                    except Exception:
                        ilog.exception(u"Cannot get value for {}".format(k))
                        return False
                    ilog.debug("Value of {} {}".format(k, value))
                    if value not in v:
                        ilog.debug("{} {} not in {}".format(k, value, v))
                        return False

                for k, v in cls.excludes.items():
                    # try to get the value for the key
                    try:
                        value = get_property(obj, k)
                    except Exception:
                        ilog.exception(u"Cannot get value for {}".format(k))
                        return True
                    ilog.debug("Value of {} {}".format(k, value))
                    if value in v:
                        ilog.debug("{} excluded {}".format(k, v))
                        return False
                return True

            """
            ProctorObject Priority:

            It is possible that there exists more than one Detector/Rectifier
            for a Condition-Context. Each Detector/Rectifier (ProctorObject) is
            bound to a filter and the filter has a priority, therefore the ProctorObject
            has that priority.

            When trying to find the Detector function for a given Condition-Context pair, the
            Proctor will check the Context against each filter in priority order.  The first
            filter that passes, identifies the Detector/Rectifier to use.

            Priority calculation:
            Priority is based on 'applies_to' and 'excludes' dictionaries.  Remember those dictionaries
            are of the form { 'prop1.prop2.prop3' : [val1, val2,..] }.

            The formula is sum of each item's weight, where the weight is:
               30 X len(properties in key) + len(values)

            Longer hierarchies are viewed as more specific, therefore weighted higher, and ties are
            broken by the length of the values that apply to each key.

            """
            # Compute the priority of the filter based on
            priority = 0

            try:
                priority += sum(
                    map(lambda x: 30 ** (len(x.split('.'))) + len(cls.applies_to[x]), cls.applies_to.keys()))
                priority += sum(
                    map(lambda x: 30 ** (len(x.split('.'))) + len(cls.excludes[x]), cls.excludes.keys()))

                ilog.debug("{} priority {}".format(cls.__name__, priority))

                cls._filter_priority = priority
                cls._filter = _filter
            except Exception:
                warnings.warn("{} NOT REGISTERED: Cannot determine filter priority".format(name), NotRegistered)
                return

        # Not really used, the thought was if a rectifier and detector are in the
        # same class, they should be presented together
        if rectifier and detector:
            cls._bonded = True

        if rectifier or detector:
            cls.pid = hashlib.sha1(cls.__name__).hexdigest()[:10].upper()
            Proctor().register(cls)
        else:
            log.warn("{} NOT REGISTERED: no detector or rectifier function".format(name))

class ProctorObject(object):
    """Base Proctor Object"""

    __metaclass__ = ProctorObjectMeta
    context = None
    applies_to = {}
    excludes = {}

    @classmethod
    def context_name(cls):
        return cls.context if isinstance(cls.context, basestring) else cls.context.__name__

    @classmethod
    def condition_name(cls):
        if cls.condition:
            return cls.condition if isinstance(cls.condition, basestring) else cls.condition.name

class ConditionMeta(type):
    """Handles the registration and checking of a condition"""

    def __init__(cls, name, bases, attrs):
        """
        Called when a derived class is imported.
        Verifies that a condition has a name and a context
        """
        log.debug("Registering Condition {}".format(name))
        if hasattr(cls, 'name') and hasattr(cls, 'context'):
            cls.pid = hashlib.sha1(cls.name).hexdigest()[:10].upper()
            Proctor().register(cls)
        else:
            log.warn("Cannot register {}".format(cls.__name__))

class ContextualCondition(Mapping):
    """
    Represents a condition checker that contains a context.
    Will contain the detector and the rectifier for the object
    being checked.  Pretty much a RegisteredCondition Proxy
    """

    def __init__(self, context, registered_condition):
        super(ContextualCondition, self).__init__()
        self.__reg_condition = registered_condition
        self.level = registered_condition.condition.level
        self.exposed = registered_condition.condition.exposed
        self.context = context
        self.name = self.__reg_condition.name
        self.rectifier = self.__reg_condition.get_rectifier(context)
        self.detector = self.__reg_condition.get_detector(context)
        self.detected = None
        self.rectified = None
        self.pid = self.__reg_condition.condition.pid
        self.detector_tried = False
        self.rectifier_tried = False
        self.last_message = ""

    @property
    def detectable(self):
        return self.detector is not None

    @property
    def rectifiable(self):
        if self.detected:
            return self.detected.rectifiable
        else:
            return self.rectifier is not None

    def context_name(self):
        return self.context if isinstance(self.context, basestring) else self.context.__class__.__name__

    def rectify(self):
        """Rectify the detected condition"""
        if self.rectifiable and self.detected:
            self.rectifier_tried = True
            self.rectified = self.detected.rectify()
            return self.rectified

    def detect(self):
        """Where the magic happens"""
        if self.detectable:
            self.detector_tried = True
            try:
                self.detector()._detector(self.context)
                self.detected = False
            except Condition as c:
                # Condition raised means we 100% found the issue
                self.detected = c
            except Exception as e:
                # Any other exception means inconclusive
                log.exception("unexpected exception in detector")
                self.detected = None
                self.last_message = e.message

        return self.detected

    def dict(self):
        """Serialize the condition"""
        data = Mapping()
        data['type'] = self.__reg_condition.condition.__name__
        data.check_key = self.__reg_condition.condition.name
        data.level = self.level
        data.pid = self.pid
        if self.detectable:
            data.detector = self.detector.__name__

        data.symptom = self.__reg_condition.condition.symptom
        data.solution = self.__reg_condition.condition.solution
        data.rectifier_tried = self.rectifier_tried
        data.detector_tried = self.detector_tried
        data.error_code = 1
        data.msg = self.last_message
        data.rectifiable = False
        if self.rectifier:
            data.rectifiable = True
            try:
                data.rectifier = self.rectifier.__name__
            except Exception:
                pass
        data.detectable = self.detectable
        data.rectified = self.rectified

        if self.detected:
            data.update(self.detected.dict())

        data.detected = True if self.detected else self.detected
        data.error_code_string = self.context_name()

        return data

class Condition(Exception):
    """
    Represents a condition.
    When raised, the ConditionObject will contain the
    Proctor functions - rectifier and detector to work on the
    condition.

    Here is what's cool, the condition (an exception really), when
    caught in the code, can be checked to see if it has a rectifier
    and it can attempt to fix the condition before really failing.
    """

    __metaclass__ = ConditionMeta
    context = None
    detector = None
    rectifier = None
    symptom = ""
    solution = ""
    exposed = False
    level = 1

    # HACK because I cannot figure out code structure to check the type
    _is_condition = True

    def __init__(self, message, context_instance=None, detector=None, inner_condition=None, **kwargs):
        """Called when condition is raised - Will attempt to find a rectifier"""
        self.context_id = None
        self.context_instance = None
        self.detector = detector
        self.data = copy.deepcopy(kwargs)

        super(Condition, self).__init__(message, **kwargs)
        self.set_context(context_instance)

    def rectify(self):
        """Rectify the condition - do the damn thang"""
        if self.rectifiable:
            return self.rectifier()._rectify(self.context_instance, condition=self)
        return False

    def set_context(self, new_context):
        """
        Set the context - will trigger getting the recitifer.
        Necessary because a detector COULD throw a different condition (maybe).
        So reload the rectifier.
        """
        self.context_instance = new_context
        if isinstance(self.context_instance, object) and hasattr(self.context_instance, "id"):
            self.context_id = self.context_instance.id
        elif isinstance(self.context_instance, basestring):
            self.context_id = ""
        self._get_rectifier()

    def _get_rectifier(self):
        try:
            self.rectifier = Proctor().get_rectifier(self, self.context_instance)
        except Exception:
            self.rectifier = None

    def dict(self):
        """Cast to serializable dict"""
        data = Mapping()
        data.check_key = self.name
        data.error_code = 1
        data.error_code_string = self.__class__.context_name()
        data.msg = self.message
        data.ctxt_class = self.context_instance.__class__.__name__
        data.ctxt_id = self.context_id

        data.symptom = self.symptom
        data.solution = self.solution
        data.rectifiable = self.rectifiable
        data.level = self.level
        data.exposed = self.exposed
        data.pid = self.pid
        if self.rectifiable:
            data.rectifiable = True
            data.rectifier = self.rectifier.__name__
        else:
            data.rectifiable = False
            data.rectifier = None
        return data

    def serialize(self):
        return {'data': str(self.context_instance)}

    @property
    def rectifiable(self):
        return not (self.rectifier is None)

    @classmethod
    def context_name(cls):
        return cls.context if isinstance(cls.context, basestring) else cls.context.__name__

    @classmethod
    def class_info(cls):
        data = Mapping(cls.__dict__)
        data.context = cls.context_name()
        data.exposed = cls.exposed
        data.level = cls.level
        return data

    def __repr__(self):
        try:
            return "{}:{}".format(self.name, self.message)
        except AttributeError:
            return super(Condition, self).__repr__()

    def __str__(self):
        try:
            return "{}:{}".format(self.name, self.message)
        except AttributeError:
            return super(Condition, self).__str__()

    def __unicode__(self):
        try:
            return "{}:{}".format(self.name, self.message)
        except AttributeError:
            return super(Condition, self).__unicode__()


import numpy as np
import cProfile
import time
#Class that stores the cube and its associated exceptions
class Cube:
  def __init__(self,size):
    self.size = size
    self.magic_cube = np.zeros((3,3,3))
    self.cube = np.copy(self.magic_cube)
    self.points = []
    self.corner_points =[]
    self.face_center = []
    self.rev_map = {}
    self._make_cube(size)
    self.neg_exception = set() # Points that are collinear but sum is not 42
    self.pos_exception = set() # Points that are not collinear but sum is 42
    self.populate_exception(size)
    print("Cube Generated. The 11 Surfaces are: ")
    self.print_11_surfaces(self.size)

  # Function that fills the entries of the magic cube.
  def _fill_entry(self,i,j,k,size):
    i += 1
    j += 1
    k += 1
    if (size%2 == 1):
      a = (i - j + k - 1 + (3*size) )%size
      b = (i - j - k + (3*size) )%size
      c = (i + j + k - 2 + (3*size) )%size
      return ( a*size*size + b*size + c + 1)
    if (size%4 == 0):
      i_ = i>size/2
      j_ = j>size/2
      k_ = k>size/2
      F = (i+j+k+i_+j_+k_)
      if (F==1):
        return ((i-1)*size*size + (j-1)*size + k)
      else:
        return ((i_-1)*size*size + (j_-1)*size + k_)
    if (size%4 == 2):
      raise Exception('Not yet implement for size of form 4k+2.')

  # Wrapper function that initalizes the cube and fills its elements
  def _make_cube(self,size):
    for i in range(size):
      for j in range(size):
        for k in range(size):
          entry = self._fill_entry(i,j,k,size)
          point = tuple([i,j,k])
          self.magic_cube[i][j][k] = entry
          self.points.append(point)
          if( (i==0 or i==2) and (j==0 or j==2) and (k==0 or k==2)):
            self.corner_points.append(point)
          elif ( (j==1 and k==1) or (i==1 and j==1) or (k==1 and j==1)):
            self.face_center.append(point)
          self.rev_map[entry] = point
  # Checks if three points p1,p2 and p3 are collinear
  def _is_collinear(self,p1,p2,p3):
    if(p1==p2 or p1==p3 or p2==p3): return False
    p1 = np.array(p1)
    p2 = np.array(p2)
    p3 = np.array(p3)
    return (np.array_equal(2*p1,p2+p3) or np.array_equal(2*p2,(p1+p3)) or np.array_equal(2*p3,(p1+p2)) )
  # Stores the positive and negative exceptions in the sets
  def populate_exception(self,size):
    assert (size == 3), "Only works if cube is 3x3x3"
    magic_sum = size*(size**3+1)/2
    self.magic_sum = magic_sum
    for p1 in self.points:
      for p2 in self.points:
        for p3 in self.points:
          if (not (p1==p2 or p2==p3 or p3==p1)):
            sum = self.magic_cube[tuple(p1)] + self.magic_cube[tuple(p2)] + self.magic_cube[tuple(p3)]
            if not self._is_collinear(p1,p2,p3):
              if sum == magic_sum:
                self.neg_exception.add(frozenset([p1,p2,p3]))
            else:
              if sum != magic_sum:
                self.pos_exception.add(frozenset([p1,p2,p3]))

  def print_cube_plane(self,index,val):
    for j in range(3):
        for k in range(3):
          print(int(self.cube[val][j][k]),end=' ')
        print("")

  def print_plane(self,index,val):
    if(index==1):
      for j in range(3):
        for k in range(3):
          print(int(self.magic_cube[val][j][k]),end=' ')
        print("")
    elif(index==2):
      for i in range(3):
        for k in range(3):
          print(int(self.magic_cube[i][val][k]),end=' ')
        print("")
    else:
      for i in range(3):
        for j in range(3):
          print(int(self.magic_cube[i][j][val]),end=' ')
        print("")

  def print_11_surfaces(self,size):
    assert (size==3), "Only works fif cube is 3x3x3"
    print ('Top Surface')
    self.print_plane(1,0)
    print ('Middle X-Y Surface')
    self.print_plane(1,1)
    print ('Bottom Surface')
    self.print_plane(1,2)
    print ('Left Surface')
    self.print_plane(3,0)
    print ('Middle Y-Z Surface')
    self.print_plane(3,1)
    print ('Right Surface')
    self.print_plane(3,2)
    print ('Back Surface')
    self.print_plane(2,0)
    print ('Middle X-Z Surface')
    self.print_plane(2,1)
    print ('Front Surface')
    self.print_plane(2,2)
    print ('Diagonal 1 Surface')
    for i in range(3):
      for j in range(3):
        print(int(self.magic_cube[i][j][j]),end=' ')
      print("")
    print ('Diagonal 2 Surface')
    for i in range(3):
      for j in range(3):
        print(int(self.magic_cube[i][j][2-j]),end=' ')
      print("")

class Game:
  # there are two players:
  # player 1
  # player 2
  def __init__(self,size):
    self.cube = Cube(size)
    self.size = size
    self.cur_player = 1
    self.is_finished = False
    self.moves = [[],[]]
    self.total_moves = 0
    self.winner = None # 0-> Draw , 1-> player 1, 2-> player 2
    self.points = [0,0]
  # Make a move p (which is a coordinate tuple) and return true if move is valid and game is not finished
  # else return false
  def is_valid_move(self,p):
    return ((not self.is_end()) and self.cube.cube[p] == 0 and not self.is_finished)
  # Function that marks a move at the point p on the cube
  def move(self,p):
    if self.is_valid_move(p):
      points_fetched = self.get_reward_points(p,self.cur_player)
      self.points[self.cur_player-1] += points_fetched
      self.cube.cube[p]=self.cur_player
      self.moves[self.cur_player-1].append(p)
      self.cur_player = self.cur_player%2 + 1
      self.total_moves += 1
  # Function that checks whether the end of game is reached i.e. total number of moves is >=20
  def is_end(self):
    if self.is_finished:
      return True
    if self.total_moves >= 20:
      self.is_finished = True
      if self.points[0] > self.points[1]:
        self.winner = 1
      elif self.points[1] > self.points[0]:
        self.winner = 2
      else:
        self.winner = 0
      return True
    return False

  # Checks if the points p1 ,p2 ,p3 make a line that fetches points
  def _correct_line(self,p1,p2,p3):
    cube = self.cube
    if cube._is_collinear(p1,p2,p3):
      if (cube.magic_cube[p1]+cube.magic_cube[p2]+cube.magic_cube[p3] == cube.magic_sum):
        if (frozenset([p1,p2,p3]) not in cube.neg_exception):
          return True
      elif(frozenset([p1,p2,p3]) in cube.pos_exception):
        return True
    return False

  # check if the given move, results in a win for player. return true if it is a winning move
  def get_reward_points(self,p,player):
    points = 0
    if self.is_valid_move(p):
      prev_moves = self.moves[player-1]
      for move_1 in prev_moves:
        for move_2 in prev_moves:
          if(move_1 != move_2):
            if self._correct_line(move_1,move_2,p):
              points += 1
    return (points/2)

  # finds the third point in the cube give two points p1 and p2
  def _find_collinear_point(self,p1,p2):
    p1_ = np.array(p1)
    p2_ = np.array(p2)
    possible = [np.asarray((p1_+p2_)/2,dtype=np.int32),(2*p1_) - p2_,(2*p2_) - p1_]
    for p in possible:
      if (self.cube._is_collinear(p1,p2,tuple(p)) and np.all(p < 3) and np.all(p>=0)):
        return tuple(p)
    return None

  # return rewarding move for a player p if it exists, else return None
  def find_rewarding_move(self,player):
    assert player in [1,2], "Player should be either 1 or 2"
    prev_moves = self.moves[player-1]
    for move_1 in prev_moves:
      for move_2 in prev_moves:
        if(move_1 != move_2):
          move = self._find_collinear_point(move_1,move_2)
          if(move!=None and self.cube.cube[move] == 0 and self._correct_line(move_1,move_2,move)):
            return move
    return None
  #returns the best available move that has not been played and is valid
  def any_available_move(self):
    for p in self.cube.corner_points:
      if(self.is_valid_move(p)):
        return p
    for p in self.cube.face_center:
      if(self.is_valid_move(p)):
        return p
    for p in self.cube.points:
      if(self.is_valid_move(p)):
        return p
    return None
  # function that prints the game board each time
  def print_game(self):
    print ('\nTop Surface')
    self.cube.print_cube_plane(1,0)
    print ('Middle Surface')
    self.cube.print_cube_plane(1,1)
    print ('Bottom Surface')
    self.cube.print_cube_plane(1,2)

  def __str__(self):
    return self.cube.cube.__str__()

game = Game(3)

firstPlayer = int(input("\n\nWho Plays First? Computer (1) or Human (2)  "))
aiPlayer = firstPlayer
firstPlayer = aiPlayer%2 + 1

while(not game.is_end()):
  if(game.cur_player == (aiPlayer)):
    if(game.is_valid_move((1,1,1))):
      game.move((1,1,1))
    else:
      p = game.find_rewarding_move(game.cur_player)
      if(p != None):
        game.move(p)
      else:
        p1 = game.find_rewarding_move( (game.cur_player%2 + 1))
        if(p1 != None):
          game.move(p1)
        else:
          p2 = game.any_available_move()
          game.move(p2)
  else:
    game.print_game()
    print("\nPoints: \nHuman - %d\nAI - %d" %(game.points[firstPlayer-1],game.points[aiPlayer-1]))
    user_input = input("Please enter the indices of your move (from 0): ")
    i, j, k = user_input.split(" ")
    i = int(i)
    j = int(j)
    k = int(k)
    if(game.is_valid_move((i,j,k))):
      game.move((i,j,k))
    else:
      print("Invalid Move, Please Retry")
game.print_game()
print("Points: \nHuman - %d\nAI - %d\n" %(game.points[firstPlayer-1],game.points[aiPlayer-1]))
if(game.winner == aiPlayer):
  print('Computer Wins')
elif (game.winner == 0):
  print('Its a draw')
else:
  print('Human Wins')


#Created by :- AJI
#Created Date :- 24-08-2020

# Standard Library
import requests
import sqlite3
import datetime
import pytz
import json

#User Defined Library
from .configurations import Emergency_Exit_url,TIME_ZONE
from .Log.log import get_logger
from .Messages import error_log , info_log
from .DB_Access import InsertDetail,database_search,RemoveDetails
from .Constant import Const_trueflag,Const_falseflag,Const_check_flag,Emergency_exit_API_Response
from Firmware.WiFi_Network import DeviceName
from .Bluetooth import baseurl_read

app_logger = get_logger("Emergency Exit")

"""

This function inform the server that the Emergency Exit button is pressed

"""
def Emergency_exit(current_time):
	DEVICE_ID=DeviceName()
	data = {"DeviceCode":DEVICE_ID,"AccessTime":current_time}
	url = baseurl_read(Emergency_Exit_url)
	results = requests.post(url, data = data)
	response_message = results.text
	app_logger.info(response_message)
	Response = json.loads(response_message)
	if(Response["Message"] == Emergency_exit_API_Response):
		app_logger.info(info_log["e26"])
	else:
		Emergency_Exit_update_query = """INSERT INTO EmergencyExit(EmergencyExitTime,SynchronizedStatus) VALUES (?,?)"""
		Emergency_Exit_data = (current_time,0)
		print(Emergency_Exit_data)
		InsertDetail(Emergency_Exit_update_query,Emergency_Exit_data)
		app_logger.info(info_log["e27"])

"""

This function Synchronize the Emergency Exit table with the server Database

"""
def Synchronize_Emergency_exit_data():
	Emergency_exit_sync = """ SELECT EmergencyExitId,EmergencyExitTime FROM EmergencyExit Where SynchronizedStatus = 0 """
	Search_Response = database_search(Emergency_exit_sync)
	Synchronization_list = [Sync_item for item in Search_Response for Sync_item in item]
	Sync_flag = Const_falseflag
	for Synchronization_data in Synchronization_list:
		if((Sync_flag % Const_check_flag) != Const_falseflag):

			Emergency_exit(Synchronization_data)
			Sync_flag = Sync_flag + Const_trueflag
		else:
			data = (Synchronization_data, )
			Remove_data = """DELETE FROM EmergencyExit WHERE EmergencyExitId = ?"""
			RemoveDetails(Remove_data ,data)
			Sync_flag = Sync_flag + Const_trueflag


class Track:
    def __init__(self, start_x, start_y):
        self.track = {}
        self.start_x = start_x
        self.start_y = start_y

    def add_point(self, x, y, speed):
        self.track[(x, y)] = speed

    def __getitem__(self, index):
        self.__validating_index(index)
        coords = tuple(self.track.keys())[index]
        speed = self.track[coords]
        return coords, speed

    def __setitem__(self, index, speed):
        self.__validating_index(index)
        coords = tuple(self.track.keys())[index]
        self.track[coords] = speed

    def __validating_index(self, index):
        if not isinstance(index, int) or not index in range(len(list(self.track.keys()))):
            raise IndexError('некорректный индекс')

tr = Track(10, -5.4)
tr.add_point(20, 0, 100) # первый линейный сегмент: indx = 0
tr.add_point(50, -20, 80) # второй линейный сегмент: indx = 1
tr.add_point(63.45, 1.24, 60.34) # третий линейный сегмент: indx = 2

tr[2] = 60
c, s = tr[2]
print(c, s)

# res = tr[3]


# -*- coding: utf-8 -*-
import jieba
import codecs
from gensim import corpora
from gensim.summarization import bm25
import os
import re
import json
import multiprocessing as mp
import time
from functools import partial

"""
需要以下几个东西：

1. Query list and Query list index to QueryID and vice versa
2. Document list and Document list index to DocumentID and vice versa
3. 完成 bm25 之后，
4.
"""

def getQList_Qmap(input_json):
    """
    :param input_json:
    :return: query list, Listindex2ID and ID2Listindex
    """
    query_list = []
    ql_ind2id = {}
    id2ql_ind = {}

    instances = input_json['questions']
    for ind, instance in enumerate(instances):
        context = instance['context']
        ID = instance['ID']
        query_list.append(context)
        ql_ind2id[ind] = ID
        id2ql_ind[ID] = ind

    return query_list, ql_ind2id, id2ql_ind

def getDlist_Dmap(input_json):
    """
    :param input_json:
    :return: doc list, Listindex2ID and ID2Listindex
    """
    doc_list = []
    dl_ind2id = {}
    id2dl_ind = {}

    instances = input_json['document']
    for ind, instance in enumerate(instances):
        context = instance['context']
        ID = instance['ID']
        doc_list.append(context)
        dl_ind2id[ind] = ID
        id2dl_ind[ID] = ind

    return doc_list, dl_ind2id, id2dl_ind

def split_str(input_str, stop_word_l):
    split_words = jieba.cut(input_str, HMM=True)
    res = list(filter(lambda x: x not in stop_word_l, split_words))
    return res

def tokenization(input_l, stop_word_l):
    res = [split_str(input_str, stop_word_l) for input_str in input_l]
    return res

def get_bm_score(q, bm_model):
    return bm_model.get_scores(q)

def get_score_list(bm_model, query_list, multi_proc):
    if multi_proc:
        partial_work = partial(get_bm_score, bm_model=bm_model)
        pool = mp.Pool()
        scores = pool.map(partial_work, query_list)
    else:
        scores = []
        for query in query_list:
            scores.append(get_bm_score(query, bm_model))
    return scores

def evaluate_res(evaluation_map):
    total_n = len(evaluation_map)
    evaluation_iters = evaluation_map.items()
    print(total_n)
    print(evaluation_iters)
    corrects = sum(any(ele in k for ele in v) for k, v in evaluation_iters)
    acc = corrects/total_n
    return acc

# if __name__ == '__main__':
#     # get stop words from pretrained file
#     stop_word_file = 'stop_words.txt'
#     stop_word_l = []
#     with codecs.open(stop_word_file, 'r', 'utf-8') as f:
#         for line in f:
#             stop_word_l.append(line.rstrip('\n'))
#
#     input_file = os.path.join(os.getcwd(), 'tf_idf_cluster.json')
#     with codecs.open(input_file, 'r', 'utf-8') as file:
#         input_json = json.load(file)
#
#     # get Q_list, D_list and their corresponding mappings
#     Q_list, Qindex2ID, ID2Qindex = getQList_Qmap(input_json)
#     D_list, Dindex2ID, ID2Dindex = getDlist_Dmap(input_json)
#
#     # Tokenization the lists
#     Q_list = tokenization(Q_list, stop_word_l)
#     D_list = tokenization(D_list, stop_word_l)
#     # print(D_list[:5])
#     # print(Q_list[:5])
#
#     # get document dictionary
#     dictionary = corpora.Dictionary(D_list)
#     # print(len(dictionary))
#
#     # bm25 calculation
#     bm25Model = bm25.BM25(D_list)
#     sample_questions = Q_list[:]
#
#     # multiprocessing
#     start_time = time.time()
#     scores = get_score_list(bm25Model, sample_questions, multi_proc=True)
#     end_time = time.time()
#     time_used = (end_time - start_time)
#
#     # evaluation result
#     # evaluation_map should be like {'TRAIN_186_QUERY_0': ['TRAIN_186', 'TRAIN_1278', 'TRAIN_892']}
#     evaluation_map = {}
#     for ind, score in enumerate(scores):
#         query_ID = Qindex2ID[ind]
#         doc_scores = [(i, val) for i, val in enumerate(score)]
#         doc_scores.sort(key=lambda x: x[1], reverse=True)
#         doc_best_ids = [ele[0] for ele in doc_scores][:3]
#         evaluation_map[query_ID] = [Dindex2ID[ele] for ele in doc_best_ids]
#
#     suning_q_IDs = ['DEV_s001_QUERY_0','DEV_s001_QUERY_1','DEV_s001_QUERY_2','DEV_s001_QUERY_3', 'DEV_s001_QUERY_4',
#                     'DEV_s002_QUERY_0','DEV_s002_QUERY_1','DEV_s002_QUERY_2','DEV_s002_QUERY_3',
#                     'DEV_s003_QUERY_0','DEV_s003_QUERY_1','DEV_s003_QUERY_2','DEV_s003_QUERY_3']
#     print({id: evaluation_map[id] for id in suning_q_IDs})
#
#     # Start evaluation how the choice evaluation
#     accuracy = evaluate_res(evaluation_map)
#     print(accuracy)


"""
Problem Description:
Cody was solving a programming puzzle in Dcoder, and as always he is unable to do it alone.
Puzzle statement is You are given three integers l,h,d and you have to find that how many integers between l and h (inclusive) are divisible by d.Lets help Cody.

Input:
Input contains 3 integers l,h and d respectively separated by a space.

Output:
Print the number of divisors as stated in the problem.

Constraints:
1≤l,h,d≤1000

Sample Input:
3 15 5

Sample Output:
3
"""

l, h, d = [int(x) for x in input().split()]
c = 0
for i in range(l, h + 1):
    if i % d == 0: c += 1
print(c)


from typing import List, Dict
import os.path
import sys

from  aimslib.access.cache import TripCache, CrewlistCache
from aimslib.common.types import Duty, NoTripDetails, CrewMember
import aimslib.access.brief_roster as Roster

CACHE_DIR = os.path.expanduser("~/.cache/")

def duties(post_func, months: int) -> List[Duty]:
    sparse_dutylist = []
    if months < 0: months += 1
    else: months -= 1
    for r in Roster.retrieve(post_func, months):
        sparse_dutylist.extend(Roster.duties(Roster.parse(r)))
    expanded_dutylist = []
    trip_cache = TripCache(CACHE_DIR + "aimslib.tripcache", post_func)
    last_id = None
    for duty in sorted(sparse_dutylist):
        if duty.trip_id == last_id: continue #avoid duplicates
        last_id = duty.trip_id
        if duty.start is None:
            try:
                expanded_dutylist.extend(trip_cache.trip(duty.trip_id))
            except NoTripDetails:
                print(f"Trip details not found for: {duty.trip_id}",
                      file=sys.stderr)
        else:
            expanded_dutylist.append(duty)
    trip_cache.store()
    return expanded_dutylist

def crew(post_func, dutylist: List[Duty]) -> Dict[str, List[CrewMember]]:
    crew_cache = CrewlistCache(CACHE_DIR + "aimslib.clcache", post_func)
    crewlist_map = {}
    for duty in dutylist:
        if duty.sectors:
            for sector in duty.sectors:
                if not sector.crewlist_id: continue
                crewlist = crew_cache.crewlist(sector.crewlist_id)
                crewlist_map[sector.crewlist_id] = crewlist
    crew_cache.store()
    return crewlist_map


import tkinter
from tkinter import *
from tkinter import filedialog,ttk
import csv
import math
import pandas as pd
import scipy.stats as stats
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)

# root = tkinter.Tk()
# selected_value = StringVar()

def open_file(root):
    # root = tkinter.Tk()
    file = filedialog.askopenfilename(parent=root,initialdir="D:/College/BTech/SEM 7/Data Mining/DataSet/",title="Select Dataset File", filetypes=[("CSV files", "*.csv*"), ("all files", "*.*")])
    print(file)
    return file

def display_file(file_name):
    with open(file_name,newline="") as file:
        reader = csv.reader(file)
        # print(reader)
        root1 = tkinter.Tk()

        # for scroll
        h = Scrollbar(root1,orient="horizontal")
        v= Scrollbar(root1,orient="vertical")

        # h.pack(side=BOTTOM,fill=X)
        # v.pack(side=RIGHT,fill=Y)

        row_no = 0
        for col in reader:
            col_no =0
            for row in col:
                label = tkinter.Label(root1,width=10,height=2,text=row,relief=tkinter.RIDGE)

                label.grid(row=row_no,column=col_no)
                col_no = col_no+1
            row_no = row_no+1

        # v.config(command=)
def measureOfCentralT(clickedAttribute,root2,clickedMCT,data):
    attribute = clickedAttribute.get()
    operation = clickedMCT.get()
    if operation == "Mean":
        sum = 0
        for i in range(len(data)):
            sum += data.loc[i, attribute]
        avg = sum/len(data)
        res = "Mean of given dataset is ("+attribute+") "+str(avg)
        Label(root2,text=res,width=80,height=3,fg='green').grid(column=1,row=8)
    elif operation == "Mode":
        freq = {}
        for i in range(len(data)):
            freq[data.loc[i, attribute]] = 0
        maxFreq = 0
        maxFreqElem = 0
        for i in range(len(data)):
            freq[data.loc[i, attribute]] = freq[data.loc[i, attribute]]+1
            if freq[data.loc[i, attribute]] > maxFreq:
                maxFreq = freq[data.loc[i, attribute]]
                maxFreqElem = data.loc[i, attribute]
        res = "Mode of given dataset is ("+attribute+") "+str(maxFreqElem)
        Label(root2,text=res,width=80,height=3,fg='green').grid(column=1,row=8)
    elif operation == "Median":
        n = len(data)
        i = int(n/2)
        j = int((n/2)-1)
        arr = []
        for i in range(len(data)):
            arr.append(data.loc[i, attribute])
        arr.sort()
        if n%2 == 1:
            res = "Median of given dataset is ("+attribute+") "+str(arr[i])
            Label(root2,text=res,width=80,height=3,fg='green').grid(column=1,row=8)
        else:
            res = "Median of given dataset is ("+attribute+") "+str((arr[i]+arr[j])/2)
            Label(root2,text=res,width=80,height=3,fg='green').grid(column=1,row=8)
    elif operation == "Midrange":
        n = len(data)
        arr = []
        for i in range(len(data)):
            arr.append(data.loc[i, attribute])
        arr.sort()
        res = "Midrange of given dataset is ("+attribute+") "+str((arr[n-1]+arr[0])/2)
        Label(root2,text=res,width=80,height=3,fg='green').grid(column=1,row=8)
    elif operation == "Variance" or operation == "Standard Deviation":
        sum = 0
        for i in range(len(data)):
            sum += data.loc[i, attribute]
        avg = sum/len(data)
        sum = 0
        for i in range(len(data)):
            sum += (data.loc[i, attribute]-avg)*(data.loc[i, attribute]-avg)
        var = sum/(len(data))
        if operation == "Variance":
            res = "Variance of given dataset is ("+attribute+") "+str(var)
            Label(root2,text=res,width=80,height=3,fg='green').grid(column=1,row=8)
        else:
            res = "Standard Deviation of given dataset is ("+attribute+") "+str(math.sqrt(var))
            Label(root2,text=res,width=80,height=3,fg='green').grid(column=1,row=8)

def computeOperation(clickedAttribute,clickedDispersion,data,root2):
    attribute = clickedAttribute.get()
    operation = clickedDispersion.get()
    if operation == "Range":
        arr = []
        for i in range(len(data)):
            arr.append(data.loc[i, attribute])
        arr.sort()
        res = "Range of given dataset is ("+attribute+") "+str(arr[len(data)-1]-arr[0])
        Label(root2,text=res,width=80,height=3,fg='green').grid(column=1,row=8)
    elif operation == "Quartiles" or operation == "Inetrquartile range":
        arr = []
        for i in range(len(data)):
            arr.append(data.loc[i, attribute])
        arr.sort()
        if operation == "Quartiles":
            res1 = "Lower quartile(Q1) is ("+attribute+") "+str((len(arr)+1)/4)
            res2 = "Middle quartile(Q2) is ("+attribute+") "+str((len(arr)+1)/2)
            res3 = "Upper quartile(Q3) is ("+attribute+") "+str(3*(len(arr)+1)/4)
            Label(root2,text=res1,width=80,height=3,fg='green').grid(column=1,row=8)
            Label(root2,text=res2,width=80,height=3,fg='green').grid(column=1,row=8)
            Label(root2,text=res3,width=80,height=3,fg='green').grid(column=1,row=9)
        else:
            res = "Interquartile range(Q3-Q1) of given dataset is ("+attribute+") "+str((3*(len(arr)+1)/4)-((len(arr)+1)/4))
            Label(root2,text=res,width=80,height=3,fg='green').grid(column=1,row=8)

    elif operation == "Minimum" or operation == "Maximum":
        arr = []
        for i in range(len(data)):
            arr.append(data.loc[i, attribute])
        arr.sort()
        if operation == "Minimum":
            res = "Minimum value of given dataset is ("+attribute+") "+str(arr[0])
            Label(root2,text=res,width=80,height=3,fg='green').grid(column=1,row=8)
        else:
            res = "Maximum value of given dataset is ("+attribute+") "+str(arr[len(data)-1])
            Label(root2,text=res,width=80,height=3,fg='green').grid(column=1,row=8)

def plt_chart(clickedAttribute1,clickedPlot,clickedAttribute2,data,clickedClass,root2):
    attribute1 = clickedAttribute1.get()
    attribute2 = clickedAttribute2.get()
    fig, ax = plt.subplots(figsize=(4, 4))
    operation = clickedPlot
    if operation == "Quantile-Quantile Plot":
        # fig, ax = plt.subplots(figsize=(4, 4))
        arr = []
        sum = 0
        for i in range(len(data)):
            arr.append(data.loc[i, attribute1])
            sum += data.loc[i, attribute1]
        avg = sum/len(arr)
        sum = 0
        for i in range(len(data)):
            sum += (data.loc[i, attribute1]-avg)*(data.loc[i, attribute1]-avg)
        var = sum/(len(data))
        sd = math.sqrt(var)
        z = (arr-avg)/sd

        stats.probplot(z, dist="norm", plot=plt)
        plt.title("Normal Q-Q plot")
        plt2 = FigureCanvasTkAgg(fig, root2)
        plt2.draw()
        # toolbar = NavigationToolbar2Tk(plt2,root2)
        # toolbar.update()
        plt2.get_tk_widget().place(x=20,y=90)
        # plt.show()

    elif operation == "Histogram":
        # fig, ax = plt.subplots(figsize=(4, 4))
        sns.set_style("whitegrid")
        sns.FacetGrid(data, hue=clickedClass.get(), height=5).map(sns.histplot, attribute1).add_legend()
        plt.title("Histogram")
        plt2 = FigureCanvasTkAgg(fig, root2)
        plt2.draw()
        # toolbar = NavigationToolbar2Tk(plt2,root2)
        # toolbar.update()
        plt2.get_tk_widget().place(x=20,y=90)

        # plt.show(block=True)
    elif operation == "Scatter Plot":
        # fig, ax = plt.subplots(figsize=(4, 4))
        sns.set_style("whitegrid")
        sns.FacetGrid(data, hue=clickedClass.get(), height=4).map(plt.scatter, attribute1, attribute2).add_legend()
        plt.title("Scatter plot")
        plt2 = FigureCanvasTkAgg(fig, root2)
        plt2.draw()
        # toolbar = NavigationToolbar2Tk(plt2,root2)
        # toolbar.update()
        plt2.get_tk_widget().place(x=20,y=90)
        # plt.show(block=True)
    elif operation == "Boxplot":
        # fig, ax = plt.subplots(figsize=(4, 4))
        sns.set_style("whitegrid")
        sns.boxplot(x=attribute1,y=attribute2,data=data)
        plt.title("Boxplot")
        # plt.show(block=True)
        plt2 = FigureCanvasTkAgg(fig, root2)
        plt2.draw()
        # toolbar = NavigationToolbar2Tk(plt2,root2)
        # toolbar.update()
        plt2.get_tk_widget().place(x=20,y=90)

def selectAttributes(root2,clickedPlot,clickedAttribute1,cols,clickedClass,clickedAttribute2):
    operation = clickedPlot
    if operation == "Quantile-Quantile Plot":
        dropCols = OptionMenu(root2, clickedAttribute1, *cols)
        dropCols.grid(column=3,row=8,padx=20,pady=30)
        Button(root2,text="Compute",command= lambda:computeOperation()).grid(column=4,row=6)

    elif operation == "Histogram":
        dropCols = OptionMenu(root2, clickedAttribute1, *cols)
        dropCols.grid(column=3,row=8,padx=20,pady=30)
        dropCols = OptionMenu(root2, clickedClass, *cols)
        dropCols.grid(column=5,row=8,padx=20,pady=30)
        Button(root2,text="Compute",command= lambda:computeOperation()).grid(column=4,row=6)

    elif operation == "Scatter Plot":
        dropCols = OptionMenu(root2, clickedAttribute1, *cols)
        dropCols.grid(column=2,row=8,padx=20,pady=30)
        dropCols = OptionMenu(root2, clickedAttribute2, *cols)
        dropCols.grid(column=3,row=8,padx=20,pady=30)
        dropCols = OptionMenu(root2, clickedClass, *cols)
        dropCols.grid(column=5,row=8)
        Button(root2,text="Compute",command= lambda:computeOperation()).grid(column=4,row=6)

    elif operation == "Boxplot":
        dropCols = OptionMenu(root2, clickedAttribute1, *cols)
        dropCols.grid(column=2,row=8,padx=20,pady=30)
        dropCols = OptionMenu(root2, clickedAttribute2, *cols)
        dropCols.grid(column=3,row=8,padx=20,pady=30)
        Button(root2,text="Compute",command= lambda:computeOperation()).grid(column=4,row=6)

def title_changed(topic_name,root2,file_name):
    # topic_name = event.widget.get()
    print(topic_name)
    newfilename = ''
    for i in file_name:
        if i == "/":
            newfilename = newfilename + "/"
            newfilename = newfilename + i
    data = pd.read_csv(file_name)
    d = pd.read_csv(file_name)
    cols = []
    for i in data.columns:
        cols.append(i)
    if(topic_name == "Data Display"):
        display_file(file_name)
    elif(topic_name == "measures of central tendency"):
        cols = []
        for i in data.columns:
            cols.append(i)
        clickedAttribute = StringVar(root2)
        clickedAttribute.set("Select Attribute")
        dropCols = OptionMenu(root2, clickedAttribute, *cols)
        dropCols.place(x=20,y=100)

        measureOfCentralTendancies = ["Mean","Mode","Median","Midrange","Variance","Standard Deviation"]
        clickedMCT = StringVar(root2)
        clickedMCT.set("Select central tendency")
        dropMCT = OptionMenu(root2, clickedMCT, *measureOfCentralTendancies)
        dropMCT.place(x=160,y=100)
        Button(root2,text="Measure",command= lambda:measureOfCentralT(clickedAttribute,root2,clickedMCT,data)).grid(column=1,row=7,padx=160,pady=170)
    elif(topic_name=="dispersion of data"):
        cols = []
        for i in data.columns:
            cols.append(i)
        clickedAttribute = StringVar(root2)
        clickedAttribute.set("Select Attribute")
        dropCols = OptionMenu(root2, clickedAttribute, *cols)
        dropCols.place(x=20,y=100)

        dispersionOfData = ["Range","Quartiles","Inetrquartile range","Minimum","Maximum"]
        clickedDispersion = StringVar(root2)
        clickedDispersion.set("Select Dispersion Operation")
        dropMCT = OptionMenu(root2, clickedDispersion, *dispersionOfData)
        dropMCT.place(x=160,y=100)
        Button(root2,text="Measure",command= lambda:computeOperation(clickedAttribute,clickedDispersion,data,root2)).grid(column=1,row=7,padx=160,pady=170)
    elif(topic_name=="statistical description"):

        clickedAttribute1 = StringVar(root2)
        clickedAttribute1.set("Select First Attribute")
        dropCols1 = OptionMenu(root2, clickedAttribute1, *cols,command=lambda x:update())
        dropCols1.place(x=20,y=20)

        clickedAttribute2 = StringVar(root2)
        clickedAttribute2.set("Select Second Attribute")
        dropCols2 = OptionMenu(root2, clickedAttribute2, *cols,command=lambda x:update())
        dropCols2.place(x=180,y=20)

        clickedClass = StringVar(root2)
        clickedClass.set("Select Class")
        dropCols3 = OptionMenu(root2, clickedClass, *cols,command=lambda x:update())
        dropCols3.place(x=350,y=20)
        def update():

            if(clickedAttribute1.get() != "Select First Attribute" and clickedAttribute2.get()!="Select Second Attribute" and clickedClass.get() != "Select Class"):
                v = IntVar()
                text_radio = ["Quantile Plot","Histogram","Scatter Plot","Boxplot"]
                # for i in range(len(text_radio)):
                Radiobutton(root2,text=text_radio[0],value=1,variable=v,command=lambda:plt_chart(clickedAttribute1,text_radio[0],clickedAttribute2,data,clickedClass,root2)).place(x=int(20+0*100),y=60)
                Radiobutton(root2,text=text_radio[1],value=2,variable=v,command=lambda:plt_chart(clickedAttribute1,text_radio[1],clickedAttribute2,data,clickedClass,root2)).place(x=int(20+1*100),y=60)
                Radiobutton(root2,text=text_radio[2],value=3,variable=v,command=lambda:plt_chart(clickedAttribute1,text_radio[2],clickedAttribute2,data,clickedClass,root2)).place(x=int(20+2*100),y=60)
                Radiobutton(root2,text=text_radio[3],value=4,variable=v,command=lambda:plt_chart(clickedAttribute1,text_radio[3],clickedAttribute2,data,clickedClass,root2)).place(x=int(20+3*100),y=60)
                print(clickedAttribute2.get(),clickedAttribute2.get(),clickedClass.get())

def title(file_name):
    # file_name = open_file()
    root2 = tkinter.Tk()
    root2.title('Data Analysis Tool')
    root2.geometry('500x300+10+10')
    data=["Data Display","measures of central tendency","dispersion of data","statistical description"]

    lbl = Label(root2,text="Select Topic : ",font=("Helvetica",12))
    lbl.place(x=20,y=10)

    cb = ttk.Combobox(root2,values=data)
    cb.place(x=280,y=10)
    cb['state'] = 'readonly'
    cb.bind('<<ComboboxSelected>>',lambda event: title_changed(event,root2,file_name))

# open_button = tkinter.Button(root,text="Upload File",command=title,fg='blue')
# open_button.place(x=230,y=110)

# button_exit = Button(root,text="Exit",command=exit,fg='red')
# button_exit.place(x=180,y=150)
# lbl = Label(root,text="Data Analysis Tool",fg='red',font=("Helvetica",18))
# lbl.place(x=80,y=100)
# lbl = Label(root,text="Upload Dataset To start : ",font=("Helvetica",12))
# lbl.place(x=40,y=110)
# # open_button.pack(fill='x')

# root.title('Data Analysis Tool')
# root.geometry('400x250+10+10')
# root.mainloop()


from ruffus import *
from rnarry.nrclip import Paths, Options, SequenceAnnotation
from rnarry.nrclip.PipelineControl import *

@files(for_each(Paths.fulltag_primary_annotation,
                Paths.fulltag_masked_readids,
                Paths.ALL_SAMPLES) +
       for_each(Paths.shorttag_primary_annotation,
                Paths.shorttag_masked_readids,
                Paths.SHORTTAG_SAMPLES))
@follows(SequenceAnnotation.annotate_sequences)
def make_list_of_masked_sequences(inputfile, outputfile, sample):
    runproc("$ZGREP '	[rt]RNA' $inputfile | $CUT -f4 | $UNIQ > $outputfile",
            outputfile)

@files(for_each([Paths.fulltag_genome_alignment_sam,
                 Paths.fulltag_masked_readids],
                Paths.fulltag_masked_genome_alignments,
                Paths.ALL_SAMPLES) +
       for_each([Paths.shorttag_genome_alignment_sam,
                 Paths.shorttag_masked_readids],
                Paths.shorttag_masked_genome_alignments,
                Paths.SHORTTAG_SAMPLES))
@follows(make_list_of_masked_sequences)
def produce_masked_sam(inputfile, outputfile, sample):
    alnfile, maskinglist = inputfile
    runproc("$SAM_ID_FILTER $alnfile $maskinglist | $GZIP -c - > $outputfile",
            outputfile)

@files(for_each([Paths.fulltag_filtered_reads, Paths.fulltag_masked_readids],
                Paths.fulltag_masked_reads,
                Paths.ALL_SAMPLES) +
       for_each([Paths.shorttag_filtered_reads, Paths.shorttag_masked_readids],
                Paths.shorttag_masked_reads,
                Paths.SHORTTAG_SAMPLES))
@follows(make_list_of_masked_sequences)
def produce_masked_fasta(inputfile, outputfile, sample):
    seqfile, maskinglist = inputfile
    runproc("$FASOMERECORDS -exclude $seqfile $maskinglist $outputfile",
            outputfile)

@files(for_each(Paths.fulltag_masked_genome_alignments,
                Paths.fulltag_genome_besthits,
                Paths.ALL_SAMPLES,
                [Options.FULLTAG_POSTPROC_ALLOWED_MISMATCHES]) +
       for_each(Paths.shorttag_masked_genome_alignments,
                Paths.shorttag_genome_besthits,
                Paths.SHORTTAG_SAMPLES,
                [Options.SHORTTAG_POSTPROC_ALLOWED_MISMATCHES]))
@follows(produce_masked_sam)
def resolve_genomic_multihits(inputfile, outputfile, sample, mismatches):
    runproc("""
        $ZCAT $inputfile | $SAM_MULTIHIT_RESOLVE $mismatches | \
        $GZIP -c - > $outputfile""", outputfile)

def tasks():
    return [
        make_list_of_masked_sequences,
        produce_masked_sam,
        produce_masked_fasta,
        resolve_genomic_multihits,
    ]


# Adapted from https://raw.githubusercontent.com/baoboa/pyqt5/master/examples/graphicsview/elasticnodes.py

from PyQt5.QtCore import QPointF, QRectF
from PyQt5.QtCore import Qt
from PyQt5.QtGui import (QBrush, QColor, QLinearGradient, QPainter,
                         QPainterPath, QPen, QPolygonF, QRadialGradient)
from PyQt5.QtGui import QTransform
from PyQt5.QtGui import QPolygonF
from PyQt5.QtGui import QFontMetrics
from PyQt5.QtGui import QFont
from PyQt5.QtGui import QCursor
from PyQt5.QtWidgets import (QGraphicsItem, QGraphicsView, QStyle)
from PyQt5.QtWidgets import QGraphicsSceneContextMenuEvent
#from graphics_rect import graphics_rect
from tv_scale_manager import original_scale

# TV Similarity Lines
class TVGLines(QGraphicsItem):
    Type = QGraphicsItem.UserType + 2

    def __init__(self):
        super(TVGLines, self).__init__()

        # height
        self.h = 200

        # bar width - must match texture_graph
        self.bar_width = 2.0

        # data
        self.tv_data1 = dict()
        self.tv_data2 = dict()
        self.step = 1

        # data width
        self.w = 0

        # scale
        self.scale = original_scale

        # draw fast sketch
        self.draw_sketch = False # must match default in draw_sketch checkbox

    def _prepare(self):

        # width
        # if both are defined then use wider of the two
        if self.tv_data1 and self.tv_data2:
            w1 = len(self.tv_data1["texture_vectors"]) * self.scale
            w2 = len(self.tv_data2["texture_vectors"]) * self.scale
            if w1 > w2:
                self.w = w1
            else:
                self.w = w2
        else:
            self.w = 0

        self.prepareGeometryChange()

    # call this if data or settings change
    def set_data(self, tv_data1, tv_data2, step, similarity_lines):
        self.tv_data1 = tv_data1
        self.tv_data2 = tv_data2
        self.step = step
        self.similarity_lines = similarity_lines
        self._prepare()

    # call this if scale changes
    def set_scale(self, scale):
        self.scale = scale
        self._prepare()

    def type(self):
        return TVGLines.Type

    # draw inside this rectangle
    def boundingRect(self):
        adjust = 2
        return QRectF(0 - adjust, 0 - adjust, self.w + adjust, self.h + adjust)

    def _draw_line(self, painter, bar_width, i, j):
        x1=i*bar_width
        y1=0
        x2=j*bar_width
        y2=200
        painter.drawLine(x1,y1,x2,y2)

    def paint(self, painter, option, widget):
        if not self.tv_data1 or not self.tv_data2:
            return

        painter.save()
        painter.translate(5+4, 20) # same as texture_graph

        bar_width = self.scale
        similarity_lines = self.similarity_lines
        step = self.step

        # paint similarity lines from left to right
        for i, values in similarity_lines.items():
            for j in values:
                 self._draw_line(painter, bar_width, i,j)

        painter.restore()


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

# In[2]:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import datetime as dt
import matplotlib.dates as mdates

weather = pd.read_csv('data/C2A2_data/BinnedCsvs_d400/fb441e62df2d58994928907a91895ec62c2c42e6cd075c2700843b89.csv')
weather['Data_Value']=weather['Data_Value']/10 #to convert tmeperature as degree celcius
weather['D_T'] = pd.to_datetime(weather['Date'])

weather_to_year_2014 = weather[weather['D_T'].dt.year != 2015]
weather_to_year_2014['Day'] = weather_to_year_2014['Date'].str[5:]
weather_to_year_2014.sort_values('Day', inplace=True)
weather_to_year_2014 = weather_to_year_2014.groupby(['Day']).Data_Value.agg([('Min','min'),('Max','max')]).add_prefix('Historic Daily ')

weather_year_2015 = weather[weather['D_T'].dt.year == 2015]
weather_year_2015.sort_values('D_T', inplace=True)
weather_year_2015['Day'] = weather_year_2015['Date'].str[5:]
weather_year_2015 = weather_year_2015.groupby(['Day']).Data_Value.agg([('Min','min'),('Max','max')]).add_prefix('2015 Daily ')

weather_combined = pd.merge(weather_year_2015, weather_to_year_2014, left_index=True, right_index=True)
weather_combined.reset_index(inplace=True)
weather_combined['Day'] = weather_combined['Day']+'-2015'
weather_combined['Day'] = pd.to_datetime(weather_combined['Day'])
weather_combined.set_index('Day', inplace=True)

daily_max = weather_combined['Historic Daily Max']
daily_min = weather_combined['Historic Daily Min']
break_record_2015_max = weather_combined['2015 Daily Max'].loc[combined['2015 Daily Max']>combined['HistMax']]
break_record_2015_min = weather_combined['2015 Daily Min'].loc[combined['2015 Daily Min']<combined['HistMin']]
Base = weather_combined.index

plt.gca().fill_between(x=Base, y1=daily_max, y2=daily_min, facecolor='violet', alpha=0.25)
plt.scatter(break_record_2015_max.index, break_record_2015_max, s=10, c='red', label= 'Record Daily Max Broken in 2015')
plt.scatter(break_record_2015_min.index, break_record_2015_min, s=10, c='blue', label= 'Record Daily Min Broken in 2015')
plt.margins(x=0)

locator = mdates.MonthLocator()
fmt = mdates.DateFormatter('%b')
X = plt.gca().xaxis
plt.ylabel('Degree Celsius')
X.set_major_locator(locator)
X.set_major_formatter(fmt)

plt.gca().spines['right'].set_visible(False)
plt.gca().spines['top'].set_visible(False)
plt.gca().spines['bottom'].set_visible(False)
plt.gca().spines['left'].set_visible(False)

plt.title('Record Daily Max and Min Termperature 10 Years Prior to 2015 \n and Reocrd Broke in 2015 ')

plt.legend()
plt.legend(loc=4, frameon=False)

plt.show()

# In[ ]:

Notebook/Visualization of the National Oceanic and Atmospheric (NOAA) Dataset.py


import argparse
from EddyBrake import EddyBrake
import numpy as np
import socket

parser = argparse.ArgumentParser()
parser.add_argument('socketPath',help='socket path')
args = parser.parse_args()

s1 = socket.socket(socket.AF_UNIX)
s1.bind(args.socketPath)
s1.listen(0)

acceptingConnections = True

while acceptingConnections:
  print("waiting for a connection...")
  s2,s2info = s1.accept()
  filename = s2.recv(2048)
  eddyBrake = EddyBrake(filename)
  print("connection accepted")
  print('Loaded file: {}'.format(filename))
  s2.sendall("ready")
  ok = True
  while ok:
    try:
      inputArr = np.frombuffer(s2.recv(1024),dtype="double")
      v = inputArr[0]
      h = inputArr[1]
      print("recieved v: {} and h: {}".format(v,h))
      outputArr = np.array([
        eddyBrake.f_drag(v,h),
        eddyBrake.f_lift(v,h),
        eddyBrake.H_y_max(v,h),
        eddyBrake.H_y_mean(v,h),
        eddyBrake.q_max(v,h),
        eddyBrake.q_mean(v,h)],dtype="double")
      s2.sendall(outputArr.tostring())
      print(outputArr)
    except:
      print("closing connection")
      s2.close()
      ok = False

s1.close()
os.unlink(args.socketPath)


import pytest
from helpers.api_requests import APIRequests
from helpers.event import Event

@pytest.mark.django_db
class TestEventsAllEndpoint:
    """
    Ensure that the /events/all endpoint is fully functional
    and protected.
    """
    event_id_1 = 101
    event_id_2 = 102
    client = APIRequests()
    token = client.get_auth_token(scope='delete')

    def test_events_all_protected_endpoint(self):
        # Don't use a token to authenticate
        status_code = self.client.get_from_all_endpoint(token=None)
        assert status_code == 401

    def test_setup(self):
        self.client.delete_event(1052482906797428737, self.token)
        e = Event(event_id=self.event_id_1)
        # Post one event to the db
        json_payload = e.build_payload()
        token = self.client.get_auth_token(scope='write')
        status_code = self.client.post_event(json_payload, token).status_code
        assert status_code == 201

        # Post a second event to the db
        json_payload["event_id"] = self.event_id_2
        status_code = self.client.post_event(json_payload, token).status_code
        assert status_code == 201

    def test_events_all_endpoint(self):
        token = self.client.get_auth_token(scope='read')
        response = self.client.get_from_all_endpoint(token, False)
        assert len(response) == 2
        assert response[0]['event_id'] == self.event_id_1
        assert response[1]['event_id'] == self.event_id_2

    def test_clear_down(self):
        assert self.client.delete_event(self.event_id_1, self.token) == 204
        assert self.client.delete_event(self.event_id_2, self.token) == 204


"""
This module handles importing data from csv files and creating the whole game world from these data.
"""

import traceback
from muddery.server.settings import SETTINGS
from muddery.server.utils.logger import logger
from muddery.server.utils.game_settings import GameSettings
from muddery.server.mappings.element_set import ELEMENT, ELEMENT_SET
from muddery.server.database.gamedata.account_characters import AccountCharacters
from muddery.server.database.gamedata.character_info import CharacterInfo
from muddery.server.database.gamedata.system_data import SystemData
from muddery.server.database.gamedata.character_location import CharacterLocation

async def create_character(account, nickname, character_key=None,
                     level=1, element_type=None, location_key=None, home_key=None):
    """
    Helper function, creates a character based on a player's name.
    """
    if not character_key:
        character_key = GameSettings.inst().get("default_player_character_key")

    if not element_type:
        element_type = SETTINGS.PLAYER_CHARACTER_ELEMENT_TYPE

    if not nickname:
        nickname = character_key

    if not location_key:
        location_key = GameSettings.inst().get("start_location_key")
        if not location_key:
            location_key = GameSettings.inst().get("default_player_home_key")
            if not location_key:
                location_key = ""

    # Get a new player character id.
    char_db_id = await SystemData.inst().load("last_player_character_id", 0, for_update=True)
    char_db_id += 1
    await SystemData.inst().save("last_player_character_id", char_db_id)

    # save data
    await AccountCharacters.inst().add(account.get_id(), char_db_id)
    await CharacterInfo.inst().add(char_db_id, element_type, character_key, nickname, level)

    # set location
    await CharacterLocation.inst().save(char_db_id, location_key)

    # set character info
    new_char = ELEMENT(element_type)()
    new_char.set_db_id(char_db_id)

    # set player's account id
    new_char.puppet(account)
    await new_char.setup_element(character_key, level=level, first_time=True)

    return


"""
UK analysis dashboard for OCF
"""

import os
from datetime import datetime, timedelta

import pandas as pd
import streamlit as st
from nowcasting_datamodel.connection import DatabaseConnection
from nowcasting_datamodel.models.metric import MetricValue

from auth import check_password
from forecast import forecast_page
from get_data import get_metric_value
from plots.all_gsps import make_all_gsps_plots
from plots.forecast_horizon import (
    make_mae_by_forecast_horizon,
    make_mae_forecast_horizon_group_by_forecast_horizon,
    make_mae_vs_forecast_horizon_group_by_date,
)
from plots.mae_and_rmse import make_rmse_and_mae_plot, make_mae_plot
from plots.pinball_and_exceedance_plots import make_pinball_or_exceedance_plot
from plots.ramp_rate import make_ramp_rate_plot
from plots.utils import get_x_y
from pvsite_forecast import pvsite_forecast_page
from sites_toolbox import sites_toolbox_page
from status import status_page
from tables.raw import make_raw_table
from tables.summary import make_recent_summary_stats, make_forecast_horizon_table

st.get_option("theme.primaryColor")
st.set_page_config(layout="centered", page_title="OCF Dashboard")

show_pvnet_gsp_sum = os.getenv("SHOW_PVNET_GSP_SUM", "False").lower() == "true"

def metric_page():
    # set up title and subheader
    # set up sidebar
    st.sidebar.subheader("Select date range for charts")
    # select start and end date
    starttime = st.sidebar.date_input(
        "Start Date", datetime.today() - timedelta(days=30)
    )
    endtime = st.sidebar.date_input("End Date", datetime.today())

    use_adjuster = st.sidebar.radio("Use adjuster", [True, False], index=1)

    st.sidebar.subheader("Select Forecast Model")
    models = ["cnn", "National_xg", "pvnet_v2"]
    if show_pvnet_gsp_sum:
        models.append("pvnet_gsp_sum")
    model_name = st.sidebar.selectbox("Select", models, 2)

    # set up database connection
    url = os.environ["DB_URL"]
    connection = DatabaseConnection(url=url, echo=True)

    # get metrics for comparing MAE and RMSE without forecast horizon

    with connection.get_session() as session:
        # read database metric values
        name_mae = "Daily Latest MAE"
        name_rmse = "Daily Latest RMSE"
        name_mae_gsp_sum = "Daily Latest MAE All GSPs"
        if use_adjuster:
            name_mae = "Daily Latest MAE with adjuster"
            name_rmse = "Daily Latest RMSE with adjuster"
            name_mae_gsp_sum = "Daily Latest MAE All GSPs"

        name_pvlive_mae = "PVLive MAE"
        name_pvlive_rmse = "PVLive RMSE"

        metric_values_mae = get_metric_value(
            session=session,
            name=name_mae,
            gsp_id=0,
            start_datetime_utc=starttime,
            end_datetime_utc=endtime,
            model_name=model_name,
        )

        metric_values_rmse = get_metric_value(
            session=session,
            name=name_rmse,
            gsp_id=0,
            start_datetime_utc=starttime,
            end_datetime_utc=endtime,
            model_name=model_name,
        )
        # get metric value for mae with pvlive gsp sum truths for comparison
        metric_values_mae_gsp_sum = get_metric_value(
            session=session,
            name=name_mae_gsp_sum,
            start_datetime_utc=starttime,
            end_datetime_utc=endtime,
            model_name=model_name,
        )

        # pvlive
        metric_values_pvlive_mae = get_metric_value(
            session=session,
            name=name_pvlive_mae,
            start_datetime_utc=starttime,
            end_datetime_utc=endtime,
            gsp_id=0,
        )
        metric_values_pvlive_rmse = get_metric_value(
            session=session,
            name=name_pvlive_rmse,
            start_datetime_utc=starttime,
            end_datetime_utc=endtime,
            gsp_id=0,
        )

        # transform SQL object into something readable
        x_mae_all_gsp, y_mae_all_gsp = get_x_y(metric_values=metric_values_mae_gsp_sum)
        x_mae, y_mae = get_x_y(metric_values=metric_values_mae)
        x_rmse, y_rmse = get_x_y(metric_values=metric_values_rmse)
        x_plive_mae, y_plive_mae = get_x_y(metric_values=metric_values_pvlive_mae)
        x_plive_rmse, y_plive_rmse = get_x_y(metric_values=metric_values_pvlive_rmse)

    st.markdown(
        f'
{"Metrics"}
',
        unsafe_allow_html=True,
    )

    make_recent_summary_stats(values=y_mae)
    make_recent_summary_stats(values=y_rmse, title="Recent RMSE")

    st.sidebar.subheader("Select Forecast Horizon")
    forecast_horizon_selection = st.sidebar.multiselect(
        "Select",
        [
            0,
            60,
            120,
            180,
            240,
            300,
            360,
            420,
            8 * 60,
            12 * 60,
            15 * 60,
            18 * 60,
            21 * 60,
            24 * 60,
            30 * 60,
            35 * 60,
        ],
        [60, 120, 240, 420],
    )

    df_mae = pd.DataFrame(
        {
            "MAE": y_mae,
            "datetime_utc": x_mae,
        }
    )

    df_rmse = pd.DataFrame(
        {
            "RMSE": y_rmse,
            "datetime_utc": x_rmse,
        }
    )

    # Make MAE plot
    fig = make_mae_plot(df_mae)
    st.plotly_chart(fig, theme="streamlit")

    # get metrics per forecast horizon
    metric_values_by_forecast_horizon = {}
    with connection.get_session() as session:
        # read database metric values
        for forecast_horizon in forecast_horizon_selection:
            metric_values = get_metric_value(
                session=session,
                name=name_mae,
                gsp_id=0,
                forecast_horizon_minutes=forecast_horizon,
                start_datetime_utc=starttime,
                end_datetime_utc=endtime,
                model_name=model_name,
            )
            metric_values = [MetricValue.from_orm(value) for value in metric_values]
            metric_values_by_forecast_horizon[forecast_horizon] = metric_values

    fig2 = make_mae_by_forecast_horizon(
        df_mae, forecast_horizon_selection, metric_values_by_forecast_horizon
    )
    with st.expander("MAE by Forecast Horizon"):
        st.plotly_chart(fig2, theme="streamlit")

    fig3 = make_mae_forecast_horizon_group_by_forecast_horizon(
        forecast_horizon_selection, metric_values_by_forecast_horizon
    )

    with st.expander("MAE by Forecast Horizon by Date"):
        st.plotly_chart(fig3, theme="streamlit")

    all_forecast_horizons_df, fig4 = make_mae_vs_forecast_horizon_group_by_date(
        forecast_horizon_selection, metric_values_by_forecast_horizon
    )

    with st.expander("MAE Forecast Horizon Values by Date"):
        st.plotly_chart(fig4, theme="streamlit")

    # comparing MAE and RMSE
    fig5 = make_rmse_and_mae_plot(
        df_mae, df_rmse, x_plive_mae, x_plive_rmse, y_plive_mae, y_plive_rmse
    )

    with st.expander("Quartz Solar and PVlive MAE with RMSE"):
        st.plotly_chart(fig5, theme="streamlit")
        st.write(
            "PVLive is the difference between the intraday and day after PVLive values."
        )

    fig6 = make_all_gsps_plots(x_mae_all_gsp, y_mae_all_gsp)

    if model_name in ["pvnet_v2", "cnn"]:
        with st.expander("MAE All GSPs"):
            st.plotly_chart(fig6, theme="streamlit")

    fig7 = make_ramp_rate_plot(session=session, model_name=model_name, starttime=starttime, endtime=endtime)
    with st.expander("Ramp Rate"):
        st.plotly_chart(fig7, theme="streamlit")

    if model_name in ["pvnet_v2", "National_xg"]:
        with connection.get_session() as session:
            with st.expander("Pinball loss"):
                fig7 = make_pinball_or_exceedance_plot(
                    session=session,
                    model_name=model_name,
                    starttime=starttime,
                    endtime=endtime,
                    forecast_horizon_selection=forecast_horizon_selection,
                    metric_name="Pinball loss",
                )
                st.plotly_chart(fig7, theme="streamlit")
            with st.expander("Exceedance"):
                fig8 = make_pinball_or_exceedance_plot(
                    session=session,
                    model_name=model_name,
                    starttime=starttime,
                    endtime=endtime,
                    forecast_horizon_selection=forecast_horizon_selection,
                    metric_name="Exceedance",
                )
                st.plotly_chart(fig8, theme="streamlit")

    make_forecast_horizon_table(all_forecast_horizons_df, y_plive_mae)

    make_raw_table(df_mae, df_rmse)

if check_password():

    page_names_to_funcs = {
        "Metrics": metric_page,
        "Status": status_page,
        "Forecast": forecast_page,
        "PV Site Forecast": pvsite_forecast_page,
        "Sites Toolbox": sites_toolbox_page,
    }

    demo_name = st.sidebar.selectbox("Choose a page", page_names_to_funcs.keys())
    page_names_to_funcs[demo_name]()


import openpyxl
from openpyxl import Workbook, load_workbook
import pandas as pd
from pandas import ExcelWriter
from datetime import datetime

now = datetime.now()
dt_string = now.strftime("%d-%m-%Y_%H-%M-%S")

wb = pd.ExcelFile('Client Detail_2021_2H_concat.xlsx', engine='openpyxl')
worksheets = wb.sheet_names # gets sheet names - works but also creates sheet named ' (200)  Storage' that needs to be deleted
new_sheets = []

del worksheets[0]

# could probably use a list comprehension here
for sheet in worksheets:
    sheet_frame = pd.read_excel(wb, sheet, header=0)
    if 'concat' in sheet_frame.columns:
        new_sheets.append(sheet)

# gets clients from weekly pallet counts - works
wpc_df = pd.read_excel(wb, 'Weekly Pallet Counts')
clients = wpc_df['concat'].unique()

for client in clients:
    writer = ExcelWriter(f'{client}_Details_{dt_string}.xlsx')
    for sheet in new_sheets:
        sheet_frame = pd.read_excel(wb, sheet, header=0)
        if 'concat' in sheet_frame.columns:
            client_sheet = sheet_frame[sheet_frame['concat'] == client]
            if client_sheet.shape[0] == 0:
                continue
            # with pd.ExcelWriter(f'{client}_Details_{dt_string}.xlsx') as writer:  # pylint: disable=abstract-class-instantiated
            client_sheet.to_excel(writer, index=False, sheet_name=sheet)
        else:
            pass
    writer.save()


from src.constants import *
from random import randint

class Battle:

    def __init__(self, team_pokemon1, team_pokemon2):

        self.team_pokemon1 = team_pokemon1
        self.team_pokemon2 = team_pokemon2
        self.pokemon1 = team_pokemon1.pokemon_team[0]
        self.pokemon2 = team_pokemon2.pokemon_team[0]

        self.actual_turn = 0

    def all_dead(self, pokemon_team):
        res = False
        counter = 0
        for pokemon in pokemon_team.pokemon_team:
            if pokemon.current_hp <= 0:
                counter +=1
        if counter == len(pokemon_team.pokemon_team):
            res = True

        return res

    def is_finished(self):
        finished = (self.pokemon1.current_hp <= 0 and self.all_dead(self.team_pokemon1)) or (self.pokemon2.current_hp <= 0 and self.all_dead(self.team_pokemon2))
        if finished:
            self.print_winner()
        return finished

    def execute_turn(self, turn):
        command1 = turn.command1
        command2 = turn.command2
        attack1 = None
        attack2 = None
        if DO_ATTACK in command1.action.keys():
            attack1 = self.pokemon1.attacks[command1.action[DO_ATTACK]]
        if DO_ATTACK in command2.action.keys():
            attack2 = self.pokemon2.attacks[command2.action[DO_ATTACK]]
        if SWAP in command1.action.keys():
            attack1 = Attack("None","None",PHYSICAL,0,0,0)
            self.team_pokemon1.change_pokemon(self)

        if SWAP in command2.action.keys():
            attack2 = Attack("None","None",PHYSICAL,0,0,0)
            self.team_pokemon2.change_pokemon(self)

        # Damage formula

        self.pokemon2.current_hp -= attack1.attack_formula(self.pokemon1, self.pokemon2, attack1)
        self.pokemon1.current_hp -= attack2.attack_formula(self.pokemon2, self.pokemon1, attack2)

        self.actual_turn += 1

    def print_winner(self):
        if self.pokemon1.current_hp <= 0 < self.pokemon2.current_hp and self.all_dead(self.team_pokemon1):
            print('The winner is ' + self.pokemon2.name + ' team!')
        elif self.pokemon2.current_hp <= 0 < self.pokemon1.current_hp and self.all_dead(self.team_pokemon2):
            print('The winner is ' + self.pokemon1.name + ' team!')
        else:
            print("It's a draw!")

    def print_current_status(self):

        print(self.pokemon1.name + ' has ' + str(self.pokemon1.current_hp) + ' hp left!')
        print(self.pokemon2.name + ' has ' + str(self.pokemon2.current_hp) + ' hp left!')

class Poketeam:
    '''

    This class will allow us to have a Pokemon team of 6 Pokemons, the first pokemon in this team is the pokemon that will
    fight first.

    Conditions:     - If Pokemon1 == dead, pokemon2 enters in the battle,
                    - When all pokemons are dead, battle == end
                    -(Will add later the function of changing of pokemons in the middle of the battle)
                    - In main.py, you introduce in a tuple the name of the 6 pokemons you want in ur team, if there
                      there are more than 6 pokemons selected, ask the player what pokemon he doesn't want to choose,
                      if he chose more than 10, make him repick pokemons.
                    - The user can choose between 1 and 6 pokemons, if it is 0, make him choose one.

    '''

    def __init__(self,pokemon_team):
        if len(pokemon_team)<=6:
            self.pokemon_team = pokemon_team
            self.index_changed_to = 0
        else:
            raise ValueError("Invalid team length")

    def change_pokemon(self, battle):

        available_pokemons = [(pokemon.name,"Indice : {}".format(i))for i, pokemon in enumerate(self.pokemon_team) if pokemon.current_hp>0]

        index = int(input("Available Pokemons, select index to change {}".format(available_pokemons)))

        if not (self.pokemon_team[index].current_hp <= 0):
            swapping = self.pokemon_team[0]
            self.pokemon_team[0] = self.pokemon_team[index]
            self.pokemon_team[index] = swapping
            self.index_changed_to = index
            if battle.team_pokemon1.pokemon_team[0] == self.pokemon_team[0]:
                battle.pokemon1 = self.pokemon_team[0]
            else:
                battle.pokemon2 = self.pokemon_team[0]

class Pokemon:

    def __init__(self, name, lvl, type1, type2):
        self.name = name
        self.lvl = lvl
        self.type1 = type1
        self.type2 = type2
        self.attacks = []
        self.stats = {}
        self.current_status = 0
        self.current_hp = 0

class Attack:

    def __init__(self, name, element, category, pp, power, accuracy):
        self.name = name
        self.element = element
        self.category = category
        self.pp = pp
        self.power = power
        self.accuracy = accuracy
        self.attackformula = 0

    def recorre_diccionario(self, atacante, defensor, diccionario):

        lista = [[[value1 for key1, value1 in value.items() if key1 == defensor] for key, value in dicc.items() if
                  key == atacante] for dicc in diccionario]

        res = 0

        if lista[0][0] != 0:
            res += lista[0][0][0]
        else:
            exit(NotImplementedError)

        return res

    def attack_formula(self, pokemon_attacking, pokemon_defending, attack):

        self.attackformula_physical = int(((((2 * pokemon_attacking.lvl) / 5) + 2) * attack.power * (
                pokemon_attacking.stats.get(ATTACK, 1) / pokemon_defending.stats.get(DEFENSE, 1)) + 2) / 50)

        self.attackformula_special = int(((((2 * pokemon_attacking.lvl) / 5) + 2) * attack.power * (
                pokemon_attacking.stats.get(SPATTACK, 1) / pokemon_defending.stats.get(SPDEFENSE, 1)) + 2) / 50)

        random_factor = int(round(randint(217, 255) / 255))
        type_attack_pokemon = 1
        type_efective_pokemon = 1
        type_not_efective_pokemon = 1  # create pokemon's type chart using this format -->   {str:{[str,str...]: int}}

        critical_chance1 = randint(0, 255)
        critical_chance2 = randint(0, 255)

        if pokemon_attacking.type1 == attack.element or pokemon_attacking.type2 == attack.element:

            type_attack_pokemon *= 1.5
        elif pokemon_attacking.type1 != attack.element or pokemon_attacking.type2 != attack.element:

            type_attack_pokemon *= 1

        if attack.category == PHYSICAL:

            if critical_chance1 < critical_chance2:
                return self.attackformula_physical * 2
            else:
                return int(round(self.attackformula_physical * random_factor * type_attack_pokemon))

        elif attack.category == SPECIAL:

            if critical_chance1 < critical_chance2:
                return self.attackformula_special * 2
            else:
                return int(round(self.attackformula_special * random_factor * type_attack_pokemon))
        else:
            raise NotImplementedError('Error in attack_formula')

class Turn:

    def __init__(self):
        self.command1 = None
        self.command2 = None

    def can_start(self):
        return self.command1 is not None and self.command2 is not None

class Command:

    def __init__(self, action):
        self.action = action