import unittest.mock as mock
import unittest

from transiter.http import flaskapp
from transiter.http import tripendpoints
from transiter.http import systemendpoints
from transiter.http import routeendpoints
from transiter.http import stopendpoints
from transiter.http import feedendpoints

class _TestEndpoints(unittest.TestCase):

    SYSTEM_ID = '1'
    ROUTE_ID = '2'
    TRIP_ID = '3'
    STOP_ID = '4'
    FEED_ID = '5'
    FEED_UPDATE_ID = '6'
    SERVICE_RESPONSE = {'A': 'B'}
    JSON_RESPONSE = 'C'
    SERVICE_NO_RESPONSE = True
    JSON_NO_RESPONSE = ''

    def setUp(self):
        pv_patcher = mock.patch('transiter.http.feedendpoints.permissionsvalidator')
        self.pv = pv_patcher.start()
        self.addCleanup(pv_patcher.stop)

        patcher = mock.patch('transiter.http.responsemanager.convert_to_json')
        self.convert_to_json = patcher.start()
        self.addCleanup(patcher.stop)

    def _test_endpoint(self, endpoint_function, service_function, args,
                       service_response, endpoint_response):

        service_function.return_value = service_response
        if endpoint_response != '':
            self.convert_to_json.return_value = endpoint_response
            #self.jsonutil.convert_for_http.return_value = endpoint_response

        (actual, __, __) = endpoint_function(*args)

        self.assertEqual(actual, endpoint_response)
        if endpoint_response != '':
            self.convert_to_json.assert_called_once_with(
                service_response)
        service_function.assert_called_once_with(*args)

    def _test_response_endpoint(self, endpoint_function, service_function, args=()):
        self._test_endpoint(endpoint_function, service_function, args,
                            self.SERVICE_RESPONSE, self.JSON_RESPONSE)

    def _test_no_response_endpoint(self, endpoint_function, service_function, args=()):
        self._test_endpoint(endpoint_function, service_function, args,
                            self.SERVICE_NO_RESPONSE, self.JSON_NO_RESPONSE)

    def _test_not_implemented_endpoint(self, endpoint_function, args=()):

        (actual, http_code, __) = endpoint_function(*args)

        self.assertEqual(actual, '')
        self.assertEqual(http_code, 501)

class TestFeedEndpoints(_TestEndpoints):

    @mock.patch('transiter.http.feedendpoints.feedservice')
    def test_list_all_in_system(self, feedservice):
        """[Feed endpoints] List all feeds in a system"""
        self._test_response_endpoint(feedendpoints.list_all_in_system,
                                     feedservice.list_all_in_system,
                                     (self.SYSTEM_ID))

    @mock.patch('transiter.http.feedendpoints.feedservice')
    def test_get_in_system_by_id(self, feedservice):
        """[Feed endpoints] Get a specific feed in a system"""
        self._test_response_endpoint(feedendpoints.get_in_system_by_id,
                                     feedservice.get_in_system_by_id,
                                     (self.SYSTEM_ID, self.ROUTE_ID))

    @mock.patch('transiter.http.feedendpoints.feedservice')
    def test_create_feed_update(self, feedservice):
        """[Feed endpoints] Create a new feed update for a specific feed"""
        self._test_response_endpoint(feedendpoints.create_feed_update,
                                     feedservice.create_feed_update,
                                     (self.SYSTEM_ID, self.FEED_ID))

    @mock.patch('transiter.http.feedendpoints.feedservice')
    def test_list_updates_in_feed(self, feedservice):
        """[Feed endpoints] List all updates for a specific feed"""
        self._test_response_endpoint(feedendpoints.list_updates_in_feed,
                                     feedservice.list_updates_in_feed,
                                     (self.SYSTEM_ID, self.FEED_ID))

    @mock.patch('transiter.http.feedendpoints.feedservice')
    def test_get_update_in_feed(self, feedservice):
        """[Feed endpoints] Get a specific feed update in a specific feed"""
        self._test_not_implemented_endpoint(feedendpoints.get_update_in_feed,
                                            (self.SYSTEM_ID, self.FEED_ID,
                                             self.FEED_UPDATE_ID))

    @mock.patch('transiter.http.feedendpoints.feedservice')
    def test_get_autoupdater_for_feed(self, feedservice):
        """[Feed endpoints] Get the autoupdater config for a specific feed"""
        self._test_not_implemented_endpoint(feedendpoints.get_autoupdater_for_feed,
                                            (self.SYSTEM_ID, self.FEED_ID))

    @mock.patch('transiter.http.feedendpoints.feedservice')
    def test_configure_autoupdater_for_feed(self, feedservice):
        """[Feed endpoints] Configure the autoupdater for a specific feed"""
        self._test_not_implemented_endpoint(
            feedendpoints.configure_autoupdater_for_feed,
                                     (self.SYSTEM_ID, self.FEED_ID))

class TestRouteEndpoints(_TestEndpoints):

    @mock.patch('transiter.http.routeendpoints.routeservice')
    def test_list_all_in_system(self, routeservice):
        """[Route endpoints] List all routes in a system"""
        self._test_response_endpoint(routeendpoints.list_all_in_system,
                                     routeservice.list_all_in_system,
                                     (self.SYSTEM_ID))

    @mock.patch('transiter.http.routeendpoints.routeservice')
    def test_get_in_system_by_id(self, routeservice):
        """[Route endpoints] Get a specific route in a system"""
        self._test_response_endpoint(routeendpoints.get_in_system_by_id,
                                     routeservice.get_in_system_by_id,
                                     (self.SYSTEM_ID, self.ROUTE_ID))

class TestStopEndpoints(_TestEndpoints):

    @mock.patch('transiter.http.stopendpoints.stopservice')
    def test_list_all_in_route(self, stopservice):
        """[Stop endpoints] List all stop in a system"""
        self._test_response_endpoint(stopendpoints.list_all_in_system,
                                     stopservice.list_all_in_system,
                                     (self.SYSTEM_ID))

    @mock.patch('transiter.http.stopendpoints.stopservice')
    def test_get_in_route_by_id(self, stopservice):
        """[Stop endpoints] Get a specific stop in a system"""
        self._test_response_endpoint(stopendpoints.get_in_system_by_id,
                                     stopservice.get_in_system_by_id,
                                     (self.SYSTEM_ID, self.STOP_ID))

class TestTripEndpoints(_TestEndpoints):

    @mock.patch('transiter.http.tripendpoints.tripservice')
    def test_list_all_in_route(self, tripservice):
        """[Trip endpoints] List all trips in a route"""
        self._test_response_endpoint(tripendpoints.list_all_in_route,
                                     tripservice.list_all_in_route,
                                     (self.SYSTEM_ID, self.ROUTE_ID))

    @mock.patch('transiter.http.tripendpoints.tripservice')
    def test_get_in_route_by_id(self, tripservice):
        """[Trip endpoints] Get a specific trip in a route"""
        self._test_response_endpoint(tripendpoints.get_in_route_by_id,
                                     tripservice.get_in_route_by_id,
                                     (self.SYSTEM_ID, self.ROUTE_ID, self.TRIP_ID))

class TestSystemEndpoints(_TestEndpoints):

    @mock.patch('transiter.http.systemendpoints.systemservice')
    def test_list_all(self, systemservice):
        """[System endpoints] List all systems installed"""
        self._test_response_endpoint(systemendpoints.list_all,
                                     systemservice.list_all)

    @mock.patch('transiter.http.systemendpoints.systemservice')
    def test_get_by_id(self, systemservice):
        """[System endpoints] Get a specific system"""
        self._test_response_endpoint(systemendpoints.get_by_id,
                                     systemservice.get_by_id,
                                     (self.SYSTEM_ID))

    @mock.patch('transiter.http.systemendpoints.inputvalidator')
    @mock.patch('transiter.http.systemendpoints.systemservice')
    def test_install(self, systemservice, inputvalidator):
        """[System endpoints] Install a system"""
        inputvalidator.validate_post_data.return_value = {}
        self._test_no_response_endpoint(systemendpoints.install,
                                        systemservice.install,
                                        (self.SYSTEM_ID))

    @mock.patch('transiter.http.systemendpoints.systemservice')
    def test_delete_by_id(self, systemservice):
        """[System endpoints] Uninstall a system"""
        self._test_no_response_endpoint(systemendpoints.delete_by_id,
                                        systemservice.delete_by_id,
                                        (self.SYSTEM_ID))

class TestFlaskApp(unittest.TestCase):

    def test_root(self):
        expected_code = 200
        (__, actual_code, __) = flaskapp.root()
        self.assertEqual(expected_code, actual_code)

    def test_about(self):
        expected_code = 200
        (__, actual_code, __) = flaskapp.about()
        self.assertEqual(expected_code, actual_code)


import re
from math import *

class ParenthesesError:
    pass

class MissingValuesError:
    pass

class MismatchedOperatorError:
    """Returned when a Left-Bracket is still present in the Operators Stack
       at the end of while-loop in parse(expr)
    """
    pass

class UnknownOperatorsError:
    """Currently Returned when the Left-Right Precedence
       of an function or operator can't be determined"""
    pass

def to_postfix(expr):

    output_queue = Queue([])
    operators_stack = Stack([])
    tokens = expr_to_list(expr)

    while len(tokens) > 0:
        token = tokens[0]

        if num(token):
            output_queue.push(token)

        elif token in OPERATORS:
            if ASSOCIATIVITY[token] is "Left":
                if operators_stack.size() > 0:
                    if PRECEDENCE[token] <= PRECEDENCE[operators_stack.peek()] and operators_stack.peek() != "(":
                        output_queue.push(operators_stack.pop())
                operators_stack.push(token)

            elif ASSOCIATIVITY[token] is "Right":
                if operators_stack.size() > 0:
                    if PRECEDENCE[token] < PRECEDENCE[operators_stack.peek()] and operators_stack.peek() != "(":
                        output_queue.push(operators_stack.pop())
                operators_stack.push(token)

            else:
                return UnknownOperatorsError

        elif token is '(':
            operators_stack.push(token)

        elif token is ')':
            while not operators_stack.peek() == '(':
                if operators_stack.is_empty():
                    return ParenthesesError()
                output_queue.push(operators_stack.pop())

            operators_stack.pop()

            if operators_stack.peek() in FUNCTIONS:
                output_queue.push(operators_stack.pop())
        tokens.pop(0)

    while not operators_stack.is_empty():
        output_queue.push(operators_stack.pop())

    if '(' in output_queue.reveal() or ')' in output_queue.reveal():
        return ParenthesesError()
    else:
        return output_queue

