Ejemplo n.º 1
0
def oncegame(a,b):
    p_1=mode(a['t'])
    p_2=mode(b['t'])
    a_now_mode=p_1.f_mode()#获取本次出拳状况
    b_now_mode=p_2.f_mode()
    a_path=''
    b_path=''
    for i in range(1,11):
        bout=i
        a_path+=a_now_mode#记录本次出拳状况,
        b_path+=b_now_mode
        a['m']+=condition[str(a_now_mode)+'_'+str(b_now_mode)][0]#根据出拳形式分配金钱
        b['m']+=condition[str(a_now_mode)+'_'+str(b_now_mode)][1]
        a_now_mode=p_1.next_mode(bout,b_path)#根据对手的出钱状况判断下一次出拳状况
        b_now_mode=p_2.next_mode(bout,a_path)
    print(a_path,b_path)
Ejemplo n.º 2
0
    def irc_324(self, command, prefix, args):
        """ 
            324 is a basic mode reply. We use it to get the mode
            of a channel we just joined.

            But we can also receive this mode for channels we have not 
            joined, in which case it will not contain the channelkey
            (if any)

            Todo: check the channelstate to see if we really want this
            info, or if the user just typed /mode #foo
        """
        # check 'await 324 flag' in model?
        modechange = mode(join(args[2:]))
        #
        # DRY - this code looks alot like the code in irc_MODE
        chanModel = self.serverState.getChannel(args[1])
        #
        # However, we don't handle all modes here (such as o,b,v)
        ## XXX DUPLICATION
        modemap = { 'p':model.channel.MODE_PRIVATE,
                    's':model.channel.MODE_SECURE,
                    'n':model.channel.MODE_NOMSG,
                    't':model.channel.MODE_TOPIC,
                    'i':model.channel.MODE_INVITE }

        for i in range(len(modechange.plusmodes())):
            c = modechange.plusmode(i)
            if c == 'l':
                # in this context, we can assume the limit is not ""
                chanModel.setlimit(atoi(modechange.plusparam(i)))
            elif c == 'k':
                # in this context, we can assume the key is not ""
                chanModel.setkey(modechange.plusparam(i))
            elif c == 'I':
                chanModel.addinvite(modechange.plusparam(i))
            elif c == 'e':
                chanModel.addexcempt(modechange.plusparam(i))
            else:
                if modemap.has_key(c):
                    chanModel.setmode(modemap[c])
                # else warn for unknown channelmode?
        for i in range(len(modechange.minmodes())):
            c = modechange.minmode(i)
            if c == 'l':
                chanModel.setlimit(0)
            elif c == 'k':
                chanModel.setkey("")
            elif c == 'I':
                chanModel.addinvite(modechange.minparam(i))
            elif c == 'e':
                chanModel.addexcempt(modechange.minparam(i))
            else:
                if modemap.has_key(i):
                     chanModel.delmode(modemap[c])
                # else warn for unknown channelmode?
        if self.channels.has_key(args[1]):
            chanView = self.channels[args[1]]
            chanView.modechange(args[0], modechange, notice=0)
Ejemplo n.º 3
0
    def __init__(self):
        ## Initializing instances of subclasses
        self.r = robot.robot()
        self.g = gripper.gripper()

        ## Initializing node and setting up topics
        rospy.init_node('main', anonymous=True)
        self.o = optoForce.optoForce(tf, rospy)  ## test
        self.m = mode.mode(self.r, self.g, self.o, self)
        self.rate = rospy.Rate(125)
        self.urPublisher = rospy.Publisher('/ur_driver/URScript',
                                           String,
                                           queue_size=10)
        self.ledPublisher = rospy.Publisher('/led', LED, queue_size=10)
        self.gripperPub = rospy.Publisher(
            '/Robotiq2FGripperRobotOutput',
            outputMsg.Robotiq2FGripper_robot_output,
            queue_size=10)
        self.optoZeroPub = rospy.Publisher('/ethdaq_zero', Bool, queue_size=1)
        rospy.Subscriber("/joint_states", JointState, self.robotCallback)
        rospy.Subscriber("/ethdaq_data", WrenchStamped,
                         self.wrenchSensorCallback)
        rospy.Subscriber("/buttons", Buttons, self.buttonsCallback)
        rospy.Subscriber("/Robotiq2FGripperRobotInput",
                         inputMsg.Robotiq2FGripper_robot_input,
                         self.gripperCallback)
        time.sleep(1)

        self.ledPublisher.publish(led1=True, led2=True, led3=True)

        ## Activating gripper
        # Sending first a reset to the gripper so if it have been wrongly activated before it will be a fresh start when our init runs.
        # Sleep 0.1s and then start the activating sequence.
        msgReset = outputMsg.Robotiq2FGripper_robot_output()
        msgReset.rACT = 0
        self.gripperPub.publish(msgReset)
        time.sleep(0.3)
        msgActivate = outputMsg.Robotiq2FGripper_robot_output()
        msgActivate.rACT = 1
        msgActivate.rGTO = 1
        msgActivate.rSP = 255
        msgActivate.rFR = 10
        self.gripperPub.publish(msgActivate)
        time.sleep(2)

        ## Initialization complete, ready for the work in workspace to be done.
        self.workspace()
Ejemplo n.º 4
0
 def setup_read_motion(self):
     print("Connecting")
     self.vehicle = connect('/dev/ttyS0',
                            wait_ready=True,
                            baud=57600,
                            rate=2,
                            use_native=True,
                            heartbeat_timeout=-1)
     self.MODE = mode(self.vehicle)
     self.CAMERA = detect()
     self.led = led()
     self.ROCK = rocking_wings(self.vehicle)
     self.count = 0
     self.flag = 0
     self.flag_count = 25
     self.dt = 0.1
     self.RED_CIRCLE = 0
     self.BLUE_SQUARE = 0
     self.mode_thread = Scheduler(self.MODE.updateMode, 0.5)
     self.rock_thread = Scheduler(self.ROCK.read_motion, 0.25)
     self.mode_thread.start()
     print("Complite Initial Setup")
     self.led.flash_second(3)
