from helpers import *
from mobject import Mobject, Mobject1D
from mobject.vectorized_mobject import VMobject
from topics.geometry import *
from topics.characters import  *
import numpy
from constants import *

class Client(VMobject):
    def generate_points(self):
        r1 = Rectangle()\
            .stretch_to_fit_width(3)\
            .stretch_to_fit_height(2)\
            .highlight(Blue)\
            .shift(5*LEFT)

        r2 = Rectangle()\
            .stretch_to_fit_width(1)\
            .stretch_to_fit_height(0.2)\
            .highlight(WHITE)\
            .next_to(r1, DOWN*2.5)\

        self.add(r1, r2)
        self.init_colors()

class Router(VMobject):
    def generate_points(self):
        c = Circle()\
            .scale(0.8)

        x = Cross()

        self.add(c, x)
        self.init_colors()

class Network(VMobject):
    def generate_points(self):
        r1 = Router()\
            .scale(0.5)\
            .shift(1*RIGHT)

        r2 = Router()\
            .scale(0.5)\
            .shift(0.9*DOWN, 0.5*RIGHT  + 1*RIGHT)

        r3 = Router()\
            .scale(0.5)\
            .shift(0.9*DOWN, 0.5*LEFT + 1*RIGHT)

        self.add(r1, r2, r3)
        self.init_colors()

class Engineer(VMobject):
    def generate_points(self):
        p1 = Person()
        p1.highlight(RED_C).set_fill(RED_C)

        helmet = SemiCircle() \
            .set_fill(YELLOW).highlight(YELLOW) \
            .scale_to_fit_width(p1.get_width()) \
            .next_to(p1, UP) \
            .shift(0.4 * DOWN)

        self.add(p1, helmet)
        self.init_colors()

class SemiCircle(VMobject):
    def generate_points(self):
        nudge = 0.05
        w_angle =  -1*degrees
        v_angle = 181*degrees

        arc = Arc(
            (1-2*nudge)*(w_angle - v_angle),
            start_angle = interpolate(v_angle, w_angle, nudge),
            radius = 2.5
        )

        line = Line(LEFT, RIGHT)\
            .next_to(arc, DOWN)\
            .stretch_to_fit_width(arc.get_width())

        self.add(arc, line)
        self.init_colors()

class Family(VMobject):
    def generate_points(self):
        c1 = Colors.Manim.random
        c2 = Colors.Manim.random
        c3 = Colors.Manim.random

        l = Person() \
            .set_fill(c2) \
            .highlight(c2) \
            .shift(1 * LEFT)

        m = Person() \
            .set_fill(c1) \
            .highlight(c1) \
            .shift(1 * RIGHT)

        j = Person() \
            .scale(0.5) \
            .set_fill(c3) \
            .highlight(c3) \
            .shift(2 * DOWN)

        self.add(l,m,j)
        self.init_colors()

class Server(VMobject):
    def generate_points(self):
        l1 = Line(RIGHT, UP)\
            .highlight(GREEN)

        l2 = Line(RIGHT, UP) \
            .next_to(l1, DOWN * 10) \
            .highlight(GREEN)

        l3 = Line(UP, DOWN) \
            .next_to(l1, DOWN) \
            .shift(LEFT * 0.5, 1.1 * UP) \
            .stretch_to_fit_height(2) \
            .highlight(GREEN)

        l4 = Line(UP, DOWN) \
            .next_to(l3, RIGHT) \
            .shift(1 * DOWN, RIGHT * 0.9) \
            .stretch_to_fit_height(2) \
            .highlight(GREEN)

        l5 = Line(LEFT, UP) \
            .next_to(l1) \
            .stretch_to_fit_height(2) \
            .stretch_to_fit_width(2) \
            .shift(RIGHT * 0.4, UP * 0.5)

        l6 = Line(LEFT, UP) \
            .next_to(l1) \
            .stretch_to_fit_height(2) \
            .stretch_to_fit_width(2) \
            .shift(RIGHT * 0.4, DOWN * 1.5)

        l7 = Line(UP, DOWN) \
            .next_to(l1, DOWN) \
            .shift(2.5 * RIGHT, 2.1 * UP) \
            .stretch_to_fit_height(2)

        l8 = Line(LEFT, UP) \
            .next_to(l1) \
            .stretch_to_fit_height(2) \
            .stretch_to_fit_width(2) \
            .shift(UP * 1.5, LEFT * 0.6)

        l9 = Line(RIGHT, UP) \
            .next_to(l1) \
            .shift(.9 * RIGHT, 2 * UP)

        self.add(l1, l2, l3, l4, l5, l6, l7, l8, l9)
        self.init_colors()

class Capacitor(VMobject):
    def generate_points(self):
        l1 = Line(RIGHT, LEFT)

        l2 = Line(UP, DOWN)\
            .next_to(l1)\
            .shift(0.1*LEFT)

        l3 = Line(UP, DOWN)\
            .next_to(l2)\
            .shift(0.5*RIGHT)

        l4 = Line(RIGHT, LEFT)\
            .next_to(l3) \
            .shift(0.1*LEFT)

        self.add(l1, l2, l3, l4)
        self.init_colors()

class App(VMobject):
    def generate_points(self):
        s1 = Square()\
            .highlight(WHITE)\
            .shift(0*LEFT)

        s2 = Square()\
            .highlight(YELLOW)\
            .shift(0.3*RIGHT, 0.3*DOWN)

        self.add(s1, s2)
        self.init_colors()

class Wifi(VMobject):
    def generate_points(self):
        nudge = 0.05
        w_angle =   3.14/3
        v_angle = 2*3.14/3
        arc1 = Arc(
            (1-2*nudge)*(w_angle - v_angle),
            start_angle = interpolate(v_angle, w_angle, nudge),
            radius = 2.5
        ).highlight(GREEN)\
         .shift(1*RIGHT)
        arc2 = Arc(
            (1-2*nudge)*(w_angle - v_angle),
            start_angle = interpolate(v_angle, w_angle, nudge),
            radius = 2
        ).shift(1*RIGHT)
        arc3 = Arc(
            (1-2*nudge)*(w_angle - v_angle),
            start_angle = interpolate(v_angle, w_angle, nudge),
            radius = 1.5
        ).shift(1*RIGHT )

        self.add(arc1, arc2, arc3)
        self.init_colors()

class NestedCircle(VMobject):
    def generate_points(self):
        c1 = Circle()
        c2 = Circle()\
            .scale(0.8)

        self.add(c1, c2)
        self.init_colors()

class SpeakerFront(VMobject):
    def generate_points(self):
        speaker = SVGMobject(file_name="speakerfront") \
            .scale(0.005) \
            .highlight(Colors.Manim.Yellow.E) \
            .stretch_to_fit_height(Square().get_height()) \
            .stretch_to_fit_width(Square().get_width())

        self.add(speaker)
        self.init_colors()

class CircleArray(VMobject):
    def generate_points(self):
        circle = []
        for i in range(8):
            circle.append(SpeakerFront())
            circle[i].scale(0.5)

        for i in range(len(circle)):
            circle[i].highlight(Colors.Manim.Yellow.E)
            if i > 0: circle[i].next_to(circle[i-1], 0.1*LEFT)

        for c in circle:
            c.shift(RIGHT*3.6)

        for i in range(len(circle)):
            self.add(circle[i])

        self.init_colors()

class SquareArray(VMobject):
    def generate_points(self):
        circle = []
        for i in range(8):
            circle.append(Square())
            circle[i].scale(0.5)

        for i in range(len(circle)):
            circle[i].highlight(Colors.Manim.Yellow.E)

            if i > 0: circle[i].next_to(circle[i-1], 0.25*LEFT)

        for c in circle:
            c.shift(RIGHT*3.6)

        for i in range(len(circle)):
            self.add(circle[i])

        self.init_colors()

class SpeakerArray(VMobject):
    def generate_points(self):
        circle = []
        for i in range(8):
            c = Square()\
                .scale(0.5)

            speaker = Speaker()
            speaker.rotate(-90*degrees)
            speaker.scale_to_fit_width(c.get_width()*2)

            circle.append(speaker)
            circle[i].scale(0.5)

        for i in range(len(circle)):
            circle[i].highlight(Colors.Manim.Yellow.E)

            if i > 0: circle[i].next_to(circle[i-1], 0.25*LEFT)

        for c in circle:
            c.shift(RIGHT*3.6)

        for i in range(len(circle)):
            self.add(circle[i])

        self.init_colors()

class SpeakerArraySmall(VMobject):
    def generate_points(self):
        circle = []
        for i in range(8):
            c = Square()\
                .scale(0.5)

            speaker = Speaker()
            speaker.rotate(180*degrees)
            speaker.scale_to_fit_width(c.get_width()*2)

            circle.append(speaker)
            circle[i].scale(0.5)

        for i in range(len(circle)):
            circle[i].highlight(Colors.Manim.Yellow.E)

            if i > 0: circle[i].next_to(circle[i-1], 0.25*LEFT)

        for c in circle:
            c.shift(RIGHT*3.6)
            c.scale(0.5)

        for i in range(len(circle)):
            self.add(circle[i])

        self.init_colors()

class Camera(VMobject):
    def generate_points(self):
        cam = SVGMobject(file_name="camera4.svg")
        cam.scale(0.005)
        self.add(cam)
        self.init_colors()

class Atlus(VMobject):
    def generate_points(self):
        atlus = CircleArray()

        #rect = Rectangle() \
        #    .stretch_to_fit_width(atlus.get_width()+0.5) \
        #    .stretch_to_fit_height(atlus.get_height()+0.5) \
        #    .highlight(VS_COLORS.GRAY)

        self.add(atlus)#, rect)

        self.init_colors()

class Eyes(VMobject):
    def generate_points(self, color=Colors.Manim.Blue.D):
        eye1 = Eye(color).scale(0.5).shift(1.8*LEFT)
        eye2 = Eye(color).scale(0.5).shift(1.8*RIGHT)
        self.add(eye1, eye2)
        self.init_colors()

class Eye(VMobject):
    def generate_points(self, color=Colors.Manim.Blue.D):
        eye = SVGMobject(file_name="eye")
        eye.scale(0.002)
        [i.highlight(color) for i in eye.submobjects[2:10]]
        eye.submobjects[10].highlight(COLORS.WHITE).set_fill(COLORS.WHITE)
        self.add(eye)
        self.init_colors()

class GenericPerson(VMobject):
    def generate_points(self):
        person = SVGMobject(file_name="person")
        person.scale(0.01)
        self.add(person)
        self.init_colors()

class RandomPerson(VMobject):
    def generate_points(self):
        person = SVGMobject(file_name="person")
        person.scale(0.01)
        color = COLORS.RANDOM()
        person.highlight(color)
        person.set_fill(color)
        self.add(person)
        self.init_colors()

class Machine(VMobject):
    def generate_points(self):
        m = SVGMobject(file_name="machine")
        m.scale(0.01)

        [i.highlight(Colors.Manim.GREY.DARK) for i in m.submobjects[0]]
        [i.highlight(Colors.Manim.GREY.NORMAL) for i in m.submobjects[1:2]]
        [i.highlight(Colors.Manim.GREY.LIGHT) for i in m.submobjects[2:5]]
        [i.highlight(Colors.Manim.RED.E) for i in m.submobjects[6]]
        [i.set_fill(Colors.Manim.RED.A) for i in m.submobjects[6]]

        self.add(m)
        self.init_colors()