def parse(expr):

    LIMIT = {"+":2,"-":2,"*":2,"/":2,"^":2,"sin":1}

    mirror_queue = to_postfix(expr)
    output_stack = Stack()
    for i in range(mirror_queue.size()):

        token = mirror_queue.remove()

        if num(token):
            output_stack.push(token)

        elif token in OPERATORS:
            if token == 'sin':
                x = cast(output_stack.pop())
                output_stack.push(str(sin(x)))

            elif token == 'cos':
                x = cast(output_stack.pop())
                output_stack.push(str(cos(x)))

            elif token == "tan":
                x = cast(output_stack.pop())
                output_stack.push(str(tan(x)))

            elif token == "asin":
                x = cast(output_stack.pop())
                output_stack.push(str(asin(x)))

            elif token == "acos":
                x = cast(output_stack.pop())
                output_stack.push(str(acos(x)))

            elif token == "atan":
                x = cast(output_stack.pop())
                output_stack.push(str(atan(x)))

            elif token == "sinh":
                x = cast(output_stack.pop())
                output_stack.push(str(sinh(x)))

            elif token == "cosh":
                x = cast(output_stack.pop())
                output_stack.push(str(cosh(x)))

            elif token == "tanh":
                x = cast(output_stack.pop())
                output_stack.push(str(tanh(x)))

            elif token == "*":
                x = cast(output_stack.pop())
                y = cast(output_stack.pop())
                output_stack.push(str(x*y))

            elif token == "/":
                x = cast(output_stack.pop())
                y = cast(output_stack.pop())
                output_stack.push(str(y/x))

            elif token == "^":
                x = cast(output_stack.pop())
                y = cast(output_stack.pop())
                output_stack.push(str(y**x))

            elif token == "+":
                x = cast(output_stack.pop())
                y = cast(output_stack.pop())
                output_stack.push(str(x + y))

            elif token == "-":
                x = cast(output_stack.pop())
                y = cast(output_stack.pop())
                output_stack.push(str(y - x))

        else:
            return UnknownOperatorsError()

    if output_stack.size() == 1:
        return output_stack
    else:
        return MismatchedOperatorError()

def num(token):
    if 'e' in token:
        try:
            eval(token)
            return True
        except NameError:
            return False
    elif '.' in token:
        try:
            float(token)
            return True
        except ValueError:
            return False
    else:
        try:
            int(token)
            return True
        except ValueError:
            return False

def cast(token):
    if 'e' in token:
        return eval(token)
    elif '.' in token:
        return float(token)
    else:
        return int(token)

def starts_with(obj, substr):
    if(obj[0:len(substr)] == substr):
        return True
    else:
        return False

def expr_to_list(expr):
    # expr: An expression expected to be a string

    # returns: A list of elements simplified from the expression
    # elements are grouped in numbers, operators, and functions
    # e.g. "(" or "10.3" or "sin"

    try:
        assert type(expr) is str
    except AssertionError:
        print("Unexpected Argument")
        return None

    elements = Stack([])
    elements.push(expr[0])
    expr = expr[1:]
    b = False

    tokens = []

    for i in expr:

        for j in FUNCTIONS:
            if starts_with(expr,j):
                tokens.append(elements.tostring())
                elements.clear()
                tokens.append(j)
                expr = expr[len(j):len(expr)]
                b = True
            else:
                b = False

        if b:
            elements.push(i)

        if elements.peek() in NUMBERS and i in NUMBERS:
            elements.push(i)

        elif elements.peek() in SYMBOLS and i in SYMBOLS:
            tokens.append(elements.tostring())
            elements.empty()

        elif elements.peek() in LETTERS and i in LETTERS:
            elements.push(i)

        else:
            tokens.append(elements.tostring())
            elements.empty()

    tokens.append(elements.tostring())

    return impl_mult(resolve_negatives(remove_spaces(tokens)))

def resolve_negatives(l):

    for i in range(len(l)):
        if i == 0 and l[i] is "-" and num(l[i+1]):
            l[i+1] = "-"+l[i+1]
            l.pop(i)
        else:
            try:
                if l[i] is "-" and num(l[i+1]) and l[i-1] in SYMBOLS:
                    l[i+1] = "-"+l[i+1]
                    l.pop(i)
            except IndexError:
                pass

    return l

def remove_spaces(l):
    for i in l:
        if i is ' ':
            l.remove(i)
    return l

def impl_mult(l):
    for i in range(len(l)):
        try:
            if l[i] == ')' and l[i+1] == '(':
                l = l[0:i+1] + ['*'] + l[i+1:len(l)]
            elif l[i] in LETTERS and i[i] not in FUNCTIONS and l[i+1] == '(':
                l = l[0:i+1] + ['*'] + l[i+1:len(l)]
            elif num(l[i]) and (l[i+1] == '(' or l[i+1] in LETTERS or l[i+1] in FUNCTIONS):
                l = l[0:i+1] + ['*'] + l[i+1:len(l)]
            elif l[i] in LETTERS and l[i+1] in FUNCTIONS:
                l = l[0:i+1] + ['*'] + l[i+1:len(l)]

            else:
                pass

        except:
            pass
    return l

class Expr:

    operands = "1234567890."

    operators = ["+","-","/","*","^",
                     "sin","cos","tan",
                     "asin","acos","atan",
                     "sinh","cosh","tanh"]

    search = "(\+|\-|\*|\/|\^|\(|\)|\sin" \
             "|\cos|\tan|\asin|\acos|\atan" \
             "|\sinh|\cosh|\tanh|\max)"

    left = ["+","-","*","/"]

    right = ["^","sin","cos","tan",
                 "asin","acos","atan",
                 "sinh","cosh","tanh"]

    value_of = {"+":1, "-":1, "*":2, "/":2,
                "%":2, "^":3, "(":4,")":4,
                "sin":4,"cos":4,"tan":4,
                "asin":4,"acos":4,"atan":4,
                "sinh":4,"cosh":4,"tanh":4,
                "fact":4
               }
    functions= ["sin","cos","tan","asin","acos","atan","sinh","cosh","tanh","max"]

    letters = "abcdefghijklmnopqrstuvwxyz"

    def __init__(self,string, variables=None):
        assert type(string) is str

        self.infix = string

        if variables is None:
            self.variables = {}
        elif type(variables) is list:
            self.variables = dict((i,None) for i in variables)
        else:
            self.variables = variables

        self.infix_list = self.to_list()
        self.postfix = self.to_postfix()
        self.parsed = ""

    def __add__(self, other):
        if type(other) is str:
            return Expr(self.expression + " + " + other, self.variables)
        elif type(other) is Expr:
            return Expr(self.expression + " + " + other.expression, self.variables.update(other.variables))
        else:
            return TypeError

    def __radd__(self, other):
        if type(other) is str:
            return Expr(other + " + " + self.expression, self.variables,)
        elif type(other) is Expr:
            return Expr(other.expression + " + " + self.expression, self.variables.update(other.variables))
        else:
            return TypeError

    def __sub__(self, other):
        if type(other) is str:
            return Expr(self.expression + " - " + other, self.variables)
        elif type(other) is Expr:
            return Expr(self.expression + " - " + other.expression, self.variables.update(other.variables))
        else:
            return TypeError

    def __rsub__(self, other):
        if type(other) is str:
            return Expr(other + " - " + self.expression, self.variables)
        elif type(other) is Expr:
            return Expr(other.expression + " - " + self.expression, self.variables.update(other.variables))
        else:
            return TypeError

    def __mul__(self, other):
        if type(other) is str:
            return Expr(self.expression + " * " + other, self.variables)
        elif type(other) is Expr:
            return Expr(self.expression + " * " + other.expression, self.variables.update(other.variables))
        else:
            return TypeError

    def __rmul__(self, other):
        if type(other) is str:
            return Expr(other + " * " + self.expression, self.variables)
        elif type(other) is Expr:
            return Expr(other.expression + " * " + self.expression, self.variables.update(other.variables))
        else:
            return TypeError

    def __truediv__(self, other):
        if type(other) is str:
            return Expr(self.expression + " / " + other, self.variables)
        elif type(other) is Expr:
            return Expr(self.expression + " / " + other.expression, self.variables.update(other.variables))
        else:
            return TypeError

    def __rtruediv__(self, other):
        if type(other) is str:
            return Expr(other + " / " + self.expression, self.variables)
        elif type(other) is Expr:
            return Expr(other.expression + " / " + self.expression, self.variables.update(other.variables))
        else:
            return TypeError

    def __lt__(self, other):
        pass

    def __le__(self, other):
        pass

    def __eq__(self, other):
        pass

    def __ne__(self, other):
        pass

    def __ge__(self, other):
        pass

    def __gt__(self, other):
        pass

    def __str__(self):
        return self.expression

    def num(self, token):
        if 'e' in token:
            try:
                eval(token)
                return True
            except NameError:
                return False
        elif '.' in token:
            try:
                float(token)
                return True
            except ValueError:
                return False
        else:
            try:
                int(token)
                return True
            except ValueError:
                return False

    def to_list(self):

        self.infix = self.infix.replace(" ","")
        return re.split(self.search,self.infix)

    def to_postfix(self):

        output = Queue([])
        operators = Stack([])
        tokens = self.infix_list

        while len(tokens) > 0:
            token = tokens[0]
            if self.num(token):
                output.push(token)

            elif token in self.left or token in self.right:

                if token in self.left:
                    if operators.size() > 0:
                        if self.value_of[token] <= self.value_of[operators.peek()] and operators.peek() != "(":
                            output.push(operators.pop())
                    operators.push(token)

                elif token in self.right:
                    if operators.size() > 0:
                        if self.value_of[token] < self.value_of[operators.peek()] and operators.peek() != "(":
                            output.push(operators.pop())
                    operators.push(token)

                else:
                    return UnknownOperatorsError

            elif token in self.variables:
                output.push(token)

            elif token is '(':
                operators.push(token)

            elif token is ')':
                while not operators.peek() == '(':
                    if operators.empty():
                        return ParenthesesError()
                    output.push(operators.pop())

                operators.pop()

                if operators.peek() in self.functions:
                    output.push(operators.pop())

            tokens.pop(0)

        while not operators.empty():
            output.push(operators.pop())

        if '(' in output.reveal() or ')' in output.reveal():
            return ParenthesesError()
        else:
            return output

    def to_infix(self):

        arg = self.postfix
        output = Stack()

        while not arg.is_empty():

            token = arg.remove()

            if token in self.operands:
                output.push(token)

            elif token in self.operators:

                if output.size() < 2:
                    return "Insufficient Values"

                else:
                    a = output.pop()
                    b = output.pop()
                    output.push("("+b+token+a+")")

        if output.size() == 1:
            return output.tostring()
        else:
            return "Too Many Values"

class ExprMachine:

    def __init__(self):
        pass

    def num(self, token):
        if 'e' in token:
            try:
                eval(token)
                return True
            except NameError:
                return False
        elif '.' in token:
            try:
                float(token)
                return True
            except ValueError:
                return False
        else:
            try:
                int(token)
                return True
            except ValueError:
                return False

    def cast(self,token):
        if 'e' in token:
            return eval(token)
        elif '.' in token:
            return float(token)
        else:
            return int(token)

    def parse(self, arg):
        assert type(arg) is str or type(arg) is Expr

        limit = {"+":2,"-":2,"*":2,"/":2,"^":2,"sin":1}

        operators = ["+","-","/","*","^","%",
                     "sin","cos","tan",
                     "asin","acos","atan",
                     "sinh","cosh","tanh"]

        if type(arg) is str:
            mirror = Expr(arg).postfix
        else:
            mirror = arg.postfix

        output = Stack()

        for i in range(mirror.size()):

            token = mirror.remove()

            if self.num(token):
                output.push(token)

            elif token in operators:
                if token == 'sin':
                    x = self.cast(output.pop())
                    output.push(str(sin(x)))

                elif token == 'cos':
                    x = self.cast(output.pop())
                    output.push(str(cos(x)))

                elif token == "tan":
                    x = self.cast(output.pop())
                    output.push(str(tan(x)))

                elif token == "asin":
                    x = self.cast(output.pop())
                    output.push(str(asin(x)))

                elif token == "acos":
                    x = self.cast(output.pop())
                    output.push(str(acos(x)))

                elif token == "atan":
                    x = self.cast(output.pop())
                    output.push(str(atan(x)))

                elif token == "sinh":
                    x = self.cast(output.pop())
                    output.push(str(sinh(x)))

                elif token == "cosh":
                    x = self.cast(output.pop())
                    output.push(str(cosh(x)))

                elif token == "tanh":
                    x = self.cast(output.pop())
                    output.push(str(tanh(x)))

                elif token == "*":
                    x = self.cast(output.pop())
                    y = self.cast(output.pop())
                    output.push(str(x*y))

                elif token == "/":
                    x = self.cast(output.pop())
                    y = self.cast(output.pop())
                    output.push(str(y/x))

                elif token == "^":
                    x = self.cast(output.pop())
                    y = self.cast(output.pop())
                    output.push(str(y**x))

                elif token == "+":
                    x = self.cast(output.pop())
                    y = self.cast(output.pop())
                    output.push(str(x + y))

                elif token == "-":
                    x = self.cast(output.pop())
                    y = self.cast(output.pop())
                    output.push(str(y - x))

            else:
                return UnknownOperatorsError()

        if output.size() == 1:
            return output.peek()
        else:
            return MismatchedOperatorError()