Ejemplo n.º 5
0
    def irc_MODE(self, command, prefix, args):
        """ MODE has several syntaxes I think """
        
        target = args[0]
        rest = args[1:]
        remainder = args[-1]
        nick = getnick(prefix)

        modechange = mode(rest)
        if self.channels.has_key(target):
            chanModel = self.serverState.getChannel(target)
            chanView = self.channels[target]

            #
            # TODO: Parse individual modes and call appropriate methods on 
            # channelview, instead of passing the entire mode change to 1 method
            chanView.modechange(nick, modechange)
            
            ###modechange.plusmodes(), 
            ###            modechange.minmodes(), modechange.plusparams(),
            ###                     modechange.minparams())

            #
            # Dict to map modechars to model modes
            modemap = { 'p':model.channel.MODE_PRIVATE,
                        's':model.channel.MODE_SECURE,
                        'n':model.channel.MODE_NOMSG,
                        't':model.channel.MODE_TOPIC,
                        'i':model.channel.MODE_INVITE }
            #
            # modes have been parsed, now analyze them and update model/view
            for i in range(len(modechange.plusmodes())):
                c = modechange.plusmodes()[i]
                if c == 'o':
                    nick = modechange.plusparam(i)
                    userModel = chanModel.getuser(nick)
                    m = userModel.setmode(model.user.MODE_OP)
                    chanView.usermodechange(nick, mode2char(m))
                elif c == 'v':
                    nick = modechange.plusparam(i)
                    userModel = chanModel.getuser(nick)
                    m = userModel.setmode(model.user.MODE_VOICE)
                    chanView.usermodechange(nick, mode2char(m))
                elif c == 'b':
                    chanModel.addban(modechange.plusparam(i))
                elif c == 'l':
                    # in this context, we can assume the limit is not ""
                    chanModel.setlimit(atoi(modechange.plusparam(i)))
                elif c == 'k':
                    # in this context, we can assume the key is not ""
                    chanModel.setkey(modechange.plusparam(i))
                elif c == 'I':
                    chanModel.addinvite(modechange.plusparam(i))
                elif c == 'e':
                    chanModel.addexcempt(modechange.plusparam(i))
                else:
                    if modemap.has_key(c):
                        chanModel.setmode(modemap[c])
                    # else warn for unknown channelmode?
            for i in range(len(modechange.minmodes())):
                c = modechange.minmodes()[i]
                if c == 'o':
                    nick = modechange.minparam(i)
                    userModel = chanModel.getuser(nick)
                    m = userModel.delmode(model.user.MODE_OP)
                    chanView.usermodechange(nick, mode2char(m))
                elif c == 'v':
                    nick = modechange.minparam(i)
                    userModel = chanModel.getuser(nick)
                    m = userModel.delmode(model.user.MODE_VOICE)
                    chanView.usermodechange(nick, mode2char(m))
                elif c == 'b':
                    chanModel.delban(modechange.minparam(i))
                elif c == 'l':
                    chanModel.setlimit(0)
                elif c == 'k':
                    chanModel.setkey("")
                elif c == 'I':
                    chanModel.delinvite(modechange.minparam(i))
                elif c == 'e':
                    chanModel.delexcempt(modechange.minparam(i))
                else:
                    if modemap.has_key(c):
                         chanModel.delmode(modemap[c])
                    # else warn for unknown channelmode?
        elif self.isme(nick):
            # The <:Test MODE Test :-i> form
            self.viewtext.modechange(nick, modechange)
        else:
            # is this likely?
            self.viewtext.announce("%s sets mode %s on %s" % \
                      (nick, join(rest, " "), target))
        ##
        ## For now, don't log user mode changes (i.e. VladDrac +i).
        ## channel - user mode changes are still logged.
        if not self.isme(target):
            self.logger.log(target, "*** %s sets mode %s on %s" % \
                      (nick, join(rest, " "), target))
Ejemplo n.º 6
0
def phase1(matrixA, D, P, L, S, H, k):
  r, M = matrixA.shape
  i = 0
  u = P
  matrixX = matrixA.copy()
  d=np.linspace(0,len(matrixA)-1,len(matrixA-1),dtype=np.int)
  c = d.copy()
  keyss = []
  values = []
  for row  in range(0, r):
       ro = RowObject()
       ro.index = row
       ro.nonzeros = nonZerosInRow(matrixA, row, 1, L - u)
       
       if (row >= S) and (row < S + H ):
           ro.isHDPC = 1
       else:
           ro.isHDPC = 0

       nonZerosArr = nonZeroRowIterator(matrixA, row, 1, L - u)
       if (ro.nonzeros == 2) and (ro.isHDPC == 0):
           for n in range(0,len(nonZerosArr)):
               cellarr = nonZerosArr[n]
               ro.degree = ro.degree ^ cellarr[1]
               ro.nodes.append(cellarr[0])     
       else:
           od = 0
           for n in range(0,len(nonZerosArr)):
               od = od + nonZerosArr[n][1] 
           ro.degree = od
       
       keyss.append(row)
       values.append(ro)

  keyss=np.array(keyss).reshape(len(keyss),1)

  columnMap={} #keyss->values
  for i1 in range(0,len(values)):
      columnMap[i1]=values[i1]

  nonHDPCRows = S + k

  chosenRowsCounter = 0
  MO = octetmath()
  index=0
  while (i + u) < L:
    mindegree = 256 * L
    r = L + 1
    ro = RowObject()
    two1s = 0
    keyss = list(columnMap.keys())
    allzeros = 1

    for ct in range(0,len(keyss)):
        row = columnMap[keyss[ct]]
        if row.nonzeros != 0:
            allzeros = 0
        
        if (row.isHDPC == 1) and (chosenRowsCounter < nonHDPCRows):
            continue
        if len(row.nodes)!=0:
            two1s=1
        if (row.nonzeros < r) and (row.nonzeros > 0):
            ro = row
            r = ro.nonzeros
            mindegree = ro.degree
        elif (row.nonzeros == r) and (row.degree < mindegree):
            ro = row
            mindegree = ro.degree  
    if (r == 2) and (two1s == 1):
        ro = 0
        noderows = []
        nodes = []
        for ct  in range(0,len(keyss)):
            row = columnMap[keyss[ct]]
            if len(row.nodes) !=0:
                noderows.append(row)
                noderows.append(row)
                nodes.extend(row.nodes)
        target = mode(nodes)
        for ct in range(0, len(nodes)):           
            if target == nodes[ct]:
                ro = noderows[ct]
                break  

    chosenRowsCounter = chosenRowsCounter + 1
    
    if ro.index!= i:
      
        matrixA[[i, ro.index], :] = matrixA[[ro.index,i], :]
        matrixX[[i, ro.index], :] = matrixX[[ro.index,i], :]
        d = swapVector(d, i, ro.index)
        other = columnMap[i]
        other.index = ro.index
        columnMap[ro.index]= other
        del columnMap[i]
        ro.index = i
    nonZeroPos = nonZeroRowIterator(matrixA, i, i, L - u)

    firstNZpos = nonZeroPos[0][0]
    
    if firstNZpos!= i:
        matrixA[:,[i,firstNZpos]] = matrixA[:,[firstNZpos,i]]
        matrixX[:,[i,firstNZpos]] = matrixX[:,[firstNZpos,i]]
        c = swapVector(c, i, firstNZpos)
    currCol = L - u-1
    nzp, ignore= len(nonZeroPos)-1,2
    while nzp > 0:
        currNZpos = nonZeroPos[nzp][0]
        if currCol != currNZpos:
            matrixA[:,[currCol,currNZpos]] = matrixA[:,[currNZpos,currCol]]
            matrixX[:,[currCol,currNZpos]] = matrixX[:,[currNZpos,currCol]]
            c = swapVector(c, currCol, currNZpos)
        nzp = nzp - 1
        currCol = currCol - 1
    alpha = matrixA[i][i]
    
    for row in range(i+1, M):
        beta = matrixA[row][i]
        
        if beta == 0:
            continue
        else:
            bOA = MO.divide(beta, alpha)   
            matrixA = MO.addRowsInPlace(matrixA, bOA, i, row)
            D = MO.addRowsInPlace(D, bOA, d[i], d[row])
    i = i + 1
    u = u + r - 1
    keyss = list(columnMap.keys())
    for ct in range(0, len(keyss)):
        row = columnMap[keyss[ct]]
        row.nonzeros = nonZerosInRow(matrixA, row.index, i, L - u)
        row.nodes = []
        if(row.nonzeros != 2) or  (row.isHDPC == 1):
            continue
        else:
            it = nonZeroRowIterator(matrixA, row.index, i, L - u)
            for bb in range(0,len(it)):
                cellarr = it[bb]
                row.nodes.append(cellarr[0])
    index+=1
   
  matrixA, d, D = phase2(matrixA, D, d, i, M, L - u + 1, L, MO)
  C = phase3(matrixA, matrixX, D, d, c, L, i, MO)
  return C
Ejemplo n.º 7
0
#!/usr/bin/env python3
from flask import Flask
from flask import render_template
from flask import send_from_directory
from flask import redirect
from flask import request
from flask import abort
import logging
from logging.handlers import RotatingFileHandler
from mode import mode

app = Flask(__name__, static_url_path='')
control = mode()


@app.route('/')
def index():
    return render_template('index.html',
                           animation_list=control.get_animation_list(),
                           argument_list=control.get_argument_list(),
                           mode_list=control.get_mode_list(),
                           brightness=str(control.get_brightness()))


@app.route('/static/<path:path>')
def serve_static(path):
    return send_from_directory('static', path)