class LongSine(Mobject1D):
    def generate_points(self):
        self.add_points(
            [(x, numpy.sin(360*degrees*x), 0) for x in np.arange(0, 5, 0.0001)])

        self.init_colors()

class Speaker(VMobject):
    def generate_points(self):
        speaker = SVGMobject(file_name="speaker")\
            .scale(0.005)\
            .highlight(Colors.Manim.Yellow.E)\
            .stretch_to_fit_height(Square().get_height())\
            .stretch_to_fit_width(Square().get_width()/2)

        semi = SemiCircle()\
            .highlight(Colors.Manim.Yellow.E)\
            .rotate(-90*degrees)\
            .scale(0.15)

        semi.shift(speaker.get_left())

        semi.shift(0.035*LEFT)

        self.add(speaker, semi)
        self.init_colors()

class Filter(VMobject):
    def generate_points(self):
        f = Square() \
            .highlight(VS_COLORS.TURQUOISE) \
            .scale(0.5) \
            .rotate(45*degrees)

        l = DashedLine(UP, DOWN)\
            .highlight(WHITE)\
            .stretch_to_fit_height(f.get_height())

        l.scale(0.8)
        l.shift(0.08*DOWN)

        self.add(f, l)
        self.init_colors()


import deep_ga
import tensorflow as tf
from tensorflow import keras
import os
import matplotlib.pyplot as plt

class AssertWeightsFinite(keras.callbacks.Callback):
    def __init__(self):
        super(AssertWeightsFinite, self).__init__()

    def on_epoch_end(self, epoch, logs=None):
        for weight in self.model.weights:
            if not tf.math.reduce_all(tf.math.is_finite(weight)):
                print(f"Weight {weight.name} not finite, stop training")
                self.model.stop_training = True
                break

class PlotPrediction(keras.callbacks.Callback):
    def __init__(self, folder, tgen, vgen, save=True):
        self.folder = folder
        self.tgen = tgen
        self.vgen = vgen
        self.save = save
        if self.save:
            os.makedirs(folder, exist_ok=True)
        super(PlotPrediction, self).__init__()

    def on_epoch_end(self, epoch, logs=None):
        ylabel = ("Match Probability"
                  if self.model.loss.__name__ == "BCE"
                  else "Predicted distance")
        tx, ty = self.tgen.get_batch(200)
        typ = self.model.predict(tx)[:, 0]
        plt.clf()
        plt.scatter(ty, typ, 2)
        plt.title("Training Data")
        plt.xlabel("Distance between local and global patch")
        plt.xlim(0, plt.xlim()[1])
        plt.ylim(0, plt.ylim()[1])
        if self.model.loss.__name__ == "BCE":
            plt.ylim(0, 1)
        plt.ylabel(ylabel)
        if self.save:
            plt.savefig(os.path.join(self.folder, f"train_{epoch:03}.pdf"))
        else:
            plt.show()

        vx, vy = self.vgen.get_batch(200)
        vyp = self.model.predict(vx)[:, 0]
        plt.clf()
        plt.scatter(vy, vyp, 2)
        plt.title("Validation Data")
        plt.xlabel("Distance between local and global patch")
        plt.xlim(0, plt.xlim()[1])
        plt.ylim(0, plt.ylim()[1])
        if self.model.loss.__name__ == "BCE":
            plt.ylim(0, 1)
        plt.ylabel(ylabel)
        if self.save:
            plt.savefig(os.path.join(self.folder, f"valid_{epoch:03}v.pdf"))
        else:
            plt.show()

class ValidationProgbar(keras.callbacks.Callback):
    def __init__(self, vgen):
        self.pbar = None
        self.N = len(vgen)
        super(ValidationProgbar, self).__init__()

    def on_test_batch_end(self, batch, logs=None):
        if batch == 0:
            print("\nValidation:")
            self.pbar = keras.utils.Progbar(
                self.N, stateful_metrics=logs.keys())
        self.pbar.add(1, values=logs.items())


# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: build/bdist.linux-x86_64/egg/turkish_morphology/validate.py
# Compiled at: 2020-03-21 19:20:28
# Size of source mod 2**32: 4957 bytes
"""Functions to validate structural well-formedness of analysis protobufs."""
from typing import Optional
from turkish_morphology import analysis_pb2
_Affix = analysis_pb2.Affix
_Analysis = analysis_pb2.Analysis
_Feature = analysis_pb2.Feature
_Ig = analysis_pb2.InflectionalGroup
_Root = analysis_pb2.Root

class IllformedAnalysisError(Exception):
    __doc__ = 'Raised when a human-readable analysis is structurally ill-formed.'

def _root(root: _Root) -> None:
    """Checks if root is structurally well-formed.

  Args:
    root: root analysis.

  Raises:
    IllformedAnalysisError: root is missing the morpheme field, or its
      morpheme field is set as empty string.
  """
    if not root.HasField('morpheme'):
        raise IllformedAnalysisError(f"Root is missing morpheme: '{root}'")
    if not root.morpheme:
        raise IllformedAnalysisError(f"Root morpheme is empty: '{root}'")

def _feature(feature: _Feature) -> None:
    """Checks if feature is structurally well-formed.

  Args:
    feature: morphological analysis feature.

  Raises:
    IllformedAnalysisError: feature is missing category or value field, or
      its category or value field is set as empty string.
  """
    if not feature.HasField('category'):
        raise IllformedAnalysisError(f"Feature is missing category: '{feature}'")
    else:
        if not feature.category:
            raise IllformedAnalysisError(f"Feature category is empty: '{feature}'")
        if not feature.HasField('value'):
            raise IllformedAnalysisError(f"Feature is missing value: '{feature}'")
        assert feature.value, f"Feature value is empty: '{feature}'"

def _affix(affix: _Affix, derivational: Optional[bool]=False) -> None:
    """Checks if affix is structurally well-formed.

  Args:
    affix: affix analysis.
    derivational: if True, affix corresponds to a derivational feature.

  Raises:
    IllformedAnalysisError: affix is missing the feature field, or affix is
      derivational but its meta_morpheme field is missing or its meta_morpheme
      field is set as empty string.
  """
    if not affix.HasField('feature'):
        raise IllformedAnalysisError(f"Affix is missing feature: '{affix}'")
    else:
        _feature(affix.feature)
        if not derivational:
            return
        if not affix.HasField('meta_morpheme'):
            raise IllformedAnalysisError(f"Derivational affix is missing meta-morpheme: '{affix}'")
        assert affix.meta_morpheme, f"Derivational affix meta-morpheme is empty: '{affix}'"

def _inflectional_group(ig: _Ig, position: int) -> None:
    """Checks if inflectional group is structurally well-formed.

  Args:
    ig: inflectional group analysis.
    position: index of the inflectional group w.r.t. the array of inflectional
      groups of the morphological analysis it belongs to.

  Raises:
    IllformedAnalysisError: inflectional group is missing part-of-speech tag,
      or its part-of-speech tag is set as empty string, or inflectional group
      is the first in morphological analysis and it is missing the root field,
      or inflectional group is derived and it is missing the derivation field.
  """
    if not ig.HasField('pos'):
        raise IllformedAnalysisError(f"Inflectional group {position + 1} is missing part-of-speech tag: '{ig}'")
    if not ig.pos:
        raise IllformedAnalysisError(f"Inflectional group {position + 1} part-of-speech tag is empty: '{ig}'")
    if position == 0:
        if not ig.HasField('root'):
            raise IllformedAnalysisError(f"Inflectional group {position + 1} is missing root: '{ig}'")
        _root(ig.root)
    else:
        if not ig.HasField('derivation'):
            raise IllformedAnalysisError(f"Inflectional group {position + 1} is missing derivational affix: '{ig}'")
        _affix((ig.derivation), derivational=True)
    for inflection in ig.inflection:
        _affix(inflection)

def analysis(analysis: _Analysis) -> None:
    """Checks if analysis protobuf is structurally well-formed.

  Args:
    analysis: morphological analysis.

  Raises:
    IllformedAnalysisError: analysis is missing inflectional groups.
  """
    if not analysis.ig:
        raise IllformedAnalysisError("Analysis is missing inflectional groups: 'analysis'")
    for position, ig in enumerate(analysis.ig):
        _inflectional_group(ig, position)


# 单个元素
# find_element_by_id
# find_element_by_name
# find_element_by_xpath
# find_element_by_link_text
# find_element_by_partial_link_text
# find_elememt_by_tag_name
# find_elememt_by_class_name
# find_elememt_by_css_selector

# 多个元素
# find_elememts_by_name
# find_elememts_by_xpath
# find_elememts_by_link_text
# find_elememts_by_partial_link_text
# find_elememts_by_tag_name
# find_elememts_by_class_name
# find_elememts_by_css_selector

from selenium import webdriver
import time

driver = webdriver.PhantomJS(executable_path=r"D:\phantomjs\bin\phantomjs.exe")  # 调用phantomJS
driver.get("https://www.python.org/")  # 打开页面的网址
time.sleep(10)

by_id = driver.find_element_by_id('downloads').get_attribute('innerHTML')
print(by_id)
driver.close()

自动化脚本/如何定位元素.py


"""Application."""
import logging
import os
from typing import TYPE_CHECKING, Any, List, Type

from ansiblelint import formatters
from ansiblelint.color import console
from ansiblelint.errors import MatchError

if TYPE_CHECKING:
    from argparse import Namespace

_logger = logging.getLogger(__package__)

class App:
    """App class represents an execution of the linter."""

    def __init__(self, options: "Namespace"):
        """Construct app run based on already loaded configuration."""
        options.skip_list = _sanitize_list_options(options.skip_list)
        options.warn_list = _sanitize_list_options(options.warn_list)

        self.options = options

        formatter_factory = choose_formatter_factory(options)
        self.formatter = formatter_factory(options.cwd, options.display_relative_path)

    def render_matches(self, matches: List[MatchError]) -> None:
        """Display given matches."""
        if isinstance(self.formatter, formatters.CodeclimateJSONFormatter):
            # If formatter CodeclimateJSONFormatter is chosen,
            # then print only the matches in JSON
            console.print(
                self.formatter.format_result(matches), markup=False, highlight=False
            )
            return None

        ignored_matches = [match for match in matches if match.ignored]
        fatal_matches = [match for match in matches if not match.ignored]
        # Displayed ignored matches first
        if ignored_matches:
            _logger.warning(
                "Listing %s violation(s) marked as ignored, likely already known",
                len(ignored_matches),
            )
            for match in ignored_matches:
                if match.ignored:
                    # highlight must be off or apostrophes may produce unexpected results
                    console.print(self.formatter.format(match), highlight=False)
        if fatal_matches:
            _logger.warning(
                "Listing %s violation(s) that are fatal", len(fatal_matches)
            )
            for match in fatal_matches:
                if not match.ignored:
                    console.print(self.formatter.format(match), highlight=False)

        # If run under GitHub Actions we also want to emit output recognized by it.
        if os.getenv('GITHUB_ACTIONS') == 'true' and os.getenv('GITHUB_WORKFLOW'):
            formatter = formatters.AnnotationsFormatter(self.options.cwd, True)
            for match in matches:
                console.print(formatter.format(match), markup=False, highlight=False)

def choose_formatter_factory(
    options_list: "Namespace",
) -> Type[formatters.BaseFormatter[Any]]:
    """Select an output formatter based on the incoming command line arguments."""
    r: Type[formatters.BaseFormatter[Any]] = formatters.Formatter
    if options_list.format == 'quiet':
        r = formatters.QuietFormatter
    elif options_list.parseable_severity:
        r = formatters.ParseableSeverityFormatter
    elif options_list.parseable or options_list.format == 'pep8':
        r = formatters.ParseableFormatter
    elif options_list.format == 'codeclimate':
        r = formatters.CodeclimateJSONFormatter
    return r

