import os
import sys
import math
import pygame
import pygame.mixer
from pygame.locals import *

class Balloon(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self) #call Sprite initializer
        self.image = pygame.image.load("balloon.jpg")
        self.rect = self.image.get_rect()
        self.mask = pygame.mask.from_surface(self.image)

width = 500
height = 300
pygame.init()
pygame.display.set_mode((width, height))

b1 = Balloon()
b2 = Balloon()

while True:
    event = pygame.event.poll()
    if event.type == pygame.QUIT:
        running = 0
    elif  pygame.sprite.spritecollide(b1, b2, False, pygame.sprite.collide_mask):
        print("sprites have collided!")


'''
    Echipa formata din: Buta Gabriel-Sebastian, Lazaroiu Teodora-Bianca, Roman Andrei-Marian, grupa 141

    Acest program se va rula in terminal si va primi ca argumente numele acestui fisier (tm.py),
un fisier ce contine un turing machine (tm_ex3.txt sau tm_ex4.txt) si un fisier ce contine mai multe siruri de input
(input_ex3.txt sau input_ex4.txt).
    Programul va incarca turing machine-ul primit si il va valida sau respinge in cazul in care nu are o
configuratie corecta. Apoi programul va citi cate un sir de input din fisier si il va accepta sau respinge.

    La exercitiul 3 primul cap va ramane in partea din stanga iar al doilea cap va trece dupa simbolul #.
Apoi se vor compara simbolurile cate 2 pentru a verifica daca al doilea este prefixul primului. Se considera
prefix inclusiv cuvantul complet, dar si cuvantul vid. Este necesar ca primul cuvant sa fie nevid.

    La exercitiul 4 am reprezentat cele 2 numere prin numarul de apartii al simbolului din alfabet si sunt separate
prin caracterul # (ex: 1 si 2 va fi a#aa). Primul cap va ramane la inceputul sirului iar cel de al doilea se va duce
la final pentru a completa sirul de input (va fi folosit pentru scriere). Sirul se va completa cu un # pentru separare
iar in continuare se vor scrie atatea caractere cate sunt in cele 2 siruri adunate (ex: a#aa#aaa)
La final, se va afisa in consola rezultatul adunarii ca numar natural.
'''

import sys

def get_section(name, l_gen):  # prin aceasta functie se vor transforma sectiunile din fisierul
                               # de configuratie in liste ce contin datele fiecarei sectiuni
    flag = False
    l_ret = []

    for line in l_gen:
        if line.lower() == name + ":":
            flag = True
            continue
        if line.lower() == "end":
            flag = False
        if flag == True:
            l_ret.append(line)

    return l_ret

def get_tm_from_file(file_name):  # functie de prelucreaza fisierul ce contine tm-ul
                                  # si il valideaza daca respecta conditiile de functionare
    f = open(file_name, "r")

    l = []

    for line in f:
        line = line.strip()
        if len(line) > 0:
            l.append(line)

    l_states = get_section("states", l)
    l_sigma = get_section("sigma", l)
    l_gamma = get_section("gamma", l)
    l_transitions = get_section("transitions", l)

    # l_states_ex va fi o lista de liste unde fiecare lista din interior contine o stare a
    # turing machine-ului, 0 sau 1 daca este stare de start, 0 sau 1 daca este stare de accept
    # si 0 sau 1 daca este stare de reject

    l_states_ex = []
    for state in l_states:
        state = state.split(",")
        l_aux = [state[0], 0, 0, 0]
        for s in state:
            if s == "S":
                l_aux[1] = 1
            if s == "A":
                l_aux[2] = 1
            if s == "R":
                l_aux[3] = 1
        l_states_ex.append(l_aux)

    # l_states va reprezenta a lista ce contine doar starile
    l = []
    for state in l_states:
        state = state.split(",", maxsplit=1)
        l.append(state[0])

    l_states = l

    # se inlocuieste simbolul '_' cu un blank
    for i in range(len(l_gamma)):
        if l_gamma[i] == '_':
            l_gamma[i] = ' '

    # o tranzitie va fi o lista ce are ca prime 3 elemente partea stanga a unei tranzitii
    # iar urmatoarele 5 elemente partea dreapta a acelei tranzitii

    # primul termen reprezinta starea din care se pleaca
    # al doilea termen reprezinta caracterul citit de primul cap
    # al treilea termen reprezinta caracterul citit de cel de al doilea cap
    # al patrulea termen reprezinta starea in care se ajunge
    # al cincilea termen reprezinta caracterul pe care il scrie primul cap
    # al saselea termen reprezinta caracterul pe care il scrie al doilea cap
    # al saptelea termen reprezinta directia in care se deplaseaza primul cap
    # al optulea termen reprezinta directia in care se deplaseaza cel de-al doilea cap

    # toate tranzitiile se vor salva intr-o lista

    l = []
    for trans in l_transitions:
        trans = trans.replace(" = ", ",")
        trans = trans.split(",")

        # se inlocuieste simbolul '_' cu un blank
        for t in trans:
            if (t == "_"):
                trans[trans.index("_")] = " "

        # se verifica daca starile din tranzitii sunt valide
        if trans[0] not in l_states:
            print(f"reject: {trans[0]} not a state")
            exit()
        if trans[3] not in l_states:
            print(f"reject: {trans[3]} not a state")
            exit()

        # se verifica daca simbolurile se afla in gamma
        if trans[1] not in l_gamma:
            print(f"reject: {trans[1]} not in gamma")
            exit()
        if trans[2] not in l_gamma:
            print(f"reject: {trans[2]} not in gamma")
            exit()
        if trans[4] not in l_gamma:
            print(f"reject: {trans[4]} not in gamma")
            exit()
        if trans[5] not in l_gamma:
            print(f"reject: {trans[5]} not in gamma")
            exit()

        # ultimii 2 termeni ai unei tranzitii trebuie sa fie L, R sau N (nu se muta)
        # pentru ca indica din ce directie sa se aleaga urmatoarele elemente
        # daca nu sunt, tranzitia nu este valida

        if trans[6] != "L" and trans[6] != "R" and trans[6] != "N":
            print(f"reject: {trans[6]} not a valid direction")
            exit()
        if trans[7] != "L" and trans[7] != "R" and trans[7] != "N":
            print(f"reject: {trans[7]} not a valid direction")
            exit()

        l.append(trans)

    l_transitions = l

    # orice simbol din sigma trebuie sa se afle si in gamma
    for s in l_sigma:
        if s not in l_gamma:
            print(f"reject: {s} in sigma, but not in gamma")
            exit()

    return l_states, l_states_ex, l_sigma, l_gamma, l_transitions

def tm_process(file_name, l_states, l_sigma, l_transitions):
    f = open(file_name, "r")
    input = [s.rstrip('\n') for s in f.readlines()]  # lista cu toate sirurile de input

    for string in input:  # se va lua fiecare sir de input pe rand si se va testa

        print(f"{string}:", end=" ")

        # transformam in lista pentru a le putea parcurge
        string = list(string)

        for s in string:  # verificam daca toate simbolurile din sirul de input sunt in sigma
            if s not in l_sigma:
                print(f"reject: input symbol \"{s}\" not in sigma")
                exit()

        for state in l_states:  # se vor determina starile de start, accept si reject
            if state[1] == 1:
                stare_curenta = state[0]
            if state[2] == 1:
                stare_accept = state[0]
            if state[3] == 1:
                stare_reject = state[0]

        i = 0 # va retine pozitia primului cap
        j = 0 # va retine pozitia celui de al doilea cap

        # luam fiecare simbol pe rand pentru a trece prin tranzitii
        # programul va rula pana cand ajunge la o stare finala

        while stare_curenta != stare_accept and stare_curenta != stare_reject:
            # pentru fiecare simbol citi se va gasi tranzitia corespunzatoare
            # din lista de tranzitii
            for trans in l_transitions:
                if trans[0] == stare_curenta and trans[1] == string[i] and trans[2] == string[j]:
                    stare_curenta = trans[3]
                    string[i] = trans[4]
                    string[j] = trans[5]

                    # daca este L, ne vom intoarce simbolul anterior
                    # daca este R, vom citi simbolul urmator
                    # daca este N, va ramane pe loc

                    if trans[6] == "L":
                        if i >= 0:
                            i = i - 1
                    if trans[6] == "R":
                        i = i + 1

                    if trans[7] == "L":
                        if j >= 0:
                            j = j - 1
                    if trans[7] == "R":
                        j = j + 1

                    # daca se depaseste lungimea sirului de input se va adauga un spatiu
                    # pentru a simula banda infinita a unei masini Turing
                    if i >= len(string):
                        string.append(" ")
                    if j >= len(string):
                        string.append(" ")

                    # in momentul in care ajunge intr-o stare de accept sau de reject
                    # procesul se incheie si se afiseaza un mesaj corespunzator
                    if stare_curenta == stare_reject:
                        print("reject")
                    if stare_curenta == stare_accept:
                        print("accept")

        # pentru fisierul de la exercitiul 4 se va afisa si rezultatul adunarii
        if file_name == "input_ex4.txt":
            # se va face o lista cu elementele de dupa al doilea #
            # iar numarul acestora va fi suma
            l = string["".join(string).rindex("#") + 1:(len(string) - 1)]
            print(f"Rezultat adunare: {len(l)}")

#
# main entry
#

l_states, l_states_ex, l_sigma, l_gamma, l_transitions = get_tm_from_file(sys.argv[1])

# afisarea componentelor tm-ului
print(f"Starile TM-ului sunt: {l_states}")
print(f"Alfabetul sigma este: {l_sigma}")
print(f"Alfabetul gamma este: {l_gamma}")
print(f"Tranzitiile TM-ului sunt: {l_transitions}\n")

tm_process(sys.argv[2], l_states_ex, l_sigma, l_transitions)

Limbaje Formale si Automate/Examen/tm.py


# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).

from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