@app.route('/animation/<path:path>/')
def animation(path):
Ejemplo n.º 8
0
def extract_modes(modes_dir, modes_file, curr_dir):
    
    # go to directory 
    os.chdir(modes_dir)
    
    #import matlab file using h5py
    # open the file
    f = h5py.File(modes_file,'r')
    # get to the 'subfile' directions
    directions = f.get('directions')
    
    # extract the signs and convert to numpy array
    signs = directions.get('signs')
    signs = np.array(signs)
    
    # extract the counts and convert to numpy array
    counts = directions.get('counts')
    counts = [float(el) for el in counts]
    counts = np.array(counts)
    
    # extract the reversible Reactions and convert to string array
    # revRcts = f.get('revRxns')
    # revRcts = np.array(revRcts)
    # print(revRcts)
    
    # how can I read out strings from the matlab file???   -> for now I've put in here manually the reaction names
    # original revRcts -> all
    revRcts = ['R_ATPS4rpp','R_ENO','R_FBA','R_FUM','R_GAPD','R_MDH','R_PGI',
               'R_PGK','R_PGM','R_PIt2r','R_RPE','R_TALA','R_TKT1','R_TKT2',
               'R_TPI','R_PIt2r_H2PO4']
    
    # reduced revRcts -> took away phosphate transporters
    # revRcts = ['R_ATPS4rpp', 'R_ENO', 'R_FBA', 'R_FUM', 'R_GAPD', 'R_MDH', 'R_PGI', 'R_PGK',
    #          'R_PGM','R_RPE', 'R_TALA','R_TKT1','R_TKT2','R_TPI']  

#original: 'ATPS4r','ENO','FBA','FUM','GAPD','MDH','PGI',
#'PGK','PGM','PIt2r','RPE','TALA','TKT1','TKT2',
#'TPI','PIt2r_H2PO4'

    # create a list of mode objects
    modes = list()
    
    #iterate over all modes and create a mode object for each mode with the corresponding values
    for i in range(0, len(counts)):
        newmode = mode.mode(revRcts, signs[i,:], counts[i], 0, 0, 0)    
        modes.append(newmode)
        
    
    #get indices of phosphate reactions to be deleted
    P1 = revRcts.index("R_PIt2r")
    P2 = revRcts.index("R_PIt2r_H2PO4")
    P2 -= 1 #because as soon as P1 is deleted P2 is shifted
    
    # I don't understand why, but this removes the two phosphate transfer reactions from all the revRcts arrays of all modes 
    # I thought it would do that only for the mode 0, but no that's not the case... ???
    modes[0].revRcts.pop(P1)
    modes[0].revRcts.pop(P2)
    
    # go through all modes
    for i in range(0, len(modes)):
        
        # delete the sign of the phosphate transfer reactions in each mode
        modes[i].signs = np.delete(modes[i].signs, P1)
        modes[i].signs = np.delete(modes[i].signs, P2)
         
    #check for now identical modes and merge them 
    for i in range(0, len(modes)):
        for j in range (i+1, len(modes)):
            # check if indices are not longer than the list of modes and check for equality of the modes (signs)
            if( i < len(modes) and  j < len(modes) and np.array_equal(modes[i].signs, modes[j].signs)):
                # add the counts of the two identical modes and remove one of them
                modes[i].count += modes[j].count
                modes.pop(j) 
        
    # calculate the probability of each mode
    sum_counts = 0
    for i in range(0,len(modes)):
        sum_counts += modes[i].count
    
    for i in range(0, len(modes)):
        modes[i].prob = 100*(modes[i].count /sum_counts)
        

    # go back to the original/ enzyme-cost directory
    os.chdir(curr_dir) 

    return modes