def _sanitize_list_options(tag_list: List[str]) -> List[str]:
    """Normalize list options."""
    # expand comma separated entries
    tags = set()
    for t in tag_list:
        tags.update(str(t).split(','))
    # remove duplicates, and return as sorted list
    return sorted(set(tags))


import os
import shutil
import numpy as np
import keras

import requests
import tempfile
import sys

import ants

def brain_extraction(image,
                     output_directory=None,
                     verbose=None):

    """
    Perform brain extraction using U-net and ANTs-based
    training data.

    Arguments
    ---------
    image : ANTsImage
        input image

    output_directory : string
        Destination directory for storing the downloaded template and model weights.
        Since these can be resused, if is None, these data will be downloaded to a
        tempfile.

    verbose : boolean
        Print progress to the screen.

    Returns
    -------
    ANTs probability brain mask image.

    Example
    -------
    >>> probability_brain_mask = brain_extraction(brain_image)
    """

    from ..architectures import create_unet_model_3d
    from ..utilities import get_pretrained_network

    classes = ("background", "brain")
    number_of_classification_labels = len(classes)

    image_mods = ["T1"]
    channel_size = len(image_mods)

    reorient_template_file_name = None
    reorient_template_file_exists = False
    if output_directory is not None:
        reorient_template_file_name = output_directory + "S_template3_resampled.nii.gz"
        if os.path.exists(reorient_template_file_name):
            reorient_template_file_exists = True

    reorient_template = None
    if output_directory is None or reorient_template_file_exists == False:
        reorient_template_file = tempfile.NamedTemporaryFile(suffix=".nii.gz")
        reorient_template_file.close()
        template_file_name = reorient_template_file.name
        template_url = "https://github.com/ANTsXNet/BrainExtraction/blob/master/Data/Template/S_template3_resampled.nii.gz?raw=true"

        if not os.path.exists(template_file_name):
            if verbose == True:
                print("Brain extraction:  downloading template.")
            r = requests.get(template_url)
            with open(template_file_name, 'wb') as f:
                f.write(r.content)
        reorient_template = ants.image_read(template_file_name)
        if output_directory is not None:
            shutil.copy(template_file_name, reorient_template_file_name)
    else:
        reorient_template = ants.image_read(reorient_template_file_name)

    resampled_image_size = reorient_template.shape

    unet_model = create_unet_model_3d((*resampled_image_size, channel_size),
        number_of_outputs = number_of_classification_labels,
        number_of_layers = 4, number_of_filters_at_base_layer = 8, dropout_rate = 0.0,
        convolution_kernel_size = (3, 3, 3), deconvolution_kernel_size = (2, 2, 2),
        weight_decay = 1e-5)

    weights_file_name = None
    if output_directory is not None:
        weights_file_name = output_directory + "brainExtractionWeights.h5"
        if verbose == True and not os.path.exists(weights_file_name):
            print("Brain extraction:  downloading template.")
            weights_file_name = get_pretrained_network("brainExtraction", weights_file_name)
    else:
        if verbose == True:
            print("Brain extraction:  downloading template.")
        weights_file_name = get_pretrained_network("brainExtraction", weights_file_name)

    unet_model.load_weights(weights_file_name)

    if verbose == True:
        print("Brain extraction:  normalizing image to the template.")

    center_of_mass_template = ants.get_center_of_mass(reorient_template)
    center_of_mass_image = ants.get_center_of_mass(image)
    translation = np.asarray(center_of_mass_image) - np.asarray(center_of_mass_template)
    xfrm = ants.create_ants_transform(transform_type="Euler3DTransform",
        center=np.asarray(center_of_mass_template), translation=translation)
    warped_image = ants.apply_ants_transform_to_image(xfrm, image, reorient_template)
    warped_image = (warped_image - warped_image.mean()) / warped_image.std()

    batchX = np.expand_dims(warped_image.numpy(), axis=0)
    batchX = np.expand_dims(batchX, axis=-1)
    batchX = (batchX - batchX.mean()) / batchX.std()

    if verbose == True:
        print("Brain extraction:  prediction and decoding.")

    predicted_data = unet_model.predict(batchX, verbose=verbose)

    origin = reorient_template.origin
    spacing = reorient_template.spacing
    direction = reorient_template.direction

    probability_images_array = list()
    probability_images_array.append(
    ants.from_numpy(np.squeeze(predicted_data[0, :, :, :, 0]),
        origin=origin, spacing=spacing, direction=direction))
    probability_images_array.append(
    ants.from_numpy(np.squeeze(predicted_data[0, :, :, :, 1]),
        origin=origin, spacing=spacing, direction=direction))

    if verbose == True:
        print("Brain extraction:  renormalize probability mask to native space.")
    probability_image = ants.apply_ants_transform_to_image(
        ants.invert_ants_transform(xfrm), probability_images_array[1], image)

    return(probability_image)


# Problem Set 3a
# Name: Aaron Bell
# Time: 5 hours

from ps3a import *
import time
from perm import *
import sys

#
#
# Problem #6A: Computer chooses a word
#
#

def comp_choose_word(hand, word_list):
	"""
	Given a hand and a word_dict, find the word that gives the maximum value score, and return it.
	This word should be calculated by considering all possible permutations of lengths 1 to HAND_SIZE.

	hand: dictionary (string -> int)
	word_list: list (string)
	"""
	# TO DO...

	'''

	A. Check the score (X)
	B. Check the score against the next word (X)
	C. If the word is higher value than the current, replace the selection with the word (X)
	D. Get permutations of hand at a certain length (X)
	E. Go through each possible length of permutations (X)
	F. Get the hand (X)
	G. Get the word_dict (X)
	H. Check if a word's in the word_list (X)
	I. return highest_value_word (X)

	'''

	current_best = 0
	selection = ''

	print('Please wait. Computer picking answer...')

	#E
	for n in reversed(range(1, HAND_SIZE + 1)):

		#D
		current_choices = get_perms(hand, n) #F

		#H
		for each in current_choices:

			#H
			if each in word_list:

				current_word_score = get_word_score(each)
				#B
				if current_word_score > current_best: #G

					#C
					current_best = current_word_score
					selection = each

	if selection is not '':
		print('---From comp_choose_word(hand, word_list)---')
		print('The hand is: ' + str(hand))
		print('The computer chooses: ' + selection)
		print('The value of the word is ' + str(get_word_score(selection)))

		#I
		return selection
	else:
		selection = '.'
		return selection
#
# Problem #6B: Computer plays a hand
#
def comp_play_hand(hand, word_list):
	"""
	 Allows the computer to play the given hand, as follows:

	 * The hand is displayed.

	 * The computer chooses a word using comp_choose_words(hand, word_dict).

	 * After every valid word: the score for that word is displayed,
	   the remaining letters in the hand are displayed, and the computer
	   chooses another word.

	 * The sum of the word scores is displayed when the hand finishes.

	 * The hand finishes when the computer has exhausted its possible choices (i.e. comp_play_hand returns None).

	 hand: dictionary (string -> int)
	 word_list: list (string)
	"""
	# TO DO ...

	total_score = 0

	while len(hand) > 0:

		display_hand(hand)
		comp_guess = comp_choose_word(hand, word_list)
		if comp_guess == '.':
			print('No answer found. Ending round.')
			print('Total score: ' + str(total_score))
			return

		while is_valid_word(comp_guess, hand, word_list) is False and comp_guess is not '.':

			comp_guess = input('The computer picked an invalid word. Press ' \
			'any button to escape this function.')
			if comp_guess == '.': return

		word_score = get_word_score(comp_guess, hand)
		total_score += word_score
		hand = update_hand(hand, comp_guess)
		print('The score for "{}" is {}. Total score: {}'.format(comp_guess, str(word_score), str(total_score)))

	print('The total score for this hand is: {}'.format(str(total_score)))

def player_or_computer(user_input):

	while user_input not in 'uce':
		user_input = input('Would you like to play? ("u") Or do you '\
		'want the computer to play? ("c") Or, press "e" to exit.\n').lower()
	if user_input == 'u':
		return play_hand(hand, word_list)
	elif user_input == 'c':
		return comp_play_hand(hand, word_list)
	elif user_input == 'e':
		print('Thanks for playing!')
		sys.exit()
#
# Problem #6C: Playing a game
#
#
def play_game(word_list):
	"""Allow the user to play an arbitrary number of hands.

	1) Asks the user to input 'n' or 'r' or 'e'.
	* If the user inputs 'n', play a new (random) hand.
	* If the user inputs 'r', play the last hand again.
	* If the user inputs 'e', exit the game.
	* If the user inputs anything else, ask them again.

	2) Ask the user to input a 'u' or a 'c'.
	* If the user inputs 'u', let the user play the game as before using play_hand.
	* If the user inputs 'c', let the computer play the game using comp_play_hand (created above).
	* If the user inputs anything else, ask them again.

	3) After the computer or user has played the hand, repeat from step 1

	word_list: list (string)
	"""
	# TO DO...

	user_input = input('New hand ("n") or exit ("e")?\n').lower()

	if user_input == 'e': return

	while True:

		if user_input == 'e':
			return
		elif user_input == 'n':
			hand = deal_hand(HAND_SIZE)
			player_or_computer(user_input)
		elif user_input == 'r':
			player_or_computer(user_input)
		user_input = input('New hand ("n"), play the same hand ("r"), ' \
			'or exit ("e")?\n')
#
# Build data structures used for entire session and play game
#
if __name__ == '__main__':
	word_list = load_words()
	play_game(word_list)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct  5 10:25:36 2019

