예제 #1
0
def recipe(term=None):
    silliness = request.args.get('silliness', 50)
    source = AllRecipesSource()
    intermediates = list(source.search(term))
    working = Recipe(term, [], [])
    recipe = average(intermediates, working, silliness=float(silliness) / 100)

    resp = make_response(render_template('recipe.json', title=recipe.title, ingredients=recipe.ingredients, method=recipe.method))
    resp.mimetype = 'application/json'
    return resp
예제 #2
0
 def plotData (self):
     import matplotlib.pyplot as plt
     import average
     data_array=average.average(self.data)
     #print data_array
     tag_array=average.getTag(self.data)	
     plt.xlabel(tag_array)
     plt.plot(range(len(data_array)),data_array)
     plt.grid(True)
     plt.title('Average Amount for each sub-category')
     plt.show()
예제 #3
0
def test_negitive():
    items = [-50, 50]
    assert average.average(items) == 0
예제 #4
0
def test_full():
    items = []

    with pytest.raises(ValueError):
        average.average(items)
예제 #5
0
import average
import createMask
import time
import os, sys
init = time.time()


class HiddenPrints:
    def __enter__(self):
        self._original_stdout = sys.stdout
        sys.stdout = open(os.devnull, 'w')

    def __exit__(self, exc_type, exc_val, exc_tb):
        sys.stdout.close()
        sys.stdout = self._original_stdout


with HiddenPrints():
    average.average()
    createMask.createMask()

print("Completed in {} seconds".format(round(time.time() - init)))
예제 #6
0
def test_average_basic_2(values, expected):
    """Otestování výpočtu průměru."""
    result = average(values)
    assert result == expected, "Očekávaná hodnota {}, vráceno {}".format(
        expected, result)
예제 #7
0
def do_run_pipeline(name, basedir):

    if name[0] != 'P' and name[0] != 'L':
        die('This code should be used only with field or observation names',
            database=False)

    do_field = (name[0] == 'P')

    try:
        qsubfile = sys.argv[2]
    except:
        qsubfile = '/home/mjh/pipeline-master/ddf-pipeline/torque/pipeline.qsub'

    workdir = basedir + '/' + name
    try:
        os.mkdir(workdir)
    except OSError:
        warn('Working directory already exists')

    report('Downloading data')
    if do_field:
        success = download_field(name, basedir=basedir)
    else:
        success = download_dataset('https://lofar-webdav.grid.sara.nl',
                                   '/SKSP/' + name + '/',
                                   basedir=basedir)

    if not success:
        die('Download failed, see earlier errors', database=False)

    report('Unpacking data')
    try:
        unpack(workdir=workdir)
    except RuntimeError:
        if do_field:
            update_status(name, 'List failed', workdir=workdir)
        raise
    if do_field:
        update_status(name, 'Unpacked', workdir=workdir)

    report('Deleting tar files')
    os.system('rm ' + workdir + '/*.tar.gz')
    os.system('rm ' + workdir + '/*.tar')

    averaged = False
    report('Checking structure')
    g = glob.glob(workdir + '/*.ms')
    msl = MSList(None, mss=g)
    uobsids = set(msl.obsids)
    for thisobs in uobsids:
        # check one MS with each ID
        for m, ch, o in zip(msl.mss, msl.channels, msl.obsids):
            if o == thisobs:
                channels = len(ch)
                print 'MS', m, 'has', channels, 'channels'
                if channels > 20:
                    update_status(name, 'Averaging', workdir=workdir)
                    print 'Averaging needed for', thisobs, '!'
                    averaged = True
                    average(wildcard=workdir + '/*' + thisobs + '*')
                    os.system('rm -r ' + workdir + '/*' + thisobs +
                              '*pre-cal.ms')
                break

    report('Making ms lists')
    success = make_list(workdir=workdir)
    if do_field:
        list_db_update(success, workdir=workdir)
    if not success:
        die('make_list could not construct the MS list', database=False)

    report('Creating custom config file from template')
    make_custom_config(name, workdir, do_field, averaged)

    # now run the job
    do_run_job(name, basedir=basedir, qsubfile=None, do_field=do_field)