Ejemplo n.º 9
0
def maquinaVirtual():
    global cuadActual, pilaContexto,contadorParam, pilaCuadActual, pilaReturn, contadorFuncEspeciales, pilaFuncionesEspeciales

    while cuadActual < cuad.contQuadAux:
        #print(cuadActual)
        #print(pilaContexto)
        #print(mem.tablaMemoriaEjecución)
        if cuad.PQuad[cuadActual]['operator'] == 'GOTO':
            cuadActual = cuad.PQuad[cuadActual]['result']
        elif cuad.PQuad[cuadActual]['operator'] == 'PRINT':
            direccionVar = cuad.PQuad[cuadActual]['result']
            if type(direccionVar) == str:
               direccionVar = mem.cambiaDireccion(direccionVar,pilaContexto[len(pilaContexto)-1])         
            print("IMPRIME CONSOLA:",mem.obtenerValordeMemoria(direccionVar,pilaContexto[len(pilaContexto)-1]))
            cuadActual += 1
        elif cuad.PQuad[cuadActual]['operator'] == 'READ':
            direccionRead = cuad.PQuad[cuadActual]['result']
            print(direccionRead)
            valorRead = input("INGRESA EL VALOR DE LA VAR: ")

            def get_type(input_data): #Identifica que tipo es lo que se ingreso'
                try:
                    return type(literal_eval(input_data))
                except (ValueError, SyntaxError):
                    # A string, so return str
                    return str

            valorTipo = str(get_type(valorRead)) #Aqui guarda string
                                                 #<class 'int'>
                                                 #<class 'float'>
                                                 #<class 'bool'>
                                                 #<class 'string'>
                                                 #dependiendo lo ingresado

            #En esta parte se comprueba que el tipo del valor ingresado concuerde
            #con el tipo de la variable ya antes declarada, si es asi, el valor
            #es convertido a el tipo correspondiente y lo almacena en memoria
            if (valorTipo[8] == 'i'):
                print('Lo que se ingresó es tipo int')
                if (direccionRead >= 1000 and direccionRead < 3000) | (direccionRead >= 11000 and direccionRead < 13000):
                    print("Si concuerda con el tipo de la variable")
                    inputVal = int(valorRead)
                else:
                    print("HORROR DE TIPOS")
                    sys.exit()
            elif (valorTipo[8] == 'f'):
                print('Lo que se ingresó es tipo float')
                if (direccionRead >= 3000 and direccionRead < 5000) | (direccionRead >= 13000 and direccionRead < 15000):
                    print("Si concuerda con el tipo de la variable")
                    inputVal = float(valorRead)
                else:
                    print("HORROR DE TIPOS")
                    sys.exit()
            elif (valorTipo[8] == 'b'):
                print('Lo que se ingresó es tipo bool')
                if (direccionRead >= 5000 and direccionRead < 7000) | (direccionRead >= 15000 and direccionRead < 17000):
                    print("Si concuerda con el tipo de la variable")
                    inputVal = bool(valorRead)
                else:
                    print("HORROR DE TIPOS")
                    sys.exit()
            else:
                print('Lo que se ingresó es tipo string')
                if (direccionRead >= 7000 and direccionRead < 9000) | (direccionRead >= 17000 and direccionRead < 19000):
                    print("Si concuerda con el tipo de la variable")
                    inputVal = valorRead
                else:
                    print("HORROR DE TIPOS")
                    sys.exit()

            mem.almacenaMemoriaEjecucion(direccionRead ,inputVal,pilaContexto[len(pilaContexto)-1])
            cuadActual += 1
        elif cuad.PQuad[cuadActual]['operator'] == '=':
            
            direccionVar = cuad.PQuad[cuadActual]['result']
            #checa si es dir indirecta -- arrays
            if type(direccionVar) == str:
               direccionVar = mem.cambiaDireccion(direccionVar,pilaContexto[len(pilaContexto)-1])
            left_operand =  cuad.PQuad[cuadActual]['left_operand']

            if type(left_operand) == str:
                left_operand= mem.cambiaDireccion(left_operand,pilaContexto[len(pilaContexto)-1])


            

            valor = mem.obtenerValordeMemoria(left_operand,pilaContexto[len(pilaContexto)-1])
            
            mem.almacenaMemoriaEjecucion(direccionVar,valor,pilaContexto[len(pilaContexto)-1])
            cuadActual += 1
        elif cuad.PQuad[cuadActual]['operator'] == '+':
            left_operand = cuad.PQuad[cuadActual]['left_operand']
            right_operand = cuad.PQuad[cuadActual]['right_operand']

            if type(left_operand) == str:
                left_operand = mem.cambiaDireccion(left_operand,pilaContexto[len(pilaContexto)-1])

            if type(right_operand) == str:
                right_operand = mem.cambiaDireccion(right_operand,pilaContexto[len(pilaContexto)-1])
                
            resultado = mem.obtenerValordeMemoria(left_operand,pilaContexto[len(pilaContexto)-1]) + mem.obtenerValordeMemoria(right_operand,pilaContexto[len(pilaContexto)-1])
            #print('suma es igual', resultado)
            mem.almacenaMemoriaEjecucion(cuad.PQuad[cuadActual]['result'],resultado,pilaContexto[len(pilaContexto)-1])
            cuadActual+=1
        elif cuad.PQuad[cuadActual]['operator'] == '+k':
            resultado = cuad.PQuad[cuadActual]['right_operand'] + mem.obtenerValordeMemoria(cuad.PQuad[cuadActual]['left_operand'],pilaContexto[len(pilaContexto)-1])
            mem.almacenaMemoriaEjecucion(cuad.PQuad[cuadActual]['result'],resultado,pilaContexto[len(pilaContexto)-1])
            cuadActual+=1
        elif cuad.PQuad[cuadActual]['operator'] == '+DirBASE':
            resultado = mem.obtenerValordeMemoria(cuad.PQuad[cuadActual]['left_operand'],pilaContexto[len(pilaContexto)-1]) + cuad.PQuad[cuadActual]['right_operand']
            #print('+DirBASE',resultado)
            direccion = '(' + str(cuad.PQuad[cuadActual]['result']) + ')'
            #print(direccion)
            mem.almacenaMemoriaEjecucion(direccion,resultado,pilaContexto[len(pilaContexto)-1])
            #print(mem.tablaMemoriaEjecución)
            cuadActual+=1
        elif cuad.PQuad[cuadActual]['operator'] == '-':
            left_operand = cuad.PQuad[cuadActual]['left_operand']
            right_operand = cuad.PQuad[cuadActual]['right_operand']

            if type(left_operand) == str:
                left_operand = mem.cambiaDireccion(left_operand,pilaContexto[len(pilaContexto)-1])

            if type(right_operand) == str:
                right_operand = mem.cambiaDireccion(right_operand,pilaContexto[len(pilaContexto)-1])
                
            resultado = mem.obtenerValordeMemoria(left_operand,pilaContexto[len(pilaContexto)-1]) - mem.obtenerValordeMemoria(right_operand,pilaContexto[len(pilaContexto)-1])
            #print('suma es igual', resultado)
            mem.almacenaMemoriaEjecucion(cuad.PQuad[cuadActual]['result'],resultado,pilaContexto[len(pilaContexto)-1])
            cuadActual+=1
        elif cuad.PQuad[cuadActual]['operator'] == '*':
            left_operand = cuad.PQuad[cuadActual]['left_operand']
            right_operand = cuad.PQuad[cuadActual]['right_operand']

            if type(left_operand) == str:
                left_operand = mem.cambiaDireccion(left_operand,pilaContexto[len(pilaContexto)-1])

            if type(right_operand) == str:
                right_operand = mem.cambiaDireccion(right_operand,pilaContexto[len(pilaContexto)-1])
                
            resultado = mem.obtenerValordeMemoria(left_operand,pilaContexto[len(pilaContexto)-1]) * mem.obtenerValordeMemoria(right_operand,pilaContexto[len(pilaContexto)-1])
            #print('suma es igual', resultado)
            mem.almacenaMemoriaEjecucion(cuad.PQuad[cuadActual]['result'],resultado,pilaContexto[len(pilaContexto)-1])
            cuadActual+=1
        elif cuad.PQuad[cuadActual]['operator'] == '/':
            left_operand = cuad.PQuad[cuadActual]['left_operand']
            right_operand = cuad.PQuad[cuadActual]['right_operand']

            if type(left_operand) == str:
                left_operand = mem.cambiaDireccion(left_operand,pilaContexto[len(pilaContexto)-1])

            if type(right_operand) == str:
                right_operand = mem.cambiaDireccion(right_operand,pilaContexto[len(pilaContexto)-1])
                
            resultado = mem.obtenerValordeMemoria(left_operand,pilaContexto[len(pilaContexto)-1]) / mem.obtenerValordeMemoria(right_operand,pilaContexto[len(pilaContexto)-1])
            #print('suma es igual', resultado)
            mem.almacenaMemoriaEjecucion(cuad.PQuad[cuadActual]['result'],resultado,pilaContexto[len(pilaContexto)-1])
            cuadActual+=1
        elif cuad.PQuad[cuadActual]['operator'] == '>':
            left_operand = cuad.PQuad[cuadActual]['left_operand']
            right_operand = cuad.PQuad[cuadActual]['right_operand']

            if type(left_operand) == str:
                left_operand = mem.cambiaDireccion(left_operand,pilaContexto[len(pilaContexto)-1])

            if type(right_operand) == str:
                right_operand = mem.cambiaDireccion(right_operand,pilaContexto[len(pilaContexto)-1])
                
            resultado = mem.obtenerValordeMemoria(left_operand,pilaContexto[len(pilaContexto)-1]) > mem.obtenerValordeMemoria(right_operand,pilaContexto[len(pilaContexto)-1])
            #print('suma es igual', resultado)
            mem.almacenaMemoriaEjecucion(cuad.PQuad[cuadActual]['result'],resultado,pilaContexto[len(pilaContexto)-1])
            cuadActual+=1
        elif cuad.PQuad[cuadActual]['operator'] == '<':
            left_operand = cuad.PQuad[cuadActual]['left_operand']
            right_operand = cuad.PQuad[cuadActual]['right_operand']

            if type(left_operand) == str:
                left_operand = mem.cambiaDireccion(left_operand,pilaContexto[len(pilaContexto)-1])

            if type(right_operand) == str:
                right_operand = mem.cambiaDireccion(right_operand,pilaContexto[len(pilaContexto)-1])
                
            resultado = mem.obtenerValordeMemoria(left_operand,pilaContexto[len(pilaContexto)-1]) < mem.obtenerValordeMemoria(right_operand,pilaContexto[len(pilaContexto)-1])
            #print('suma es igual', resultado)
            mem.almacenaMemoriaEjecucion(cuad.PQuad[cuadActual]['result'],resultado,pilaContexto[len(pilaContexto)-1])
            cuadActual+=1
        elif cuad.PQuad[cuadActual]['operator'] == '==':
            left_operand = cuad.PQuad[cuadActual]['left_operand']
            right_operand = cuad.PQuad[cuadActual]['right_operand']

            if type(left_operand) == str:
                left_operand = mem.cambiaDireccion(left_operand,pilaContexto[len(pilaContexto)-1])

            if type(right_operand) == str:
                right_operand = mem.cambiaDireccion(right_operand,pilaContexto[len(pilaContexto)-1])
                
            resultado = mem.obtenerValordeMemoria(left_operand,pilaContexto[len(pilaContexto)-1]) == mem.obtenerValordeMemoria(right_operand,pilaContexto[len(pilaContexto)-1])
            #print('suma es igual', resultado)
            mem.almacenaMemoriaEjecucion(cuad.PQuad[cuadActual]['result'],resultado,pilaContexto[len(pilaContexto)-1])
            cuadActual+=1
        elif cuad.PQuad[cuadActual]['operator'] == '!=':
            left_operand = cuad.PQuad[cuadActual]['left_operand']
            right_operand = cuad.PQuad[cuadActual]['right_operand']

            if type(left_operand) == str:
                left_operand = mem.cambiaDireccion(left_operand,pilaContexto[len(pilaContexto)-1])

            if type(right_operand) == str:
                right_operand = mem.cambiaDireccion(right_operand,pilaContexto[len(pilaContexto)-1])
                
            resultado = mem.obtenerValordeMemoria(left_operand,pilaContexto[len(pilaContexto)-1]) != mem.obtenerValordeMemoria(right_operand,pilaContexto[len(pilaContexto)-1])
            #print('suma es igual', resultado)
            mem.almacenaMemoriaEjecucion(cuad.PQuad[cuadActual]['result'],resultado,pilaContexto[len(pilaContexto)-1])
            cuadActual+=1
        elif cuad.PQuad[cuadActual]['operator'] == '>=':
            left_operand = cuad.PQuad[cuadActual]['left_operand']
            right_operand = cuad.PQuad[cuadActual]['right_operand']

            if type(left_operand) == str:
                left_operand = mem.cambiaDireccion(left_operand,pilaContexto[len(pilaContexto)-1])

            if type(right_operand) == str:
                right_operand = mem.cambiaDireccion(right_operand,pilaContexto[len(pilaContexto)-1])
                
            resultado = mem.obtenerValordeMemoria(left_operand,pilaContexto[len(pilaContexto)-1]) >= mem.obtenerValordeMemoria(right_operand,pilaContexto[len(pilaContexto)-1])
            #print('suma es igual', resultado)
            mem.almacenaMemoriaEjecucion(cuad.PQuad[cuadActual]['result'],resultado,pilaContexto[len(pilaContexto)-1])
            cuadActual+=1
        elif cuad.PQuad[cuadActual]['operator'] == '<=':
            left_operand = cuad.PQuad[cuadActual]['left_operand']
            right_operand = cuad.PQuad[cuadActual]['right_operand']

            if type(left_operand) == str:
                left_operand = mem.cambiaDireccion(left_operand,pilaContexto[len(pilaContexto)-1])

            if type(right_operand) == str:
                right_operand = mem.cambiaDireccion(right_operand,pilaContexto[len(pilaContexto)-1])
                
            resultado = mem.obtenerValordeMemoria(left_operand,pilaContexto[len(pilaContexto)-1]) <= mem.obtenerValordeMemoria(right_operand,pilaContexto[len(pilaContexto)-1])
            #print('suma es igual', resultado)
            mem.almacenaMemoriaEjecucion(cuad.PQuad[cuadActual]['result'],resultado,pilaContexto[len(pilaContexto)-1])
            cuadActual+=1
        elif cuad.PQuad[cuadActual]['operator'] == 'AND':
            left_operand = cuad.PQuad[cuadActual]['left_operand']
            right_operand = cuad.PQuad[cuadActual]['right_operand']

            if type(left_operand) == str:
                left_operand = mem.cambiaDireccion(left_operand,pilaContexto[len(pilaContexto)-1])

            if type(right_operand) == str:
                right_operand = mem.cambiaDireccion(right_operand,pilaContexto[len(pilaContexto)-1])
                
            resultado = mem.obtenerValordeMemoria(left_operand,pilaContexto[len(pilaContexto)-1]) and mem.obtenerValordeMemoria(right_operand,pilaContexto[len(pilaContexto)-1])
            #print('suma es igual', resultado)
            mem.almacenaMemoriaEjecucion(cuad.PQuad[cuadActual]['result'],resultado,pilaContexto[len(pilaContexto)-1])
            cuadActual+=1
        elif cuad.PQuad[cuadActual]['operator'] == 'OR':
            left_operand = cuad.PQuad[cuadActual]['left_operand']
            right_operand = cuad.PQuad[cuadActual]['right_operand']

            if type(left_operand) == str:
                left_operand = mem.cambiaDireccion(left_operand,pilaContexto[len(pilaContexto)-1])

            if type(right_operand) == str:
                right_operand = mem.cambiaDireccion(right_operand,pilaContexto[len(pilaContexto)-1])
                
            resultado = mem.obtenerValordeMemoria(left_operand,pilaContexto[len(pilaContexto)-1]) or mem.obtenerValordeMemoria(right_operand,pilaContexto[len(pilaContexto)-1])
            #print('suma es igual', resultado)
            mem.almacenaMemoriaEjecucion(cuad.PQuad[cuadActual]['result'],resultado,pilaContexto[len(pilaContexto)-1])
            cuadActual+=1       
        elif cuad.PQuad[cuadActual]['operator'] == 'GOTOF':
            evalua = mem.obtenerValordeMemoria(cuad.PQuad[cuadActual]['left_operand'],pilaContexto[len(pilaContexto)-1])
            if not evalua:
                cuadActual = cuad.PQuad[cuadActual]['result']
            else:
                cuadActual += 1
        elif cuad.PQuad[cuadActual]['operator'] == 'ERA':
            #solicitar crear espeacio en memoria para la func
            if cuad.PQuad[cuadActual]['left_operand'] != pilaContexto[len(pilaContexto)-1]:
                pilaContexto.append(cuad.PQuad[cuadActual]['left_operand'])
                mem.generaMemoriaEjecucion(pilaContexto[len(pilaContexto)-1])
            else:            
                pilaContexto.append(cuad.PQuad[cuadActual]['left_operand'])
            #print(mem.tablaMemoriaEjecución)
            cuadActual+=1
        elif cuad.PQuad[cuadActual]['operator'] == 'PARAM':
            #obtener dir de memoria de param
            tempVarParam = directorio.funcionLista[pilaContexto[len(pilaContexto)-1]]['paramDefinidos'][contadorParam]['name']
            direccion = directorio.funcionLista[pilaContexto[len(pilaContexto)-1]]['variables'][tempVarParam]['dirMemoria']
            #obtener los valores del contexto anterior en base a los cuads
            valor = mem.obtenerValordeMemoria(cuad.PQuad[cuadActual]['left_operand'],pilaContexto[len(pilaContexto)-2])
            mem.almacenaMemoriaEjecucion(direccion,valor,pilaContexto[len(pilaContexto)-1])
            contadorParam +=1
            if cuad.PQuad[cuadActual+1]['operator'] == 'GOSUB':
                contadorParam = 1
                pilaCuadActual.append(cuadActual+1)
                cuadActual = directorio.funcionLista[pilaContexto[len(pilaContexto)-1]]['cuadInicial']
            else:
                cuadActual+=1
        elif cuad.PQuad[cuadActual]['operator'] == 'GOSUB':
            if cuad.PQuad[cuadActual]['left_operand'] != pilaContexto[len(pilaContexto)-2]:
                mem.tablaMemoriaEjecución[pilaContexto[len(pilaContexto)-1]].clear()
            
            pilaContexto.pop()
            cuadActual += 1
        elif cuad.PQuad[cuadActual]['operator'] == 'ENDPROC':
            cuadActual = pilaCuadActual.pop()
        elif cuad.PQuad[cuadActual]['operator'] == 'RETURN':
            result = mem.obtenerValordeMemoria(cuad.PQuad[cuadActual]['result'],pilaContexto[len(pilaContexto)-1])
            direccion = directorio.funcionLista['MAIN']['variables'][pilaContexto[len(pilaContexto)-1]]['dirMemoria']
            mem.almacenaMemoriaEjecucion(direccion,result,pilaContexto[len(pilaContexto)-2])
            cuadActual +=1
        elif cuad.PQuad[cuadActual]['operator'] == 'AVERAGE':
            result = mem.obtenerValordeMemoria(cuad.PQuad[cuadActual]['result'],pilaContexto[len(pilaContexto)-1])
            pilaFuncionesEspeciales.append(result)
            if len(pilaFuncionesEspeciales) == 4:
                print('PROCESANDO DATOS.....')
                avg.average(pilaFuncionesEspeciales[0],pilaFuncionesEspeciales[1],pilaFuncionesEspeciales[2],pilaFuncionesEspeciales[3])
                pilaFuncionesEspeciales.clear()
            cuadActual += 1
        elif cuad.PQuad[cuadActual]['operator'] == 'MEDIAN':
            result = mem.obtenerValordeMemoria(cuad.PQuad[cuadActual]['result'],pilaContexto[len(pilaContexto)-1])
            pilaFuncionesEspeciales.append(result)
            if len(pilaFuncionesEspeciales) == 4:
                print('PROCESANDO DATOS.....')
                median.median(pilaFuncionesEspeciales[0],pilaFuncionesEspeciales[1],pilaFuncionesEspeciales[2],pilaFuncionesEspeciales[3])
                pilaFuncionesEspeciales.clear()
            cuadActual += 1
        elif cuad.PQuad[cuadActual]['operator'] == 'MODE':
            result = mem.obtenerValordeMemoria(cuad.PQuad[cuadActual]['result'],pilaContexto[len(pilaContexto)-1])
            pilaFuncionesEspeciales.append(result)
            if len(pilaFuncionesEspeciales) == 2:
                print('PROCESANDO DATOS.....')
                mode.mode(pilaFuncionesEspeciales[0],pilaFuncionesEspeciales[1])
                pilaFuncionesEspeciales.clear()
            cuadActual += 1
        elif cuad.PQuad[cuadActual]['operator'] == 'PLOT':
            result = mem.obtenerValordeMemoria(cuad.PQuad[cuadActual]['result'],pilaContexto[len(pilaContexto)-1])
            pilaFuncionesEspeciales.append(result)
            if len(pilaFuncionesEspeciales) == 4:
                print('PROCESANDO DATOS.....')
                plot.plot(pilaFuncionesEspeciales[0],pilaFuncionesEspeciales[1],pilaFuncionesEspeciales[2],pilaFuncionesEspeciales[3])
                pilaFuncionesEspeciales.clear()
            cuadActual += 1
        elif cuad.PQuad[cuadActual]['operator'] == 'PIECHART':
            result = mem.obtenerValordeMemoria(cuad.PQuad[cuadActual]['result'],pilaContexto[len(pilaContexto)-1])
            pilaFuncionesEspeciales.append(result)
            if len(pilaFuncionesEspeciales) == 3:
                print('PROCESANDO DATOS.....')
                pie.pieChart(pilaFuncionesEspeciales[0],pilaFuncionesEspeciales[1],pilaFuncionesEspeciales[2])
                pilaFuncionesEspeciales.clear()
            cuadActual += 1
        elif cuad.PQuad[cuadActual]['operator'] == 'VARIANZA':
            result = mem.obtenerValordeMemoria(cuad.PQuad[cuadActual]['result'],pilaContexto[len(pilaContexto)-1])
            pilaFuncionesEspeciales.append(result)
            if len(pilaFuncionesEspeciales) == 4:
                print('PROCESANDO DATOS.....')
                varianza.varianza(pilaFuncionesEspeciales[0],pilaFuncionesEspeciales[1],pilaFuncionesEspeciales[2],pilaFuncionesEspeciales[3])
                pilaFuncionesEspeciales.clear()
            cuadActual += 1
        elif cuad.PQuad[cuadActual]['operator'] == 'DESVT':
            result = mem.obtenerValordeMemoria(cuad.PQuad[cuadActual]['result'],pilaContexto[len(pilaContexto)-1])
            pilaFuncionesEspeciales.append(result)
            if len(pilaFuncionesEspeciales) == 4:
                print('PROCESANDO DATOS.....')
                std.std(pilaFuncionesEspeciales[0],pilaFuncionesEspeciales[1],pilaFuncionesEspeciales[2],pilaFuncionesEspeciales[3])
                pilaFuncionesEspeciales.clear()
            cuadActual += 1
        elif cuad.PQuad[cuadActual]['operator'] == 'DISTN':
            result = mem.obtenerValordeMemoria(cuad.PQuad[cuadActual]['result'],pilaContexto[len(pilaContexto)-1])
            pilaFuncionesEspeciales.append(result)
            if len(pilaFuncionesEspeciales) == 2:
                print('PROCESANDO DATOS.....')
                dN.distN(pilaFuncionesEspeciales[0],pilaFuncionesEspeciales[1])
                pilaFuncionesEspeciales.clear()
            cuadActual += 1
        elif cuad.PQuad[cuadActual]['operator'] == 'BASICV':
            result = mem.obtenerValordeMemoria(cuad.PQuad[cuadActual]['result'],pilaContexto[len(pilaContexto)-1])
            pilaFuncionesEspeciales.append(result)
            if len(pilaFuncionesEspeciales) == 2:
                print('PROCESANDO DATOS.....')
                violin.violin(pilaFuncionesEspeciales[0],pilaFuncionesEspeciales[1])
                pilaFuncionesEspeciales.clear()
            cuadActual += 1
        elif cuad.PQuad[cuadActual]['operator'] == 'VER':
            valor = mem.obtenerValordeMemoria(cuad.PQuad[cuadActual]['left_operand'],pilaContexto[len(pilaContexto)-1])
            if valor >= cuad.PQuad[cuadActual]['right_operand'] and valor <= cuad.PQuad[cuadActual]['result']:
                pass
            else:
                print('HORROR: Numero fuera de los limites del arreglo')
                return sys.exit()
            cuadActual += 1  


            
        else:
            cuadActual+=1