class ZincAnalysis(object):
  """Parsed representation of a zinc analysis.

  Note also that all files in keys/values are full-path, just as they appear in the analysis file.
  If you want paths relative to the build root or the classes dir or whatever, you must compute
  those yourself.
  """

  FORMAT_VERSION_LINE = b'format version: 6\n'

  def __init__(self, compile_setup, relations, stamps, apis, source_infos, compilations):
    (self.compile_setup, self.relations, self.stamps, self.apis, self.source_infos, self.compilations) = \
      (compile_setup, relations, stamps, apis, source_infos, compilations)

  def is_equal_to(self, other):
    for self_element, other_element in zip(
        (self.compile_setup, self.relations, self.stamps, self.apis,
         self.source_infos, self.compilations),
        (other.compile_setup, other.relations, other.stamps, other.apis,
         other.source_infos, other.compilations)):
      if not self_element.is_equal_to(other_element):
        return False
    return True

  def __ne__(self, other):
    return not self.__eq__(other)

  def __hash__(self):
    return hash((self.compile_setup, self.relations, self.stamps, self.apis,
                 self.source_infos, self.compilations))

  def write_to_path(self, outfile_path):
    with open(outfile_path, 'wb') as outfile:
      self.write(outfile)

  def write(self, outfile):
    outfile.write(ZincAnalysis.FORMAT_VERSION_LINE)
    self.compile_setup.write(outfile)
    self.relations.write(outfile)
    self.stamps.write(outfile)
    self.apis.write(outfile)
    self.source_infos.write(outfile)
    self.compilations.write(outfile)

  # Translate the contents of this analysis. Useful for creating anonymized test data.
  # Note that the resulting file is not a valid analysis, as the base64-encoded serialized objects
  # will be replaced with random base64 strings. So these are useful for testing analysis parsing,
  # but not for actually reading into Zinc.
  def translate(self, token_translator):
    for element in [self.compile_setup, self.relations, self.stamps, self.apis,
                    self.source_infos, self.compilations]:
      element.translate(token_translator)


from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, LSTM, Bidirectional
from tensorflow.python.keras.layers.embeddings import Embedding
from tensorflow.keras import optimizers

def build_model_lstm_emb_(dim_output, embedding_layer):
    """
    Build a LSTM network with a given embedding layer. The model is built with a binary cross entropy loss
    and the Adam optimizer.

    :param dim_output: Dimension of the output in the LSTM layer
    :param embedding_layer: Embedding layer of type tensorflow.python.keras.layers.embedding
    :return: LSTM network
    """

    model = Sequential([
        embedding_layer,
        LSTM(dim_output),
        Dense(1, activation='relu')])

    model.compile(loss='binary_crossentropy',
                  optimizer='adam',
                  metrics=['accuracy'])

    return model

def build_model_lstm_emb(filters, vocab_size, n_dim, embedding_matrix, len_max_tweet, lr):
    """
    Build a LSTM network with a given embedding matrix. The model is built with a binary cross entropy loss
    and the Adam optimizer.

    :param dim_output: Dimension of the output in the LSTM layer
    :param embedding_layer: Embedding layer of type keras.layers.embedding
    :return: LSTM network
    """
    model = Sequential([
        Embedding(vocab_size, n_dim, weights=[embedding_matrix], input_length=len_max_tweet,
                  trainable=False),
        LSTM(filters),
        Dense(1, activation='sigmoid')])

    opt = optimizers.Adam(learning_rate=lr)

    model.compile(loss='binary_crossentropy',
                  optimizer=opt,
                  metrics=['accuracy'])

    return model


# 2015.02.05 17:22:05 IST
from thrift.Thrift import *
import Shared.ttypes
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol, TProtocol
try:
    from thrift.protocol import fastbinary
except:
    fastbinary = None

class InterfacePropertyIDL(object):
    """
      Hard property for interface which is
      obtained only once from NE.

      Attributes:
       - slot
       - port
       - speed
       - shortname
       - subif_id
      """

    thrift_spec = (None,
     (1,
      TType.I32,
      'slot',
      None,
      None),
     (2,
      TType.I32,
      'port',
      None,
      None),
     (3,
      TType.I32,
      'speed',
      None,
      None),
     (4,
      TType.STRING,
      'shortname',
      None,
      None),
     (5,
      TType.I64,
      'subif_id',
      None,
      None))

    def __init__(self, slot = None, port = None, speed = None, shortname = None, subif_id = None):
        self.slot = slot
        self.port = port
        self.speed = speed
        self.shortname = shortname
        self.subif_id = subif_id

    def read(self, iprot):
        if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
            fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
            return
        iprot.readStructBegin()
        while True:
            (fname, ftype, fid,) = iprot.readFieldBegin()
            if ftype == TType.STOP:
                break
            if fid == 1:
                if ftype == TType.I32:
                    self.slot = iprot.readI32()
                else:
                    iprot.skip(ftype)
            elif fid == 2:
                if ftype == TType.I32:
                    self.port = iprot.readI32()
                else:
                    iprot.skip(ftype)
            elif fid == 3:
                if ftype == TType.I32:
                    self.speed = iprot.readI32()
                else:
                    iprot.skip(ftype)
            elif fid == 4:
                if ftype == TType.STRING:
                    self.shortname = iprot.readString()
                else:
                    iprot.skip(ftype)
            elif fid == 5:
                if ftype == TType.I64:
                    self.subif_id = iprot.readI64()
                else:
                    iprot.skip(ftype)
            else:
                iprot.skip(ftype)
            iprot.readFieldEnd()

        iprot.readStructEnd()

    def write(self, oprot):
        if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
            oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
            return
        oprot.writeStructBegin('InterfacePropertyIDL')
        if self.slot != None:
            oprot.writeFieldBegin('slot', TType.I32, 1)
            oprot.writeI32(self.slot)
            oprot.writeFieldEnd()
        if self.port != None:
            oprot.writeFieldBegin('port', TType.I32, 2)
            oprot.writeI32(self.port)
            oprot.writeFieldEnd()
        if self.speed != None:
            oprot.writeFieldBegin('speed', TType.I32, 3)
            oprot.writeI32(self.speed)
            oprot.writeFieldEnd()
        if self.shortname != None:
            oprot.writeFieldBegin('shortname', TType.STRING, 4)
            oprot.writeString(self.shortname)
            oprot.writeFieldEnd()
        if self.subif_id != None:
            oprot.writeFieldBegin('subif_id', TType.I64, 5)
            oprot.writeI64(self.subif_id)
            oprot.writeFieldEnd()
        oprot.writeFieldStop()
        oprot.writeStructEnd()

        def validate(self):
            pass

    def __repr__(self):
        L = [ '%s=%r' % (key, value) for (key, value,) in self.__dict__.iteritems() ]
        return '%s(%s)' % (self.__class__.__name__, ', '.join(L))

    def __eq__(self, other):
        return isinstance(other, self.__class__) and self.__dict__ == other.__dict__

    def __ne__(self, other):
        return not self == other

class IssubInterfaceIDL(object):
    """
      subif_id is uint32_t

      Attributes:
       - is_sub
      """

    thrift_spec = (None, (1,
      TType.I32,
      'is_sub',
      None,
      None))

    def __init__(self, is_sub = None):
        self.is_sub = is_sub

    def read(self, iprot):
        if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
            fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
            return
        iprot.readStructBegin()
        while True:
            (fname, ftype, fid,) = iprot.readFieldBegin()
            if ftype == TType.STOP:
                break
            if fid == 1:
                if ftype == TType.I32:
                    self.is_sub = iprot.readI32()
                else:
                    iprot.skip(ftype)
            else:
                iprot.skip(ftype)
            iprot.readFieldEnd()

        iprot.readStructEnd()

    def write(self, oprot):
        if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
            oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
            return
        oprot.writeStructBegin('IssubInterfaceIDL')
        if self.is_sub != None:
            oprot.writeFieldBegin('is_sub', TType.I32, 1)
            oprot.writeI32(self.is_sub)
            oprot.writeFieldEnd()
        oprot.writeFieldStop()
        oprot.writeStructEnd()

        def validate(self):
            pass

    def __repr__(self):
        L = [ '%s=%r' % (key, value) for (key, value,) in self.__dict__.iteritems() ]
        return '%s(%s)' % (self.__class__.__name__, ', '.join(L))

    def __eq__(self, other):
        return isinstance(other, self.__class__) and self.__dict__ == other.__dict__

    def __ne__(self, other):
        return not self == other

class InterfaceConfigSpeedIDL(object):
    """
    Attributes:
     - configured
     - operational
     - capability
    """

    thrift_spec = (None,
     (1,
      TType.I32,
      'configured',
      None,
      None),
     (2,
      TType.I32,
      'operational',
      None,
      None),
     (3,
      TType.I32,
      'capability',
      None,
      None))

    def __init__(self, configured = None, operational = None, capability = None):
        self.configured = configured
        self.operational = operational
        self.capability = capability

    def read(self, iprot):
        if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
            fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
            return
        iprot.readStructBegin()
        while True:
            (fname, ftype, fid,) = iprot.readFieldBegin()
            if ftype == TType.STOP:
                break
            if fid == 1:
                if ftype == TType.I32:
                    self.configured = iprot.readI32()
                else:
                    iprot.skip(ftype)
            elif fid == 2:
                if ftype == TType.I32:
                    self.operational = iprot.readI32()
                else:
                    iprot.skip(ftype)
            elif fid == 3:
                if ftype == TType.I32:
                    self.capability = iprot.readI32()
                else:
                    iprot.skip(ftype)
            else:
                iprot.skip(ftype)
            iprot.readFieldEnd()

        iprot.readStructEnd()

    def write(self, oprot):
        if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
            oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
            return
        oprot.writeStructBegin('InterfaceConfigSpeedIDL')
        if self.configured != None:
            oprot.writeFieldBegin('configured', TType.I32, 1)
            oprot.writeI32(self.configured)
            oprot.writeFieldEnd()
        if self.operational != None:
            oprot.writeFieldBegin('operational', TType.I32, 2)
            oprot.writeI32(self.operational)
            oprot.writeFieldEnd()
        if self.capability != None:
            oprot.writeFieldBegin('capability', TType.I32, 3)
            oprot.writeI32(self.capability)
            oprot.writeFieldEnd()
        oprot.writeFieldStop()
        oprot.writeStructEnd()

        def validate(self):
            pass

    def __repr__(self):
        L = [ '%s=%r' % (key, value) for (key, value,) in self.__dict__.iteritems() ]
        return '%s(%s)' % (self.__class__.__name__, ', '.join(L))

    def __eq__(self, other):
        return isinstance(other, self.__class__) and self.__dict__ == other.__dict__

    def __ne__(self, other):
        return not self == other