예제 #8
0
 def test_average_five_values(self, input_values, expected_result):
     """Otestování výpočtu průměru."""
     result = average(input_values)
     assert result == expected_result, "Očekávaná hodnota {}, vráceno {}".format(
         expected_result, result)
예제 #9
0
def test_average_basic_1(printer, values, expected):
    """Otestování výpočtu průměru."""
    printer("About to compute average from {} with expected output {}".format(values, expected))
    result = average(values)
    printer("Computed average is {}".format(result))
    assert result == expected, "Očekávaná hodnota {}, vráceno {}".format(expected, result)
예제 #10
0
def test_average_exception_not_raised():
    """Otestování výpočtu průměru."""
    with pytest.raises(ZeroDivisionError) as excinfo:
        result = average([1, 2])
예제 #11
0
import average

print(average.average(2, 3))
print(average.average(10, 15))
예제 #12
0
 def setUp(self):
     self.average = average()
예제 #13
0
def moving_average(series, n):
	return average(series[-n:])
예제 #14
0
from argparse import ArgumentParser
from average import average
from rwcsv import csv_write, csv_read

if __name__ == "__main__":
    """
    The entrypoint for the column averaging software suite.
    """
    parser = ArgumentParser(description="Give it a input csv")
    parser.add_argument("inputcsv")
    parser.add_argument("outputcsv")
    arguments = parser.parse_args()
    data_columns = csv_read(arguments.inputcsv)
    average_columns = average(data_columns)
    write_csv = csv_write(arguments.outputcsv, average_columns)
예제 #15
0
def main():
    x = average(1, 2, 3, 4, 5)
    print(x)
예제 #16
0
 def test_running_list_mag_negative(self):  # 4
     """Test a list of negative values."""
     argument = [-1, -5, -3, -4]
     expected = -3.25
     argument = avg.average(argument)
     self.assertEqual(expected, argument, "The list contains only negative values.")
예제 #17
0
 def test_does_not_accept_strings(self):
     result = average.average(["ten", "two", 3, 4, 5])
     self.assertEqual("numbers only", result)
예제 #18
0
 def test_empty(self):
     lst = []
     ans = _("When the list is empty you should return None.")
     self.assertEqual(None, average.average(lst), ans)
예제 #19
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
예제 #20
0
import average

print(average.average(2, 2))
print(average.average(1, 10))
예제 #21
0
# Author: Sisinty Sasmita Patra
# Runs all other techniques

import cv2
import sys
import time

import average, xyz_lum, yuv_lum, lab_lum, lab_lum_en, color2gray

in_file = sys.argv[1] + ".jpg"
in1 = cv2.imread(in_file)

# average
start = time.clock()
out1 = average.average(in1)
end = time.clock()

out_file = sys.argv[1] + "_out_avg.jpg"
cv2.imwrite(out_file, out1)
print "average : ", end - start, " seconds."

# xyz
start = time.clock()
out1 = xyz_lum.xyz_luminance(in1)
end = time.clock()
out_file = sys.argv[1] + "_out_xyz.jpg"
cv2.imwrite(out_file, out1)
print "xyz_lum : ", end - start, " seconds."

# yuv
예제 #22
0
def test_average_basic():
    """Otestování výpočtu průměru."""
    result = average([1, 2])
    assert result == 1.5
예제 #23
0
 def average_all_sequence(self):
     average(self)
예제 #24
0
def randorator(dict_val):
# The function gets the dictionary with input values.

    from simple import rando
    from average import average
    from rsd import randorateGauss, relstdev, rsd_calc
# Modules to generate random numbers list are loaded.
# RSD adjusting and calculating modules are loaded.
    from math import log, copysign
# Logarithm counting and sign copy functions are loaded.
    from sys import version
# To support Python 2 & 3.
    from i18n.locator import locale
# Localization.

    if dict_val["log_algor"]:
        from randomwrapper import shuffle
    else:
        from random import shuffle
# Here it is an import of a list shuffling function from the chosen module.

    def punctu(txt):
        try:
            return(float(txt.replace(",", ".")))
        except ValueError:
            return(0)
#Функция принимает строковое значение и возвращает число с точкой. Для обработки введённых данных.

    def set_float_data(in_data):
        out_data = 0
        if in_data != "":
            out_data = punctu(in_data)
        return(out_data)