Ejemplo n.º 10
0
def test_mode():
    assert mode([1,3,3,5,5]) == 
Ejemplo n.º 11
0
def test_mode_3():
    assert mode([1,3,3]) == 3
Ejemplo n.º 12
0
def test_mode_1():
    assert mode([2]) == 2
Ejemplo n.º 13
0
    def test_input_1(self):

        # Failure message:
        # expected mode([1, 2, 1]) to equal 1
        self.assertEqual(mode([1, 2, 1]), 1)
Ejemplo n.º 14
0
    def test_input_2(self):

        # Failure message:
        # expected mode([2, 4, 1, 2, 3, 3, 4, 4, 5, 4, 4, 6, 4, 6, 7, 4]) to equal 4
        self.assertEqual(
            mode([2, 4, 1, 2, 3, 3, 4, 4, 5, 4, 4, 6, 4, 6, 7, 4]), 4)
def dailyEmail():
    """
    This function sends out the daily email. 
    """
    SMTP_SERVER = 'smtp.gmail.com' #Email Server 
    SMTP_PORT = 587 #Server Port 
    GMAIL_USERNAME = '******' 
    GMAIL_PASSWORD = ''
    lister = []
    inp = []
    Max = 0
    Min = 0
    try:
        cur.execute("""SELECT * FROM temperature WHERE taken_at > "{}" AND taken_at < "{}";""".format((datetime.datetime.now()-datetime.timedelta(days=9)).strftime("%Y-%m-%d"),datetime.datetime.now().strftime("%Y-%m-%d")))#Internal Temp
        for id, temp, taken_at in cur:
            lister.append(temp)
            if Max <= temp:
                Max = temp
            if Min >= temp and temp != 0:
                Min = temp
        inp.append(average(lister))#average temp, 0
        inp.append(Max)#max temp, 1
        inp.append(Min)#min temp, 2
        Max = 0
        Min = 0
        lister.clear()
        cur.execute("""SELECT * FROM humidity WHERE taken_at > "{}" AND taken_at < "{}";""".format((datetime.datetime.now()-datetime.timedelta(days=9)).strftime("%Y-%m-%d"),datetime.datetime.now().strftime("%Y-%m-%d")))#Internal Humid
        for id, humid, taken_at in cur:
            lister.append(humid)
            if Max <= humid:#max humidity
                Max = humid
            if Min >= humid and humid != 0:#min humidity
                Min = humid
        inp.append(average(lister))#average Humid, 3
        inp.append(Max)#max humid, 4
        inp.append(Min)#min Humid, 5
        Max = 0
        Min = 0
        lister.clear()
        cur.execute("""SELECT * FROM temp_ext WHERE taken_at > "{}" AND taken_at < "{}";""".format((datetime.datetime.now()-datetime.timedelta(days=9)).strftime("%Y-%m-%d"),datetime.datetime.now().strftime("%Y-%m-%d")))#External Temp
        for id, temp, taken_at in cur:
            lister.append(temp)
            if Max <= temp:
                Max = temp
            if Min >= temp and temp != 0:
                Min = temp
        inp.append(average(lister))
        inp.append(Max)
        inp.append(Min)
        Max = 0
        Min = 0
        lister.clear()
        cur.execute("""SELECT * FROM humid_ext WHERE taken_at > "{}" AND taken_at < "{}";""".format((datetime.datetime.now()-datetime.timedelta(days=9)).strftime("%Y-%m-%d"),datetime.datetime.now().strftime("%Y-%m-%d")))#External Humid
        for id, humid, taken_at in cur:
            lister.append(humid)
            if Max <= humid:
                Max = humid
            if Min >= humid and humid != 0:
                Min = humid
        inp.append(average(lister))
        inp.append(Max)
        inp.append(Min)
        Max = 0
        Min = 0
        lister.clear()
        cur.execute("""SELECT * FROM wind_direction WHERE taken_at > "{}" AND taken_at < "{}";""".format((datetime.datetime.now()-datetime.timedelta(days=9)).strftime("%Y-%m-%d"),datetime.datetime.now().strftime("%Y-%m-%d")))#Wind Direction
        for id,letterDire,numberDire,taken_at in cur:
            lister.append(letterDire)
        inp.append(mode.mode(lister))
        lister.clear()
        cur.execute("""SELECT * FROM wind_speed WHERE taken_at > "{}" AND taken_at < "{}";""".format((datetime.datetime.now()-datetime.timedelta(days=9)).strftime("%Y-%m-%d"),datetime.datetime.now().strftime("%Y-%m-%d")))#Wind Speed
        for id, speed, taken_at in cur:
            lister.append(speed)
            if Max <= speed:
                Max = speed
        inp.append(average(lister))
        inp.append(Max)
        Max = 0
        Min = 0
        lister.clear()
        cur.execute("""SELECT * FROM ppfd WHERE taken_at > "{}" AND taken_at < "{}";""".format((datetime.datetime.now()-datetime.timedelta(days=9)).strftime("%Y-%m-%d"),datetime.datetime.now().strftime("%Y-%m-%d")))#PPFD
        for id, ppfd, taken_at in cur:
            lister.append(ppfd)
        inp.append(average(lister))
        Max = 0
        Min = 0
        lister.clear()
        cur.execute("""SELECT * FROM rainfall WHERE taken_at > "{}" AND taken_at < "{}";""".format((datetime.datetime.now()-datetime.timedelta(days=9)).strftime("%Y-%m-%d"),datetime.datetime.now().strftime("%Y-%m-%d")))#Rain
        for id, rain, taken_at in cur:
            if Max <= rain:
                Max = rain
        inp.append(Max)
        Max = 0
        Min = 0
        lister.clear()
        cur.execute("""SELECT * FROM soil_moisture WHERE taken_at > "{}" AND taken_at < "{}";""".format((datetime.datetime.now()-datetime.timedelta(days=9)).strftime("%Y-%m-%d"),datetime.datetime.now().strftime("%Y-%m-%d")))#Soil Moisture
        for id, moisture, taken_at in cur:
            lister.append(moisture)
        inp.append(average(lister))
        Max = 0
        Min = 0
        mess = """\tHello, I am the Automated Greenhouse!
        Here is todays daily report:
        Greenhouse Internal Temperature: Avg: {} F High: {} F Low: {} F
        Greenhouse Internal Humidity:    Avg: {}% High: {}% Low: {}%
        Greenhouse External Temperature: Avg: {} F High: {} F Low: {} F
        Greenhouse External Humidity:    Avg: {}% High: {}% Low: {}%
        External Wind Direction:         Avg: {}
        External Wind Speed:             Avg: {} MPH High: {} MPH
        Internal Light Intensity:        Avg: {} μmol/s/m2
        Rainfall:                        Total: {} Inches
        Soil Moisture:                   Avg: {} %
        """.format(inp[0],inp[1],inp[2],inp[3],inp[4],inp[5],inp[6],inp[7],inp[8],inp[9],inp[10],inp[11],inp[12],inp[13],inp[14],inp[15],inp[16],inp[17])
        actions ="""
        Here are the actions taken in the greenhouse today:
        Number of times drip irrigation was activated: {} Times
        Number of times shade system was activated: {} Times
        Number of times heating system was activated: {} Times
        Number of times cooling system was activated: {} Times
        Number of times venting system was activated: {} Times
        Number of times lighting system was activated: {} Times
         """.format(dataPasser.action[0], dataPasser.action[1],dataPasser.action[2],dataPasser.action[3],dataPasser.action[4],dataPasser.action[5])
        msg = MIMEText(mess+actions)
        me = '*****@*****.**'
        you = '[email protected], [email protected]'
        msg['Subject'] = "Daily Generated Report: {}".format(datetime.date.today())
        msg['From'] = me
        msg['To'] = you
        s = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
        s.starttls()
        s.login(GMAIL_USERNAME, GMAIL_PASSWORD)
        s.send_message(msg)
        s.quit()
    except mariadb.Error as e:
        print(f"Error: {e}")
        cleanExit()