class Stack:

    def __init__(self,l=None):
        if l is None:
            self.stack = []
        else:
            self.stack = l[:]

    def __str__(self):
        return str(self.stack)

    def push(self,item):
        self.stack[len(self.stack):] = [item]

    def pop(self):
        return self.stack.pop(len(self.stack)-1)

    def peek(self):
        if self.empty():
            return None
        else:
            return self.stack[self.size()-1]

    def reveal(self):
        return self.stack

    def empty(self):
        if len(self.stack) == 0:
            return True
        else:
            return False

    def size(self):
        return len(self.stack)

    def clear(self):
        self.stack = []

    def contains(self,t):
        if t in self.stack:
            return True
        else:
            return False

    def tostring(self):
        return "".join(self.stack)

class Queue():

    def __init__(self,l=None):
        if l is None:
            self.queue = []
        else:
            self.queue = l[:]

    def push(self,item):
        self.queue[len(self.queue):] = [item]

    def remove(self):
        return self.queue.pop(0)

    def reveal(self):
        return self.queue

    def is_empty(self):
        if len(self.queue) == 0:
            return True
        else:
            return False

    def size(self):
        return len(self.queue)

    def peek(self):
        if self.is_empty():
            return None
        else:
            return self.queue[0]

    def tostring(self):
        return ''.join(self.queue)

    def __str__(self):
        return str(self.queue)

NUMBERS = "1234567890.e"

OPERATORS = ["+","-","/","*","^","%",
             "sin","cos","tan",
             "asin","acos","atan",
             "sinh","cosh","tanh"]

PRECEDENCE = {"+":1, "-":1, "*":2, "/":2,
              "%":2, "^":3, "(":4,")":4,
              "sin":4,"cos":4,"tan":4,
              "asin":4,"acos":4,"atan":4,
              "sinh":4,"cosh":4,"tanh":4,
              "fact":4
              }

ASSOCIATIVITY = {"+":"Left", "-":"Left", "*":"Left", "/":"Left","%":"Left",
                 "^":"Right","sin":"Right","cos":"Right","tan":"Right",
                 "asin":"Right","acos":"Right","atan":"Right",
                 "sinh":"Right","cosh":"Right","tanh":"Right",
                 "fact":"Right"
                 }

FUNCTIONS = ["sin","cos","tan","asin","acos","atan","sinh","cosh","tanh","max"]

SYMBOLS = "+-*/^()%"

LETTERS = "abcdefghijklmnopqrstuvwxyz"

s = Expr("1 + 2",[])
print(s.postfix)
print(s.to_infix())


import socket,json

def handler(request):
    host="163.18.26.108"
    port=request.json['port']
    msg=request.json['msg']
    data=bytes(json.dumps(msg),"utf-8")
    syslogSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # 送出
    syslogSocket.sendto(data, (host, port))
    # 清除socket
    syslogSocket.close()
    return {"Status":"Ok"}


from collections import Counter
from math import factorial as f

def countcurr(letlist, ch):
	if ch not in letlist: return 0
	letlist.remove(ch)
	return (f(len(letlist)))/(f(letlist.count("A"))*f(letlist.count("B"))*f(letlist.count("C"))*f(letlist.count("D")))

a, b, c, d, n = list(map(int, input().split()))
letnum = [a, b, c, d]
letstr = ["A", "B", "C", "D"]

ordered = []
tot = sum(letnum)
p = 0

while sum(letnum) > 0:
	#Available letters
	aletters = [i for i in Counter(dict(zip(letstr, letnum))).elements()]
	#Find next letter in list
	s, cletter = p, -1
	while s < n:
		cletter += 1
		p = s
		s += countcurr(aletters[:], letstr[cletter])
	ordered.append(letstr[cletter])
	aletters.remove(letstr[cletter])
	letnum[cletter] -= 1

for i in ordered:
	print(i, end="")


#! /usr/bin/env python

import requests
import logging
from uuid import uuid4
import urllib
from flask import (Flask, abort, request, redirect, url_for)

logging.basicConfig()
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.DEBUG)

CLIENT_ID = 'RBcaJYcKibya8NaoHpZKEo8u4LU7gvBlhe5GmImS'
CLIENT_SECRET = (
    'Dn7zahEcBBTgmAtCiCvz2kOjI8uQiQsJstrtuTzNObOcFbfaZS2K241yttO4L20'
    'PmuMItDnKaiWzkUNL3r5KcLIH6nMBuGqmBvwOQO75ByJc5JniUO47Liwf4JFLliwk'
)
REDIRECT_URI = 'http://localhost:5000/auth_callback/'
BASE_URL = 'https://simeng2.dev.sunpower.com'

app = Flask(__name__)
@app.route('/')
def homepage():
    text = (
        '
AuthCodeTest

Authenticate with PVAPI
'
    )
    return text % make_authorization_url()

def make_authorization_url():
    # Generate a random string for the state parameter
    # Save it for use later to prevent xsrf attacks
    state = str(uuid4())
    save_created_state(state)
    params = {"client_id": CLIENT_ID,
              "response_type": "code",
              "state": state,
              "redirect_uri": REDIRECT_URI,
              "duration": "temporary",
              "scope": "read write groups"}
    url = BASE_URL + '/o/authorize/?' + urllib.urlencode(params)
    LOGGER.debug('authorization URL:\n%s', url)
    return url

# Left as an exercise to the reader.
# You may want to store valid states in a database or memcache,
# or perhaps cryptographically sign them and verify upon retrieval.

def save_created_state(state):
    pass

def is_valid_state(state):
    return True

@app.route('/auth_callback/')
def auth_callback():
    error = request.args.get('error', '')
    if error:
        return "Error: " + error
    state = request.args.get('state', '')
    if not is_valid_state(state):
        # Uh-oh, this request wasn't started by us!
        abort(403)
    code = request.args.get('code')
    # We'll change this next line in just a moment
    LOGGER.debug("got a code! %s", code)
    return redirect(url_for('success', code=get_token(code)))

def get_token(code):
    # client id/secret can either be supplied as POST data or as basic auth
    post_data = {"grant_type": "authorization_code",
                 "code": code,
                 "redirect_uri": REDIRECT_URI}
    response = requests.post(BASE_URL + '/o/token/',
                             auth=(CLIENT_ID, CLIENT_SECRET),
                             data=post_data)
    token_json = response.json()
    LOGGER.debug('response:\n%r', token_json)
    return token_json["access_token"]

@app.route('/success/')
def success(code):
    text = (
        '
AuthCodeTest

"Got access token!
%s
'
        'Return home or go to PVAPI?
'
    )
    return text % (code, BASE_URL)

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


N = int(input())
arr = list(map(int, input().split()))

if arr == list(range(1,N+1)):
    print(-1)
else:
    before_num = 0
    for idx, num in enumerate(reversed(arr)):
        if before_num:
            if before_num < num:
                pos = N - idx - 1
                break
        before_num = num

    tmp = arr.copy()
    tmp1 = tmp[pos:]
    tmp1.sort()
    #print(pos)
    #print(tmp1)
    answer = arr[:pos]
    answer.append(tmp1[tmp1.index(arr[pos])-1])
    for _ in answer:
        if _ in tmp:
            tmp.remove(_)
    tmp.sort(reverse=True)
    answer.extend(tmp)
    print(*answer)


import matplotlib
import os
import sys
from matplotlib import backend_tools, cbook
from matplotlib._pylab_helpers import Gcf
from matplotlib.backend_bases import (
    _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2,
    TimerBase, cursors, ToolContainerBase, StatusbarBase, MouseButton)
import matplotlib.backends.qt_editor.figureoptions as figureoptions
from matplotlib.backends.qt_editor.formsubplottool import UiSubplotTool
from matplotlib.backend_managers import ToolManager
from matplotlib.backends.qt_compat import(
    QtCore, QtGui, QtWidgets, _isdeleted, _getSaveFileName,
    is_pyqt5, __version__, QT_API)

backend_version = __version__
from matplotlib.backends.backend_qt5 import SubplotToolQt

cursord = {
    cursors.MOVE: QtCore.Qt.SizeAllCursor,
    cursors.HAND: QtCore.Qt.PointingHandCursor,
    cursors.POINTER: QtCore.Qt.ArrowCursor,
    cursors.SELECT_REGION: QtCore.Qt.CrossCursor,
    cursors.WAIT: QtCore.Qt.WaitCursor,
    }

# make place holder
qApp = None