@author: khaled
"""

#### Travelling with a Tesla ####

import matplotlib.pyplot as plt
import sys
import psutil
import os
import numpy as np
import pandas as pd
import time
from multiprocessing import Pool, cpu_count

import sklearn
import mlrose

## https://mortada.net/the-traveling-tesla-salesman.html
#https://teslamotorsclub.com/tmc/threads/a-list-of-all-supercharger-coordinates-and-a-script-to-grab-them.37948/

#### Corordinates of the superchargers in California, USA (2014) ####
coordsSupershargersCA= [(47.8803440000, 10.0403420000),
                        (35.4865850000, -120.6663780000),
                        (34.8491090000, -117.0854420000),
                        (34.6145550000, -120.1884320000),
                        (39.9264600000, -122.1984000000),
                        (38.6422910000, -121.1881300000),
                        (37.4924390000, -121.9447250000),
                        (37.0244500000, -121.5653500000),
                        (36.2541430000, -120.2379200000),
                        (33.9210630000, -118.3300740000),
                        (41.3102220000, -122.3173100000),
                        (38.7712080000, -121.2661490000),
                        (33.4985380000, -117.6630900000),
                        (34.9873700000, -118.9462720000),
                        (38.3666450000, -121.9581360000),
                        (39.3274380000, -120.2074100000),
                        (34.2381150000, -119.1780840000),
                        (33.7412910000, -116.2150290000),
                        (34.1135840000, -117.5294270000)]

coordsMayanmar=[(16.47, 96.10),
                (16.47, 94.44),
                (20.09, 92.54),
                (22.39, 93.37),
                (25.23, 97.24),
                (22.00, 96.05),
                (17.20, 96.29),
                (16.30, 97.38),
                (14.05, 98.12),
                (16.53, 97.38),
                (21.52, 95.59),
                (19.41, 97.13),
                (20.09, 94.55)]

dist_list = [(0, 1, 3.1623), (0, 2, 4.1231), (0, 3, 5.8310), (0, 4, 4.2426), \
(0, 5, 5.3852), (0, 6, 4.0000), (0, 7, 2.2361), (1, 2, 1.0000), \
(1, 3, 2.8284), (1, 4, 2.0000), (1, 5, 4.1231), (1, 6, 4.2426), \
(1, 7, 2.2361), (2, 3, 2.2361), (2, 4, 2.2361), (2, 5, 4.4721), \
(2, 6, 5.0000), (2, 7, 3.1623), (3, 4, 2.0000), (3, 5, 3.6056), \
(3, 6, 5.0990), (3, 7, 4.1231), (4, 5, 2.2361), (4, 6, 3.1623), \
(4, 7, 2.2361), (5, 6, 2.2361), (5, 7, 3.1623), (6, 7, 2.2361)]

coords_list= [(1,1), (4,2), (5,2), (6,4), (4,4), (3,6), (1,5), (2,3)]

fitness= mlrose.TravellingSales(coords= coordsSupershargersCA);
#fitness= mlrose.TravellingSales(distances= dist_list);

problem=mlrose.TSPOpt(length=19, fitness_fn=fitness, maximize=False)

#problem=mlrose.TSPOpt(length=8, fitness_fn=fitness, maximize=True)

maxIter=[10, 100, 500, 1000, 1500, 2000, 3000, 5000, 10000]
#maxIter=[10, 100]
maxAttempts=10
popSize=1000
muProb=0.1

print("Simulating Genetic Algorithm.......")
for i in range(len(maxIter)):
    if i==0:
        scoreFitnessGA=[]
        usageTimeGA=[]

    start_time = time.time()
    best_state_ga, best_fitness_ga, best_curve_ga=mlrose.genetic_alg(problem, max_iters=maxIter[i],
                            pop_size=popSize, mutation_prob=muProb, curve=True, max_attempts=maxAttempts, random_state = 3)

    usageTimeGA.append(time.time()-start_time);
    scoreFitnessGA.append(1/best_fitness_ga)

print("Simulating Random Hill Climbing Algorithm.......")
for i in range(len(maxIter)):
    if i==0:
        scoreFitnessRHC=[]
        usageTimeRHC=[]

    start_time = time.time()
    best_state_rhc, best_fitness_rhc, best_curve_rhc=mlrose.random_hill_climb(problem, max_iters=maxIter[i],
                                                                curve=True, max_attempts=maxAttempts, random_state = 3)

    usageTimeRHC.append(time.time()-start_time);
    scoreFitnessRHC.append(1/best_fitness_rhc)

print("Simulating Simulated Annealing Algorithm.......")
for i in range(len(maxIter)):
    if i==0:
        scoreFitnessSA=[]
        usageTimeSA=[]

    start_time = time.time()
    best_state_sa, best_fitness_sa, best_curve_sa=mlrose.simulated_annealing(problem, max_iters=maxIter[i],
                                                                curve=True, max_attempts=maxAttempts, random_state = 3)

    usageTimeSA.append(time.time()-start_time);
    scoreFitnessSA.append(1/best_fitness_sa)

print("Simulating MIMIC Algorithm.......")
for i in range(len(maxIter)):
    if i==0:
        scoreFitnessMM=[]
        usageTimeMM=[]

    start_time = time.time()
    best_state_mm, best_fitness_mm, best_curve_mm=mlrose.mimic(problem, max_iters=maxIter[i],
                                 keep_pct= 0.2, curve=True, max_attempts=maxAttempts, random_state = 3)

    usageTimeMM.append(time.time()-start_time);
    scoreFitnessMM.append(1/best_fitness_mm)

plt.figure('TWTesla_01')
plt.title('Fitness vs Iterations', fontsize=16);
plt.ylabel('Fitness', fontsize=14);
plt.xlabel('Number of Iterations', fontsize=14);
#plt.xlim(0, 100)
plt.ylim(0.003, 0.0035)
plt.plot(maxIter, scoreFitnessGA, 'go', label='Genetic Algorithm')
plt.plot(maxIter, scoreFitnessRHC, 'rs' , label='Random Hill Climbing')
plt.plot(maxIter, scoreFitnessSA, 'b*', label='Simulated Annealing')
plt.plot(maxIter, scoreFitnessMM, 'mD' , label='MIMIC')
plt.legend(loc='lower right', fontsize=12)
plt.savefig('./Plots/TWTesla_Fitness.png')
plt.show(block=False)

plt.figure('TWTesla_02')
plt.title('Run Time vs Iterations', fontsize=16);
plt.ylabel('Run Time (s)', fontsize=14);
plt.xlabel('Number of Iterations', fontsize=14);
#plt.xlim(0, 100)
#plt.ylim(-1, 20)
plt.yscale('log')
plt.plot(maxIter, usageTimeGA, 'go', label='Genetic Algorithm')
plt.plot(maxIter, usageTimeRHC, 'rs' , label='Random Hill Climbing')
plt.plot(maxIter, usageTimeSA, 'b*', label='Simulated Annealing')
plt.plot(maxIter, usageTimeMM, 'mD' , label='MIMIC')
plt.legend(loc='best', fontsize=12)
plt.savefig('./Plots/TWTesla_RunTime.png')
plt.show()


from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
import math

def calc(x):
	return str(math.log(abs(12*math.sin(int(x)))))

def main():
	try:
		browser = webdriver.Firefox()
		browser.get("http://suninjuly.github.io/explicit_wait2.html")

		button = WebDriverWait(browser, 12).until(
							 EC.text_to_be_present_in_element((By.ID, "price"), "$100"))

		browser.find_element_by_css_selector("button").click()

		browser.implicitly_wait(2)
		x = browser.find_element_by_id("input_value").text
		y = calc(x)

		browser.find_element_by_id("answer").send_keys(y)
		browser.find_element_by_id("solve").click()

		browser.implicitly_wait(10)
	finally:
		browser.quit()

if __name__ == "__main__":
	main()
	print("(.)(.)----------------Nice work!---------------(.)(.)")


import xlrd
from xlutils.copy import copy
import os

# ============================================
# 对excel进行封装
# 从excel文件中读取测试用例
# 向Excel写入测试结果
# ============================================

# 获取上级目录
# print(os.path.abspath(os.path.dirname(os.getcwd())))
test_data_dir = os.path.join(os.path.abspath(os.path.dirname(os.getcwd())), "testdata")
#print(test_data_dir)

class DoExcel():

    def __init__(self, file_name, sheet_name):
        '''
        初始化excel文件对象
        :param file_name: excel文件名
        :param sheet_name: sheet名
        '''
        self.file_name = os.path.join(test_data_dir, file_name);
        self.workbook = xlrd.open_workbook(self.file_name)
        self.sheet = self.workbook.sheet_by_name(sheet_name)

    def get_row_num(self, cols_num, case_id):
        '''
        获取指定测试用例id对应的行号
        :param cols_num: 测试用例id所在的列号
        :param case_id: 指定的测试用例id
        :return:
        '''
        # 获取指定列的所有的值
        cols = self.sheet.col_values(cols_num)

        row_num = 0
        for col_data in cols:
            if col_data == case_id:
                break
            row_num += 1
        return row_num

    def get_rowline_data(self, row):
        '''
        获取某一行的值
        :param row:
        :return:
        '''
        return self.sheet.row_values(row)

    def read_cell(self, row_num, col_num):
        return self.sheet.cell(row_num, col_num).value

    def write_excel(self, sheetnum, row, col, value):
        '''
        向excel中写数据
        :param sheetnum: sheet索引
        :param row: 行索引
        :param col: 列索引
        :param value: 要写入的值
        :return:
        '''
        new_workbook = xlrd.open_workbook(self.file_name)
        new_wbook = copy(new_workbook)
        sheet = new_wbook.get_sheet(sheetnum)

        sheet.write(row, col, value)
        new_wbook.save(self.file_name)

# =============================================================
# 测试代码，验证DoExcel的正确性
# =============================================================

if __name__ == "__main__":
    excel = DoExcel("case.xls", "Sheet1")
    row = excel.get_row_num(0, "bd-001")
    print(row)
    row_data = excel.get_rowline_data(row)
    print(row_data)
    print("=============================")

    excel.write_excel(0, 1, 6, "test")
    # 问题：为什么这里取到的是修改之前的值
    row_data1 = excel.get_rowline_data(row)
    print(row_data1)


'''
Created on Nov 28, 2016

@author: Stan
'''
import unittest
from domain.Student import Student
from validator.StudentValidator import StudentValidationException,\
    StudentValidator
"""Class that validates the StudentValidator"""

class Test(unittest.TestCase):

    """Function that tests if the Validator raises exception if the student id is string"""

    def testStudentValidatorIDstring(self):
        s=Student("a","b",3)
        SV=StudentValidator()
        self.assertRaises(StudentValidationException,SV.validate_student,s)

    """Function that tests if the Validator raises exception if the student id is negative"""

    def testStudentValidatorIDnegative(self):
        s=Student(-5,"b",3)
        SV=StudentValidator()
        self.assertRaises(StudentValidationException,SV.validate_student,s)

    """Function that tests if the Validator raises exception if the student id is empty"""

    def testStudentValidatorIDempty(self):
        s=Student("","b",3)
        SV=StudentValidator()
        self.assertRaises(StudentValidationException,SV.validate_student,s)

    """Function that tests if the Validator raises exception if the group is string"""

    def testStudentValidatorGroupString(self):
        s=Student(5,"b","c")
        SV=StudentValidator()
        self.assertRaises(StudentValidationException,SV.validate_student,s)

    """Function that tests if the Validator raises exception if the student name is empty"""

    def testStudentNameEmpty(self):
        s = Student(5, "", "c")
        SV = StudentValidator()
        self.assertRaises(StudentValidationException, SV.validate_student, s)

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()

Python/Fundamentals of Programming - 1st semester/Lab 5 - 7 with GUI/src/validator/Test_Student_Validator.py


# Copyright 2017 LasLabs Inc.
# Copyright 2017 ACSONE SA/NV.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError

class ProductProduct(models.Model):
    _inherit = 'product.product'

    is_contract = fields.Boolean('Is a contract')

class SaleOrderLine(models.Model):
    _inherit = 'sale.order.line'

    @api.multi
    def _prepare_contract_line_values(
        self, contract, predecessor_contract_line_id=False
    ):
        """
        :param contract: related contract
        :param predecessor_contract_line_id: contract line to replace id
        :return: new contract line dict
        """
        self.ensure_one()
        recurring_next_date = self.env[
            'contract.line'
        ]._compute_first_recurring_next_date(
            self.date_start or fields.Date.today(),
            self.recurring_invoicing_type,
            self.recurring_rule_type,
            1,
        )
        termination_notice_interval = (
            self.product_id.termination_notice_interval
        )
        termination_notice_rule_type = (
            self.product_id.termination_notice_rule_type
        )
        return {
            'sequence': self.sequence,
            'product_id': self.product_id.id,
            'name': self.name,
            # The quantity on the generated contract line is 1, as it
            # correspond to the most common use cases:
            # - quantity on the SO line = number of periods sold and unit
            #   price the price of one period, so the
            #   total amount of the SO corresponds to the planned value
            #   of the contract; in this case the quantity on the contract
            #   line must be 1
            # - quantity on the SO line = number of hours sold,
            #   automatic invoicing of the actual hours through a variable
            #   quantity formula, in which case the quantity on the contract
            #   line is not used
            # Other use cases are easy to implement by overriding this method.
            'quantity': self.product_uom_qty,
            'uom_id': self.product_uom.id,
            'price_unit': self.price_unit,
            'discount': self.discount,
            'date_end': self.date_end,
            'date_start': self.date_start or fields.Date.today(),
            'recurring_next_date': recurring_next_date,
            'recurring_interval': 1,
            'recurring_invoicing_type': self.recurring_invoicing_type,
            'recurring_rule_type': self.recurring_rule_type,
            'is_auto_renew': self.is_auto_renew,
            'auto_renew_interval': self.auto_renew_interval,
            'auto_renew_rule_type': self.auto_renew_rule_type,
            'termination_notice_interval': termination_notice_interval,
            'termination_notice_rule_type': termination_notice_rule_type,
            'contract_id': contract.id,
            'sale_order_line_id': self.id,
            'predecessor_contract_line_id': predecessor_contract_line_id,
            'analytic_account_id': self.order_id.analytic_account_id.id,
        }


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

import datetime, pytz
from odoo import models, fields, api, _
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT, float_compare

class HrAttendanceInherit(models.Model):
    _inherit = "hr.attendance"

    def _get_planned_check_in(self):
        planned_check_in = self.env['ir.config_parameter'].sudo().get_param('hr_attendance.planned_check_in')
        if planned_check_in:
            return planned_check_in
        else:
            return False

    def _get_planned_check_out(self):
        planned_check_out = self.env['ir.config_parameter'].sudo().get_param('hr_attendance.planned_check_out')
        if planned_check_out:
            return planned_check_out
        else:
            return False

    def _get_planned_overtime_affect_hour(self):
        planned_overtime_affect_hour = self.env['ir.config_parameter'].sudo().get_param('hr_attendance.planned_overtime_affect_hour')
        if planned_overtime_affect_hour:
            return planned_overtime_affect_hour
        else:
            return False

    def _get_planned_overtime_max_hour(self):
        planned_overtime_max_hour = self.env['ir.config_parameter'].sudo().get_param('hr_attendance.planned_overtime_max_hour')
        if planned_overtime_max_hour:
            return planned_overtime_max_hour
        else:
            return False

    def _get_max_allowed_check_in(self):
        max_allowed_check_in = self.env['ir.config_parameter'].sudo().get_param('hr_attendance.max_allowed_check_in')
        if max_allowed_check_in:
            return max_allowed_check_in
        else:
            return False

    def _get_max_allowed_hours_for_nursing_mother(self):
        max_allowed_hours_for_nursing_mother = self.env['ir.config_parameter'].sudo().get_param('hr_attendance.max_allowed_hours_for_nursing_mother')
        if max_allowed_hours_for_nursing_mother:
            return max_allowed_hours_for_nursing_mother
        else:
            return False

    planned_check_in = fields.Float(string='Planned check in', default=_get_planned_check_in)
    planned_check_out = fields.Float(string='Planned check out', default=_get_planned_check_out)
    planned_overtime_affect_hour = fields.Float(string='Planned overtime affect hour', default=_get_planned_overtime_affect_hour)
    planned_overtime_max_hour = fields.Float(string='Planned overtime max hour', default=_get_planned_overtime_max_hour)
    max_allowed_check_in = fields.Float(string='Max allowed check in', default=_get_max_allowed_check_in)
    max_allowed_hours_for_nursing_mother = fields.Float(string='Max allowed hours for nursing mother', default=_get_max_allowed_hours_for_nursing_mother)
    nursing_mother_remaining_hrs = fields.Float(string='Nursing mother remaining hours', default=_get_max_allowed_hours_for_nursing_mother)
    late_in = fields.Float(compute='_calc_late_in', string='Late in', store=True)
    early_out = fields.Float(compute='_calc_early_out', string='Early out', store=True)
    overtime = fields.Float(compute='_calc_overtime', string='Overtime', store=True)
    last_day_overtime = fields.Float(compute='_get_last_day_overtime', string='Last day overtime', store=True)
    att_date = fields.Date(compute='_get_att_date', store=True)

    @api.depends('check_in')
    def _get_att_date(self):
        for rec in self:
            if rec.check_in:
                rec.att_date = rec.check_in

    @api.depends('check_in', 'check_out', 'planned_check_in', 'last_day_overtime', 'max_allowed_check_in')
    @api.multi
    def _calc_late_in(self):
        user_tz = pytz.timezone(self.env.context.get('tz') or self.env.user.tz or 'UTC')
        utc_tz = pytz.timezone('UTC')
        for rec in self:
            if rec.check_in and rec.planned_check_in:
                # get check-in time
                check_in_time = utc_tz.localize(datetime.datetime.strptime(rec.check_in, DEFAULT_SERVER_DATETIME_FORMAT))
                check_in_time = check_in_time.astimezone(user_tz).time()
                check_in_time = check_in_time.hour+check_in_time.minute/60.0
                if float_compare(check_in_time, rec.planned_check_in, 2) == 1:
                    # check last day day overtime hours to deduct from the day after latency
                    if float_compare(check_in_time, rec.max_allowed_check_in, 2) in [0, -1] and rec.last_day_overtime:
                        late_in = check_in_time - rec.planned_check_in
                        if float_compare(late_in, rec.last_day_overtime, 2) in [0, 1]:
                            rec.late_in = late_in - rec.last_day_overtime
                        else:
                            rec.late_in = False
                    else:
                        rec.late_in = check_in_time - rec.planned_check_in

                    # check nursing mother allowance
                    if rec.late_in and rec.employee_id and rec.employee_id.gender == 'female' \
                            and rec.employee_id.is_nursing_mother and rec.max_allowed_hours_for_nursing_mother:
                        if float_compare(rec.late_in, rec.max_allowed_hours_for_nursing_mother, 2) in [0, -1]:
                            rec.nursing_mother_remaining_hrs = rec.max_allowed_hours_for_nursing_mother - rec.late_in
                            rec.late_in = False
                else:
                    rec.late_in = False

    @api.depends('check_out', 'check_in', 'planned_check_out', 'employee_id', 'nursing_mother_remaining_hrs')
    @api.multi
    def _calc_early_out(self):
        user_tz = pytz.timezone(self.env.context.get('tz') or self.env.user.tz or 'UTC')
        utc_tz = pytz.timezone('UTC')
        for rec in self:
            if rec.check_out and rec.planned_check_out:
                # get check-out time
                check_out_time = utc_tz.localize(
                    datetime.datetime.strptime(rec.check_out, DEFAULT_SERVER_DATETIME_FORMAT))
                check_out_time = check_out_time.astimezone(user_tz).time()
                check_out_time = check_out_time.hour + check_out_time.minute / 60.0
                if float_compare(check_out_time, rec.planned_check_out, 2) == -1:
                    # check nursing mother allowance
                    if rec.employee_id and rec.employee_id.gender == 'female' and rec.employee_id.is_nursing_mother and rec.max_allowed_hours_for_nursing_mother:
                        early_out = rec.planned_check_out - check_out_time
                        if float_compare(early_out, rec.nursing_mother_remaining_hrs, 2) in [0, -1]:
                            early_out = False
                        rec.early_out = early_out
                    else:
                        rec.early_out = rec.planned_check_out - check_out_time
                else:
                    rec.early_out = False

    @api.depends('check_out', 'planned_check_out', 'planned_overtime_affect_hour', 'planned_overtime_max_hour')
    @api.multi
    def _calc_overtime(self):
        user_tz = pytz.timezone(self.env.context.get('tz') or self.env.user.tz or 'UTC')
        utc_tz = pytz.timezone('UTC')
        for rec in self:
            if rec.check_out and rec.planned_check_out:
                # get check-in time
                check_out_time = utc_tz.localize(
                    datetime.datetime.strptime(rec.check_out, DEFAULT_SERVER_DATETIME_FORMAT))
                check_out_time = check_out_time.astimezone(user_tz).time()
                check_out_time = check_out_time.hour + check_out_time.minute / 60.0

                if float_compare(check_out_time, rec.planned_check_out, 2) == 1 and float_compare(check_out_time, rec.planned_overtime_affect_hour, 2) in [0, 1]:
                    if float_compare(check_out_time, rec.planned_overtime_max_hour, 2) in [1] and rec.planned_overtime_max_hour:
                        rec.overtime = rec.planned_overtime_max_hour - rec.planned_overtime_affect_hour
                    else:
                        rec.overtime = check_out_time - rec.planned_overtime_affect_hour
                else:
                    rec.overtime = False

    @api.depends('check_in','employee_id')
    @api.multi
    def _get_last_day_overtime(self):
        for rec in self:
            # we take the latest overtime before our check_in time
            last_attendance_before_check_in = self.env['hr.attendance'].search([
                ('employee_id', '=', rec.employee_id.id),
                ('check_in', '<', rec.check_in)
            ], order='check_in desc', limit=1)
            if last_attendance_before_check_in and last_attendance_before_check_in.overtime:
                rec.last_day_overtime = last_attendance_before_check_in.overtime


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May  6 11:26:55 2020

@author: Izak de Heer
"""