Ejemplo n.º 16
0
def check(test):
    A, staff_sol = test
    student_sol = mode(A)
    return staff_sol == student_sol
def Exterior(name): #Thread 3
    countDHTout = 0
    countWind = 0
    wind_count = 0
    radius_cm = 9
    interval = 5
    store_speeds = []
    wind_gust = 0
    water_const = 0.2794 #Millimiters of water :)
    rain_count = 0
    store_rain = []
    mmToIn = .0393
    total_rain = 0
    def spin():
        global wind_count
        wind_count = wind_count + 1
    def rain():
        global rain_count
        rain_count += 1
    def reset_rain():
        global rain_count
        rain_count = 0
    def rainfall(time_sec):
        global rain_count  
        water = rain_count * water_const * mmToIn
        return (water/time_sec)
    
    wind_speed_sensor = Button(16)
    wind_speed_sensor.when_pressed = spin
    SPI_PORT   = 0
    SPI_DEVICE = 0
    mcp = MCP.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
    store_dire =[]
    rain_gauge_sensor = Button(26)
    rain_gauge_sensor.when_pressed = rain
    
    
    def reset_wind():
        global wind_count
        wind_count = 0

    def calculate_speed(time_sec):
        global wind_count
        circumference_cm = (2 * math.pi) * radius_cm
        rotations = wind_count / 2
    
        dist_cm = circumference_cm * rotations
        dist_miles = dist_cm / 160934.4
    
        time_hr = time_sec / 3600
    
        speed = dist_miles / time_hr
    
        return speed

    def convert(input):
        """Converts the value from the MCP value to the actual wind direction\n
        Returns a Tuple data type"""
        switch = {
            752: ("N",0),
            92: ("E",90),
            285: ("S",180),
            890: ("W",270),
            455: ("NE",45),
            183: ("SE",135),
            611: ("SW",225),
            840: ("NW",315),
            400: ("NNE",22.5),
            83: ("ENE",67.5),
            65: ("ESE",112.5),
            126: ("SSE",157.5),
            243: ("SSW",202.5),
            583: ("WSW",247.5),
            790: ("WNW",292.5),
            660: ("NNW",337.5)
                }
        return switch.get(input,-1)

    #WORK NEEDED HERE FOR TABLE STUFF
    while True:
        humid, temp = dht.read_retry(dht.DHT22, 24)
        if humid is not None and temp is not None:
            countDHTout = 0
            try:
                logging.info("Thread %s: Logging External Temp/Humid into MariaDB",name)
                tempin = temp*(9/5)+32
                cur.execute("INSERT INTO temp_ext (temp,taken_at) VALUES (?,?)", (tempin,datetime.datetime.now()))
                cur.execute("INSERT INTO humid_ext (humid,taken_at) VALUES (?,?)", (humid,datetime.datetime.now()))
                conn.commit()
            except mariadb.Error as e:
                print(f"Error: {e}")
                dataStorageFail("External DHT22")
                cleanExit()
        else:
            print("External DHT Data could not be retrieved")
            countDHTout = countDHTout + 1 #Counts here bc data was not collected
        
        #shoving more stuff in here than usual, PLZ TEST ME :)
        start_time = time.time()
        while time.time() - start_time <= interval:
            reset_wind()
            time.sleep(interval)
            final_speed = calculate_speed(interval)
            store_speeds.append(final_speed)
            if (wind_gust <= max(store_speeds)):
                wind_gust = max(store_speeds)
            windSpeed = statistics.mean(store_speeds)
            store_speeds.clear()

            reset_rain()
            time.sleep(interval)
            final_rain = rainfall(interval)
            store_rain.append(final_rain)
            for x in store_rain:
                total_rain += x
            print("rain value:",final_rain,"inches over 5 seconds")
            print("total rain of day:",total_rain,"inches")
            store_rain.clear()
            wind = mcp.read_adc(0)
            store_dire.append(wind)
            most = mode.mode(store_dire)
            windDirection = convert(most)
            if windDirection == -1:
                most = most -6
            while windDirection == -1:
                most += 1
                windDirection = convert(most)
        if windSpeed is not None and windDirection is not None:
            try:
                logging.info("Thread %s: Logging wind Dire/Speed into MariaDB",name)
                cur.execute("INSERT INTO wind_direction (letterDire,numberDire,taken_at) VALUES (?,?,?)", (windDirection[0],windDirection[1],datetime.datetime.now()))
                cur.execute("INSERT INTO wind_speed (speed,taken_at) VALUES (?,?)", (windSpeed,datetime.datetime.now()))
                cur.execute("INSERT INTO rainfall (rain,taken_at) VALUES (?,?)", (total_rain,datetime.datetime.now()))
                conn.commit()
            except mariadb.Error as e:
                print(f"Error: {e}")
                dataStorageFail("Anemometer/Wind Vane")
        
        else:
            print("External Wind Data was not collected")
            countWind = countWind + 1
            #counts here bc data was not collected. 
        
        if countDHTout >= 5:
            #Send email, but no shut off
            noDataExt("DHT22")
            countDHTout = 0
        if countWind >= 5:
            #Send email, but no shut off
            noDataExt("Wind System")
            countWind = 0