class NavigationToolbar_(NavigationToolbar2, QtWidgets.QToolBar):
    message = QtCore.Signal(str)

    def __init__(self, canvas, parent, coordinates=True):
        """coordinates: should we show the coordinates on the right?"""
        self.canvas = canvas
        self.parent = parent
        self.coordinates = coordinates
        self._actions = {}
        """A mapping of toolitem method names to their QActions"""

        QtWidgets.QToolBar.__init__(self, parent)
        NavigationToolbar2.__init__(self, canvas)

    def _icon(self, name, color=None):
        if is_pyqt5():
            name = name.replace('.png', '_large.png')
        pm = QtGui.QPixmap(os.path.join(self.basedir, name))
        if hasattr(pm, 'setDevicePixelRatio'):
            pm.setDevicePixelRatio(self.canvas._dpi_ratio)
        if color is not None:
            mask = pm.createMaskFromColor(QtGui.QColor('black'),
                                          QtCore.Qt.MaskOutColor)
            pm.fill(color)
            pm.setMask(mask)
        return QtGui.QIcon(pm)

    def _init_toolbar(self):
        self.basedir = str(cbook._get_data_path('images'))

        background_color = self.palette().color(self.backgroundRole())
        foreground_color = self.palette().color(self.foregroundRole())
        icon_color = (foreground_color
                      if background_color.value() < 128 else None)

        for text, tooltip_text, image_file, callback in self.toolitems:

            if callback not in ['zoom', 'pan' , 'back' , 'forward','home','configure_subplots']:

                if text is None:
                    #self.addSeparator()
                    pass
                else:
                    a = self.addAction(QIcon('res\\save_icon.ico'),
                                    text, getattr(self, callback))
                    self._actions[callback] = a

                    if tooltip_text is not None:
                        a.setToolTip(tooltip_text)
                    if text == 'Subplots':
                        a = self.addAction(self._icon("qt4_editor_options.png",
                                                    icon_color),
                                        'Customize', self.edit_parameters)
                        a.setToolTip('Edit axis, curve and image parameters')

        # Add the (x, y) location widget at the right side of the toolbar
        # The stretch factor is 1 which means any resizing of the toolbar
        # will resize this label instead of the buttons.
        self.measure_win_A=QtWidgets.QAction(QIcon("res\\m_icon.ico"),"Open Measurement Window",self)
        self.measure_win_A.triggered.connect(self.parent.Open_measure_window)
        self.addAction(self.measure_win_A)

        self.statusLabel = QtWidgets.QLabel("", self)
        self.statusLabel.setAlignment(
                QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)

        self.statusLabel.setSizePolicy(
            QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum,
                                    QtWidgets.QSizePolicy.Ignored))

        self.statusLabel.setStyleSheet("QLabel { color : red; }")
        self.statusLabelAction = self.addWidget(self.statusLabel)
        font1 = QtGui.QFont("Times", 12)
        self.statusLabelAction.setVisible(False)
        self.statusLabel.setFont(font1)

        if self.coordinates:
            self.locLabel = QtWidgets.QLabel("", self)
            self.locLabel.setAlignment(
                    QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
            self.locLabel.setSizePolicy(
                QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding,
                                      QtWidgets.QSizePolicy.Ignored))
            self.coordinateLabel = self.addWidget(self.locLabel)
            newfont = QtGui.QFont("Times", 12)
            self.coordinateLabel.setVisible(True)
            self.locLabel.setFont(newfont)

    @cbook.deprecated("3.1")
    @property
    def buttons(self):
        return {}

    @cbook.deprecated("3.1")
    @property
    def adj_window(self):
        return None

    def edit_parameters(self):
        axes = self.canvas.figure.get_axes()
        if not axes:
            QtWidgets.QMessageBox.warning(
                self.parent, "Error", "There are no axes to edit.")
            return
        elif len(axes) == 1:
            ax, = axes
        else:
            titles = [
                ax.get_label() or
                ax.get_title() or
                " - ".join(filter(None, [ax.get_xlabel(), ax.get_ylabel()])) or
                f"<anonymous {type(ax).__name__}>"
                for ax in axes]
            duplicate_titles = [
                title for title in titles if titles.count(title) > 1]
            for i, ax in enumerate(axes):
                if titles[i] in duplicate_titles:
                    titles[i] += f" (id: {id(ax):#x})"  # Deduplicate titles.
            item, ok = QtWidgets.QInputDialog.getItem(
                self.parent, 'Customize', 'Select axes:', titles, 0, False)
            if not ok:
                return
            ax = axes[titles.index(item)]
        figureoptions.figure_edit(ax, self)

    def _update_buttons_checked(self):
        # sync button checkstates to match active mode
        if 'pan' in self._actions:
            self._actions['pan'].setChecked(self._active == 'PAN')
        if 'zoom' in self._actions:
            self._actions['zoom'].setChecked(self._active == 'ZOOM')

    def pan(self, *args):
        super().pan(*args)
        self._update_buttons_checked()

    def zoom(self, *args):
        super().zoom(*args)
        self._update_buttons_checked()

    def set_message(self, s):
        self.message.emit(s)
        if self.coordinates:
            s=s.replace("x=","t=")
            self.locLabel.setText(s.rstrip(' y=')+" s")

    def set_cursor(self, cursor):
        self.canvas.setCursor(cursord[cursor])

    def draw_rubberband(self, event, x0, y0, x1, y1):
        height = self.canvas.figure.bbox.height
        y1 = height - y1
        y0 = height - y0
        rect = [int(val) for val in (x0, y0, x1 - x0, y1 - y0)]
        self.canvas.drawRectangle(rect)

    def remove_rubberband(self):
        self.canvas.drawRectangle(None)

    def configure_subplots(self):
        image = str(cbook._get_data_path('images/matplotlib.png'))
        dia = SubplotToolQt(self.canvas.figure, self.canvas.parent())
        dia.setWindowIcon(QtGui.QIcon(image))
        dia.exec_()

    def save_figure(self, *args):

        filetypes = self.canvas.get_supported_filetypes_grouped()
        sorted_filetypes = sorted(filetypes.items())
        default_filetype = self.canvas.get_default_filetype()

        startpath = os.path.expanduser(
            matplotlib.rcParams['savefig.directory'])
        start = os.path.join(startpath, self.canvas.get_default_filename())
        filters = []
        selectedFilter = None
        for name, exts in sorted_filetypes:
            exts_list = " ".join(['*.%s' % ext for ext in exts])
            filter = '%s (%s)' % (name, exts_list)
            if default_filetype in exts:
                selectedFilter = filter
            filters.append(filter)
        filters = ';;'.join(filters)

        fname, filter = _getSaveFileName(self.canvas.parent(),
                                         "Choose a filename to save to",
                                         start, filters, selectedFilter)
        if fname:
            # Save dir for next time, unless empty str (i.e., use cwd).
            if startpath != "":
                matplotlib.rcParams['savefig.directory'] = (
                    os.path.dirname(fname))
            try:
                self.canvas.figure.savefig(fname)
            except Exception as e:
                QtWidgets.QMessageBox.critical(
                    self, "Error saving file", str(e),
                    QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.NoButton)

    def set_history_buttons(self):
        can_backward = self._nav_stack._pos > 0
        can_forward = self._nav_stack._pos < len(self._nav_stack._elements) - 1
        if 'back' in self._actions:
            self._actions['back'].setEnabled(can_backward)
        if 'forward' in self._actions:
            self._actions['forward'].setEnabled(can_forward)

from matplotlib.backends.backend_qt5 import NavigationToolbar2QT
from PyQt5.QtGui import QIcon
NavigationToolbar2QT=NavigationToolbar_


from __future__ import print_function, division

import os
import matplotlib.pyplot as plt
#import matplotlib.ticker as ticker
import numpy as np
import argparse

import LHCMeasurementTools.mystyle as ms
import LHCMeasurementTools.savefig as sf
from LHCMeasurementTools.mystyle import colorprog
import LHCMeasurementTools.TimestampHelpers as TH
import LHCMeasurementTools.LHC_Heatloads as HL
from LHC_Heat_load_dict import mask_dict, main_dict as large_hl_dict, arc_list
import dict_utils as du

plt.close('all')

moment = 'scrubbing'
main_dict = du.load_dict('./scrubbing_dict_2017.pkl')
plot_fmt = '.-'

def legend(sp, bbox_to_anchor=(1,1), loc='upper left', **kwargs):
    sp.legend(bbox_to_anchor=bbox_to_anchor, loc=loc, **kwargs)

date_on_xaxis = False
filln_range = None # Tuple of min / max fill

fontsz = 16
markersize = 10
linewidth = 3
ms.mystyle_arial(fontsz=fontsz, dist_tick_lab=5)

# mask fill nrs

mask = main_dict['filln'] > 5720
main_dict = mask_dict(main_dict,mask)

if date_on_xaxis:
    time_in = 'datetime'
    t_plot_tick_h = None #'4weeks'
    time_conv = TH.TimeConverter(time_in, t_plot_tick_h=t_plot_tick_h)
    tc = time_conv.from_unix
    x_axis = tc(main_dict[moment]['t_stamps'])
else:
    x_axis = main_dict['filln']

fig2 = ms.figure('Arc heat loads')

sp5 = plt.subplot(2,1,1, sharex=None)
sp1 = sp5
sp5.grid('on')
sp5.set_ylim(0,200)

sp6 = plt.subplot(2,1,2, sharex=sp1)
sp6.grid('on')
sp6.set_ylim(0, 6e-13)

#~ sp5.set_title('Arc heat loads')
#~ sp6.set_title('Normalized arc heat loads.')

# plot vs integrated heat load
figinteg = plt.figure(100)
spinteg = plt.subplot(111)
figinteg.set_facecolor('w')

#Plot vs allocated scrubbing time
t_start_prescrubbing_string = '2017_05_29 08:00:00'
t_start_prescrubbing = TH.localtime2unixstamp(t_start_prescrubbing_string)
t_start_scrubbing_string = '2017_06_06 08:00:00'
t_start_scrubbing = TH.localtime2unixstamp(t_start_scrubbing_string)

t_scrub = 0.*main_dict[moment]['t_stamps']
mask_prescrub = main_dict[moment]['t_stamps']<t_start_scrubbing
t_scrub[mask_prescrub] = main_dict[moment]['t_stamps'][mask_prescrub]-t_start_prescrubbing
t_scrub[~mask_prescrub] = main_dict[moment]['t_stamps'][~mask_prescrub]-t_start_scrubbing+24*3600

figtscrub = plt.figure(200)
sptscrub = plt.subplot(111)
figtscrub.set_facecolor('w')

zeros = []

average, divisor = 0, 0
for key in arc_list:
    hl = main_dict[moment]['heat_load']['arc_averages'][key]
    average += np.nan_to_num(hl)
    divisor += np.isfinite(hl)
average /= divisor

tot_int = main_dict[moment]['intensity']['total']
#~ #plot average
#~ sp5.plot(x_axis, average, plot_fmt, label='Average', color='black', markersize=markersize, linewidth=linewidth)
#~ sp6.plot(x_axis, average/tot_int, plot_fmt, label='Average', color='black', markersize=markersiz, linewidth=linewidth)

for arc_ctr, key in enumerate(arc_list):
    color = colorprog(arc_ctr, 8)
    arc_hl = main_dict[moment]['heat_load']['arc_averages'][key]

    #~ #insert interruption between pre-scrubbing and scrubbing
    #~ interr_after_fill = 5728
    #~ n_before = np.sum(main_dict['filln']<=interr_after_fill)
    #~ x_axis_cut = np.array(list(x_axis[:n_before])+[np.nan]+list(x_axis[n_before:]))
    #~ arc_hl_cut = np.array(list(arc_hl[:n_before])+[np.nan]+list(arc_hl[n_before:]))
    #~ tot_int_cut = np.array(list(tot_int[:n_before])+[np.nan]+list(tot_int[n_before:]))
    #~ sp5.plot(x_axis_cut, arc_hl_cut, plot_fmt, label=key, color=color, markersize=markersize, linewidth=linewidth)
    #~ sp6.plot(x_axis_cut, arc_hl_cut/tot_int_cut, plot_fmt, label=key, color=color, markersize=markersize, linewidth=linewidth)

    sp5.plot(x_axis, arc_hl, plot_fmt, label=key, color=color, markersize=markersize, linewidth=linewidth)
    sp6.plot(x_axis, arc_hl/tot_int, plot_fmt, label=key, color=color, markersize=markersize, linewidth=linewidth)

    sptscrub.plot(t_scrub/3600/24., arc_hl/tot_int, plot_fmt, label=key, color=color, markersize=markersize, linewidth=linewidth)

    integ_hl_this = np.cumsum(main_dict['hl_integrated']['arc_averages'][key])

    spinteg.plot(integ_hl_this, arc_hl/tot_int, '.-', color=color, markersize=markersize, linewidth=linewidth)

arc_average = average

#sp6.legend(bbox_to_anchor=(1.22,1.04))
legend(sp6)
sp5.set_ylabel('Heat load [W/hcell]')
sp6.set_ylabel('Norm. heat load [W/hcell/p+]')
plt.setp(sp5.get_xticklabels(), visible = False)