from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import (QWidget, QPushButton, QRadioButton, QVBoxLayout,
                             QCheckBox, QGridLayout, QGroupBox, QTabWidget,
                             QGraphicsView, QGraphicsScene, QListWidget, QLabel)
from PyQt5.QtCore import QThread, pyqtSignal, QSize, Qt

import pyqtgraph as pg
from pyqtgraph import QtGui

import sys

import numpy as np

class DrawingWidget(pg.ImageView):

    def __init__(self, parent=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.flag_is_drawing = False
        self.new_roi = False

        self.vertices = []
        self.roilist = []
        self.pen = QtGui.QPen(QtCore.Qt.yellow)
        self.ui_widget = parent

        self.ui.roiBtn.hide()
        self.ui.menuBtn.hide()
        self.ui.normGroup.hide()
        self.ui.roiPlot.hide()

        self.parent = parent

    def append_to_roilist(self, roi):
        self.roilist.append(roi)

    def clear_rois(self):
        for roi in self.roilist:
            self.scene.removeItem(roi)

        self.roilist = []

    def enable_drawing(self, val):
        if val:
            self.scene.sigMouseMoved.connect(self.mouseMoveEventDrawing)
            # self.scene.sigMouseClicked.connect(self.mousePressEventDrawing)
        else:
            try:
                self.scene.sigMouseMoved.disconnect(self.mouseMoveEventDrawing)
                # self.scene.sigMouseClicked.disconnect(self.mousePressEventDrawing)
            except TypeError:
                pass

    # def mousePressEventDrawing(self, e):
    #     if self.flag_is_drawing:
    #         self.flag_is_drawing = False
    #     else:
    #         self.new_roi = True
    #         self.flag_is_drawing = True
    #         self.start_point = self.getView().mapToView(e.pos())

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Space:
            if self.flag_is_drawing:
                self.flag_is_drawing = False
            else:
                self.flag_is_drawing = True
                self.new_roi = True

    def mouseMoveEventDrawing(self, pos):
        if not self.flag_is_drawing:
            return

        point = self.getView().mapToView(pos)

        if self.new_roi:
            self.start_point = self.getView().mapToView(pos)

            self.selectedroi = pg.graphicsItems.ROI.PolyLineROI(positions=[self.start_point, point])
            self.roilist.append(self.selectedroi)

            self.selectedroi.setPen(self.pen)
            self.getView().addItem(self.selectedroi)
            self.new_roi = False

        else:
            self.selectedroi.addFreeHandle(point)

            # Remove closing segment of previous mouse movement
            if len(self.selectedroi.segments) > 1:
                self.selectedroi.removeSegment(self.selectedroi.segments[-1])

            self.selectedroi.addSegment(self.selectedroi.handles[-1]['item'], self.selectedroi.handles[-2]['item'])

            # Add new closing segment
            self.selectedroi.addSegment(self.selectedroi.handles[0]['item'], self.selectedroi.handles[-1]['item'])

    def resizeEvent(self, event):
        """
        Forces the widget to be square upon resize event
        """
        # Create a square base size of 10x10 and scale it to the new size
        # maintaining aspect ratio.
        new_size = QSize(10, 10)
        new_size.scale(event.size(), Qt.KeepAspectRatio)
        self.resize(new_size)


# -*- coding: utf-8 -*-
"""
deepecoach
~~~~~~~~~~~~~~~~~~~

Deep neural approach to Boundary and Disfluency Detection.

:copyright: (c) 2017 by Marcos Treviso
:licence: MIT, see LICENSE for more details
"""
from __future__ import absolute_import, unicode_literals
import logging

# Generate your own AsciiArt at:
# patorjk.com/software/taag/#f=Calvin%20S&t=deepecoach
__banner__ = r"""
╔╦╗┌─┐┌─┐┌─┐
 ║║├┤ ├┤ ├─┘ by Mehedi Hasan
═╩╝└─┘└─┘┴
"""

__prog__ = "deepecoach"
__title__ = 'DeepEcoach'
__summary__ = 'Deep neural approach for text segmentation'
__uri__ = 'https://github.com/teanalab/eCoaching-Text-Segmentation'

__version__ = '0.0.1-alpha'

__author__ = 'Mehedi Hasan'
__email__ = 'mehedi@wayne.edu'

__license__ = 'MIT'
__copyright__ = 'Copyright 2018 Mehedi Hasan'

# the user should dictate what happens when a logging event occurs
logging.getLogger(__name__).addHandler(logging.NullHandler())

# imports
from . import error_analysis
from . import train
from .pipeline import Pipeline


#!/usr/bin/python
#-*- coding: UTF-8 -*-
#
# @file: logger.py
#   python2.7.x logger function
#
# @create: 2017-12-08
#
# @update: 2019-03-15 11:55:28
#
################################################################################

def set_logger(logger, log_path, log_level):
    import os, sys
    import utility as util
    import evntlog as elog

    log_level = log_level.strip().upper()

    if log_level not in ['TRACE', 'DEBUG', 'INFO', 'WARN', 'ERROR']:
        util.error("log level(=%r) not one of: TRACE | DEBUG | INFO | WARN | ERROR" % log_level)
        sys.exit(-1)

    # set logger:
    logpath = util.source_abspath(log_path)
    if not os.path.isdir(logpath):
        util.error("log path not found: %r" % logpath)
        sys.exit(-1)

    logging_config = logger['logging_config']
    if not util.file_exists(logging_config):
        util.error("logging.config file not found: %s" % logging_config)
        sys.exit(-1)

    # init logger: main
    try:
        logger_file = os.path.join(logpath, logger['file'])

        loggingConfigDict = elog.init_logger(
            logger_name = logger['name'],
            logging_config = logging_config,
            logger_file = logger_file,
            logger_level = log_level)

        elog.force("logging config : %s", logging_config)
        elog.force("logger file    : %s", logger_file)
        elog.force("logger level   : %s", log_level)
        elog.force("logger name    : %s", logger['name'])

        if not loggingConfigDict:
            util.error("logging config file error: %s" % logging_config)
            sys.exit(-1)

        return loggingConfigDict
    except Exception as ex:
        util.error("error init logger: %r" % ex)
        sys.exit(-1)


#calss header
class _SURVEY():
	def __init__(self,):
		self.name = "SURVEY"
		self.definitions = [u'to look at or examine all of something, especially carefully: ', u'to measure an area of land, and to record the details of it, especially on a map: ', u'If a building is surveyed, it is examined carefully by a specially trained person, in order to discover if there is anything wrong with its structure.', u'to ask people questions in order to find out about their opinions or behaviour: ']

		self.parents = []
		self.childen = []
		self.properties = []
		self.jsondata = {}

		self.specie = 'verbs'

	def run(self, obj1 = [], obj2 = []):
		return self.jsondata


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

# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.

# Importing Libraries

import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State

import plotly.express as px
import pandas as pd
import plotly.graph_objects as go
from datetime import date
from time import time
import datetime as dt
import calendar

external_stylesheets = ['https://stackpath.bootstrapcdn.com/bootswatch/4.5.2/superhero/bootstrap.min.css', "https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css", 'styles.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.config.suppress_callback_exceptions = True

#Reading the dataset to get all the meters and append the names with '_results' for further use
df_labels = pd.read_excel("../data/Analysis/Meter Names and Labels.xlsx")

names_cleaned = []

for item in df_labels["Name"]:
    name = item.split("-")[0].replace("'", "").replace(" ", "").strip()
    if name == "JacksonLibraryTower_kWh":
        name = "JacksonLibraryTower"
    names_cleaned.append(name)

df_labels["Names_cleaned"] = names_cleaned

# the style arguments for the sidebar. We use position:fixed and a fixed width
SIDEBAR_STYLE = {
    "position": "fixed",
    "top": 0,
    "left": 0,
    "bottom": 0,
    "width": "16rem",
    "padding": "2rem 1rem",
    "backgroundColor": "#ffb71b",
    "color": "#0f2044"
}

# the styles for the main content position it is to the right of the sidebar and
# add some padding.
CONTENT_STYLE = {
    "marginLeft": "18rem",
    "marginRight": "2rem",
    "backgroundColor": "#0f2044",
    "fontFamily": "Sofia Pro"
}

NAVLINK = {
    "color": "#0f2044"
}

NAVLINK_ACTIVE = {
    "color": "#fff",
    "backgroundColor": "#0f2044"
}

LAYOUT = {
    "backgroundColor": "#0f2044",
    "fontFamily": "Sofia Pro",
    "height": "100vh"
}

DROPDOWN = {
    "color": "black"
}

LABEL = {
    "height": "25px"
}

HEADER = {
    "fontWeight": "bold",
}

SUBTITLE = {
    "color": "#fff",
    "fontWeight": "bold"
}

CONTENT_HEADER = {
    "paddingTop": "1rem",
    "color": "#ffb71b",
    "fontSize": "x-large"
}

HELP = {
    "fontSize": "x-large",
}

HELP_BUTTON = {
    "margin": "1rem",
    "backgroundColor":"#0f2044"
}

MODAL = {
    "backgroundColor":"#fff"
}

# Sidebar Layout
sidebar = html.Div(
    [
        html.H4("Hackathon", className="display-6", style=HEADER),
        html.Hr(),
        html.P(
            "Funded by the UNCG Green Fund", className="lead", style=SUBTITLE
        ),
        dbc.Nav(
            [
                dbc.NavLink("Energy Consumption & Prediction", href="/task-1", id="page-1-link", style=NAVLINK, className="navlink-active"),
                dbc.NavLink("Average Predictions By Group", href="/task-2", id="page-2-link", style=NAVLINK, className="navlink-active"),
            ],
            vertical=True,
            pills=True
        ),
    ],
    style=SIDEBAR_STYLE,
)

content = html.Div(id="page-content", style=CONTENT_STYLE)

# Layout for Task-1
content_T1_layout = html.Div([
    dbc.Container([
        html.Br(),
        dbc.Row(
            [
                dbc.Col(
                    html.Span([
                            html.Span("Energy Consumption & Prediction", style=CONTENT_HEADER),
                            html.Span([
                                html.A(html.I(className="fa fa-question-circle", style=HELP), id="open", style=HELP_BUTTON, title="Help"),
                                dbc.Modal(
                                    [
                                        dbc.ModalHeader("Help"),
                                        dbc.ModalBody([
                                            html.H5("Energy consumption- Actual and Predicted"),
                                            html.Div([
                                                html.P("User should select a meter or multiple meters for which they want to visualise the graph"),
                                                html.Div([
                                                    html.P("Then select a time interval which has the options Hour, Week, Month, Day and Time."),
                                                    html.P("1. Hour: Please select to and from dates and to and from hours(Note: Select dates which are less then 6 months to check the hourly consumption otherwise it may take a longer time to load)."),
                                                    html.P("2. Week: Once you click on week you will get Year and Week dropdown and you can select both the options and you can see the consumption graph for the weeks of the selected year."),
                                                    html.P("3. Month: Once you select the dates from the datepicker, you will get all the months consumption for that specific period of time."),
                                                    html.P("4. Year: Once you select the dates from the datepicker, you will get the years consumption for the selected period of time."),
                                                    html.P("5. Day: Once you select the to and from dates from the datepicker you will get the daily consumption of all the dates between the selected dates."),
                                                ], className="HelpSubText"),
                                                html.P("User can choose from average and total consumption for all the above graphs from the dropdown."),
                                                html.P("We have a Predictions checkbox if you click that user will get the actual and predicted graph for all the above conditions. And for the hourly consumption we have the displayed prediction interval too."),
                                                html.P("We also have a range slider for all the graphs where the user can shrink to to see detailed data.")

                                            ], className="HelpText"),

                                        ]
                                        ),
                                        dbc.ModalFooter(
                                            dbc.Button("Close", id="close", className="ml-auto")
                                        ),
                                    ],
                                    id="modal",
                                    size="xl",
                                    className= "mymodel"
                                )
                                ])])
                )
            ]
        ),
        html.Br(),
        dbc.Row(
            [
                dbc.Col(
                    html.P("Meters :"),
                    style=LABEL
                )
            ]
        ),
        dbc.Row(
            [
                dbc.Col(
                    dcc.Dropdown(
                        id="meters",
                        options=[{"label": row['Label'], "value": row['Names_cleaned']}
                                 for index, row in df_labels.iterrows()],
                        value=[df_labels["Names_cleaned"][0]],
                        clearable=False,
                        multi=True,
                        style=DROPDOWN,
                        className="multi-dropdown-custom"

                    ),

                ),

            ],
            align="start",
        ),
        html.Br(),
        dbc.Row(
            [
                dbc.Col(
                    html.P("Time Interval :"),
                    style=LABEL
                ),

                dbc.Col(
                    html.P("Average/Total Consumption :"),
                    style=LABEL
                )
            ]
        ),
        dbc.Row(
            [
                dbc.Col(

                    dcc.Dropdown(
                        id="option-dropdown",
                        options=[
                            {'label': 'Year', 'value': 'year'},
                            {'label': 'Month', 'value': 'month'},
                            {'label': 'Week', 'value': 'week'},
                            {'label': 'Day', 'value': 'day'},
                            {'label': 'Hour', 'value': 'hour'},
                        ],
                        value='hour',
                        clearable=False,
                        style=DROPDOWN,
                        className="dropdown-custom"
                    )
                ),
                dbc.Col(

                    dcc.Dropdown(
                        id="demo-dropdown",
                        options=[
                            {'label': 'Total Consumption', 'value': 'TC'},
                            {'label': 'Average Consumption', 'value': 'AC'}
                        ],
                        value='TC',
                        clearable=False,
                        style=DROPDOWN,
                        className="dropdown-custom"
                    )
                )

            ],
            align="start",
        ),
        html.Br(),
        html.Div([
            dbc.Row(
                [
                    dbc.Col(
                        html.P("Year :"),
                        style=LABEL
                    ),
                    dbc.Col(
                        html.P("Week :"),
                        style=LABEL
                    )
                ]
            ),

            dbc.Row(
                [
                    dbc.Col(
                        dcc.Dropdown(
                            id="year-dropdown",
                            options=[
                                {'label': x, 'value': x, 'disabled': False}
                                for x in range(2015, 2022)
                            ],
                            value=['2018', '2019'],
                            multi=True,
                            clearable=True,
                            style=DROPDOWN,
                            className="dropdown-custom"
                        )
                    ),
                    dbc.Col(
                        dcc.Dropdown(
                            id="week-dropdown",
                            options=[
                                {'label': x, 'value': x, 'disabled': False}
                                for x in range(1, 53)
                            ],
                            value=['30', '35'],
                            multi=True,
                            clearable=True,
                            style=DROPDOWN,
                            className="dropdown-custom"

                        )
                    ),

                ],
                align="start",
            ), ], id='datatable-container'),
        html.Br(),
        html.Div([
        dbc.Row(
            [
                dbc.Col(
                    html.P("Date :"),
                    style=LABEL
                ),
                dbc.Col(
                    html.P("Start Time (in hours) :"),
                    style=LABEL
                ),
                dbc.Col(
                    html.P("End Time (in hours) :"),
                    style=LABEL
                ),

            ]
        ),

        dbc.Row(
            [
                dbc.Col(

                    dcc.DatePickerRange(
                        id='my-date-picker-range',
                        min_date_allowed=date(1995, 8, 5),
                        max_date_allowed=date(2021, 11, 12),
                        initial_visible_month=date(2015, 1, 1),
                        start_date=date(2020, 1, 1),
                        end_date=date(2020, 1, 2),
                        className="date-picker-custom"
                    )

                ),
                dbc.Col(
                    dcc.Dropdown(
                        id="start-hour-dropdown",
                        options=[{'label': str(x), 'value': str(x), 'disabled': False}
                                 for x in range(0, 24)],
                        value='0',
                        multi=False,
                        style=DROPDOWN,
                        className="dropdown-custom"
                    )
                ),
                dbc.Col(
                    dcc.Dropdown(
                        id="end-hour-dropdown",
                        options=[{'label': str(x), 'value': str(x), 'disabled': False}
                                 for x in range(0, 24)],
                        value='23',
                        multi=False,
                        style=DROPDOWN,
                        className="dropdown-custom"
                    )
                )

            ],
            align="start",
        ),],id="datatable-container4"),
        html.Br(),
        dbc.Row(
            [
                dbc.Col(

                    dcc.Checklist(
                        id="prediction-checklist",
                        options=[
                            {'label': 'Predictions', 'value': 'Predictions'}
                        ],
                        value=['Predictions']
                    ),

                ),

            ],
            align="start",
        ),
        html.Div(id='dd-output-container'),
        html.Br(),
        html.Div(
            [
                dcc.Loading(
                    id="loading-2",
                    children=[html.Div([html.Div(id="loading-output-2")])],
                    type="circle"
                ),
                dcc.Graph(id='task1_map', figure={})
            ]
        )
    ])
])

# Layout for Task-2
content_T2_layout = html.Div([
    dbc.Container([
        html.Br(),
        dbc.Row(
            [
                dbc.Col(
                    html.Span([
                            html.Span("Average Predictions By Group", style=CONTENT_HEADER),
                            html.Span([
                                html.A(html.I(className="fa fa-question-circle", style=HELP), id="open", style=HELP_BUTTON, title="Help"),
                                dbc.Modal(
                                    [
                                        dbc.ModalHeader("Help"),
                                        dbc.ModalBody([
                                            html.H5("Average Predictions By Group"),
                                            html.Div([
                                                html.P("We choose a time category and we get the graph visualised based on that."),
                                                html.P("For example, if the user chooses hour of day, the Bryan Building meter. The graph would plot the average actual and average predicted consumption in Bryan from for the year 2020 by hour of the day. There would be one observation per hour in a day (24 total)."),
                                            ], className="HelpText"),

                                        ]
                                        ),
                                        dbc.ModalFooter(
                                            dbc.Button("Close", id="close", className="ml-auto")
                                        ),
                                    ],
                                    id="modal",
                                    size="xl",
                                    className= "mymodel"
                                )
                                ])])
                )
            ]
        ),
        html.Br(),
        dbc.Row(
            [
                dbc.Col(
                    html.P("Meters :"),
                    style=LABEL
                )
            ]
        ),
        dbc.Row(
            [
                dbc.Col(
                    dcc.Dropdown(
                        id="meters_2",
                        options=[{"label": row['Label'], "value": row['Names_cleaned']}
                                 for index, row in df_labels.iterrows()],
                        value=[df_labels["Names_cleaned"][0]],
                        clearable=False,
                        multi=True,
                        style=DROPDOWN,
                        className="multi-dropdown-custom"
                    ),

                ),

            ],
            align="start",
        ),
        html.Br(),
        dbc.Row(
            [
                dbc.Col(
                    html.P("Choose a time category :"),
                    style=LABEL
                ),

            ]
        ),
        dbc.Row(
            [
                dbc.Col(

                    dcc.Dropdown(id='choice_dropdown',
                                 options=[
                                     {'label': 'Hour of Day', 'value': 'hour'},
                                     {'label': 'Day of Week', 'value': 'day'},
                                     {'label': 'Week of Year', 'value': 'week'},
                                     {'label': 'Month of Year', 'value': 'month'},
                                 ],
                                 value='month',
                                 clearable=False,
                                 style=DROPDOWN,
                                 className="dropdown-custom"
                                 ),

                ),

            ],
            align="start",
        ),
        html.Br(),
        dbc.Row(
            [
                dbc.Col(
                    html.P("From Year :"),
                    style=LABEL
                ),
                dbc.Col(
                    html.P(" Month :"),
                    style=LABEL
                ),
                dbc.Col(
                    html.P("To Year :"),
                    style=LABEL
                ),
                dbc.Col(
                    html.P(" Month :"),
                    style=LABEL
                ),

            ]
        ),
        dbc.Row(
            [
                dbc.Col(
                        dcc.Dropdown(
                            id="from-year-dropdown",
                            options=[{'label':'2020', 'value': '2020', 'disabled': False}],
                            value='2020',
                            multi=False,
                            style=DROPDOWN,
                            className="dropdown-custom",
                            clearable=False
                        )
                ),
                dbc.Col(
                    dcc.Dropdown(
                        id="from-month-dropdown",
                        options=[{'label':calendar.month_name[x] , 'value': str(x), 'disabled': False}
                                 for x in range(1, 12)],
                        value='1',
                        multi=False,
                        style=DROPDOWN,
                        className="dropdown-custom",
                        clearable=False
                    )
                ),
                dbc.Col(
                    dcc.Dropdown(
                        id="to-year-dropdown",
                        options=[{'label': '2020', 'value': '2020', 'disabled': False}],
                        value='2020',
                        multi=False,
                        style=DROPDOWN,
                        className="dropdown-custom",
                        clearable=False
                    )
                ),
                dbc.Col(
                    dcc.Dropdown(
                        id="to-month-dropdown",
                        options=[{'label': calendar.month_name[x], 'value': str(x), 'disabled': False}
                                 for x in range(1, 12)],
                        value='7',
                        multi=False,
                        style=DROPDOWN,
                        className="dropdown-custom",
                        clearable=False
                    )
                ),

            ],
            align="start",
        ),
        html.Br(),
        html.Div(id='dummy-container'),
        dcc.Graph(id='task2_map', figure={})
    ])
])

# App Layout
app.layout = html.Div([
    dcc.Location(id="url"),
    sidebar,
    content
], style=LAYOUT)

# this callback uses the current pathname to set the active state of the
# corresponding nav link to true, allowing users to tell which page they are on
@app.callback(
    [Output(f"page-{i}-link", "active") for i in range(1, 3)],
    [Input("url", "pathname")],
)

def toggle_active_links(pathname):
    if pathname == "/":
        # Treat page 1 as the homepage / index
        return True, False
    return [pathname == f"/task-{i}" for i in range(1, 3)]

#Callback for navbar
@app.callback(Output("page-content", "children"), [Input("url", "pathname")])
def render_page_content(pathname):
    if pathname in ["/", "/task-1"]:
        return content_T1_layout
    elif pathname == "/task-2":
        return content_T2_layout
    return dbc.Jumbotron(
        [
            html.H1("404: Not found", className="text-danger"),
            html.Hr(),
            html.P(f"The pathname {pathname} was not recognised..."),
        ]
    )

@app.callback(
    Output("modal", "is_open"),
    [Input("open", "n_clicks"), Input("close", "n_clicks")],
    [State("modal", "is_open")],
)
def toggle_modal(n1, n2, is_open):
    if n1 or n2:
        return not is_open
    return is_open

# Callbacks for Task-1

#Callback to display only year and week when week is selected
@app.callback(
    dash.dependencies.Output('datatable-container', 'style'),
    [dash.dependencies.Input('option-dropdown', 'value')])
def toggle_container3(toggle_value):
    if toggle_value == 'week':
        return {'display': 'block'}
    else:
        return {'display': 'none'}

#Callback to display datepicker when options other than week are selected
@app.callback(
    dash.dependencies.Output('datatable-container4', 'style'),
    [dash.dependencies.Input('option-dropdown', 'value')])
def toggle_container1(toggle_value):
    if toggle_value == 'year' or toggle_value == 'month' or toggle_value == 'day' or toggle_value == 'hour':
        return {'display': 'block'}
    else:
        return {'display': 'none'}

#Callback for the task
@app.callback(
    [dash.dependencies.Output("loading-output-2", "figure"),
     dash.dependencies.Output('dd-output-container', 'string_prefix'),
     dash.dependencies.Output('task1_map', 'figure')],
    [dash.dependencies.Input('meters', 'value'),
     dash.dependencies.Input('option-dropdown', 'value'),
     dash.dependencies.Input('demo-dropdown', 'value'),
     dash.dependencies.Input('my-date-picker-range', 'start_date'),
     dash.dependencies.Input('my-date-picker-range', 'end_date'),
     dash.dependencies.Input('start-hour-dropdown', 'value'),
     dash.dependencies.Input('end-hour-dropdown', 'value'),
     dash.dependencies.Input('prediction-checklist', 'value'),
     dash.dependencies.Input('year-dropdown', 'value'),
     dash.dependencies.Input('week-dropdown', 'value')
     ])
#Inputs in the form
def update_output(meters, selected_value, value, start_date, end_date, start_hour, end_hour, pred_, year, week):
    start_time = time()
    string_prefix = 'You have selected: '
    if start_date is not None:
        start_date_object = date.fromisoformat(start_date)
        mytime = dt.datetime.strptime(start_hour, '%H').time()
        start_datetime_object = dt.datetime.combine(start_date_object, mytime)
        start_date_string = start_datetime_object.strftime('%B %d, %Y  %H:%M')
        string_prefix = string_prefix + 'Start Date: ' + start_date_string + ' | '
    if end_date is not None:
        end_date_object = date.fromisoformat(end_date)
        mytime = dt.datetime.strptime(end_hour, '%H').time()
        end_datetime_object = dt.datetime.combine(end_date_object, mytime)
        end_date_string = end_datetime_object.strftime('%B %d, %Y %H:%M')
        string_prefix = string_prefix + 'End Date: ' + end_date_string
    if len(string_prefix) == len('You have selected: '):
        string_prefix = 'Select a date to see it displayed here'

#Funtion to get all the date parameters
    def f(df):
        # df = df.copy()
        # df['Datetime'] = df['Datetime']
        df['Date'] = df['Datetime'].dt.strftime('%Y-%m-%d')
        df['Year'] = df['Datetime'].dt.year
        df['Month'] = df['Datetime'].dt.strftime('%Y-%m')
        df['Week'] = df['Datetime'].dt.week
        df['Day'] = df['Datetime'].dt.strftime('%Y-%m-%d')
        df['Hour'] = df['Datetime'].dt.strftime('%Y-%m-%d %H')
        df['Year-Week'] = df['Datetime'].dt.week.astype(str) + '-' +  df['Datetime'].dt.year.astype(str)
        return df

    layout = go.Layout(
        autosize=False,
        height=350,

        xaxis=go.layout.XAxis(linecolor='black',
                              linewidth=1,
                              mirror=True),

        yaxis=go.layout.YAxis(linecolor='black',
                              linewidth=1,
                              mirror=True)

    )

    fig = go.Figure(layout=layout)

    #Looping through the selected meters
    for meter in meters:

        df_meter = pd.read_csv("../data/Analysis/" + meter + "_results.csv")
        df_meter['Datetime'] = pd.to_datetime(df_meter['Datetime'], utc=True)
        df_week_meter = pd.read_csv("../data/Analysis/" + meter + "_results.csv")
        df_week_meter['Datetime'] = pd.to_datetime(df_meter['Datetime'], utc=True)
        df_meter = df_meter[(df_meter['Datetime'] >= pd.to_datetime(start_datetime_object, utc=True)) &
                            (df_meter['Datetime'] <= pd.to_datetime(end_datetime_object, utc=True))]

        df_meter = f(df_meter)
        df_week_meter = f(df_week_meter)
        #Logic for the selected paraemeters
        # df_meter['Date'] = df_meter.Datetime.apply(lambda d: d.split(" ", 1)[0])
        if value == 'TC':
            y_label = "Total Energy Consumption"
            if selected_value == 'week':
                x_label = "Week"
                fig_title = "Total Energy Consumption for each week"
                df_selected = df_week_meter[df_week_meter['Year'].isin(year)]
                df_selected = df_selected[df_selected['Week'].isin(week)]
                df_selected = df_selected.groupby("Year-Week").agg(
                    {'Hour': 'count', 'Actual': 'sum', 'Predicted': 'sum'}).reset_index()
                x = df_selected["Year-Week"]
            elif selected_value == 'day':
                x_label = "Day"
                fig_title = "Total Energy Consumption for each day"
                df_selected = df_meter.groupby(["Date"]).sum().reset_index()
                x = df_selected["Date"]
            elif selected_value == 'hour':
                x_label = "Hour"
                fig_title = "Total Energy Consumption for each hour"
                df_selected = df_meter
                x = df_selected["Hour"]
            elif selected_value == 'month':
                x_label = "Month"
                fig_title = "Total Energy Consumption for each month"
                df_selected = df_meter.groupby(["Month"]).sum().reset_index()
                x = df_selected["Month"]
            else:
                x_label = "Year"
                fig_title = "Total Energy Consumption for each year"
                df_selected = df_meter.groupby(["Year"]).sum().reset_index()
                x = df_selected["Year"]
        else:
            y_label = "Average Hourly Energy Consumption"
            if selected_value == 'week':
                x_label = "Week"
                fig_title = "Average Hourly Energy Consumption by week"
                df_selected = df_week_meter[df_week_meter['Year'].isin(year)]
                df_selected = df_selected[df_selected['Week'].isin(week)]
                df_selected = df_selected.groupby("Year-Week").agg(
                    {'Hour': 'count', 'Actual': 'mean', 'Predicted': 'mean'}).reset_index()
                x = df_selected["Year-Week"]
            elif selected_value == 'day':
                x_label = "Day"
                fig_title = "Average Hourly Energy Consumption by day"
                df_selected = df_meter.groupby(["Date"]).mean().reset_index()
                x = df_selected["Date"]
            elif selected_value == 'hour':
                x_label = "Hour"
                fig_title = "Average Hourly Energy Consumption by hour"
                df_selected = df_meter
                x = df_selected["Hour"]
            elif selected_value == 'month':
                x_label = "Month"
                fig_title = "Average Hourly Energy Consumption by month"
                df_selected = df_meter.groupby(["Month"]).mean().reset_index()
                x = df_selected["Month"]
            else:
                x_label = "Year"
                fig_title = "Average Hourly Energy Consumption by year"
                df_selected = df_meter.groupby(["Year"]).mean().reset_index()
                x = df_selected["Year"]

        #Plotting the Pedictions
        if len(pred_) != 0:
            fig.add_trace(go.Scatter(
                name=meter + ' Actual',
                mode='markers', x=x, y=df_selected["Actual"]
            ))

            fig.add_trace(go.Scatter(
                name=meter + ' Predicted',
                mode="markers+lines", x=x, y=df_selected["Predicted"]
            ))

            if selected_value == 'hour':
                fig.add_trace(go.Scatter(
                    name=meter + ' Lower',
                    mode="lines", x=x, y=df_selected["obs_ci_lower"],
                    fill="tonexty",
                    marker={"color": "rgba(135, 206, 250, 0.1)"},
                ))

                fig.add_trace(go.Scatter(
                    name=meter + ' Upper',
                    mode="lines", x=x, y=df_selected["obs_ci_upper"],
                    fill="tonexty",
                    marker={"color": "rgba(135, 206, 250, 0.1)"},
                ))

        else:
            fig.add_trace(go.Scatter(
                name=meter,
                mode="markers+lines", x=x, y=df_selected["Actual"]
            ))

    fig.update_xaxes(
        rangeslider_visible=True,
        rangeselector=dict(
            buttons=list([
                dict(count=1, label="1d", step="day", stepmode="backward"),
                dict(count=1, label="1m", step="month", stepmode="backward"),
                dict(count=6, label="6m", step="month", stepmode="backward"),
                dict(count=1, label="YTD", step="year", stepmode="todate"),
                dict(count=1, label="1y", step="year", stepmode="backward"),
                dict(step="all")
            ])
        )
    )
    string_prefix = string_prefix + "; response time is {:04f} seconds".format(time() - start_time)

    fig.update_layout(title=fig_title, xaxis_title=x_label, yaxis_title=y_label, legend_title="Meters",)

    return fig, string_prefix, fig

#Callback for task 2
@app.callback(
    [dash.dependencies.Output('task2_map', 'figure')],
    [dash.dependencies.Input('meters_2', 'value'),
     dash.dependencies.Input('choice_dropdown', 'value'),
     dash.dependencies.Input('from-year-dropdown', 'value'),
     dash.dependencies.Input('from-month-dropdown', 'value'),
     dash.dependencies.Input('to-year-dropdown', 'value'),
     dash.dependencies.Input('to-month-dropdown', 'value')])

#Inputs from the form
def update_output_2(meters, category_value, start_year, start_month, end_year, end_month):

    start_date_object = dt.datetime.strptime(start_year+start_month, "%Y%m").date()
    end_date_object = dt.datetime.strptime(end_year + end_month + str(calendar.monthrange(int(end_year), int(end_month))[1]), "%Y%m%d").date()

    def f(df):
        # df = df.copy()
        # df['Datetime'] = df['Datetime']
        df['Month'] = df['Datetime'].dt.month
        df['Weekday'] = df['Datetime'].apply(lambda t: t.weekday())
        df['Week'] = df['Datetime'].dt.week
        df['Day'] = df['Datetime'].dt.day
        df['Hour'] = df['Datetime'].dt.hour
        df['Year-Week'] = df['Datetime'].dt.year.astype(str) + '-' + df['Datetime'].dt.week.astype(str)
        return df

    layout = go.Layout(
            autosize=False,
            height=500,

            xaxis=go.layout.XAxis(linecolor='black',
                                  linewidth=1,
                                  mirror=True,),

            yaxis=go.layout.YAxis(linecolor='black',
                                  linewidth=1,
                                  mirror=True),
        )

    fig = go.Figure(layout=layout)

    for meter in meters:

        df_meter = pd.read_csv("../data/Analysis/" + meter + "_results.csv")
        df_meter['Datetime'] = pd.to_datetime(df_meter['Datetime'], utc=True)
        df_meter = df_meter[(df_meter['Datetime'] >= pd.to_datetime(start_date_object, utc=True)) &
                            (df_meter['Datetime'] <= pd.to_datetime(end_date_object, utc=True))]
        df_meter = f(df_meter)

        # df_meter['Date'] = df_meter.Datetime.apply(lambda d: d.split(" ", 1)[0])
        if category_value == 'month':
            df_selected = df_meter.groupby("Month").mean().reset_index()
            x = df_selected["Month"]
            fig_title = "Usage on basis of Month of the Year"
            x_title = "Month"
        if category_value == 'day':
            fig_title = "Usage on basis of Day of the Week"
            df_selected = df_meter.groupby("Weekday").mean().reset_index()
            x = df_selected["Weekday"]
            x_title = "Day"
        elif category_value == 'hour':
            fig_title = "Usage on basis of Hour of the Day"
            df_selected = df_meter.groupby(["Hour"]).mean().reset_index()
            x = df_selected["Hour"]
            x_title = "Hour"
        elif category_value == 'week':
            fig_title = "Usage on basis of Week of the Year"
            df_selected = df_meter.groupby(["Week"]).mean().reset_index()
            x = df_selected["Week"]
            x_title = "Week"

        fig.add_trace(go.Scatter(
            name=meter + ' Actual',
            mode='markers', x=x, y=df_selected["Actual"]
        ))

        fig.add_trace(go.Scatter(
            name=meter + ' Predicted',
            mode="markers+lines", x=x, y=df_selected["Predicted"]
        ))

    fig.update_xaxes(
        title_text = x_title,
        rangeslider_visible=True,
        rangeselector=dict(
            buttons=list([
                dict(count=1, label="1d", step="day", stepmode="backward"),
                dict(count=1, label="1m", step="month", stepmode="backward"),
                dict(count=6, label="6m", step="month", stepmode="backward"),
                dict(count=1, label="YTD", step="year", stepmode="todate"),
                dict(count=1, label="1y", step="year", stepmode="backward"),
                dict(step="all")
            ])
        ),
        dtick = 1
    )
    fig.update_yaxes(title_text = "Average Energy Consumption")
    if category_value == "month":
        fig.update_layout(
            xaxis=dict(
                tickmode='array',
                tickvals=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
                ticktext=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
            )
        )
    elif category_value =="day":
        fig.update_layout(
            xaxis=dict(
                tickmode='array',
                tickvals=[0, 1, 2, 3, 4, 5, 6],
                ticktext=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
            )
        )
    elif category_value =="hour":
        fig.update_layout(
            xaxis=dict(
                tickmode='array',
                tickvals=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23],
                ticktext=['12 AM', '1 AM', '2 AM', '3 AM', '4 AM', '5 AM', '6 AM', '7 AM', '8 AM', '9 AM', '10 AM', '11 AM',
                          '12 PM', '1 PM', '2 PM', '3 PM', '4 PM', '5 PM', '6 PM', '7 PM', '8 PM', '9 PM', '10 PM', '11 PM']
            )
        )

    fig.update_layout(title=fig_title, legend_title="Meters")

    return [fig]

if __name__ == '__main__':
    app.run_server(debug=True)