#Функция принимает строковое значение и возвращает число с точкой или 0,
#если строка пустая. Для обработки введённых данных.

    def set_int_data(in_data, fallback_d):
        if in_data != "":
            try:
                out_data = int(round(abs(punctu(in_data)), 0))
            except TypeError:
                pass
        else:
            out_data = fallback_d
        return(out_data)
#Функция принимает строковое значение и число, возвращает целое число
#или второе число, если строка пустая. Для обработки введённых данных.

    def to_text(in_data, rounding):
        if rounding >= 0:
            in_data = round(in_data, rounding)
            out_data = str(in_data)
            out_data += "0" * (rounding - len(out_data) + out_data.find(".") + 1)
        else:
            out_data = str(in_data)
        if rounding == 0:
            out_data = out_data.replace(".0", "")
        return(out_data)
#Число преобразуется в строку, если необходимо, округляется с добавлением нулей.
#У числа, округлённого до целой части, отбрасывается ".0".

    def check_limits(limits_add, str_avera, n, mini, maxi, mean):
        dict_check = {}
        limits_n = len(limits_add)
        dict_check["log_avera"] = False
        if str_avera != "":
            if n > limits_n:
                mean = ((mean * n) - sum(limits_add)) / (n - limits_n)
# The mean value should be corrected.

                dict_check["num_avera"] = mean
                if maxi > mean > mini:
                    dict_check["log_avera"] = True
                    dict_check["str_error"] = u""
# New average value should be checked.

            if not dict_check["log_avera"]:
                dict_check["str_error"] = u"core_error_incompatibility"
        dict_check["num_quant"] = max(0, (n - limits_n))
        return(dict_check)
# Here it is a funcion to transform input value in according
# to correspond with interval limit(s) marked to be added.

    def parse_sortm(str_sortm):
        str_sortm = str_sortm.replace(","," ")
# Let comma be the valid separating character.
        lst_sortm_in = str_sortm.split()
# The string is splitted by spaces into strings list.

        lst_sortm_out = []
        for i in lst_sortm_in:
            if u"-" in i:
# A substring with a dash should be transformed.

                n = i.split(u"-")
                n0 = int(n[0])
                n1 = int(n[1])
                k = range(n0, n1, (int(copysign(1, (n1 - n0))))) + [n1]
# Also we should add right interval limit to the range.

                lst_sortm_out += k
            else:
                lst_sortm_out.append(int(i))
        return(lst_sortm_out)
# Here it is a function to parse input string with setted sorting mode.

    def do_sortm(lst_numbz_in, str_sortm):
        lst_sortm = parse_sortm(str_sortm)
        lst_numbz_out = []
        lst_numbz_in.sort()
        for i in lst_sortm:
            lst_numbz_out.append(lst_numbz_in[i - 1])
        return(lst_numbz_out)
# Here it is a function to apply setted sorting mode.

    def wrapError(ErrorID, Language, ErrorzList):
        '''Prints error text and transfers it into UI.'''
        ErrorText = locale(ErrorID, Language)
        print(ErrorText)
        if ErrorID.startswith(u"core_error"):
# Let's not show information messages at UI.
            ErrorzList.append(ErrorText)
        return(ErrorzList)

    matrix = []
    errorz = []
    dict_txt  = {
    "str_numbz": u"",
    "str_infoz": u""}
    mini = set_float_data(dict_val["str_minim"])
    maxi = set_float_data(dict_val["str_maxim"])
    if (dict_val["str_avera"] != ""):
        mean = punctu(dict_val["str_avera"])
    n = set_int_data(dict_val["str_quant"], 1)
    rounding = set_int_data(dict_val["str_round"], -1)

    limits_add = []
    if dict_val["log_min_v"]:
        limits_add.append(mini)
    if dict_val["log_max_v"]:
        limits_add.append(maxi)
# Here it is a list with interval limit(s) marked to be added.

    if dict_val["log_horiz"]:
        NumbersSeparator = "\t"
# Horizontal numbers output into one row.
    else:
        NumbersSeparator = "\n"
# Vertical numbers output into one column.

    if mini > maxi:
        maxi, mini = mini, maxi
        wrapError(u"core_error_min>max", dict_val["str_langu"], errorz)