if date_on_xaxis:
    time_conv.set_x_for_plot(fig2, sp1)
else:
    sp6.set_xlabel('Fill nr')

spinteg.set_ylim(0, None)
spinteg.grid('on')
spinteg.set_ylabel('Norm. heat load [W/hcell/p+]')
spinteg.set_xlabel('Integrated heat load [J/hcell]')
figinteg.subplots_adjust(bottom=.12)

sptscrub.set_ylim(0, None)
sptscrub.grid('on')
sptscrub.set_ylabel('Norm. heat load [W/hcell/p+]')
sptscrub.set_xlabel('Scrubbing time [days]')
figtscrub.subplots_adjust(bottom=.12)

plt.show()


from django import forms
from django.forms import modelform_factory, ModelForm

from .models import *

class SubmissionsForm(forms.ModelForm):
	class Meta:
		model = Submissions
		fields = ['file_path']

class NewDwgForm(forms.ModelForm):

	#Getting the reverse of the many2many field. It is filtered out in the view
	submissions = forms.ModelMultipleChoiceField(Submissions.objects.all())
	class Meta:
		model = Drawings
		# fields = ['project','dn_project','dn_originator','dn_volume_system','dn_type','dn_discipline','dn_series','dn_level','dn_zone_sequence','drawing_title1','drawing_title2','drawing_title3','studio','model_location','revision_offset','scale','paper','dwg_type','discipline','phase','originator',
		# 'submissions',

		# ]
		fields = ['data_store']
		widgets = {'project': forms.HiddenInput()}

	#This is some function that saves the special reverse m2m field
	def save(self, *args, **kwargs):
		instance = super(NewDwgForm, self).save(*args, **kwargs)
		# instance.submissions.add(self.cleaned_data['submissions'])
		instance.submissions.set(self.cleaned_data['submissions'])

		#This has to run to make sure the drawing number gets generated after the form is made!!!
		instance.drawingNumber()
		instance.save()
		return instance

class NewSubForm(forms.ModelForm):
	class Meta:
		model = Submissions
		fields = ['sub_date','req_drawings','project']
		labels = {
			'sub_date':('Submission Date')
		}
		help_texts = {
			'sub_date':('This should be in the format of... Year(XX), Month(XX), Day(XX)')
		}

		widgets = {'project': forms.HiddenInput(),

		}
  #           'sub_date': Charfield(attrs={'cols': 80, 'rows': 20}),
  #       }


import cv2
import random
from albumentations import (
    HorizontalFlip,
    IAAPerspective,
    ShiftScaleRotate,
    CLAHE,
    RandomRotate90,
    Transpose,
    ShiftScaleRotate,
    Blur,
    OpticalDistortion,
    GridDistortion,
    HueSaturationValue,
    IAAAdditiveGaussianNoise,
    GaussNoise,
    MotionBlur,
    MedianBlur,
    IAAPiecewiseAffine,
    IAASharpen,
    IAAEmboss,
    RandomContrast,
    RandomBrightness,
    JpegCompression,
    Flip,
    OneOf,
    Compose,
    RandomGamma,
    ElasticTransform,
    ChannelShuffle,
    RGBShift,
    Rotate,
    Normalize,
    RandomBrightnessContrast,
    Resize,
    CenterCrop,
    PadIfNeeded
)

from albumentations.torch import ToTensor
from albumentations.core.transforms_interface import ImageOnlyTransform

def resize_sa(img, size):
    '''Resize, keeping the aspect ratio same
    Larger side is set to `size`, smaller side adjusted
    acc to aspect ratio
    image.shape -> height, width
    cv2.resize takes (width, height)
    '''

    h, w, _ = img.shape
    if h <= w: # equality is imp.
        nh, nw = int(size * (h/w) ), size
    elif h > w:
        nh, nw = size, int(size * (w/h) )
    nimg = cv2.resize(img, (nw, nh))
    return nimg

def strong_aug(p=1):
    """for reference, doesn't help"""
    return Compose(
        [
            OneOf([IAAAdditiveGaussianNoise(), GaussNoise()], p=0.2),
            OneOf(
                [
                    MotionBlur(p=0.2),
                    MedianBlur(blur_limit=3, p=0.1),
                    Blur(blur_limit=3, p=0.1),
                ],
                p=0.2,
            ),
            # ShiftScaleRotate(shift_limit=0.0625, scale_limit=0.2, rotate_limit=45, p=.2),
            OneOf(
                [
                    OpticalDistortion(p=0.3),
                    GridDistortion(p=0.1),
                    IAAPiecewiseAffine(p=0.3),
                ],
                p=0.2,
            ),
            OneOf(
                [
                    CLAHE(clip_limit=2),
                    IAASharpen(),
                    IAAEmboss(),
                    RandomContrast(),
                    RandomBrightness(),
                ],
                p=0.3,
            ),
            # HueSaturationValue(p=0.3),
        ],
        p=p,
    )

class MyCenterCrop(ImageOnlyTransform):
    """Customized center crop, randomly center crops, keeping the aspect ratio
    intact.

    Targets:
        image

    Image types:
        uint8, float32
    """

    def __init__(self, always_apply=False, p=1.0):
        super(MyCenterCrop, self).__init__(always_apply, p)

    def apply(self, image, **params):
        w, h, _ = image.shape
        ratio = random.choice([0.8, 0.85, 0.9, 0.95])
        aug = CenterCrop(int(w * ratio), int(h * ratio), p=1)
        image = aug(image=image)['image']
        return image

    def get_transform_init_args_names(self):
        return ()

def get_transforms(phase, cfg):
    size = cfg["size"]
    mean = eval(cfg["mean"])
    std = eval(cfg["std"])

    list_transforms = []
    img_trfms = []
    if phase == "train":
        list_transforms.extend(
            [
                #HorizontalFlip(),
                ShiftScaleRotate(
                    shift_limit=0.1,
                    scale_limit=0.1,
                    rotate_limit=20,
                    p=0.7,
                    border_mode=1 #cv2.BORDER_CONSTANT
                ),
            ]
        )
        img_trfms = Compose([
                OneOf(
                    [
                        CLAHE(clip_limit=2),
                        IAASharpen(),
                        IAAEmboss(),
                        RandomBrightnessContrast(),
                        JpegCompression(),
                        Blur(),
                        GaussNoise(),
                    ],
                    p=0.5,
                ),
        ])

    list_transforms.extend(
        [
            Resize(size, size),
            Normalize(mean=mean, std=std, p=1),
            ToTensor(),  # [6]
        ]
    )

    list_trfms = Compose(list_transforms)

    return list_trfms, img_trfms

def get_tta():
    tta = Compose(
        [
            Rotate(limit=180, p=0.5),
            Transpose(p=0.5),
            Flip(p=0.5),
            #RandomScale(scale_limit=0.1),
            ShiftScaleRotate(
                shift_limit=0,  # no resizing
                scale_limit=0.1,
                rotate_limit=120,
                p=0.5,
                border_mode=cv2.BORDER_CONSTANT
            ),

        ]
    )
    return tta


import speech_recognition as sr
import moviepy.editor as mp
clip=mp.VideoFileClip(r"Dog_story.mp4")
clip.audio.write_audiofile(r"audio_dog.wav")
r=sr.Recognizer()
audio=sr.AudioFile('audio_dog.wav')
with audio as source:
    audio_file=r.record(source)
result=r.recognize_google(audio_file)
with open('recognized.txt',mode='w') as file:
    file.write("Recgnized Speech:")
    file.write("\n")
    file.write(result)
    print("Your text is ready")


import json

from example.tests import TestBase

from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse, reverse_lazy
from django.conf import settings

class FormatKeysSetTests(TestBase):
    """
    Test that camelization and underscoring of key names works if they are activated.
    """
    list_url = reverse_lazy('user-list')

    def setUp(self):
        super(FormatKeysSetTests, self).setUp()
        self.detail_url = reverse('user-detail', kwargs={'pk': self.miles.pk})

        # Set the format keys settings.
        setattr(settings, 'REST_EMBER_FORMAT_KEYS', True)
        setattr(settings, 'REST_EMBER_PLURALIZE_KEYS', True)

    def tearDown(self):
        # Remove the format keys settings.
        delattr(settings, 'REST_EMBER_FORMAT_KEYS')
        delattr(settings, 'REST_EMBER_PLURALIZE_KEYS')

    def test_camelization(self):
        """
        Test that camelization works.
        """
        response = self.client.get(self.list_url)
        self.assertEqual(response.status_code, 200)

        user = get_user_model().objects.all()[0]
        expected = {
            u'user': [{
                u'id': user.pk,
                u'firstName': user.first_name,
                u'lastName': user.last_name,
                u'email': user.email
            }]
        }

        json_content = json.loads(response.content)
        meta = json_content.get('meta')

        self.assertEquals(expected.get('user'), json_content.get('user'))
        self.assertEqual('http://testserver/user-viewset/?page=2', meta.get('nextLink'))

    def test_pluralization(self):
        """
        Test that the key name is pluralized.
        """
        response = self.client.get(self.list_url, {'page_size': 2})
        self.assertEqual(response.status_code, 200)

        users = get_user_model().objects.all()
        expected = {
            u'users': [{
                u'id': users[0].pk,
                u'firstName': users[0].first_name,
                u'lastName': users[0].last_name,
                u'email': users[0].email
            },{
                u'id': users[1].pk,
                u'firstName': users[1].first_name,
                u'lastName': users[1].last_name,
                u'email': users[1].email
            }]
        }

        json_content = json.loads(response.content)
        self.assertEquals(expected.get('users'), json_content.get('users'))


import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name="salesforcecli",
    version="0.0.12",
    author="Will Watkinson",
    author_email="wjwats4295@gmail.com",
    description="A package to explore a Salesforce org, perform queries, bulk creates, updates and deletes",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://gitlab.com/wjwatkinson/salesforcecli",
    packages=["sfcli"],
    install_requires=['simple-salesforce',
                      'tabulate',
                      'pandas',
                      'python-dotenv'],
    entry_points={
        'console_scripts': [
            'salesforcecli = sfcli.__main__:main',
        ],
    },
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    python_requires='>=3.6',
)


import pandas as pd

GENDER_DATA = 'F:\\TU\\6.sem\\bac\\gender-classifier-DFE-791531.csv\\file.csv'

def extract_gender_username(file_path):
    df_gender = pd.read_csv(GENDER_DATA)
    # reduces size from 20.050 to 13.926
    df_gender = df_gender[df_gender['gender:confidence'] == 1]
    return df_gender[["_golden", "gender", "name"]]

def df_to_csv(df, filename):
    df[["name","gender"]].to_csv(filename, header=False, index=False)

if __name__ == "__main__":
    df = extract_gender_username(GENDER_DATA)
    all_ng_data = df[~df["_golden"]].sample(frac=1, random_state=12345)
    training_data = all_ng_data[:300]
    validation_data = df[df["_golden"]]
    test_data = all_ng_data[300:]

    df_to_csv(training_data, "training_users.csv")
    df_to_csv(validation_data, "validation_users.csv")
    df_to_csv(test_data, "test_users.csv")


#!/usr/bin/env python3.7
# Copyright: Ismael Narváez Berenjeno
from decimal import Decimal, getcontext
from typing import Union
from metric_standarization.lib.welford_online_algorithm import WelfordOnlineAlgorithm