class InterfaceConfigDuplexIDL(object):
    """
    Attributes:
     - configured
     - operational
    """

    thrift_spec = (None, (1,
      TType.BYTE,
      'configured',
      None,
      None), (2,
      TType.BYTE,
      'operational',
      None,
      None))

    def __init__(self, configured = None, operational = None):
        self.configured = configured
        self.operational = operational

    def read(self, iprot):
        if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
            fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
            return
        iprot.readStructBegin()
        while True:
            (fname, ftype, fid,) = iprot.readFieldBegin()
            if ftype == TType.STOP:
                break
            if fid == 1:
                if ftype == TType.BYTE:
                    self.configured = iprot.readByte()
                else:
                    iprot.skip(ftype)
            elif fid == 2:
                if ftype == TType.BYTE:
                    self.operational = iprot.readByte()
                else:
                    iprot.skip(ftype)
            else:
                iprot.skip(ftype)
            iprot.readFieldEnd()

        iprot.readStructEnd()

    def write(self, oprot):
        if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
            oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
            return
        oprot.writeStructBegin('InterfaceConfigDuplexIDL')
        if self.configured != None:
            oprot.writeFieldBegin('configured', TType.BYTE, 1)
            oprot.writeByte(self.configured)
            oprot.writeFieldEnd()
        if self.operational != None:
            oprot.writeFieldBegin('operational', TType.BYTE, 2)
            oprot.writeByte(self.operational)
            oprot.writeFieldEnd()
        oprot.writeFieldStop()
        oprot.writeStructEnd()

        def validate(self):
            pass

    def __repr__(self):
        L = [ '%s=%r' % (key, value) for (key, value,) in self.__dict__.iteritems() ]
        return '%s(%s)' % (self.__class__.__name__, ', '.join(L))

    def __eq__(self, other):
        return isinstance(other, self.__class__) and self.__dict__ == other.__dict__

    def __ne__(self, other):
        return not self == other

class InterfaceConfigAutonegIDL(object):
    """
    Attributes:
     - configured
     - operational
    """

    thrift_spec = (None, (1,
      TType.BYTE,
      'configured',
      None,
      None), (2,
      TType.BYTE,
      'operational',
      None,
      None))

    def __init__(self, configured = None, operational = None):
        self.configured = configured
        self.operational = operational

    def read(self, iprot):
        if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
            fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
            return
        iprot.readStructBegin()
        while True:
            (fname, ftype, fid,) = iprot.readFieldBegin()
            if ftype == TType.STOP:
                break
            if fid == 1:
                if ftype == TType.BYTE:
                    self.configured = iprot.readByte()
                else:
                    iprot.skip(ftype)
            elif fid == 2:
                if ftype == TType.BYTE:
                    self.operational = iprot.readByte()
                else:
                    iprot.skip(ftype)
            else:
                iprot.skip(ftype)
            iprot.readFieldEnd()

        iprot.readStructEnd()

    def write(self, oprot):
        if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
            oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
            return
        oprot.writeStructBegin('InterfaceConfigAutonegIDL')
        if self.configured != None:
            oprot.writeFieldBegin('configured', TType.BYTE, 1)
            oprot.writeByte(self.configured)
            oprot.writeFieldEnd()
        if self.operational != None:
            oprot.writeFieldBegin('operational', TType.BYTE, 2)
            oprot.writeByte(self.operational)
            oprot.writeFieldEnd()
        oprot.writeFieldStop()
        oprot.writeStructEnd()

        def validate(self):
            pass

    def __repr__(self):
        L = [ '%s=%r' % (key, value) for (key, value,) in self.__dict__.iteritems() ]
        return '%s(%s)' % (self.__class__.__name__, ', '.join(L))

    def __eq__(self, other):
        return isinstance(other, self.__class__) and self.__dict__ == other.__dict__

    def __ne__(self, other):
        return not self == other

class InterfaceConfigFlowCtrlIDL(object):
    """
    Attributes:
     - input_configured
     - input_operational
     - output_configured
     - output_operational
    """

    thrift_spec = (None,
     (1,
      TType.BYTE,
      'input_configured',
      None,
      None),
     (2,
      TType.BYTE,
      'input_operational',
      None,
      None),
     (3,
      TType.BYTE,
      'output_configured',
      None,
      None),
     (4,
      TType.BYTE,
      'output_operational',
      None,
      None))

    def __init__(self, input_configured = None, input_operational = None, output_configured = None, output_operational = None):
        self.input_configured = input_configured
        self.input_operational = input_operational
        self.output_configured = output_configured
        self.output_operational = output_operational

    def read(self, iprot):
        if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
            fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
            return
        iprot.readStructBegin()
        while True:
            (fname, ftype, fid,) = iprot.readFieldBegin()
            if ftype == TType.STOP:
                break
            if fid == 1:
                if ftype == TType.BYTE:
                    self.input_configured = iprot.readByte()
                else:
                    iprot.skip(ftype)
            elif fid == 2:
                if ftype == TType.BYTE:
                    self.input_operational = iprot.readByte()
                else:
                    iprot.skip(ftype)
            elif fid == 3:
                if ftype == TType.BYTE:
                    self.output_configured = iprot.readByte()
                else:
                    iprot.skip(ftype)
            elif fid == 4:
                if ftype == TType.BYTE:
                    self.output_operational = iprot.readByte()
                else:
                    iprot.skip(ftype)
            else:
                iprot.skip(ftype)
            iprot.readFieldEnd()

        iprot.readStructEnd()

    def write(self, oprot):
        if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
            oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
            return
        oprot.writeStructBegin('InterfaceConfigFlowCtrlIDL')
        if self.input_configured != None:
            oprot.writeFieldBegin('input_configured', TType.BYTE, 1)
            oprot.writeByte(self.input_configured)
            oprot.writeFieldEnd()
        if self.input_operational != None:
            oprot.writeFieldBegin('input_operational', TType.BYTE, 2)
            oprot.writeByte(self.input_operational)
            oprot.writeFieldEnd()
        if self.output_configured != None:
            oprot.writeFieldBegin('output_configured', TType.BYTE, 3)
            oprot.writeByte(self.output_configured)
            oprot.writeFieldEnd()
        if self.output_operational != None:
            oprot.writeFieldBegin('output_operational', TType.BYTE, 4)
            oprot.writeByte(self.output_operational)
            oprot.writeFieldEnd()
        oprot.writeFieldStop()
        oprot.writeStructEnd()

        def validate(self):
            pass

    def __repr__(self):
        L = [ '%s=%r' % (key, value) for (key, value,) in self.__dict__.iteritems() ]
        return '%s(%s)' % (self.__class__.__name__, ', '.join(L))

    def __eq__(self, other):
        return isinstance(other, self.__class__) and self.__dict__ == other.__dict__

    def __ne__(self, other):
        return not self == other