#Если при вводе были перепутаны границы, то они меняются местами.
#Запись соответствующего сообщения об ошибке.

    if dict_val["str_avera"] != "":

        if dict_val["str_minim"] == "":
            if mean > 0:
                mini = 0
            else:
                mini = 10 * mean
            if (mean == 0) and (dict_val["str_maxim"] != ""):
                mini = -1 * maxi
        if dict_val["str_maxim"] == "":
            if mean > 0:
                maxi = 10 * mean
            else:
                maxi = 0
            if (mean == 0) and (dict_val["str_minim"] != ""):
                maxi = -1 * mini
# If a limit value isn't set but an average value is set
# the limit will be calculated according to the average.

        if (maxi > mean > mini):
            average_used = True
        else:
            average_used = False
            wrapError(u"core_error_incompatible_average", dict_val["str_langu"], errorz)
    else:
        average_used = False
        wrapError(u"core_info_no_average", dict_val["str_langu"], errorz)
# The existence and the possibility of use of average value is checked.
#Запись соответствующего сообщения об ошибке.

    if limits_add != []:
        if average_used:
            dict_check = check_limits(limits_add, dict_val["str_avera"], n, mini, maxi, mean)
            average_used = dict_check["log_avera"]
            if average_used:
                mean = dict_check["num_avera"]
            if dict_check["str_error"] != u"":
                wrapError(dict_check["str_error"], dict_val["str_langu"], errorz)
        else:
            dict_check = check_limits(limits_add, "", n, mini, maxi, None)
        n = dict_check["num_quant"]

    m = n - 1
    if version < '3':
        fromzeroton = xrange(n)
        fromzerotom = xrange(m)
    else:
        fromzeroton = range(n)
        fromzerotom = range(m)
#Создаются пустые списки и текст. Обрабатываются числовые параметры.
#Вычисляется удобное число m. Создаются удобные списки.

    rsd_used = False
    rsd_used2 = False
    if dict_val["str_rsd_p"] != "":
        if (not dict_val["log_max_v"]) and (not dict_val["log_min_v"]):
# RSD adjustment with maximum or minimum included to the output isn't implemented.

            if n > 1:
                if (mini * maxi >= 0):
                    rsd = punctu(dict_val["str_rsd_p"])
                    if not average_used:
                        mean = (mini + maxi) / 2
                    if mean != 0:
                        if rsd > 0:
                            rsd_used = True
                            if dict_val["log_rsd_w"]:
                                matrix = randorateGauss(fromzeroton, mean, (mean * rsd / 100))
                                print(u"RSD value was selected and randorated.")
                                rsd_used2 = True
                                if dict_val["log_algor"]:
                                    errorz.append(u"No true random if precise RSD value!")
# rsd_used2 indicates if matrix has been already randorated.
# rsd_used indicates if rsd algorithms will be used at all.
                        else:
                            errorz.append(u"RSD должно быть больше 0!")
                            print(u"RSD value was selected but couldn't be randorated.")
                else:
                    errorz.append(u"RSD не может быть рассчитано для интервала, включающего 0!")
                    print(u"RSD value was selected but couldn't be randorated.")
            else:
                errorz.append(u"RSD не может быть рассчитано менее чем для двух чисел!")
                print(u"RSD value was selected but couldn't be randorated.")

        else:
            errorz.append(u"Оптимизация по RSD отключена при добавлении границы интервала!")
            print(u"RSD value was selected but couldn't be randorated.")
# If fixed RSD value is set and can be used Gauß distribution will be randorated.

    if (not rsd_used2):
        if average_used:
            matrix = average(mini, maxi, n, mean, m, fromzerotom, dict_val["log_algor"])
            print(u"Average value was selected and randorated.")
        else:
            matrix = rando(mini, maxi, fromzeroton, dict_val["log_algor"])

    if rsd_used:
        if not average_used:
            mean = sum(matrix) / n
        dict_torsd = {
            "lst_numbz": matrix,
            "str_quant": n,
            "str_avera": mean,
            "str_rsd_p": rsd,
            "lst_index": fromzeroton,
            "log_rsd_w": dict_val["log_rsd_w"]}
        dict_rsd = relstdev(dict_torsd)
        rsd_used = True