Ejemplo n.º 18
0
 def test_mode(self):
     from mode import mode
     assert mode(data) == '1'
Ejemplo n.º 19
0
    def updateMotor(self, flag):
        if flag == 0:
            self.upMotor()
        else:
            self.downMotor()


if __name__ == '__main__':
    # Import DroneKit-Python
    from dronekit import connect, VehicleMode
    from mode import mode
    # Connect to the Vehicle.
    print("Connecting")
    vehicle = connect('/dev/ttyS0', wait_ready=True, baud=57600)

    mode = mode(vehicle)
    servo = servo()

    while (True):
        mode.updateMode()
        SERVO, ROCKING_WINGS, CAMERA, RCSAFETY = mode.getMode()

        if SERVO == 0:
            servo.upMotor()
        else:
            servo.downMotor()

        if RCSAFETY == 1:
            break

        print("SERVO:%d" % SERVO)
Ejemplo n.º 20
0
 def test_mode_fail(self):
     from mode import mode
     assert mode(data) != '23'
Ejemplo n.º 21
0
        "1.Population Mean 2. Median 3. Mode 4. Population Standard Deviation 5. Variance of population proportion 6. "
        "Z-Score 7. Standardized score 8. Population Correlation Coefficient 9. Confidence Interval 10. Population "
        "Variance 11. P Value 12. Proportion 13. Sample Mean 14. Sample Standard Deviation 15. Variance of sample "
        "proportion")
    c = int(input())
    if c == 1:
        from pmean import pmean
        print((pmean(data)))
    elif c == 2:
        from median import median

        print(str(median(data)))
    elif c == 3:
        from mode import mode

        print(str(mode(data)))
    elif c == 4:
        from popstddev import popstddev

        print(str(popstddev(data)))
    elif c == 5:
        from variancepopprop import variancepopprop

        print(str(variancepopprop(data)))
    elif c == 6:
        from zscore import zscore

        print(str(zscore(data)))
    elif c == 7:
        from stdscore import stdscore
        print(float(stdscore(data)))