class MetricStandarization(WelfordOnlineAlgorithm):
    """
    Standarize metric to analyze data behaviour.

    Using this method, we can standarize using only last
    value received.

    It is based on Welford Online Algorithm. That method doesn't offer
    protection against number samples overflow.

    We solve this problem setting a max. value for the
    number of samples.

    Also, you can set MAX_NUMBER_SAMPLES with a low value number
    to increment last values weights, incrementing importance of new samples over
    operations.
    """

    def __init__(
        self,
        logger,
        dimension_name: str,
        prec: int = 28,
        min_number_samples: int = 10000,
        max_number_samples: int = 86400*30
    ):
        if min_number_samples > max_number_samples:
            raise ValueError(
                "Min. number samples can't be greather than max. number samples"
            )
        super().__init__(
            logger=logger,
            dimension_name=dimension_name,
            prec=prec,
            max_number_samples=max_number_samples
        )
        self.__prec = int(prec)
        getcontext().prec = self.__prec
        self.min_number_samples = min_number_samples
        self.__standarized_value = None
        self.logger.debug(
            f"Instantiated {self.__class__.__name__} "
            + f"for dimension {self.name}"
        )

    def __repr__(self):
        return (
            f"<MetricStandarization for dimension {self.name}"
            + f" | {self.mean} +- {self.std} | Samples: {self.number_samples}>"
        )

    @property
    def backup(self) -> dict:
        """
        Get important info to backup.

        :return: Backup info
        """
        backup_data = super().backup
        backup_data['min_number_samples'] = self.min_number_samples
        return backup_data

    def restore(
        self,
        dimension_name: str,
        mean: Union[Decimal, str, int, float],
        std: Union[Decimal, str, int, float],
        variance: Union[Decimal, str, int, float],
        sum_of_squares: Union[Decimal, str, int, float],
        number_samples: Union[Decimal, int, str, float],
        prec: int = 28,
        min_number_samples: int = 10000,
        max_number_samples: int = 86400*30,
        ) -> None:
        """
        We'll use this method to avoid precision lost.
        """
        super().restore(
            dimension_name=dimension_name,
            mean=mean,
            std=std,
            variance=variance,
            sum_of_squares=sum_of_squares,
            number_samples=number_samples,
            prec=prec,
            max_number_samples=max_number_samples
        )
        getcontext().prec = self.__prec
        self.min_number_samples = min_number_samples

    @property
    def standarized_value(self) -> Union[None, Decimal]:
        """
        Return standarized value.

        :return: standarized value
        """
        return self.__standarized_value

    @property
    def z_score(self) -> Union[None, Decimal]:
        """
        Return Z-Score.

        :return: Z score
        """
        return self.standarized_value

    def __calculate_z_score(self, value: Decimal) -> Union[None, Decimal]:
        """
        Calculate Z score if metric is distributed like a gaussian distribution.

        it cannot calculate Z score if metric isn't distributed like Gaussian
        distribution.

        :return: None for not gaussian distribution, Z score if it is ok
        """
        if self.std == 0:
            self.logger.warning(
                f"Metric {self.name} isn't distributed like "
                f"a Gaussian distribution. Mean: {self.mean} | Std: {self.std} "
                f"| Number samples: {self.number_samples}"
            )
            return None
        else:
            return Decimal(
                (value - self.mean)/self.std
            )

    def update(self, value: Decimal) -> None:
        """
        Update stats.

        :param value: New value
        """
        super().update(value)
        if self.number_samples >= self.min_number_samples:
            self.__standarized_value = self.__calculate_z_score(value)
        else:
            self.__standarized_value = None


import six

from marshmallow import Schema as MarshmallowSchema
from marshmallow import fields

from .base import DynamORMSchema
from ..exceptions import ValidationError

class Schema(MarshmallowSchema, DynamORMSchema):
    """This is the base class for marshmallow based schemas"""

    @staticmethod
    def field_to_dynamo_type(field):
        """Given a marshmallow field object return the appropriate Dynamo type character"""
        if isinstance(field, fields.Raw):
            return 'B'
        if isinstance(field, fields.Number):
            return 'N'
        return 'S'

    @classmethod
    def dynamorm_fields(cls):
        return cls().fields

    @classmethod
    def dynamorm_validate(cls, obj, partial=False, native=False):
        if native:
            data, errors = cls().load(obj, partial=partial)
        else:
            data, errors = cls(partial=partial).dump(obj)
        if errors:
            raise ValidationError(obj, cls.__name__, errors)

        # When asking for partial native objects (during model init) we want to return None values
        # This ensures our object has all attributes and we can track partial saves properly
        if partial and native:
            for name in six.iterkeys(cls().fields):
                if name not in data:
                    data[name] = None

        return data

    @staticmethod
    def base_field_type():
        return fields.Field


def strandSort(inputList):
    #create outputList
    outputList = []
    #create sublist
    sublist = []
    #while inputList is not empty
    while inputList:
        #move first item of inputList to sublist
        sublist.append(inputList[0])
        del inputList[0]
        #traverse inputList
        index = 0
        while index < len(inputList):
            #if current number is greater than last number in sublist, move number from inputList to sublist
            if inputList[index] > sublist[-1]:
                sublist.append(inputList[index])
                del inputList[index]
                index -= 1
            index += 1
        #merge sublist into outputList
        outputList = merge(sublist, outputList)
        del sublist[:]
    return outputList

#merge two lists already sorted in increasing order into one list sorted in increasing order
def merge(list1, list2):
    indexList1 = 0
    indexList2 = 0
    outputList = []
    #while indexList1 is not equal to length of list1 and indexList2 is not equal to length of list2
    while indexList1 != len(list1) and indexList2 != len(list2):
        #if number at indexList1 in list 1 is smaller than number at indexList2 in list 2
        if list1[indexList1] < list2[indexList2]:
            #append current number at indexList1 in list 1 to outputList and increase indexList1 by 1
            outputList.append(list1[indexList1])
            indexList1 += 1
        #otherwise, append number at indexList2 in list 2 to outputList and increase indexList2 by 1
        else:
            outputList.append(list2[indexList2])
            indexList2 += 1
    #if there are any numbers left in list 1, append them to output list
    while indexList1 != len(list1):
        outputList.append(list1[indexList1])
        indexList1 += 1
    #if there are any numbers left in list 2, append them to output list
    while indexList2 != len(list2):
        outputList.append(list2[indexList2])
        indexList2 += 1
    return outputList

myList = [43, 54, 15, 13, 45, 87, 545, 435, 63, 245, 15, 753, 45, 2, 534, 15]
print(myList)
print(strandSort(myList))


import sys
import gzip
import argparse
import logging
import json
from typing import Dict

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

class Dimensions:
    def __init__(self):
        self.p1 = Point(sys.maxsize, sys.maxsize)
        self.p2 = Point(-sys.maxsize, -sys.maxsize)

    def update(self, p:Point):
        if p.x < self.p1.x:
            self.p1.x = p.x
        if p.y < self.p1.y:
            self.p1.y = p.y
        if p.x > self.p2.x:
            self.p2.x = p.x
        if p.y > self.p2.y:
            self.p2.y = p.y

MARGIN = Point(10, 10)
GRAY = 'rgb(204, 204, 204)'

def error_exit(message):
    logging.error(message)
    sys.exit()

def classes_defs(labels_template):
    return [{
        'name': 'text-black',
        'fill': 'rgb(0, 0, 0)'
    }, {
        'name': 'text-red',
        'fill': 'rgb(255, 0, 255)'
    }, {
        'name': 'text-green',
        'fill': 'rgb(0, 255, 0)'
    }, {
        'name': 'text-blue',
        'fill': 'rgb(0, 0, 255)'
    }, {
        'name': 'text-gray',
        'fill': 'rgb(204, 204, 204)'
    }, {
        'name': 'text-brown',
        'fill': 'rgb(211.65, 104.55, 30.6)'
    },  {
        'element-wise': True,
        'name': 'text',
        'fill': 'rgb(0, 0, 0)',
        'text-anchor': 'middle',
        'dominant-baseline': 'middle'
    }, {
        'name': 'circle-black',
        'stroke': 'rgb(0, 0, 0)',
        'fill': 'none'
    }, {
        'name': 'circle-red',
        'stroke': 'rgb(255, 0, 255)',
        'fill': 'none'
    }, {
        'name': 'circle-green',
        'stroke': 'rgb(0, 255, 0)',
        'fill': 'none'
    }, {
        'name': 'circle-blue',
        'stroke': 'rgb(0, 0, 255)',
        'fill': 'none'
    }, {
        'name': 'circle-gray',
        'stroke': GRAY,
        'fill': 'none'
    }, {
        'name': 'circle-brown',
        'stroke': 'rgb(211.65, 104.55, 30.6)',
        'fill': 'none'
    }, {
        'name': 'circle',
        'stroke': 'rgb(0, 0, 0)'
    }, {
        'name': 'numbering-label',
        'fill': GRAY
    }, {
        'name': 'numbering-line',
        'stroke': GRAY
    }, {
        'name': 'sequential' if labels_template else 'template',
        'visibility': 'hidden'
    }, {
        'name': 'bp-line',
        'stroke': 'rgb(0, 0, 0)'
    }, {
        'name': 'residue-circle',
        'fill': 'rgb(255,255,255)'
    }, {
        'name': 'res-line',
        'stroke': GRAY
    },
    ]

def get_font_size(classes):
    return (float)((list(filter(lambda x: x["name"] == "font", classes))[0]["font-size"]).replace("px", ""))

def classes_to_svg(data, labels_template):

    classes = data['classes'] + classes_defs(labels_template)

    svg_classes = '<style type="text/css" >\n'
    svg_classes += '<![CDATA[\n'
    for cls in classes:
        # text.brown {fill: rgb(211.65, 104.55, 30.6); }
        content = ""
        for k, v in cls.items():
            if k != 'name':
                content += f'{k}: {v}; '

        selector = cls["name"] if 'element-wise' in cls else '.' + cls["name"]
        svg_classes += f'{selector} {{ {content} }}\n'

    svg_classes += ']]>\n'
    svg_classes += '</style>\n'

    return svg_classes

def residues_to_svg(rna, dim: Dimensions, res_pos: Dict[int, Point], font_size):

    residues = '<g class="residues">'

    # Lines connected residues in the sequence are drawn
    p_prev: Point = None
    for res in rna['sequence']:
        p = Point(round(float(res['x']), 2), round(float(res['y']), 2)) + MARGIN
        if p_prev:
            residues += f'<line x1="{p_prev.x}" y1="{p_prev.y}" x2="{p.x}" y2="{p.y}" class="bp-line res-line" />\n'
        p_prev = p

    # Circles forming the background of the residues (these need to come AFTER the connecting lines as they need to be "above" them and SVG does not have z-index)
    for res in rna['sequence']:
        p = Point(round(float(res['x']), 2), round(float(res['y']), 2)) + MARGIN
        residues += f"<circle cx=\"{p.x}\" cy=\"{p.y}\" class=\"residue-circle\" r=\"{font_size*0.75}\"/>\n"

    # Residue letters
    for res in rna['sequence']:
        p = Point(round(float(res['x']), 2), round(float(res['y']), 2)) + MARGIN
        res_pos[res['residueIndex']] = p
        dim.update(p)
        cls = " ".join(res['classes'])
        residues += f"<g>" \
                    f"<title>{res['residueIndex']} (position.label in template: {res['templateResidueIndex']}.{res['templateResidueName']}')</title>" \
                    f"<text x=\"{p.x}\" y=\"{p.y}\" class=\"{cls}\" >{res['residueName']}</text>" \
                    f"</g>\n"

    residues += '</g>'

    return residues