# RSD value is adjusted.

    if dict_val["log_min_v"]:
        matrix.append(mini)
    if dict_val["log_max_v"]:
        matrix.append(maxi)
# Selected numbers are included to the output.

    if not (mini == maxi == 0):
        mini = abs(mini)
        maxi = abs(maxi)
        if mini > maxi:
            maxi, mini = mini, maxi
        if mini == 0:
            mini = maxi / 10
        elif maxi == 0:
            maxi = mini * 10
# Logarithm of nonpositive numbers couldn't be calculated!

        log_mini = log(mini, 10)
        if (log_mini > 11) or (log(maxi, 10) < -4):
            if rounding != -1:
                errorz.append(u"Округление больших и маленьких чисел не поддерживается!")
                rounding = -1
# Rounding of small and big numbers doesn't work.

        else:
            round_max = (-1 * log_mini) + 11
            if rounding > round_max:
                rounding = int(round_max)
                errorz.append(u"Не более " + str(rounding) + u" цифер после запятой!")
# If rounding is set more than the maximum value
# that could be applied the rounding is truncated.

    else:
        errorz.append(u"Кого бы поделить на ноль?")
        rounding = 0
# Here it is an easter egg ^,,^

    if dict_val["log_rsd_a"]:
        rsd_out = [False, None]

        if rsd_used:
            rsd_out = [True, dict_rsd["num_rsd_q"]]
# Use calculated RSD value when it exists.

        else:
            if (n > 1) and (mini * maxi >= 0):
                if not average_used:
                    mean = sum(matrix) / n
                if mean != 0:
                    rsd_out = [True, rsd_calc(fromzeroton, matrix, mean, n, True)]
# Or calculate it if it is possible.

            else:
                errorz.append(u"Невозможно рассчитать RSD!")
                print(u"RSD couldn't be calculated.")

        if rsd_out[0]:
            dict_txt["str_infoz"] += str(sum(matrix) / n) + u"; RSD, % = " + str(rsd_out[1])
# If RSD is requested to show and could be get it will be outputed.
# NOTE I don't really understand why this code is required but it is:
            if ((errorz != []) and (dict_val["log_verbo"])):
                dict_txt["str_infoz"] = "\n" + dict_txt["str_infoz"]
            else:
                dict_txt["str_infoz"] = dict_txt["str_infoz"] + "\n"
# End of NOTE

    if dict_val["log_verbo"] and (errorz != []):
        TempList = []
        if version < '3':
            ErrorzIndex = xrange(len(errorz))
        else:
            ErrorzIndex = range(len(errorz))
        for i in ErrorzIndex:
            TempList.append(errorz[i])
            TempList.append("\n")
        dict_txt["str_infoz"] = dict_txt["str_infoz"].join(TempList)
#Если задано, и ошибки есть, они переносятся в текст.

    if matrix != []:
        n = len(matrix)
        m = n - 1
        if version < '3':
            fromzerotom = xrange(m)
        else:
            fromzerotom = range(m)
# Proper values are restored.

        if dict_val["str_sortm"] != u"":
            if dict_val["str_sortm"] == u"1-":
                matrix.sort()
            elif dict_val["str_sortm"] == u"-1":
                matrix.sort()
                matrix.reverse()
            else:
                try:
                    matrix = do_sortm(matrix, dict_val["str_sortm"])
                except (IndexError, ValueError, UnicodeEncodeError):
                    dict_txt["str_infoz"] += u"Некорректный режим сортировки!" + "\n"
        else:
            if n > 2:
                shuffle(matrix)
        TempList = []
        for i in fromzerotom:
            TempList.append(to_text(matrix[i], rounding))
            TempList.append(NumbersSeparator)
        if m >= 0:
            TempList.append(to_text(matrix[m], rounding))
        dict_txt["str_numbz"] = dict_txt["str_numbz"].join(TempList)
#Cписок c количеством элементов больше 3 перемешивается и преобразуется в текст.
#Каждое число с красной строки. Округление при необходимости.
    
    if not dict_val["log_punct"]:
        dict_txt["str_numbz"] = dict_txt["str_numbz"].replace(".", ",")
#Если требуется, то точки заменяются запятыми.

    return(dict_txt)