Ejemplo n.º 22
0
def main():
    
    # set input and output directory for bacterial model 
    xml_dir = '/Users/medeafux/Desktop/ETH/Masterarbeit/Bacterial-RBA-models/Escherichia-coli-K12-WT'
    output_dir = xml_dir
    # set directory and file of modes origin (should in the end be used for the extract_modes function)
    modes_dir = '/Users/medeafux/Desktop/ETH/Masterarbeit/code-Mattia/hyperflux/data/results/core_example/glc/samples'
    modes_file = 'state_e_coli_gerosa2015_glc.mat'   
    # set current directory
    curr_dir = '/Users/medeafux/Desktop/ETH/Masterarbeit/enzyme_cost'

    # import modes, delete phosphate transfer and remove duplicate modes
    modes = extract_modes(modes_dir, modes_file, curr_dir) 
    os.chdir(curr_dir)
    
    plot()
    
    # run the unconstrained model
    print('Model building from XML files ...')
    model = rba.RbaModel.from_xml(xml_dir) 
    print('Starting iterative RBA resolution (default model)...')
    results = model.solve()
    print('Optimal growth rate is {}.'.format(results.mu_opt))
    results.write(output_dir)
          
    gr = results.mu_opt
    AA_cost = parse_enzyme_cost(output_dir,curr_dir)
    AA_cost_per_gr = AA_cost/gr
    
    mode_unc = mode(0, 0, 'unc', AA_cost, gr, 0)
    modes.append(mode_unc)
    
    ######################################
    # go through modes and run for each mode: 
    # constrain targets, run constraint RBA, save growth rate, calculate cost
    # loop over the modes
    for i in range(0, len(modes)-1):
            
        # create a new TargetGroup object = group of target fluxes
        target_group = TargetGroup('mode_targets')
       
        # loop over the reactions of each mode (are actually the same for all of them)
        for j in range(0, len(modes[i].revRcts)):
                
            # create a new TargetReaction = Association of a target value with a chemical reaction (use id of wanted reaction)
            target_reaction = TargetReaction(modes[i].revRcts[j])
            # constrain the upper or lower bound according to the sign of the rev reaction inside the mode
            if modes[i].signs[j] == 1 :
                target_reaction.lower_bound = 'zero'
            elif modes[i].signs[j] == -1 :
                target_reaction.upper_bound = 'zero' 
            # add the target flux value of the target reaction to the list of reaction fluxes in the target group object
            target_group.reaction_fluxes.append(target_reaction)

        # add the target reaction flux to the model (why is this step needed?)
        model.targets.target_groups.append(target_group)
        results = model.solve()        
        print('Optimal growth rate is {}.'.format(results.mu_opt))
        results.write(output_dir)
         
        #save optimal growth rate for each mode
        modes[i].opt_GR = results.mu_opt
        # calculate cost and save cost 
        modes[i].cost = parse_enzyme_cost(output_dir,curr_dir) 
        
        #remove target group from the model = reset model
        model.targets.target_groups.remove(target_group)
    
    # write results into a file
    write_modes(modes)