class InterfaceConfigIDL(object):
    """
      Soft property (configuration) of interface
      Currently retrieved on demand
      in future can be refreshed automatically

      Attributes:
       - layer2
       - mtu
       - snmp
       - tx
       - rx
       - mode
       - encap
       - duplex
       - displayName
       - macaddr
       - descr
       - ipRedirect
       - ipUnreachable
       - ipProxyArp
       - ipUnicastReversePath
       - ipHelperAddr
       - speedIDL
       - duplexIDL
       - autoNegIDL
       - fcIDL
       - fwdClassID
      """

    thrift_spec = (None,
     (1,
      TType.I32,
      'layer2',
      None,
      None),
     (2,
      TType.I32,
      'mtu',
      None,
      None),
     (3,
      TType.I64,
      'snmp',
      None,
      None),
     (4,
      TType.I32,
      'tx',
      None,
      None),
     (5,
      TType.I32,
      'rx',
      None,
      None),
     (6,
      TType.BYTE,
      'mode',
      None,
      None),
     (7,
      TType.BYTE,
      'encap',
      None,
      None),
     (8,
      TType.BYTE,
      'duplex',
      None,
      None),
     (9,
      TType.STRING,
      'displayName',
      None,
      None),
     (10,
      TType.LIST,
      'macaddr',
      (TType.BYTE, None),
      [1,
       2,
       3,
       4,
       5,
       6]),
     (11,
      TType.STRING,
      'descr',
      None,
      None),
     (12,
      TType.I32,
      'ipRedirect',
      None,
      None),
     (13,
      TType.I32,
      'ipUnreachable',
      None,
      None),
     (14,
      TType.I32,
      'ipProxyArp',
      None,
      None),
     (15,
      TType.I32,
      'ipUnicastReversePath',
      None,
      None),
     (16,
      TType.LIST,
      'ipHelperAddr',
      (TType.STRUCT, (Shared.ttypes.NetworkAddressIDL, Shared.ttypes.NetworkAddressIDL.thrift_spec)),
      None),
     (17,
      TType.STRUCT,
      'speedIDL',
      (InterfaceConfigSpeedIDL, InterfaceConfigSpeedIDL.thrift_spec),
      None),
     (18,
      TType.STRUCT,
      'duplexIDL',
      (InterfaceConfigDuplexIDL, InterfaceConfigDuplexIDL.thrift_spec),
      None),
     (19,
      TType.STRUCT,
      'autoNegIDL',
      (InterfaceConfigAutonegIDL, InterfaceConfigAutonegIDL.thrift_spec),
      None),
     (20,
      TType.STRUCT,
      'fcIDL',
      (InterfaceConfigFlowCtrlIDL, InterfaceConfigFlowCtrlIDL.thrift_spec),
      None),
     (21,
      TType.I32,
      'fwdClassID',
      None,
      None))

    def __init__(self, layer2 = None, mtu = None, snmp = None, tx = None, rx = None, mode = None, encap = None, duplex = None, displayName = None, macaddr = thrift_spec[10][4], descr = None, ipRedirect = None, ipUnreachable = None, ipProxyArp = None, ipUnicastReversePath = None, ipHelperAddr = None, speedIDL = None, duplexIDL = None, autoNegIDL = None, fcIDL = None, fwdClassID = None):
        self.layer2 = layer2
        self.mtu = mtu
        self.snmp = snmp
        self.tx = tx
        self.rx = rx
        self.mode = mode
        self.encap = encap
        self.duplex = duplex
        self.displayName = displayName
        if macaddr is self.thrift_spec[10][4]:
            macaddr = [1,
             2,
             3,
             4,
             5,
             6]
        self.macaddr = macaddr
        self.descr = descr
        self.ipRedirect = ipRedirect
        self.ipUnreachable = ipUnreachable
        self.ipProxyArp = ipProxyArp
        self.ipUnicastReversePath = ipUnicastReversePath
        self.ipHelperAddr = ipHelperAddr
        self.speedIDL = speedIDL
        self.duplexIDL = duplexIDL
        self.autoNegIDL = autoNegIDL
        self.fcIDL = fcIDL
        self.fwdClassID = fwdClassID

    def read(self, iprot):
        if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
            fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
            return
        iprot.readStructBegin()
        while True:
            (fname, ftype, fid,) = iprot.readFieldBegin()
            if ftype == TType.STOP:
                break
            if fid == 1:
                if ftype == TType.I32:
                    self.layer2 = iprot.readI32()
                else:
                    iprot.skip(ftype)
            elif fid == 2:
                if ftype == TType.I32:
                    self.mtu = iprot.readI32()
                else:
                    iprot.skip(ftype)
            elif fid == 3:
                if ftype == TType.I64:
                    self.snmp = iprot.readI64()
                else:
                    iprot.skip(ftype)
            elif fid == 4:
                if ftype == TType.I32:
                    self.tx = iprot.readI32()
                else:
                    iprot.skip(ftype)
            elif fid == 5:
                if ftype == TType.I32:
                    self.rx = iprot.readI32()
                else:
                    iprot.skip(ftype)
            elif fid == 6:
                if ftype == TType.BYTE:
                    self.mode = iprot.readByte()
                else:
                    iprot.skip(ftype)
            elif fid == 7:
                if ftype == TType.BYTE:
                    self.encap = iprot.readByte()
                else:
                    iprot.skip(ftype)
            elif fid == 8:
                if ftype == TType.BYTE:
                    self.duplex = iprot.readByte()
                else:
                    iprot.skip(ftype)
            elif fid == 9:
                if ftype == TType.STRING:
                    self.displayName = iprot.readString()
                else:
                    iprot.skip(ftype)
            elif fid == 10:
                if ftype == TType.LIST:
                    self.macaddr = []
                    (_etype3, _size0,) = iprot.readListBegin()
                    for _i4 in xrange(_size0):
                        _elem5 = iprot.readByte()
                        self.macaddr.append(_elem5)

                    iprot.readListEnd()
                else:
                    iprot.skip(ftype)
            elif fid == 11:
                if ftype == TType.STRING:
                    self.descr = iprot.readString()
                else:
                    iprot.skip(ftype)
            elif fid == 12:
                if ftype == TType.I32:
                    self.ipRedirect = iprot.readI32()
                else:
                    iprot.skip(ftype)
            elif fid == 13:
                if ftype == TType.I32:
                    self.ipUnreachable = iprot.readI32()
                else:
                    iprot.skip(ftype)
            elif fid == 14:
                if ftype == TType.I32:
                    self.ipProxyArp = iprot.readI32()
                else:
                    iprot.skip(ftype)
            elif fid == 15:
                if ftype == TType.I32:
                    self.ipUnicastReversePath = iprot.readI32()
                else:
                    iprot.skip(ftype)
            elif fid == 16:
                if ftype == TType.LIST:
                    self.ipHelperAddr = []
                    (_etype9, _size6,) = iprot.readListBegin()
                    for _i10 in xrange(_size6):
                        _elem11 = Shared.ttypes.NetworkAddressIDL()
                        _elem11.read(iprot)
                        self.ipHelperAddr.append(_elem11)

                    iprot.readListEnd()
                else:
                    iprot.skip(ftype)
            elif fid == 17:
                if ftype == TType.STRUCT:
                    self.speedIDL = InterfaceConfigSpeedIDL()
                    self.speedIDL.read(iprot)
                else:
                    iprot.skip(ftype)
            elif fid == 18:
                if ftype == TType.STRUCT:
                    self.duplexIDL = InterfaceConfigDuplexIDL()
                    self.duplexIDL.read(iprot)
                else:
                    iprot.skip(ftype)
            elif fid == 19:
                if ftype == TType.STRUCT:
                    self.autoNegIDL = InterfaceConfigAutonegIDL()
                    self.autoNegIDL.read(iprot)
                else:
                    iprot.skip(ftype)
            elif fid == 20:
                if ftype == TType.STRUCT:
                    self.fcIDL = InterfaceConfigFlowCtrlIDL()
                    self.fcIDL.read(iprot)
                else:
                    iprot.skip(ftype)
            elif fid == 21:
                if ftype == TType.I32:
                    self.fwdClassID = iprot.readI32()
                else:
                    iprot.skip(ftype)
            else:
                iprot.skip(ftype)
            iprot.readFieldEnd()

        iprot.readStructEnd()

    def write(self, oprot):
        if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
            oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
            return
        oprot.writeStructBegin('InterfaceConfigIDL')
        if self.layer2 != None:
            oprot.writeFieldBegin('layer2', TType.I32, 1)
            oprot.writeI32(self.layer2)
            oprot.writeFieldEnd()
        if self.mtu != None:
            oprot.writeFieldBegin('mtu', TType.I32, 2)
            oprot.writeI32(self.mtu)
            oprot.writeFieldEnd()
        if self.snmp != None:
            oprot.writeFieldBegin('snmp', TType.I64, 3)
            oprot.writeI64(self.snmp)
            oprot.writeFieldEnd()
        if self.tx != None:
            oprot.writeFieldBegin('tx', TType.I32, 4)
            oprot.writeI32(self.tx)
            oprot.writeFieldEnd()
        if self.rx != None:
            oprot.writeFieldBegin('rx', TType.I32, 5)
            oprot.writeI32(self.rx)
            oprot.writeFieldEnd()
        if self.mode != None:
            oprot.writeFieldBegin('mode', TType.BYTE, 6)
            oprot.writeByte(self.mode)
            oprot.writeFieldEnd()
        if self.encap != None:
            oprot.writeFieldBegin('encap', TType.BYTE, 7)
            oprot.writeByte(self.encap)
            oprot.writeFieldEnd()
        if self.duplex != None:
            oprot.writeFieldBegin('duplex', TType.BYTE, 8)
            oprot.writeByte(self.duplex)
            oprot.writeFieldEnd()
        if self.displayName != None:
            oprot.writeFieldBegin('displayName', TType.STRING, 9)
            oprot.writeString(self.displayName)
            oprot.writeFieldEnd()
        if self.macaddr != None:
            oprot.writeFieldBegin('macaddr', TType.LIST, 10)
            oprot.writeListBegin(TType.BYTE, len(self.macaddr))
            for iter12 in self.macaddr:
                oprot.writeByte(iter12)

            oprot.writeListEnd()
            oprot.writeFieldEnd()
        if self.descr != None:
            oprot.writeFieldBegin('descr', TType.STRING, 11)
            oprot.writeString(self.descr)
            oprot.writeFieldEnd()
        if self.ipRedirect != None:
            oprot.writeFieldBegin('ipRedirect', TType.I32, 12)
            oprot.writeI32(self.ipRedirect)
            oprot.writeFieldEnd()
        if self.ipUnreachable != None:
            oprot.writeFieldBegin('ipUnreachable', TType.I32, 13)
            oprot.writeI32(self.ipUnreachable)
            oprot.writeFieldEnd()
        if self.ipProxyArp != None:
            oprot.writeFieldBegin('ipProxyArp', TType.I32, 14)
            oprot.writeI32(self.ipProxyArp)
            oprot.writeFieldEnd()
        if self.ipUnicastReversePath != None:
            oprot.writeFieldBegin('ipUnicastReversePath', TType.I32, 15)
            oprot.writeI32(self.ipUnicastReversePath)
            oprot.writeFieldEnd()
        if self.ipHelperAddr != None:
            oprot.writeFieldBegin('ipHelperAddr', TType.LIST, 16)
            oprot.writeListBegin(TType.STRUCT, len(self.ipHelperAddr))
            for iter13 in self.ipHelperAddr:
                iter13.write(oprot)

            oprot.writeListEnd()
            oprot.writeFieldEnd()
        if self.speedIDL != None:
            oprot.writeFieldBegin('speedIDL', TType.STRUCT, 17)
            self.speedIDL.write(oprot)
            oprot.writeFieldEnd()
        if self.duplexIDL != None:
            oprot.writeFieldBegin('duplexIDL', TType.STRUCT, 18)
            self.duplexIDL.write(oprot)
            oprot.writeFieldEnd()
        if self.autoNegIDL != None:
            oprot.writeFieldBegin('autoNegIDL', TType.STRUCT, 19)
            self.autoNegIDL.write(oprot)
            oprot.writeFieldEnd()
        if self.fcIDL != None:
            oprot.writeFieldBegin('fcIDL', TType.STRUCT, 20)
            self.fcIDL.write(oprot)
            oprot.writeFieldEnd()
        if self.fwdClassID != None:
            oprot.writeFieldBegin('fwdClassID', TType.I32, 21)
            oprot.writeI32(self.fwdClassID)
            oprot.writeFieldEnd()
        oprot.writeFieldStop()
        oprot.writeStructEnd()

        def validate(self):
            pass

    def __repr__(self):
        L = [ '%s=%r' % (key, value) for (key, value,) in self.__dict__.iteritems() ]
        return '%s(%s)' % (self.__class__.__name__, ', '.join(L))

    def __eq__(self, other):
        return isinstance(other, self.__class__) and self.__dict__ == other.__dict__

    def __ne__(self, other):
        return not self == other