def bps_to_svg(rna, res_pos: Dict[int, Point]):

    bps = '<g class="bps">'
    for bp in rna['basePairs']:
        r1 = bp['residueIndex1']
        r2 = bp['residueIndex2']
        p1 = res_pos[r1]
        p2 = res_pos[r2]
        cls = " ".join(bp['classes'])
        bps += f'<line x1="{p1.x}" y1="{p1.y}" x2="{p2.x}" y2="{p2.y}" class="{cls}" />\n'
    bps += '</g>'

    return bps

def labels_to_svg(rna, dim: Dimensions):

    svg_labels = '<g class="labels">\n'
    for lbl in rna['labels']:
        lbl_content = lbl['labelContent']
        lbl_line = lbl['labelLine']
        svg_labels += '<g class="label">\n'
        p = Point(lbl_content["x"],lbl_content["y"]) + MARGIN
        p1 = Point(lbl_line["x1"], lbl_line["y1"]) + MARGIN
        p2 = Point(lbl_line["x2"], lbl_line["y2"]) + MARGIN
        dim.update(p)
        dim.update(p1)
        dim.update(p2)
        svg_labels += f'<text x="{p.x}" y="{p.y}" class="{" ".join(lbl_content["classes"])}" >{lbl_content["label"]}</text>\n'
        svg_labels += f'<line x1="{p1.x}" y1="{p1.y}" x2="{p2.x}" y2="{p2.y}" class="{" ".join(lbl_line["classes"])}" />\n'
        svg_labels += '</g>'

    svg_labels += '</g>\n'

    return svg_labels

def to_svg(data, labels_template):

    dim = Dimensions()

    rna = data['rnaComplexes'][0]['rnaMolecules'][0]
    svg_classes = classes_to_svg(data, labels_template)
    res_pos: Dict[int, Point] = {}
    residues = residues_to_svg(rna, dim, res_pos, get_font_size(data['classes']))
    bps = bps_to_svg(rna, res_pos)
    svg_labels = labels_to_svg(rna, dim)

    svg = f'<svg xmlns="http://www.w3.org/2000/svg" width="{dim.p2.x + 2*MARGIN.x}" height="{dim.p2.y + 2*MARGIN.y}">\n'
    svg += svg_classes + '\n'
    svg += bps + '\n'
    svg += residues + '\n'
    svg += svg_labels + '\n'
    svg += '</svg>'
    return svg

def main():

    with open(args.input, "r") as fr:
        data = json.load(fr)
        with (sys.stdout if args.output is None else open(args.output, "w")) as fw:
            fw.write(to_svg(data, args.labels_template))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()

    parser.add_argument("-i", "--input",
                        required=True,
                        metavar='FILE',
                        help="Input structure in the JSON format.")
    parser.add_argument("-o", "--output",
                        metavar='FILE',
                        help="Output file name for the SVG file. "
                             "If non entered, the standard output will be used.")
    parser.add_argument("-l", "--labels-template",
                        action='store_true',
                        help="If set, the numbering labels will be based on numbering labels from template (e.g. Sprinzl positions for tRNA). ")

    args = parser.parse_args()

    logging.basicConfig(
        level=logging.DEBUG,
        format='%(asctime)s [%(levelname)s] %(module)s - %(message)s',
        datefmt='%H:%M:%S')

    main()


#python

#django
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static

#local
from schedule.periods import Year, Month, Week, Day

try:
    from django.conf.urls import patterns, url
except ImportError:
    from django.conf.urls.defaults import patterns, url
from django.views.generic.list import ListView
from schedule.models import Calendar
from schedule.feeds import UpcomingEventsFeed
from schedule.feeds import CalendarICalendar
from schedule.periods import Year, Month, Week, Day
from schedule.views import DeleteEventView