예제 #25
0
def test_average_empty_list_1():
    """Otestování výpočtu průměru pro prázdný vstup."""
    with pytest.raises(ZeroDivisionError) as excinfo:
        result = average([])
예제 #26
0
	data from BMP180 publish everything via MQTT.
	"""
	args = sys.argv
	delay = 10.0

	if len(args) > 1:
		delay = float(args[1])

	result = dht.read()
	if result.is_valid():
		humidity.append(result.humidity)
		i += 1

	if time_i == 30:
		data = bmp.read()
		data["humidity"] = average(humidity)
		data["light"] = light.read()
		data["moisture"] = moisture.read()
		i = 0
		time_i = 0
		humidity = []
		ts = int(time.time())

		log.debug("Sending MQTT messages")
		publish.single(MQTT_TEMP,"{0};{1}".format(ts, data["temperature"]), hostname=HOST)
		publish.single(MQTT_HUM,"{0};{1}".format(ts, data["humidity"]), hostname=HOST)
		publish.single(MQTT_PRES,"{0};{1}".format(ts, data["pressure"]), hostname=HOST)
		publish.single(MQTT_LIGHT,"{0};{1}".format(ts, data["light"]), hostname=HOST)
		publish.single(MQTT_MOISTURE,"{0};{1}".format(ts, data["moisture"]), hostname=HOST)

	time_i += 1
예제 #27
0
            csvfile_write.close()
        #new item
        else:
            print('\t' + vg_csv_file(vagetable) + ' do not exist')
            print('\tcreat ' + vg_csv_file(vagetable))
            csvfile = open(vg_csv_file(vagetable), 'w', newline='')
            fieldnames = ['year', 'month', 'day', 'weight', 'price']
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
            writer.writeheader()

            #parse from default_start_date
            date = default_start_date
            while (date != end_date):
                data = get_oneday(vagetable, date)
                print('\t', data)
                #one day
                writer.writerow({
                    'year': data['year'],
                    'month': data['month'],
                    'day': data['day'],
                    'weight': data['weight'],
                    'price': data['price']
                })
                date += oneday
            csvfile.close()

    average()
    typhoon()
    merge()
    transToJson()
예제 #28
0
#!/usr/bin/env python

from argparse import ArgumentParser
import array
import average

size = 10

arg_parser = ArgumentParser(description='test Cython errors')
arg_parser.add_argument('--m', type=int, default=0, help='lower bound')
arg_parser.add_argument('--n', type=int, default=size, help='upper bound')
options = arg_parser.parse_args()
data = array.array('d', list(range(size)))
print('with except:')
try:
    print(average.average(data, options.m, options.n))
except Exception as e:
    print('caught exception {0}: {1}'.format(str(e.__class__), str(e)))
print('without except:')
try:
    print(average.average_no_except(data, options.m, options.n))
    print('no exception caught')
except Exception as e:
    print('caught exception {0}: {1}'.format(e.__class__, str(e)))
예제 #29
0
def test_average():
    items = [100, 50]
    assert average.average(items) == 75
예제 #30
0
def test_average_empty_list():
    """Otestování výpočtu průměru."""
    result = average([])
    expected = 0.0
    assert result == expected, "Očekávaná hodnota {}, vráceno {}".format(
        expected, result)
예제 #31
0
 def test_running_list_mag_items(self):  # 3
     """Test a two-item list."""
     argument = [5, 2]
     expected = 3.5
     argument = avg.average(argument)
     self.assertEqual(expected, argument, "The list contains two items.")
예제 #32
0
def test_average_basic():
    """Otestování výpočtu průměru."""
    result = average([1, 2])
    expected = 1.5
    assert result == expected, "Očekávaná hodnota {}, vráceno {}".format(
        expected, result)
예제 #33
0
 def test_running_list_mag_zeros(self):  # 5
     """Test a list of zeros."""
     argument = [0, 0, 0, 0]
     expected = 0
     argument = avg.average(argument)
     self.assertEqual(expected, argument, "The list contains only zeros.")
예제 #34
0
 def test_calculates_average_of_numbers_in_list(self):
     result = average.average([10, 2, 3, 4, 5])
     self.assertEqual(4.8, result)