class InterfaceStatusIDL(object):
    """
      Snapshot of dynamic status, retrieved on demand

      Attributes:
       - link
       - lineproto
      """

    thrift_spec = (None, (1,
      TType.I32,
      'link',
      None,
      None), (2,
      TType.I32,
      'lineproto',
      None,
      None))

    def __init__(self, link = None, lineproto = None):
        self.link = link
        self.lineproto = lineproto

    def read(self, iprot):
        if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
            fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
            return
        iprot.readStructBegin()
        while True:
            (fname, ftype, fid,) = iprot.readFieldBegin()
            if ftype == TType.STOP:
                break
            if fid == 1:
                if ftype == TType.I32:
                    self.link = iprot.readI32()
                else:
                    iprot.skip(ftype)
            elif fid == 2:
                if ftype == TType.I32:
                    self.lineproto = iprot.readI32()
                else:
                    iprot.skip(ftype)
            else:
                iprot.skip(ftype)
            iprot.readFieldEnd()

        iprot.readStructEnd()

    def write(self, oprot):
        if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
            oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
            return
        oprot.writeStructBegin('InterfaceStatusIDL')
        if self.link != None:
            oprot.writeFieldBegin('link', TType.I32, 1)
            oprot.writeI32(self.link)
            oprot.writeFieldEnd()
        if self.lineproto != None:
            oprot.writeFieldBegin('lineproto', TType.I32, 2)
            oprot.writeI32(self.lineproto)
            oprot.writeFieldEnd()
        oprot.writeFieldStop()
        oprot.writeStructEnd()

        def validate(self):
            pass

    def __repr__(self):
        L = [ '%s=%r' % (key, value) for (key, value,) in self.__dict__.iteritems() ]
        return '%s(%s)' % (self.__class__.__name__, ', '.join(L))

    def __eq__(self, other):
        return isinstance(other, self.__class__) and self.__dict__ == other.__dict__

    def __ne__(self, other):
        return not self == other

class InterfaceStatisticsIDL(object):
    """
    Attributes:
     - retcode
     - stats
    """

    thrift_spec = (None, (1,
      TType.I32,
      'retcode',
      None,
      None), (2,
      TType.I64,
      'stats',
      None,
      None))

    def __init__(self, retcode = None, stats = None):
        self.retcode = retcode
        self.stats = stats

    def read(self, iprot):
        if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
            fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
            return
        iprot.readStructBegin()
        while True:
            (fname, ftype, fid,) = iprot.readFieldBegin()
            if ftype == TType.STOP:
                break
            if fid == 1:
                if ftype == TType.I32:
                    self.retcode = iprot.readI32()
                else:
                    iprot.skip(ftype)
            elif fid == 2:
                if ftype == TType.I64:
                    self.stats = iprot.readI64()
                else:
                    iprot.skip(ftype)
            else:
                iprot.skip(ftype)
            iprot.readFieldEnd()

        iprot.readStructEnd()

    def write(self, oprot):
        if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
            oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
            return
        oprot.writeStructBegin('InterfaceStatisticsIDL')
        if self.retcode != None:
            oprot.writeFieldBegin('retcode', TType.I32, 1)
            oprot.writeI32(self.retcode)
            oprot.writeFieldEnd()
        if self.stats != None:
            oprot.writeFieldBegin('stats', TType.I64, 2)
            oprot.writeI64(self.stats)
            oprot.writeFieldEnd()
        oprot.writeFieldStop()
        oprot.writeStructEnd()

        def validate(self):
            pass

    def __repr__(self):
        L = [ '%s=%r' % (key, value) for (key, value,) in self.__dict__.iteritems() ]
        return '%s(%s)' % (self.__class__.__name__, ', '.join(L))

    def __eq__(self, other):
        return isinstance(other, self.__class__) and self.__dict__ == other.__dict__

    def __ne__(self, other):
        return not self == other

class InterfaceVlanIDL(object):
    """
    Attributes:
     - encapType
     - vlanTag1
     - vlanTag2
    """

    thrift_spec = (None,
     (1,
      TType.I32,
      'encapType',
      None,
      None),
     (2,
      TType.I32,
      'vlanTag1',
      None,
      None),
     (3,
      TType.I32,
      'vlanTag2',
      None,
      None))

    def __init__(self, encapType = None, vlanTag1 = None, vlanTag2 = None):
        self.encapType = encapType
        self.vlanTag1 = vlanTag1
        self.vlanTag2 = vlanTag2

    def read(self, iprot):
        if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
            fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
            return
        iprot.readStructBegin()
        while True:
            (fname, ftype, fid,) = iprot.readFieldBegin()
            if ftype == TType.STOP:
                break
            if fid == 1:
                if ftype == TType.I32:
                    self.encapType = iprot.readI32()
                else:
                    iprot.skip(ftype)
            elif fid == 2:
                if ftype == TType.I32:
                    self.vlanTag1 = iprot.readI32()
                else:
                    iprot.skip(ftype)
            elif fid == 3:
                if ftype == TType.I32:
                    self.vlanTag2 = iprot.readI32()
                else:
                    iprot.skip(ftype)
            else:
                iprot.skip(ftype)
            iprot.readFieldEnd()

        iprot.readStructEnd()

    def write(self, oprot):
        if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
            oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
            return
        oprot.writeStructBegin('InterfaceVlanIDL')
        if self.encapType != None:
            oprot.writeFieldBegin('encapType', TType.I32, 1)
            oprot.writeI32(self.encapType)
            oprot.writeFieldEnd()
        if self.vlanTag1 != None:
            oprot.writeFieldBegin('vlanTag1', TType.I32, 2)
            oprot.writeI32(self.vlanTag1)
            oprot.writeFieldEnd()
        if self.vlanTag2 != None:
            oprot.writeFieldBegin('vlanTag2', TType.I32, 3)
            oprot.writeI32(self.vlanTag2)
            oprot.writeFieldEnd()
        oprot.writeFieldStop()
        oprot.writeStructEnd()

        def validate(self):
            pass

    def __repr__(self):
        L = [ '%s=%r' % (key, value) for (key, value,) in self.__dict__.iteritems() ]
        return '%s(%s)' % (self.__class__.__name__, ', '.join(L))

    def __eq__(self, other):
        return isinstance(other, self.__class__) and self.__dict__ == other.__dict__

    def __ne__(self, other):
        return not self == other

class PChannel_MemberIDL(object):
    """
    Attributes:
     - xosHandle
    """

    thrift_spec = (None, (1,
      TType.I64,
      'xosHandle',
      None,
      None))

    def __init__(self, xosHandle = None):
        self.xosHandle = xosHandle

    def read(self, iprot):
        if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
            fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
            return
        iprot.readStructBegin()
        while True:
            (fname, ftype, fid,) = iprot.readFieldBegin()
            if ftype == TType.STOP:
                break
            if fid == 1:
                if ftype == TType.I64:
                    self.xosHandle = iprot.readI64()
                else:
                    iprot.skip(ftype)
            else:
                iprot.skip(ftype)
            iprot.readFieldEnd()

        iprot.readStructEnd()

    def write(self, oprot):
        if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
            oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
            return
        oprot.writeStructBegin('PChannel_MemberIDL')
        if self.xosHandle != None:
            oprot.writeFieldBegin('xosHandle', TType.I64, 1)
            oprot.writeI64(self.xosHandle)
            oprot.writeFieldEnd()
        oprot.writeFieldStop()
        oprot.writeStructEnd()

        def validate(self):
            pass

    def __repr__(self):
        L = [ '%s=%r' % (key, value) for (key, value,) in self.__dict__.iteritems() ]
        return '%s(%s)' % (self.__class__.__name__, ', '.join(L))

    def __eq__(self, other):
        return isinstance(other, self.__class__) and self.__dict__ == other.__dict__

    def __ne__(self, other):
        return not self == other

# decompiled 1 files: 1 okay, 0 failed, 0 verify failed
# 2015.02.05 17:22:06 IST


# -*- coding: utf-8 -*-
"""
Created on Mon Apr 10 14:02:33 2017

@author: Dell
"""
import numpy as np
from matplotlib.font_manager import FontProperties
from matplotlib import pyplot as plt

class code_spectrum(object):
    def __init__(self,alpha_max,Tg,xi):
        gamma=0.9+(0.05-xi)/(0.3+6*xi)
        eta1=0.02+(0.05-xi)/(4+32*xi)
        eta1=eta1 if eta1>0 else 0
        eta2=1+(0.05-xi)/(0.08+1.6*xi)
        eta2=eta2 if eta2>0.55 else 0.55
        T=np.linspace(0,6,601)
        alpha=[]
        for t in T:
            if t<0.1:
                alpha.append(np.interp(t,[0,0.1],[0.45*alpha_max,eta2*alpha_max]))
            elif t<Tg:
                alpha.append(eta2*alpha_max)
            elif t<5*Tg:
                alpha.append((Tg/t)**gamma*eta2*alpha_max)
            else:
                alpha.append((eta2*0.2**gamma-eta1*(t-5*Tg))*alpha_max)
        self.__spectrum={'T':T,'alpha':alpha}

    @property
    def spectrum(self):
        return self.__spectrum

if __name__=='__main__':
    cs1=code_spectrum(0.12,0.45,0.02)
    cs2=code_spectrum(0.34,0.45,0.02)
    cs3=code_spectrum(0.72,0.45,0.02)

    font = FontProperties(fname=r"C:\\WINDOWS\\Fonts\\simsun.ttc", size=14)#C:\WINDOWS\Fonts
    plt.xlabel('T(s)',fontproperties=font)
    plt.ylabel('α',fontproperties=font)
    plt.plot(cs1.spectrum['T'],cs1.spectrum['alpha'],label=u'小震')
    plt.plot(cs2.spectrum['T'],cs2.spectrum['alpha'],label=u'中震')
    plt.plot(cs3.spectrum['T'],cs3.spectrum['alpha'],label=u'大震')
    plt.legend(prop=font)