urlpatterns = patterns('',
    url(r'^$', 'timetableapp.views.home', name='home'),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^accounts/login/$', 'timetableapp.views.login'),
    url(r'^accounts/auth/$', 'timetableapp.views.auth_view'),
    url(r'^accounts/logout/$', 'timetableapp.views.logout'),
    url(r'^accounts/loggedin/$', 'timetableapp.views.loggedin'),
    url(r'^accounts/invalid/$', 'timetableapp.views.invalid_login'),
    url(r'^accounts/register/$', 'timetableapp.views.register_user'),
    url(r'^accounts/register_success/$', 'timetableapp.views.register_success'),

    url(r'^timetable/(?P<calendar_slug>[-\w]+)/$',
        'schedule.views.calendar_by_periods',
        name="day_calendar",
        kwargs={'periods': [Day], 'template_name': 'schedule/calendar_day.html'}),

    url(r'^timetable/compact_month/(?P<calendar_slug>[-\w]+)/$',
        'schedule.views.calendar_by_periods',
        name="compact_calendar",
        kwargs={'periods': [Month], 'template_name': 'schedule/calendar_compact_month.html'}),

    url(r'^timetable/month/(?P<calendar_slug>[-\w]+)/$',
        'schedule.views.calendar_by_periods',
        name="month_calendar",
        kwargs={'periods': [Month], 'template_name': 'schedule/calendar_month.html'}),

    url(r'^timetable/week/(?P<calendar_slug>[-\w]+)/$',
        'schedule.views.calendar_by_periods',
        name="week_calendar",
        kwargs={'periods': [Week], 'template_name': 'schedule/calendar_week.html'}),

    url(r'^timetable/daily/(?P<calendar_slug>[-\w]+)/$',
        'schedule.views.calendar_by_periods',
        name="day_calendar",
        kwargs={'periods': [Day], 'template_name': 'schedule/calendar_day.html'}),

    url(r'^lecture/$', 'timetableapp.views.lecture'),
    url(r'^calendar/$', 'schedule.views.calendar'),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

urlpatterns += patterns('',
    url(r'^cal/', include('schedule.urls')),
)


# -*-coding:utf8 -*-
#顶头加一句编码集，不然注释会报错
import os
from flask import Flask,g
from flask_ckeditor import CKEditor

ckeditor = CKEditor()
def create_app():
	app = Flask(__name__)

	#一定要添加SECRET_KEY啊，不然post请求会报错no secret key was set
	app.config['SECRET_KEY']='dev'
	app.DEBUG=True
	app.config['CKEDITOR_SERVE_LOCAL'] = True
	app.config['CKEDITOR_HEIGHT'] = 400

	# @app.template_filter('ellipsis')
	# def do_ellipsis(arg):
	# 	import re
	# 	return re.sub(r"<.*?>",'',arg)

	# from . import db
	db.init_app(app)
	# from . import auth
	# app.register_blueprint(auth.bp)

	# from . import blog
	# app.register_blueprint(blog.bp)
	# app.add_url_rule('/',endpoint='index')

	# ckeditor.init_app(app)

	return app


#/usr/bin/python3
"""
author: xiche
create at: 06/16/2018
description:
    Utils for io operation
Change log:
Date         Author      Version    Description
06/16/2018    xiche      1.0.1      Add replace variables features for TxtUtils
06/17/2018    xiche      1.0.2      add TxtUtils.read_first_line
07/30/2018    xiche      1.0.3      add cls for class method

"""
import csv
import os

def getDirFromFullPath(filePath):
    fileDir = filePath
    index1 = filePath.rfind("\\")
    index2 = filePath.rfind("/")
    index = index1 if index1 > index2 else index2
    if(index > -1):
        fileDir = filePath[0:index]
    return fileDir

def checkDir(filePath):
    fileDir = getDirFromFullPath(filePath)
    if not os.path.exists(fileDir):
        os.makedirs(fileDir)

class CSVUtils:
    @classmethod
    def writeToCSVFile(cls,filePath, rowsList, delimiterX=',',quotecharX=' ', quotingX=csv.QUOTE_MINIMAL):
        with open(filePath, 'w', newline='') as csvfile:
            spamwriter = csv.writer(csvfile, delimiter=delimiterX, quotechar=quotecharX, quoting=quotingX)
            for rows in rowsList:
                spamwriter.writerow(rows)
    @classmethod
    def readCSVRowsList(cls,filePath):
        csvRowsList = []
        with open(filePath, newline='') as csvfile:
            csvReader = csv.reader(csvfile, delimiter=',', quotechar='|')
            for row in csvReader:
                csvRowsList.append(row)
        return csvRowsList

class TxtUtils:
    @classmethod
    def write_list_to_file_with_newline(cls, filePath, rowsList, mode='w'):
        checkDir(filePath)
        with open(filePath, mode) as f:
            for row in rowsList:
                f.write("%s\n" % row)

    @classmethod
    def writeListToTxtFile(cls, filePath, rowsList, mode='w'):
        checkDir(filePath)
        with open(filePath, mode, newline='') as f:
            for row in rowsList:
                f.write("%s" % row)

    @classmethod
    def remove_first_line(cls, filePath):
        rowList = cls.readTxtRowsListWithNewLine(filePath)
        rowList = list(rowList)
        cls.writeListToTxtFile(filePath, rowList[1:])

    @classmethod
    def read_first_line(cls, filePath):
        rowList = []
        with open(filePath, newline='') as f:
            rowList = f.read().splitlines()
            rowList = (x for x in rowList if x.strip())
            rowList = list(rowList)
        return rowList[0] if len(rowList) > 0 else ""

    @classmethod
    def readTxtRowsList(cls, filePath):
        rowList = []
        with open(filePath, newline='') as f:
            rowList = f.read().splitlines()
            rowList = (x for x in rowList if x.strip())
        return rowList

    @classmethod
    def readTxtRowsListWithNewLine(cls, filePath):
        rowList = []
        with open(filePath, newline='') as f:
            rowList = f.readlines()
            rowList = (x for x in rowList if x.strip())
        return rowList

    @classmethod
    def replaceVariables(cls, file_template, file_destination, dict):
        new_lines = []
        for line in cls.readTxtRowsListWithNewLine(file_template):
            for key,val in dict.items():
                line = line.replace(key, val)
            new_lines.append(line)
        cls.writeListToTxtFile(file_destination, new_lines)

class ConfigUtils:
    @staticmethod
    def set(filePath, section, key, value):
        lines = []
        new_lines = []
        sec_expected = False
        key_expected = False
        set_ready    = False
        with open(filePath, 'r', newline='') as f:
            lines = f.readlines()

        for index, line in enumerate(lines):
            is_section = "[" in line.strip().lower()
            if(is_section and section.lower() in line.strip().lower()):
                sec_expected = True
                new_lines.append(line)
                continue
            if(sec_expected and key.lower() in line.lower()):
                key_expected = True
                line = "{0}={1}\r\n".format(key, value)
                new_lines.append(line)
                continue
            if(is_section and sec_expected and not key_expected):
                new_lines.append("{0}={1}\r\n".format(key, value))
                sec_expected = False
                key_expected = True
            new_lines.append(line)

        with open(filePath, 'w', newline='') as f:
            f.writelines(new_lines)


import sys

import numpy as np
from matplotlib import pylab as plt
from sklearn.decomposition import PCA

from data.dataimport import import_data
from encoders.baseencoder import AbstractEncoder

if __name__ == '__main__':
    if len(sys.argv) != 3:
        print("Usage <encoderPkl> <dataset.json.gz>")
        sys.exit(-1)

    data = import_data(sys.argv[2])
    encoder = AbstractEncoder.load(sys.argv[1])

    query_expressions_with_annotations = {'a': 'b', '~a': 'r', 'b': 'b', '~b': 'r', 'c': 'b', '~c': 'r',
                                          'a&b': 'b', '~(a&b)': 'r', 'a|b': 'b', '~(a|b)': 'r',
                                          # 'a^b':'b', '~(a^b)':'r', 'a>>b':'b', '~(a>>b)':'r', 'b>>a':'b', '~(b>>a)':'r',
                                          'a&c': 'b', '~(a&c)': 'r', 'a|c': 'b', '~(a|c)': 'r',
                                          # 'a^c', '~(a^c)', 'a>>c', '~(a>>c)', 'c>>a', '~(c>>a)',
                                          'b&c': 'b', '~(b&c)': 'r', 'b|c': 'b', '~(b|c)': 'r',
                                          # 'b^c', '~(b^c)', 'b>>c', '~(b>>c)', 'c>>b', '~(c>>b)',
                                          'a&(b&c)': 'b', '~(a&(b&c))': 'r', 'a|(b|c)': 'b', '~(a|(b|c))': 'r',
                                          'a|(b&c)': 'b', '~(a|(b&c))': 'r', 'a&(b|c)': 'b', '~(a&(b|c))': 'r'
                                          }
    pairs = [
        ('a', '~a'), ('b', '~b'), ('c', '~c'),
        ('a&b', '~(a&b)'), ('a|b', '~(a|b)'),
        ('a&c', '~(a&c)'), ('a|c', '~(a|c)'),
        ('b&c', '~(b&c)'), ('b|c', '~(b|c)'),
        ('a&(b&c)', '~(a&(b&c))'), ('a|(b|c)', '~(a|(b|c))'),
        ('a|(b&c)', '~(a|(b&c))'), ('a&(b|c)', '~(a&(b|c))')
    ]

    used_expressions = {}

    def add_matching(expr_data):
        expr = ''.join(expr_data[0])
        if expr in query_expressions_with_annotations:
            used_expressions[expr] = expr_data

    for name, code in data.items():
        add_matching(code['original'])
        for noisy_sample in code['noise']:
            add_matching(noisy_sample)

    query_expressions = list(query_expressions_with_annotations)
    query_encodings = [encoder.get_encoding(used_expressions[e]) for e in query_expressions]
    query_encodings = np.array(query_encodings)

    pca = PCA(n_components=2)
    pca.fit(query_encodings)
    query_encodings = pca.transform(query_encodings) * .8

    for exp1, exp2 in pairs:
        enc1 = query_encodings[query_expressions.index(exp1)]
        enc2 = query_encodings[query_expressions.index(exp2)]
        plt.plot([enc1[0], enc2[0]], [enc1[1], enc2[1]], '--', color=(.7, .7, .7))

    def make_latex_expr(expr: str):
        expr = expr.replace('&', '\\wedge ').replace('|', '\\vee ').replace('~', '\\neg ')
        return '$' + expr + '$'

    for i, expression in enumerate(query_expressions):
        color = query_expressions_with_annotations[expression]
        plt.scatter(query_encodings[i, 0], query_encodings[i, 1], color=color, s=30, marker='o')
        plt.annotate(make_latex_expr(expression), xy=(query_encodings[i, 0], query_encodings[i, 1]), color=color,
                     fontsize=15)

    plt.tick_params(
        which='both', bottom='off',
        top='off', left='off', right='off',
        labelbottom='off', labelleft='off')
    plt.tight_layout()
    plt.show()


#encoding=utf8
from numpy import *

#CART算法代码实现
def loadDataSet(fileName):
    dataMat = []
    fr = open(fileName)
    for line in fr.readlines():
        curLine = line.strip().split('\t')
        fltLine = map(float,curLine)
        dataMat.append(fltLine)
    return dataMat

def binSplitDataSet(dataSet, feature, value):
    mat0 = dataSet[nonzero(dataSet[:,feature] > value)[0],:][0]
    mat1 = dataSet[nonzero(dataSet[:,feature] <= value)[0],:][0]
    return mat0,mat1

#生成叶节点
def regLeaf(dataSet):
    return mean(dataSet[:,-1])
#在给定数据上计算目标变量的平方误差
def regErr(dataSet):
    return var(dataSet[:,-1]) * shape(dataSet)[0]

def createTree(dataSet, leafType = regLeaf, errType=regErr,ops=(1,4)):
    feat,val = chooseBestSplit(dataSet,leafType,errType,ops)
    if feat == None: return val #满足停止条件时返回叶节点值
    retTree = {}
    retTree['spInd'] = feat
    retTree['spVal'] = val
    lSet, rSet = binSplitDataSet(dataSet,feat,val)
    retTree['left'] = createTree(lSet,leafType,errType,ops)
    retTree['right'] = createTree(rSet,leafType,errType,ops)
    return retTree

#回归树的切分函数
def chooseBestSplit(dataSet,leafType = regLeaf,errType=regErr,ops=(1,4)):
    tolS = ops[0];tolN = ops[1]
    if len(set(dataSet[:,-1].T.tolist()[0])) ==1:
        return None, leafType(dataSet)
    m,n = shape(dataSet)
    S = errType(dataSet)
    bestS = inf; bestIndex = 0; bestValue = 0
    for featIndex in range(n-1):
        for splitVal in set(dataSet[:,featIndex]):
            mat0,mat1 = binSplitDataSet(dataSet,featIndex,splitVal)
            if(shape(mat0)[0] < tolN) or (shape(mat1)[0] < tolN):continue
            newS = errType(mat0) + errType(mat1)
            if newS < bestS :
                bestIndex = featIndex
                bestValue = splitVal
                bestS = newS
    if(S - bestS ) < tolS :
        return None,leafType(dataSet)
    mat0 ,mat1 = binSplitDataSet(dataSet,bestIndex,bestValue)
    if (shape(mat0)[0] < tolN) or (shape(mat1)[0] < tolN):
        return None, leafType(dataSet)
    return bestIndex,bestValue

if __name__ == '__main__':
    # testMat = mat(eye(4))
    # print testMat
    # mat0,mat1 = binSplitDataSet(testMat,1,0.5)
    # print mat0

    myDat = loadDataSet('data/ex00.txt')
    myMat = mat(myDat)
    createTree(myMat)


"""
https://leetcode.com/problems/basic-calculator-ii/

Use a stack to store ops, another stack to store nums.
When we see nums, we need to check the last op, if it is '*/', we need to do the computation.
At the end, ops stack only have '+-'. We can easily compute the final value.

Time complexity: O(N)
"""
class Solution:
    def calculate(self, s: str) -> int:
        ops, nums = [], []
        i = 0
        while i < len(s):
            if s[i] == " ":
                pass
            elif s[i] in "+-*/":
                ops.append(s[i])
            else: # digit
                num = int(s[i])
                while i + 1 < len(s) and s[i+1].isdigit():
                    num = num * 10 + int(s[i+1])
                    i += 1
                if ops and ops[-1] in "*/":
                    op = ops.pop()
                    num_prev = nums.pop()
                    if op == "*":
                        num = num * num_prev
                    else:
                        num = int(num_prev / num)
                nums.append(num)
            i += 1

        ans = nums[0]
        for i in range(len(ops)):
            if ops[i] == '+':
                ans += nums[i+1]
            else:
                ans -= nums[i+1]
        return ans


import unittest
import re
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

class TestFooter(unittest.TestCase):
    def setUp(self):
        self.browser = webdriver.Chrome()

    def testfamiliespage(self):
        """Launch the web page"""
        self.browser.get('https://higherground-boston.org/')
        """Check the navigation to partners pages"""
        whatwedo="//*[@id='menu-item-140']/div/a"
        WebDriverWait(self.browser, 5).until(lambda driver: self.browser.find_element_by_xpath(whatwedo)).click()
        ForPartners = "//*[@id='menu-item-135']/a"
        WebDriverWait(self.browser, 5).until(lambda driver: self.browser.find_element_by_xpath(ForPartners)).click()
        """Check JoinUs feature"""
        JoinUs="//*[@id='fl-post-129']/div/div[1]/div/div/div/div[2]/div/div/div/div/div/a/span"
        WebDriverWait(self.browser, 5).until(lambda driver: self.browser.find_element_by_xpath(JoinUs)).click()
        ContactUs = WebDriverWait(self.browser, 5).until(lambda driver: self.browser.find_element_by_xpath("//*[@id='fl-post-21']/div/div[1]/div/div/div/div/div/div/div[3]/div/div/h2/strong"))
        if ContactUs.is_displayed():
            print("Test Passed")
        else:
            print("Error! Try Again")

if __name__ == '__main__':
    unittest.main()


# https://www.geeksforgeeks.org/kmp-algorithm-for-pattern-searching/

def get_lps(pat):
  n = len(pat)
  lps = [0] * n    # longest proper prefix which is also suffix
  i = 1
  l = 0
  while i < n:
    if pat[i] == pat[l]:
      l += 1
      lps[i] = l
      i += 1
    else:
      if 0 < l:
        l = lps[l-1]
      else:
        i += 1

  return lps

def find(text, pat):
  res = []
  n = len(text)
  m = len(pat)

  i = 0
  l = 0
  lps = get_lps(pat)
  while i < n:
    if text[i] == pat[l]:
      i += 1
      l += 1
    else:
      if 0 < l:
        l = lps[l-1]
      else:
        i += 1

    if l == m:
      res.append(i-m)
      l = lps[l-1]

  return res

if __name__ == '__main__':
  text = 'THIS IS A TEST TEXT'
  pat = 'TEST'
  [10] == find(text, pat)

  text = 'AABAACAADAABAABA'
  pat = 'AABA'
  [0, 9, 12] == find(text, pat)

  assert [0, 1, 2, 3]== get_lps('AAAA')
  assert [0, 1, 2, 0]== get_lps('AAAB')
  assert [0, 1, 0, 1]== get_lps('AABA')
  assert [0, 0, 1, 2]== get_lps('ABAB')
  assert [0, 1, 0, 1, 2] == get_lps('AACAA')


"""pro2 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from app2.views import model_form_upload, contact_page
from .views import login_page,home_page, logout_page,dept
from django.conf import settings
from django.conf.urls.static import static
from subjects.views import Books, Articles, Papers, cse_watch,ece_watch,it_watch, read

urlpatterns = [
    url(r'^$',home_page,name="home"),
    url(r'^upload/$',model_form_upload,name='upload'),
    url(r'^login/$',login_page,name="login"),
    url(r'^admin/', admin.site.urls),
    url(r'^search/', include('search.urls', namespace='search')),
    url(r'^logout/$',logout_page,name="logout"),
    url(r'^books/$',Books,name="books"),
    url(r'^articles/$',Articles,name="articles"),
    url(r'^papers/$',Papers,name="papers"),
    url(r'^cse_watch/$',cse_watch,name="cse_watch"),
    url(r'^ece_watch/$',ece_watch,name="ece_watch"),
    url(r'^it_watch/$',it_watch,name="it_watch"),
    url(r'^read/$',read,name="read"),
    url(r'^dept/$',dept,name="dept"),
    url(r'^contact/$',contact_page,name="contact"),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)