class Solution(object):
    def numDecodings(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s:return 0
        leng=len(s)
        memo=[1]*(leng+1)

        ind=leng-1
        while(ind>=0):
            if int(s[ind])==0: memo[ind]=0
            elif ind<leng-1 and 9<int(s[ind])*10+int(s[ind+1])<27:
                memo[ind]=memo[ind+1]+memo[ind+2]
            elif ind<leng-1:
                memo[ind]=memo[ind+1]
            ind-=1
        return memo[0]


import logging

import pandas as pd

from utils.utils import inc_data_folder_path, get_engine

daily_market_file_path = inc_data_folder_path + "DailyMarket.txt"

def load(conn):
    logging.info("Begin FactMarketHistory - Incremental Update")
    cur = conn.cursor()

    # needs to execute incremental_setup.sql first
    df_ = pd.read_csv(daily_market_file_path, sep="|", parse_dates={"Date": ["DM_DATE"]}, keep_date_col=True,
                      names=["CDC_FLAG","CDC_DSN","DM_DATE", "DM_S_SYMB", "DM_CLOSE", "DM_HIGH", "DM_LOW", "DM_VOL"])

    df_fact = pd.DataFrame(columns=["SK_SecurityID", "SK_CompanyID", "SK_DateID", "PERatio", "Yield",
                                    "SK_FiftyTwoWeekHighDate", "SK_FiftyTwoWeekLowDate", "ClosePrice",
                                    "DayHigh", "DayLow", "Volume", "BatchID"])

    df_fact["ClosePrice"] = df_["DM_CLOSE"]
    df_fact["DayHigh"] = df_["DM_HIGH"]
    df_fact["DayLow"] = df_["DM_LOW"]
    df_fact["Volume"] = df_["DM_VOL"]
    df_fact["BatchID"] = 2

    df_fact["Symbol"] = df_["DM_S_SYMB"]  # value used by the trigger
    df_fact["Date"] = df_["Date"]  # value used by the trigger
    df_fact["SK_DateID"] = 0  # value set by the trigger
    df_fact["SK_FiftyTwoWeekLowDate"] = 0  # value set by the trigger
    df_fact["SK_FiftyTwoWeekHighDate"] = 0  # value set by the trigger
    df_fact["SK_SecurityID"] = 0  # value set by the trigger
    df_fact["SK_CompanyID"] = 0  # value set by the trigger
    df_fact["PERatio"] = 0  # value set by the trigger
    df_fact["Yield"] = 0  # value set by the trigger

    df_52 = get_52_weeks_data(df_)
    df_fact = pd.merge(df_fact, df_52, on=["Date", "Symbol"])

    df_fact["quarter"] = df_fact["Date"].apply(lambda x: 1 + (x.month - 1) // 3)
    df_fact["year"] = df_fact["Date"].apply(lambda x: x.year)
    df_fact = df_fact.apply(get_previous_quarters, axis=1)
    df_fact.drop("quarter", inplace=True, axis=1)
    df_fact.drop("year", inplace=True, axis=1)

    logging.info("Incrementally updating into MySQL")
    df_fact.to_sql("FactMarketHistory", index=False, if_exists="append", con=get_engine())

    logging.info("Dropping auxiliary columns")
    cur.execute("DROP TRIGGER tpcdi.INC_FactMarketHistory;")
    cur.execute("ALTER TABLE FactMarketHistory DROP COLUMN prev1_quarter;")
    cur.execute("ALTER TABLE FactMarketHistory DROP COLUMN prev2_quarter;")
    cur.execute("ALTER TABLE FactMarketHistory DROP COLUMN prev3_quarter;")
    cur.execute("ALTER TABLE FactMarketHistory DROP COLUMN prev4_quarter;")
    cur.execute("ALTER TABLE FactMarketHistory DROP COLUMN prev1_year;")
    cur.execute("ALTER TABLE FactMarketHistory DROP COLUMN prev2_year;")
    cur.execute("ALTER TABLE FactMarketHistory DROP COLUMN prev3_year;")
    cur.execute("ALTER TABLE FactMarketHistory DROP COLUMN prev4_year;")
    cur.execute("ALTER TABLE FactMarketHistory DROP COLUMN Date;")
    cur.execute("ALTER TABLE FactMarketHistory DROP COLUMN Symbol;")
    cur.execute("ALTER TABLE FactMarketHistory DROP COLUMN FiftyTwoWeekHigh;")
    cur.execute("ALTER TABLE FactMarketHistory DROP COLUMN FiftyTwoWeekLow;")

    conn.commit()

def get_52_weeks_data(df):
    df_grouped = df.groupby("DM_S_SYMB").rolling('365D', on="Date").agg({"DM_HIGH": "max", "DM_LOW": "min"})
    df_grouped = df_grouped.reset_index()
    return df_grouped.rename(columns={"DM_S_SYMB": "Symbol", "DM_HIGH": "FiftyTwoWeekHigh", "DM_LOW": "FiftyTwoWeekLow"})

def get_previous_quarters(row):
    year = row["year"]
    prev_year = year - 1
    quarter = row["quarter"]

    if quarter == 1:
        sequence = [4, prev_year, 3, prev_year, 2, prev_year, 1, prev_year]
    elif quarter == 2:
        sequence = [1, year, 4, prev_year, 3, prev_year, 2, prev_year]
    elif quarter == 3:
        sequence = [2, year, 1, year, 4, prev_year, 3, prev_year]
    elif quarter == 4:
        sequence = [3, year, 2, year, 1, year, 4, prev_year]
    else:
        sequence = 0 / 0

    row["prev1_quarter"] = sequence[0]
    row["prev1_year"] = sequence[1]
    row["prev2_quarter"] = sequence[2]
    row["prev2_year"] = sequence[3]
    row["prev3_quarter"] = sequence[4]
    row["prev3_year"] = sequence[5]
    row["prev4_quarter"] = sequence[6]
    row["prev4_year"] = sequence[7]

    return row


class Destination:

    def __init__(self, destinationID, country, airport, flightDuration, distanceFromIceland, contactName, contactNumber):

        self.destinationID = destinationID
        self.country = country
        self.airport = airport
        self.flightDuration = flightDuration
        self.distanceFromIceland = distanceFromIceland
        self.contactName = contactName
        self.contactNumber = contactNumber

    def __str__(self):
        return self.country + " " + self.airport + " " + self.flightDuration


board = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
placesDone = []

def printBoard():
    for j in range(len(board)):
        for i in range(len(board[0])):
            if i != 2:
                print(' ', board[j][i], ' | ', end='')
            else:
                print(' ', board[j][i], end='')
        if j != 2:
            print('\n -----------------')
        else:
            print('\n')

def place(pos, mark):
    if 1 <= pos <= 3:
        board[0][pos - 1] = mark
    elif pos <= 6:
        board[1][pos - 1 - 3] = mark
    else:
        board[2][pos - 1 - 6] = mark
    printBoard()

def check(mark):
    # check in row
    for i in range(len(board)):
        j = 0
        if board[i][j] == board[i][j + 1] == board[i][j + 2] == mark:
            return True
    # check in column
    for i in range(len(board)):
        j = 0
        if board[j][i] == board[j + 1][i] == board[j + 2][i] == mark:
            return True
    # check diagonals
    if board[0][0] == board[1][1] == board[2][2] == mark:
        return True
    if board[0][2] == board[1][1] == board[2][0] == mark:
        return True
    return False

def correctNumber(mark):
    if 1 <= mark <= 9 and mark not in placesDone:
        placesDone.append(mark)
        return int(mark)
    else:
        return correctNumber(int(input("Wrong Number, enter again: ")))

def main():
    keep_playing = 1
    while keep_playing:
        printBoard()
        print("NOTE: player 1 is X \nplayer 2 is O")
        player1 = input("Enter player 1 name: ")
        player2 = input("Enter player 2 name: ")
        k = 1
        while k != 9:
            if k % 2 == 0:
                pos = correctNumber(int(input(player1 + " enter where u want to place: ")))
                place(pos, 'X')
                done = check('X')
                if done:
                    print(player1 + " won the match")
                    break
            else:
                pos = correctNumber(int(input(player2 + " enter where u want to place: ")))
                place(pos, 'O')
                done = check('O')
                if done:
                    print(player2 + " won the match")
                    break
            k += 1
        keep_playing = int(input('\nPress 1 to continue playing, 0 to stop: '))

main()


class Tarefa:
    chegada = -1
    tempo_execucao = -1
    prioridade = -1

    tempo_restante = -1
    tempo_total_execucao = 0
    tempo_ultima_interrupcao = 0
    tempo_espera = 0

    prioridade_dinamica = -1

    def __str__(self):
        return "tarefa [ chegada: " + str(self.chegada) \
               + ", tempo de execução: " + str(self.tempo_execucao) \
               + ", prioridade: " + str(self.prioridade) \
               + ", tempo restante: " + str(self.tempo_restante) \
               + ", tempo de espera: " + str(self.tempo_espera) \
               + ", tempo total de execução: " + str(self.tempo_total_execucao) + "]\n "

def print_relatorio_tarefas(tarefas, nome_algoritmo):
    tempo_total_espera = 0
    tempo_total_execucao = 0
    print("\n=====  " + nome_algoritmo + "  =====\n")
    for tarefa in tarefas:
        print(tarefa)
        tempo_total_execucao += tarefa.tempo_total_execucao
        tempo_total_espera += tarefa.tempo_espera
    print("- tempo medio de execução = " + str(tempo_total_execucao / len(tarefas)))
    print("- tempo medio de espera = " + str(tempo_total_espera / len(tarefas)))
    print("\n======================================\n")


#!/usr/bin/env python

"""Auslesen von Sensorwerten aus Home Assistant zur visuellen Rückmeldung der Raumqualität über eine im Raum angebrachte Hue Lampe"""

__author__      = "FarbenFroh"

import homeassistant.remote as remote
import json
#import configparser
import ast
import time
#import logging

class FarbenFroh:

    def init(self):
        pass

    #Let the light pulsating to a maximum brightness
    def pulsatingLightCall(self, Config, api, exceeded, bright_max, color):
        #actual brightness
        bright = 1.0
        #when the maximum brigthness is reached
        reachedmax = False
        lamp = Config.get('Sensors', 'Lamp')
        global goodRoom

        #Loop to control the light
        while (exceeded == True):
            if bright <= bright_max and not reachedmax:
                bright = bright + 1
                if (bright >= bright_max):
                    reachedmax = True
            else:
                if bright == 1:
                    exceeded = False
                    reachedmax = False
                    #Set global variable that one value is out of the defined borders
                    goodRoom = False

                bright = bright - 1

            #Call Home Assistant to set the light
            remote.call_service(api, 'light', 'turn_on', {'entity_id': lamp, 'brightness': bright, 'rgb_color': color})
            #Wait 0,1 seconds to make the brightness change smooth
            time.sleep(0.1)

    #Call the diferent functions for the values
    def setLightColor(self, Config, api, values):

        #Mimimum temperature
        color = ast.literal_eval(Config.get('Sectors', 'Temp_Min_Color'))
        FarbenFroh.pulsatingLightCall(self, Config, api, values['temp_min'], values['temp_bright'], color)

        #Maximum temperature
        color = ast.literal_eval(Config.get('Sectors', 'Temp_Max_Color'))
        FarbenFroh.pulsatingLightCall(self, Config, api, values['temp_max'], values['temp_bright'], color)

        #Minimum humidity
        color = ast.literal_eval(Config.get('Sectors', 'Hum_Min_Color'))
        FarbenFroh.pulsatingLightCall(self, Config, api, values['hum_min'], values['hum_bright'], color)

        #Maximum humidity
        color = ast.literal_eval(Config.get('Sectors', 'Hum_Max_Color'))
        FarbenFroh.pulsatingLightCall(self, Config, api, values['hum_max'], values['hum_bright'], color)

        #Maximum Co2
        color = ast.literal_eval(Config.get('Sectors', 'Co2_Max_Color'))
        FarbenFroh.pulsatingLightCall(self, Config, api, values['Co2_max'], values['Co2_bright'], color)

        #Minimum light
        color = ast.literal_eval(Config.get('Sectors', 'Light_Min_Color'))
        FarbenFroh.pulsatingLightCall(self, Config, api, values['light_min'], values['light_bright'], color)

        #When no value border is exceeded set the light to default
        color = ast.literal_eval(Config.get('Sectors', 'Default_Color'))
        remote.call_service(api, 'light', 'turn_on', {'entity_id': Config.get('Sensors', 'Lamp'), 'brightness': 1, 'rgb_color': color})

    #Check that the brightness value is in the range from 0 to 100
    def maxBright(self, value):
        if(value>100):
            value = 100
        elif(value<1):
            value = 1
        return value

    def changeLightColor(self, Config, values, api, tempAvg, humAvg, Co2Avg, lightAvg):
        #Variable to show that no value is out of bounderies
        goodRoom = True
        textlist = []
        #Get average temperature from sensors
        if tempAvg < int(Config.get('Sectors', 'Temp_Min')):
            values['temp_bright'] = FarbenFroh.maxBright(self, (tempAvg - int(Config.get('Sectors', 'Temp_Min'))) * -10)
            if values['temp_min'] == False:
                values['temp_min'] = True
                #logging.info("Temp;Min;"+str(values['temp_bright']))
            if values['temp_max'] == True:
                values['temp_max'] = False
            textlist.append('tempTooLow')
        elif tempAvg > int(Config.get('Sectors', 'Temp_Max')):
            values['temp_bright'] = FarbenFroh.maxBright(self, (tempAvg - int(Config.get('Sectors', 'Temp_Max'))) * 10)
            if values['temp_max'] == False:
                values['temp_max'] = True
                #logging.info("Temp;Max;"+str(values['temp_bright']))
            if values['temp_min'] == True:
                values['temp_min'] = False
            textlist.append('tempTooHigh')
        elif values['temp_min'] == True or values['temp_max'] == True:
            values['temp_min'] = False
            values['temp_max'] = False
            #logging.info("Temp;Normal;0")

        #Get average humidity from sensors
        if humAvg < int(Config.get('Sectors', 'Hum_Min')):
            values['hum_bright'] = FarbenFroh.maxBright(self, (humAvg - int(Config.get('Sectors', 'Hum_Min'))) * -5)
            if values['hum_min'] == False:
                values['hum_min'] = True
                #logging.info("Hum;Min;"+str(values['hum_bright']))
            if values['hum_max'] == True:
                values['hum_max'] = False
            textlist.append('humTooLow')
        elif humAvg > int(Config.get('Sectors', 'Hum_Max')):
            values['hum_bright'] = FarbenFroh.maxBright(self, (humAvg - int(Config.get('Sectors', 'Hum_Max'))) * 5)
            if values['hum_max'] == False:
                values['hum_max'] = True
                #logging.info("Hum;Max;"+str(values['hum_bright']))
            if values['hum_min'] == True:
                values['hum_min'] = False
            textlist.append('humTooHigh')
        elif values['hum_min'] == True or values['hum_max'] == True:
            values['hum_min'] = False
            values['hum_max'] = False
            #logging.info("Hum;Normal;0")

        #Get average Co2 value from sensors
        if Co2Avg > int(Config.get('Sectors', 'Co2_Max')):
            values['Co2_bright'] = FarbenFroh.maxBright(self, (Co2Avg - int(Config.get('Sectors', 'Co2_Max'))) * 0.1)
            if values['Co2_max'] == False:
                values['Co2_max'] = True
                #logging.info("Co2;Max;"+str(values['Co2_bright']))
            textlist.append('Co2TooHigh')
        elif values['Co2_max'] == True:
            values['Co2_max'] = False
            #logging.info("Co2;Normal;0")

        #Get average light value from sensors
        if lightAvg < int(Config.get('Sectors', 'Light_Min')):
            values['light_bright'] = FarbenFroh.maxBright(self, (lightAvg - int(Config.get('Sectors', 'Light_Min'))) * 0.5)
            if values['light_min'] == False:
                values['light_min'] = True
                #logging.info("Light;Max;0"))
            textlist.append('lightTooLow')
        elif values['light_min'] == True:
            values['light_min'] = False
            #logging.info("Light;Normal;0")

        #logging.debug(values)

        #Set lights calculated by the average values
        FarbenFroh.setLightColor(self, Config, api, values)
        return textlist


from __future__ import division
from multiprocessing import Pool
import sys
import os
import argparse
# # necessary to add cwd to path when script run
# # by slurm (since it executes a copy)
sys.path.append(os.getcwd())
import cv2
import numpy as np
from openslide import OpenSlide
from PIL import Image
from resizeimage import resizeimage
import random

global inputdir
global outputdir

def full_slide_to_jpeg(imgfilename, inputdir, outputdir):
    # For TCGA SLIDES
    #print(imgfilename, inputdir, outputdir)
    #print('in loop')
    sample_id = imgfilename.split(".")[0]
    # try:
    img = OpenSlide(os.path.join(inputdir, imgfilename))
    print('img.dimensions  ', img.dimensions)
    x_0 = img.dimensions[0]
    x_1 = img.dimensions[1]
    y_0 = x_0 // 8
    y_1 = x_1 // 8
    r_0 = x_0 % 8
    r_1 = x_1 % 8
    print('x_0 ', x_0, ' x_1 ', x_1, ' y_0 ', y_0, ' y_1 ', y_1, ' r_0 ', r_0, ' r_1 ', r_1)
    list_coordsx = []
    list_coordsy = []
    for i in range(1,8):
        X = y_0 * (i -1)
        Y = y_1 * (i-1)
        list_coordsx.append(X)
        list_coordsy.append(Y)
    list_coordsx.append(y_0 * 7)
    list_coordsy.append(y_1 * 7)

    np_array_f = np.zeros((int(x_0//8/10 * 8  + (x_0 - y_0*7 ) /10),  int(x_1//8/10 * 8  + (x_1 - y_1*7 ) /10) , 3))
    print(np_array_f.shape)
    cx = 0
    for elex in list_coordsx:
        cy = 0
        for eley in list_coordsy:
            ele = (elex, eley)
            if cy < 8 and cx < 8:
                try:
                    img1=img.read_region(location=ele, level=0, size=(y_0 -1 , y_1 - 1 ))
                    img11=img1.convert("RGB")
                    img111=img11.resize((int(round(y_0 / 10)),
                                            int(round(y_1 / 10))),Image.ANTIALIAS)

                    img111 = np.array(img111).transpose(1,0,2)
                    print('img111 ', img111.shape)
                    np_array_f[int(round(ele[0]/10)):  int(round(ele[0]/10)) + img111.shape[0],
                                int(round(ele[1]/10)): int(round(ele[1]/10)) + img111.shape[1],:] = img111
                except:
                    with open('errorFullSlides1stBatch_806_2159.txt', 'a') as f:
                        f.write('\n{}\t{}\t{}'.format(sample_id,elex,eley))

            elif cy >= 8 and cx <8:
                try:
                    img1=img.read_region(location=ele, level=0, size=(y_0 -1 , y_1 - 1  + r_1))
                    img11=img1.convert("RGB")
                    img111=img11.resize((int(round(y_0 / 10)),
                                            int(round(y_1 / 10))),Image.ANTIALIAS)
                    img111 = np.array(img111).transpose(1,0,2)
                    np_array_f[int(round(ele[0]/10)):  int(round(ele[0]/10)) + img111.shape[0],
                                int(round(ele[1]/10)): ,:] = img111
                except:
                    with open('errorFullSlides1stBatch_806_2159.txt', 'a') as f:
                        f.write('\n{}\t{}\t{}'.format(sample_id,elex,eley))

            elif cx >= 8 and cy <8:
                try:
                    img1=img.read_region(location=ele, level=0, size=(y_0 -1  + r_0, y_1 - 1 ))
                    img11=img1.convert("RGB")
                    img111=img11.resize((int(round(y_0 / 10)),   int(round(y_1 / 10))),Image.ANTIALIAS)
                    img111 = np.array(img111).transpose(1,0,2)

                    np_array_f[int(round(ele[0]/10)): ,
                                    int(round(ele[1]/10)): int(round(ele[1]/10)) + img111.shape[1] ,:] = img111
                except:
                    with open('errorFullSlides1stBatch_806_2159.txt', 'a') as f:
                        f.write('\n{}\t{}\t{}'.format(sample_id,elex,eley))

            else:
                try:
                    img1=img.read_region(location=ele, level=0, size=(y_0 -1 + r_0 , y_1 - 1  + r_1))
                    img11=img1.convert("RGB")
                    img111=img11.resize((int(round(y_0 / 10)),
                                            int(round(y_1 / 10))),Image.ANTIALIAS)
                    img111 = np.array(img111).transpose(1,0,2)
                    np_array_f[int(round(ele[0]/10)): ,
                                int(round(ele[1]/10)): ,:] = img111
                except:
                    with open('errorFullSlides1stBatch_806_2159.txt', 'a') as f:
                        f.write('\n{}\t{}\t{}'.format(sample_id,elex,eley))

            cy +=1
        cx += 1
    im = Image.fromarray(np_array_f.astype(np.uint8))
    im.save( os.path.join(outputdir, sample_id + '.jpg'  ) , 'JPEG', optimize=True, quality=94)

    #   print('Error with the file : ', sample_id)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Test set carcinoids for scanners.')
    parser.add_argument('--inputdir', type=str,    help="Input directory where the images are stored")
    parser.add_argument('--outputdir', type=str,    help='output directory where the files will be stored')
    args = parser.parse_args()
    outputdir = args.outputdir
    inputdir = args.inputdir

    images_l = []
    all_f = os.listdir(inputdir) # To change main folder
    for f in all_f:
        if f.find(".mrxs") != -1 or f.find(".svs") != -1:
            sample_id = f.split('.')[0]
            num = int(f.split('.')[0].split('TNE')[-1])
            #print(num)
            outputfilename = sample_id + '.jpg'
            print(sample_id)
            if num>806 and num<=2159  and outputfilename not in os.listdir(outputdir) and f not in os.listdir('/data/gcs/lungNENomics/work/follm/Images/2nd_batch_LNEN_HES') :
                print('Accept ', num)
                images_l.append(f)

    array_of_args = [(i, inputdir, outputdir) for i in images_l]
    with Pool(len(images_l)) as p:
        p.starmap(full_slide_to_jpeg, array_of_args)


import os
import re
import errno
import hashlib

from weakref import ref as weakref
from werkzeug.datastructures import Headers
from werkzeug.utils import cached_property

_member_re = re.compile(r'^(\d{4})_(.*?).txt$')
_kv_re = re.compile(r'^(.*?)\s*:\s*(.*?)$')

def _normpath(x):
    return os.path.normpath(os.path.realpath(x))

class _MetaViewContainer(object):

    def __init__(self, metaview):
        self._metaview = weakref(metaview)

    @property
    def metaview(self):
        rv = self._metaview()
        if rv is not None:
            return rv
        raise AttributeError('Meta view went away')

def read_mime(f):
    headers = []
    h = hashlib.sha1()

    def _readline():
        line = f.readline()
        h.update(line)
        line = line.decode('utf-8')
        if not line.strip():
            return u''
        return line.rstrip('\r\n')

    while 1:
        line = _readline()
        if not line:
            break
        match = _kv_re.match(line)
        if match is not None:
            headers.append(match.groups())
            continue
        elif line[:1].isspace():
            old_key, old_value = headers[-1]
            headers[-1] = (old_key, old_value + u' ' + line[1:])
        else:
            raise ValueError('Invalid mime data')

    payload = f.read()
    h.update(payload)
    return Headers(headers), payload, h.hexdigest()

class Person(_MetaViewContainer):

    def __init__(self, metaview, path, f):
        _MetaViewContainer.__init__(self, metaview)
        self.path = _normpath(os.path.join(metaview.member_path, path))
        self.meta, payload, self.checksum = read_mime(f)
        self.description = payload.decode('utf-8').rstrip()

    @property
    def name(self):
        return self.meta.get('name')

    @property
    def twitter(self):
        return self.meta.get('twitter')

    @property
    def email(self):
        return self.meta.get('e-mail')

    def to_json(self, compact=False):
        return {
            'num': self.num,
            'login': self.login,
            'name': self.name,
            'twitter': self.twitter,
            'email': self.email,
            'description': self.description,
        }

    def __repr__(self):
        return '<Person %r>' % (
            self.name,
        )

class Member(Person):

    def __init__(self, metaview, path, num, login, f):
        Person.__init__(self, metaview, path, f)
        self.num = num
        self.login = login

    @cached_property
    def sponsor(self):
        sponsor = self.meta.get('sponsor')
        if sponsor not in (None, '', '<self>'):
            return self.metaview.members_by_login.get(sponsor)

    def to_json(self, compact=False):
        if compact:
            return {'num': self.num, 'login': self.login,
                    'name': self.name}
        rv = Person.to_json(self, compact=compact)
        if self.sponsor is None:
            rv['sponsor'] = None
        else:
            rv['sponsor'] = self.sponsor.to_json(compact=True)
        return rv

    def __repr__(self):
        return '<Member %04d: %r>' % (
            self.num,
            self.login,
        )

class ExtensionStatus(_MetaViewContainer):

    def __init__(self, metaview, f):
        _MetaViewContainer.__init__(self, metaview)
        self.meta = read_mime(f)[0]

    @property
    def is_approved(self):
        return self.meta.get('approved') == 'yes'

    def to_json(self):
        return {
            'is_approved': self.is_approved,
        }

    def __repr__(self):
        return '<ExtensionStatus %r>' % (
            self.meta,
        )

class Project(_MetaViewContainer):

    def __init__(self, metaview, filename):
        _MetaViewContainer.__init__(self, metaview)
        self.short_name = filename

    @property
    def path(self):
        return os.path.join(self.metaview.projects_path, self.short_name)

    @cached_property
    def meta(self):
        try:
            with open(os.path.join(self.path, 'META'), 'rb') as f:
                return read_mime(f)[0]
        except IOError as e:
            if e.errno != errno.ENOENT:
                raise
            return Headers()

    @property
    def name(self):
        return self.meta.get('name')

    @property
    def website(self):
        return self.meta.get('website')

    @property
    def github(self):
        return self.meta.get('github')

    @property
    def bugtracker(self):
        return self.meta.get('bugtracker')

    @property
    def documentation(self):
        return self.meta.get('documentation')

    @property
    def pypi(self):
        return self.meta.get('pypi')

    @property
    def license(self):
        return self.meta.get('license')

    @property
    def status(self):
        return self.meta.get('status')

    @cached_property
    def readme(self):
        for choice in 'README.rst', 'README.md', 'README':
            try:
                with open(os.path.join(self.path, choice), 'rb') as f:
                    return f.read().decode('utf-8').rstrip()
            except IOError:
                pass

    @cached_property
    def extension_status(self):
        try:
            with open(os.path.join(
                    self.path, 'EXTENSION_STATUS'), 'rb') as f:
                return ExtensionStatus(self.metaview, f)
        except IOError:
            pass

    @property
    def is_extension(self):
        return self.extension_status is not None

    @cached_property
    def project_lead(self):
        p = os.path.join(self.path, 'PROJECT_LEAD')
        if not os.path.exists(p):
            return
        rv = self.metaview.locate_linked_member(
            os.path.join(self.path, 'PROJECT_LEAD'))
        if rv is None:
            with open(p, 'rb') as f:
                rv = Person(self.metaview, p, f)
        return rv

    @cached_property
    def stewards(self):
        p = os.path.join(self.path, 'stewardship')
        try:
            files = os.listdir(p)
        except OSError:
            return ()
        rv = []
        for filename in files:
            mem = self.metaview.locate_linked_member(os.path.join(p, filename))
            if mem is not None:
                rv.append(mem)
        return tuple(rv)

    def to_json(self):
        return {
            'short_name': self.short_name,
            'name': self.name,
            'website': self.website,
            'github': self.github,
            'bugtracker': self.bugtracker,
            'documentation': self.documentation,
            'pypi': self.pypi,
            'license': self.license,
            'status': self.status,
            'readme': self.readme,
            'extension_status': self.extension_status
                and self.extension_status.to_json() or None,
            'is_extension': self.is_extension,
            'project_lead': self.project_lead
                and self.project_lead.to_json(compact=True) or None,
            'stewards': [x.to_json(compact=True) for x in self.stewards],
        }

    def __repr__(self):
        return '<Project %r>' % (
            self.short_name,
        )

def read_members(metaview):
    rv = []
    for filename in os.listdir(metaview.member_path):
        match = _member_re.match(filename)
        if match is None:
            continue
        if isinstance(filename, bytes):
            filename = filename.decode('utf-8')
        num, login = match.groups()
        with open(os.path.join(metaview.member_path, filename), 'rb') as f:
            rv.append(Member(metaview, filename, int(num), login, f))
    rv.sort(key=lambda x: x.num)
    return rv

def read_projects(metaview):
    rv = []
    for filename in os.listdir(metaview.projects_path):
        if filename[:1] == '.':
            continue
        if os.path.isdir(os.path.join(metaview.projects_path, filename)):
            rv.append(Project(metaview, filename))
    return rv

class MetaView(object):

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

        self.members_by_num = {}
        self.members_by_login = {}
        self.members_by_checksum = {}
        self.members_by_path = {}

        for mem in read_members(self):
            self.members_by_num[mem.num] = mem
            self.members_by_login[mem.login] = mem
            self.members_by_checksum[mem.checksum] = mem
            self.members_by_path[mem.path] = mem

        self.projects = {}
        for proj in read_projects(self):
            self.projects[proj.short_name] = proj

    def to_json(self):
        return {
            'members': [x.to_json() for x in self.iter_members()],
            'projects': [x.to_json() for x in self.iter_projects()],
        }

    def iter_members(self):
        return (x[1] for x in sorted(self.members_by_num.items()))

    def iter_projects(self):
        return self.projects.values()

    def locate_linked_member(self, path):
        npath = _normpath(path)
        try:
            lpath = _normpath(os.path.join(os.path.dirname(path),
                                           os.readlink(path)))
            rv = self.members_by_path.get(lpath)
            if rv is not None:
                return rv
        except OSError:
            pass

        try:
            with open(npath, 'rb') as f:
                checksum = hashlib.sha1(f.read()).hexdigest()
                return self.members_by_checksum.get(checksum)
        except IOError:
            pass

    @property
    def member_path(self):
        return os.path.join(self.path, 'members')

    @property
    def projects_path(self):
        return os.path.join(self.path, 'projects')

if __name__ == '__main__':
    import json
    mv = MetaView(os.path.join(os.path.dirname(__file__), '..'))
    print(json.dumps(mv.to_json(), indent=2))