예제 #1
0
def addNode(nodeName,fNodeId):    
    conn = Db.getConn()
    cursor = conn.cursor()
    # 获取id
    cursor.execute('select MAX(id) as id from t_catalog ')
    row = cursor.fetchone()
    newId = row[0]
    if newId == None:
      newId = 500
    newId = newId +1
    # print(newId)
    
    # 计算最大序号
    cursor.execute('select MAX(serNo) as serNo from t_catalog where fnodeId=%s', (fNodeId,))
    row = cursor.fetchone()
    serNo = row[0]
    if serNo == None:
      serNo = 0
    serNo = serNo +1
    # 插入记录
    cursor.execute('insert into t_catalog (id,fnodeId,nodeName,serNo) values (%s,%s, %s,%s)', (newId,fNodeId, nodeName,serNo))     
    
    conn.commit()
    cursor.close()
    return newId
예제 #2
0
파일: views.py 프로젝트: CCorazza/Intra42
def profile(request, user):
  if ('connected' in request.session):
    u = User(request.session['username'], request.session['password'])
    data = {}
    if (u.connected):
      data = u.get_info(user)
      if (data != {}):
        data['location'] = u.get_location(user)
        if (data['location'] != 'Hors-Ligne'):
          Db.update(uid=user, fields = {'latest_location': data['location'],
                                        'latest_activity': 1})
        latest = Db.get(uid=user, fields = ('latest_activity',))
        if ('latest_activity' in latest) and (latest['latest_activity']):
          data['latest'] = '%s @ (%s)' % (latest['latest_activity'], data['location']) 
    return render(request, "profile.html", {'data': data, 'sess' : request.session})
  else:
    return redirect('/login')
예제 #3
0
def get_file(episode_descriptor):

  dir = Db.get_config('completed_dir') 
  filelist = []
  for (a,b,c) in os.walk(dir):
    for f in c:
      filelist.append((f,a))

  return episode_descriptor.filter(filelist)
예제 #4
0
  def move_downloaded(self):

    log.info("move_downloaded")
    dl = DownloadProvider.getProvider()
    to = TorrentProvider.getProvider()

    for series in self.subs.get_series():
      for episode in self.subs.get_episodes(series['tvdb_series']):
        series_name = series['series_name']
        season_number = episode['season_number']
        episode_number = episode['episode_number']

        if episode['state'] != "enqueued":
          continue

        ds = SimpleEpisodeDescriptor(series_name, 
              int(season_number), 
              int(episode_number), episode)
        try:

          f = get_file(ds)

          if len(f) == 1:
            log.info("found file for %s: %s" %(str(ds), repr(f)))
          else:
            raise RuntimeError("file not found")


          # pick first element of result array as file.
          # result will contain only one element anyhow
          f = f[0]

          targetdir = Db.get_config('sorted_dir')
          targetdir = os.path.join(targetdir, clean_fn(series_name), "Season %d" %(season_number,))
          if not os.path.isdir(targetdir):
            os.makedirs(targetdir)

          log.info("created directory")
          extension = os.path.splitext(f[0])[1][1:]
          src = os.path.join(f[1], f[0])
          dst = os.path.join(targetdir, ds.get_file_name(extension))
          log.info("moving file %s to %s" % (src, dst))
          shutil.move(src, dst)

          self.subs.update_episode_state(episode['tvdb_series'], 
              episode['tvdb_episode'], 
              "done")

        except Exception as ex:

          log.warn("failed to find file for %s/%s/%s: %s" % (series_name, season_number, episode_number, format_exc(ex)))
예제 #5
0
파일: TaskDao.py 프로젝트: metecyu/Prj_Al
def getTaskListByDate(searchDate):    
    conn = Db.getConn()
    cursor = conn.cursor()
    # 获取id
    cursor.execute('select id,taskName,status from t_task  where date=%s',(searchDate,))

    rows = cursor.fetchall()
    outList =[]
    for row in rows:
       #print(row) 
       task = Task()
       task.id = row[0] 
       task.taskName = row[1]
       task.status = row[2]       
       outList.append(task)
      
    cursor.close()
    conn.close()
    return outList
예제 #6
0
파일: Server.py 프로젝트: mru00/serial_rent
 def POST(self, key, value):
   unquoted = urllib.unquote(value)
   Db.set_config(key, unquoted)
   log.info("setting config value '%s' to '%s'" % (str(key), str(unquoted)))
   return json.dumps(None)
예제 #7
0
def main():

    global dbUtils
    global routerServer
    global logger
    global HTTP_PORT

    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("--port",
                        help="display a square of a given number",
                        type=int,
                        required=True)

    parser.add_argument("--isFirstInit",
                        help="display a square of a given number",
                        type=bool)

    parser.add_argument("--gcmServerAuth",
                        help="gcm key for push notifications",
                        type=str)

    parser.add_argument("--serverId", help="serverId", type=str, required=True)

    parser.add_argument("--serverAddr",
                        help="external ip address ",
                        type=str,
                        required=True)

    parser.add_argument(
        "--serverGroup",
        help="unique to identify group , like main , development-1 etc",
        type=str)

    args = parser.parse_args()

    Config.serverGroup = args.serverGroup if args.serverGroup else Config.serverGroup
    Config.serverId = args.serverId

    Utils.logger = logger = create_timed_rotating_log('quizapp_logs/quizapp' +
                                                      "_" + Config.serverId +
                                                      '.log')

    logger.info("PROCESS_PID: " + str(os.getpid()))
    logger.info("initializing dbUtils..")
    Utils.dbUtils = dbUtils = Db.DbUtils(Config.dbServer)  #initialize Db

    #     if(not args.serverAddr.endswith(str(args.port))):
    #         print "Serveradd should end with port, continue only if you have configured domain-name:port to your serving host"
    if (not args.serverAddr.startswith("http")):
        print "Serveraddr should shart with http or https"
        return

    if (dbUtils.isServerIdExists(Config.serverId, Config.serverGroup)):
        print "there is already a server entry with the same serverId %s in this group %s clear , if there is no such such server running you can continue" % (
            Config.serverId, Config.serverGroup)
        if (raw_input("y/n : ").lower() == "n"):
            return

    dbUtils.updateServerMap({Config.serverId: args.serverAddr},
                            Config.serverGroup)
    ##generate a random key and send an email to help manage
    dbUtils.addSecretKey(HelperFunctions.generateKey(10))

    logger.info("initialing router utilities")
    Utils.routerServer = routerServer = RouterServerUtils.RouterServerUtils(
        dbUtils)
    HTTP_PORT = args.port
    if (args.isFirstInit):
        from CreateBots import createBots
        bots = createBots(dbUtils, Db.UserWinsLosses)
        logger.info("creating bots..")
        print bots
        dbUtils.loadBotUids()

        if (not args.gcmServerAuth):
            print "You must supply a  gcm key on first init"
            return

    if (args.gcmServerAuth):
        dbUtils.config("gcmauth", args.gcmServerAuth)

    reloadGcmConfig()

    http_server = tornado.httpserver.HTTPServer(QuizApp())
    http_server.listen(HTTP_PORT)
    ## this should be moved to seperate queuing service
    tornado.ioloop.PeriodicCallback(sendGcmMessages, 2000).start()
    tornado.ioloop.IOLoop.instance().start()
예제 #8
0
def Main():

    u = os.system('reset')

    db = Db.Db()
    message = Msg.Msg(0, 0)
    door = True

    try:

        while True:

            #override
            if (db.override() == "0"):
                u = os.system('clear')
                print("stopped")

                db.state = 0

                message.data = db.override()
                message.send()

            else:
                #restart
                if (db.state == 0):
                    print("restarting...")
                    message.data = db.getNext()
                    message.send()
                    #db.state = 1

                message.recieve()

                if message.new is not None:
                    #u = os.system('clear')

                    print(message.new)
                    print("current: " + str(db.getCurrent()))
                    print("next: " + str(db.getNext()))

                    #if from motor controller update current
                    if int(message.nodeId) == 101:
                        db.updateCurrent(message.data)

                    #if from a node
                    if int(message.nodeId) == 200 or int(
                            message.nodeId) == 201 or int(
                                message.nodeId) == 202 or int(
                                    message.nodeId) == 203:
                        if int(message.data) == 8:
                            door = True
                        elif int(message.data) == 9:
                            door = False
                        else:
                            db.insertDebug(message.nodeId, message.data)
                            db.insertQueue(message.nodeId, message.data)

                #dequeue if not moving
                if door == True:
                    if (db.getCurrent() == db.getNext()):

                        message.data = db.dequeue()

                        #don't bother sending if queue is empty/same floor
                        if (message.data != db.getCurrent()):
                            message.send()

                        db.updateNext(message.data)
                    else:
                        print("moving........")

    except (KeyboardInterrupt):
        pass
예제 #9
0
def evalMin(individual):
    mtct = list()
    #por cada gen del individuo (camion en posicion 0 del array o lista)
    for truck, shovel in enumerate(individual):
        tType = "" #truck type
        mTime = "" #tiempo maniobra
        #1. que tipo de camion es?  y tiempo de maniobra      
        if 0 <= truck <= truckTypes[0][5]-1:
            tType = truckTypes[0][0]
            mTime = truckTypes[0][3]
            truckEmptySpeed = truckTypes[0][1]
        if truckTypes[0][5] <= truck <= truckTypes[0][5]+truckTypes[1][5]-1:
            tType = truckTypes[1][0]
            mTime = truckTypes[1][3]
            truckEmptySpeed = truckTypes[1][1]
        if truck == truckTypes[0][5]+truckTypes[1][5]+truckTypes[2][5]-1:
            tType = truckTypes[2][0]
            mTime = truckTypes[2][3]
            truckEmptySpeed = truckTypes[1][1]

        #3. tiempo carga = ton/min x capacidad camion

        #obtener posicion en mapa gen (camion) actual -> se obtiene al comienzo por c# var home
        #obtener posibles rutas hasta el destino
        conn = Db.Connect(cdata)
        #cambiar a ingles todo al final
        destinationNode = str('Pala'+str(shovel))        
        routesToDestination =  conn.getRoutesToDestination(home, destinationNode)
        conn.disconnect()
        route = random.choice(routesToDestination)
        distance = route[3]
        estimatedTravelTime = distance * truckEmptySpeed
        #obtener tiempo espera estimado en cola (para ello consultar camiones que se encuentran en la cola y el tiempo estimado de los que se encuentran camino al mismo destino)
        conn = Db.Connect(cdata)
        #buscar cuantos y que tipos de camion se encuentran en cola
        TrucksInShovel =  conn.getTrucksInShovel(destinationNode)
        #buscar si hay un camion que esta siendo cargado
        inputTrucksWaitTime = 0
        processingTruckLoadTime = 0
        totalWaitingTime = 0

        shovelData = conn.getShovel(destinationNode)
        
        #calcular tiempo aproximado espera antes de que el camion comience a ser cargado por la pala
        if len(TrucksInShovel) > 0:
            for truck in TrucksInShovel:
                truckCapacity = conn.getTruckCapacity(truck[2])
                if truck[5] == 'Processing':
                    #tiempo carga = tiempo carga pala x espacio disponible camion
                    processingTruckLoadTime = (shovelData[2] * truckCapacity)
                elif truck[5] == 'Input':
                    #sumar tiempo carga sgte camion 
                    inputTrucksWaitTime = inputTrucksWaitTime + shovelData[0][2] * truckCapacity[4] + mTime
            #tiempo carga camion processing + tiempo carga camion input
            totalWaitingTime = processingTruckLoadTime + inputTrucksWaitTime 
        conn.disconnect()
        #obtener tiempo carga
        #lista de mtct en i0 guardar:
        #tiempo de ciclo estimado (tiempo de viaje) + tiempo espera estimado en cola + tiempo maniobra + tiempo carga
        estimatedcycletime = mTime + estimatedTravelTime + totalWaitingTime
        mtct.append(estimatedcycletime)
    #resultado mtct individuo actual
    mctc1 = list()
    mctc1.append(sum(mtct))
    return mctc1 #suma todos los elementos de la lista devolver como iterable
예제 #10
0
def main(current_simulation_time):

    #
    #
    #
    #
    #
    #
    #
    #
    #

    #random.seed(64) -> nose para que es xd
    #set current simlation time
    tCurrent = float(current_simulation_time.replace(',','.'))



    creator.create("FitnessMin", base.Fitness, weights=(-1.0,))
    creator.create("Individual", list, fitness=creator.FitnessMin)

    toolbox = base.Toolbox()

    conn = Db.Connect()
    SHOVEL_NUMBER = conn.getShovelNumber()-1
    #tCurrent = formData['timeNow']
    TRUCK_STATES = conn.getTruckStates()
    TRUCKS_NUMBER = conn.getTruckNumber()

    # Attribute generator 
    #                      define 'attr_bool' to be an attribute ('gene')
    #                      which corresponds to integers sampled uniformly
    #                      from the range [0,1] (i.e. 0 or 1 with equal
    #                      probability)
    #Genera valor de attr_bool de forma aleatoria esto en mi ag va desde 0 hasta el numero maximo de palas-1
    toolbox.register("no_shovel", random.randint, 0, SHOVEL_NUMBER)


    # Structure initializers
    #                         define 'individual' to be an individual
    #                         consisting of 100 'attr_bool' elements ('genes')
    # en mi ga el individuo consiste de valores enteros hasta el numero de camiones utilizados o registrados en la bd
    toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.no_shovel, TRUCKS_NUMBER)

    # define the population to be a list of individuals
    #igual en mi AG
    toolbox.register("population", tools.initRepeat, list, toolbox.individual)

    #FUNCIONES DE UTILIDAD
    #
    #
    #
    def findTruck(id):
        my_truck = ''
        for truck in TRUCK_STATES:
            if id == truck[10]:
                my_truck = truck
        return my_truck

    def calcTA(truckstate):
        #calcta es llamada cada vez que se realiza la evaluacion del individuo
        #shovel assignment sera el numero generado aleatoriamente por el cromosoma del individuo
        #ts[7] == "vc" or ts[7] == "vd" no realizan cambios ya que no son observados
        estimatedarrivaltime = 0
        #si el camion se encuentra en viaje se asigna valor 0
        if truckstate:
            if str(truckstate[7]) == "v":
                #0 no se puede determinar u observar
                estimatedarrivaltime = 0

            elif str(truckstate[7]) == "d":
                    
                #se encuentra en descarga 
                unload = conn.getUnloadStation(truckstate[3])
                deltatime = abs(tCurrent - float(truckstate[8].replace(",", ".")))
                #resultado = (capacidad camion * vel. descarga pala) + tiempo maniobra de camion - (tiempo actual simulacion -> timeNow - tiempo inicio -> tiempo en el que llego a d)
                estimatedarrivaltime = (truckstate[13] * unload[2]) + truckstate[12] - deltatime

            elif str(truckstate[7]) == "cd":
                
                unload = conn.getUnloadStation(truckstate[3])
                trucksinunload = conn.getTrucksInStation(truckstate[3])
                queuearrivaltime = 0

                #busca posicion de camion actual en cola y calcula tiempo de descarga de camion que se encuentre descargando
                for truckinunload in trucksinunload:

                    if truckinunload[3] == "cd":
                        #buscar posicion camion en cola
                        if truckstate[1] == truckinunload[1]:
                            #obtener indice
                            queuearrivaltime = truckinunload[4]

                    elif truckinunload[3] == "d":
                        #usar formula de camion cargando que se encuentra en la estacion de descarga
                        deltatime = abs(tCurrent - float(truckinunload[4].replace(",", ".")))
                        estimatedarrivaltime = (truckinunload[9] * unload[2]) + truckinunload[8] - deltatime

                for truckinunload in trucksinunload:
                    #si el tiempo de llegada del camion que esta en el array es menor o = al tiempo de llegada del camion para calc ta sumar
                    if truckinunload[4] <= queuearrivaltime:
                        deltatime = abs(tCurrent - float(truckinunload[4].replace(",", ".")))
                        estimatedarrivaltime = estimatedarrivaltime + (truckinunload[9] * unload[2]) + truckinunload[8] - deltatime

            elif str(truckstate[7]) == "c":
                
                #camion se encuentra cargando: capacidad camion * vel descarga + tiempo maniobra + tiempo actual - tiempo inicial
                shovel = conn.getShovel(truckstate[3])
                unloadroutes = conn.getRoutesToDestination(truckstate[3], shovel[3])
                unload = conn.getUnloadStation(shovel[3])
                trucksinunload = conn.getTrucksInStation(shovel[3])
                meanunloadroute = 0
                queuetime = 0

                #calcula distancia promedio de rutas hacia descarga
                for unloadroute in unloadroutes:
                    meanunloadroute = meanunloadroute + unloadroute[3]
                
                meanunloadroute = meanunloadroute/len(unloadroutes)

                #calcula tiempo de espera en descarga
                for truckinunload in trucksinunload:
                    deltatime = abs(tCurrent - float(truckinunload[4].replace(",", ".")))
                    queuetime = queuetime + (truckinunload[12] * unload[2]) + truckinunload[11] - deltatime
                #resultado = (capacidad camion * vel. descarga pala) + tiempo maniobra de camion + (distancia de viaje * vel camion cargado) + tiempo de camiones que estan en la zona de descarga) 
                # - (tiempo actual simulacion -> timeNow - tiempo inicio -> tiempo en el que llego a d)
                estimatedarrivaltime = (truckstate[12] * shovel[2]) + truckstate[11] + (meanunloadroute * truckstate[11]) + queuetime - deltatime

            elif str(truckstate[7]) == "cc":
                
                #camion se encuentra esperando carga
                shovel = conn.getShovel(truckstate[3])
                trucksinshovel = conn.getTrucksInStation(truckstate[3])
                unloadroutes = conn.getRoutesToDestination(truckstate[3], shovel[3])
                trucksinunload = conn.getTrucksInStation(shovel[3])

                meanunloadroute = 0
                queuearrivaltime = 0
                queuetime = 0
                estimatedarrivaltime = 0
                #calcula tiempos aprox para que el camion salga de la pala
                for truckinshovel in trucksinshovel:
                    if truckinshovel[3] == "cc":

                        if truckstate[1] == truckinshovel[1]:
                            queuearrivaltime = truckinshovel[4]

                    elif truckinshovel[3] == "c":
                        
                        deltatime = abs(tCurrent - float(truckinshovel[4].replace(",", ".")))
                        estimatedarrivaltime = (truckinshovel[9] * shovel[2]) + truckinshovel[8] - deltatime

                for truckinshovel in trucksinshovel:
                    
                    if truckinshovel[4] <= queuearrivaltime:
                        deltatime = abs(tCurrent - float(truckinshovel[4].replace(",", ".")))
                        estimatedarrivaltime = estimatedarrivaltime + (truckinshovel[9] * shovel[2]) + truckinshovel[8] - deltatime

                #calcula tiempo de viaje estimado y lo adiciona al estimatedarrivaltime
                for unloadroute in unloadroutes:
                    meanunloadroute = meanunloadroute + unloadroute[3]
                
                meanunloadroute = meanunloadroute/len(unloadroutes)

                #suma tiempos de los camiones que se encuentran en destino (descarga)
                for truckinunload in trucksinunload:
                    deltatime = abs(tCurrent - float(truckinunload[4].replace(",", ".")))
                    queuetime = queuetime + (truckinunload[12] * unload[2]) + truckinunload[11] - deltatime
                estimatedarrivaltime = estimatedarrivaltime + (truckstate[12] * shovel[2]) + truckstate[11] + (meanunloadroute * truckstate[11]) + queuetime - deltatime

            elif str(truckstate[7]) == "sag":
                
                #ya se encuentra en el ultimo estado
                estimatedarrivaltime = 0
            
            return estimatedarrivaltime
    
    
    # the goal ('fitness') function to be maximized
    #en mi ag necesito qud se minimize
    def evalOneMin(individual):
        #calcular como en TA segun 
        trucksCycleTime = 0
        listshovel = individual

        #recorre cada indice de la lista del individuo

        for index,value in enumerate(listshovel,1):
            truck = findTruck(index)
            if truck[7] !=  "v":
                shovelname = "Pala"+str(value)
                shovel = conn.getShovel(shovelname)

                #datos obligatorios

                loadroutes = conn.getRoutesToDestination(truck[3], shovelname)
                trucksinshovel = conn.getTrucksInStation(shovelname)
                unloadroutes = conn.getRoutesToDestination(shovel[1], shovel[3])
                unload = conn.getUnloadStation(shovel[3])
                trucksinunload = conn.getTrucksInStation(shovel[3])                

                # distancia prom ruta viaje a carga

                loadmeandistance = 0
                for loadroute in loadroutes:
                    loadmeandistance = loadmeandistance + loadroute[3]
                loadmeandistance = loadmeandistance / len(loadroutes)
                loadtraveltime = loadmeandistance * truck[12]

                #suma camiones en carga
                sumtrucksinshovel = 0
                for truckinshovel in trucksinshovel:
                    deltatime = abs(float(tCurrent) -float(truckinshovel[4].replace(",", ".")))
                    sumtrucksinshovel = sumtrucksinshovel + (truckinshovel[9] * shovel[2]) + truckinshovel[8] - deltatime

                #distancia prom ruta viaje a descarga
                unloadmeandistance = 0
                for unloadroute in unloadroutes:
                    unloadmeandistance = unloadmeandistance + unloadroute[3]
                unloadmeandistance = unloadmeandistance / len(unloadroutes)
                unloadtraveltime = unloadmeandistance * truck[12]

                #suma camiones en descarga
                sumtrucksinunload = 0
                for truckinunload in trucksinunload:
                    deltatime = abs(tCurrent - float(truckinunload[4].replace(",", ".")))
                    sumtrucksinunload = sumtrucksinunload + (truckinunload[9] * unload[2]) + truckinunload[8] - deltatime

                trucksCycleTime = loadtraveltime + sumtrucksinshovel + unloadtraveltime + sumtrucksinunload
                #se agrega el TA
                trucksCycleTime = trucksCycleTime + individual[index-1]
        #calcular TGA
        return trucksCycleTime,
        #return sum(individual),

    #----------
    # Operator registration
    #----------
    # register the goal / fitness function
    toolbox.register("evaluate", evalOneMin)

    # register the crossover operator
    toolbox.register("mate", tools.cxTwoPoint)

    # register a mutation operator with a probability to
    # flip each attribute/gene of 0.05
    toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)

    # operator for selecting individuals for breeding the next
    # generation: each individual of the current generation
    # is replaced by the 'fittest' (best) of three individuals
    # drawn randomly from the current generation.
    toolbox.register("select", tools.selTournament, tournsize=3)

    # create an initial population of 300 individuals (where
    # each individual is a list of integers)
    pop = toolbox.population(n=300)

    # CXPB  is the probability with which two individuals
    #       are crossed
    #
    # MUTPB is the probability for mutating an individual
    CXPB, MUTPB = 0.5, 0.2
    
    print("Start of evolution")
    
    # Evaluate the entire population
    fitnesses = list(map(toolbox.evaluate, pop))
    for ind, fit in zip(pop, fitnesses):
        ind.fitness.values = fit
    
    print("  Evaluated %i individuals" % len(pop))

    # Extracting all the fitnesses of 
    fits = [ind.fitness.values[0] for ind in pop]

    # Variable keeping track of the number of generations
    g = 0
    
    # Begin the evolution
    #tiempo maximo de ejecucion 1 minuto
    time_current = int(time.time()/60)
    while (int(time.time()/60) - time_current) < 1 and g < 500:
        # A new generation
        time_current = int(time.time()/60)
        g = g + 1
        print("-- Generation %i --" % g)
        
        # Select the next generation individuals
        offspring = toolbox.select(pop, len(pop))
        # Clone the selected individuals
        offspring = list(map(toolbox.clone, offspring))
    
        # Apply crossover and mutation on the offspring
        for child1, child2 in zip(offspring[::2], offspring[1::2]):

            # cross two individuals with probability CXPB
            if random.random() < CXPB:
                toolbox.mate(child1, child2)

                # fitness values of the children
                # must be recalculated later
                del child1.fitness.values
                del child2.fitness.values

        for mutant in offspring:

            # mutate an individual with probability MUTPB
            if random.random() < MUTPB:
                toolbox.mutate(mutant)
                del mutant.fitness.values
    
        # Evaluate the individuals with an invalid fitness
        invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
        fitnesses = map(toolbox.evaluate, invalid_ind)
        for ind, fit in zip(invalid_ind, fitnesses):
            ind.fitness.values = fit
        
        print("  Evaluated %i individuals" % len(invalid_ind))
        
        # The population is entirely replaced by the offspring
        pop[:] = offspring
        
        # Gather all the fitnesses in one list and print the stats
        fits = [ind.fitness.values[0] for ind in pop]
        
        length = len(pop)
        mean = sum(fits) / length
        sum2 = sum(x*x for x in fits)
        std = abs(sum2 / length - mean**2)**0.5
        
        print("  Min %s" % min(fits))
        print("  Max %s" % max(fits))
        print("  Avg %s" % mean)
        print("  Std %s" % std)
    
    print("-- End of (successful) evolution --")
    best_ind = tools.selBest(pop, 1)[0]
    print("Best individual is %s, %s" % (best_ind, best_ind.fitness.values))
    estimated_arrival_time = []
    for index, val in enumerate(best_ind, start = 1):
        ta = calcTA(findTruck(index))
        estimated_arrival_time.append(ta)
    print("mejor individuo, tiempo estimado, fitness")
    return  best_ind, estimated_arrival_time, best_ind.fitness.values
예제 #11
0
    def OnBotaoSalvarButton(self, event): #pra já deixar maiusculo
        NomeAluno = self.campoNomeAluno.GetValue()
        NomeAluno = NomeAluno.upper()
        self.campoNomeAluno.SetValue(NomeAluno)

        NomeMae = self.campoNomeMae.GetValue()
        NomeMae = NomeMae.upper()
        self.campoNomeMae.SetValue(NomeMae)

        NomePai = self.campoNomePai.GetValue()
        NomePai = NomePai.upper()
        self.campoNomePai.SetValue(NomePai)

        Complemento = self.campoComplemento.GetValue()
        Complemento = Complemento.upper()
        self.campoComplemento.SetValue(Complemento)

        Endereco = self.campoEndereco.GetValue()
        Endereco = Endereco.upper()
        self.campoEndereco.SetValue(Endereco)

        Bairro = self.campoBairro.GetValue()
        Bairro = Bairro.upper()
        self.campoBairro.SetValue(Bairro)

        Matricula = self.campoMatricula.GetValue()
        Matricula = Matricula.upper()
        self.campoMatricula.SetValue(Matricula)

        Email = self.campoEmail.GetValue()
        Email = Email.upper()
        self.campoEmail.SetValue(Email)


        #Inserção no banco
        #Primeiro Declaro todo mundo:
        try:
            self.__cpf              =self.campoCPF.GetValue()
            self.__data_nascimento  =self.campoAniversario.GetValue()

            if self.selecionaSexo.GetStringSelection() == 'Feminino':
                self.__sexo = 0
            else:
                self.__sexo = 1
                
            self.__nome             =self.campoNomeAluno.GetValue()
            self.__mae              =self.campoNomeMae.GetValue()
            self.__pai              =self.campoNomePai.GetValue()
            if self.__pai=='': #caso seja vazio
                self.pai = None
            self.__cep              =self.campoCEP.GetValue()
            self.__numero           =self.campoNumero.GetValue()
            self.__complemento      =self.campoComplemento.GetValue()
            if self.__complemento=='':
                self.__complemento= None
            self.__endereco         =self.campoEndereco.GetValue()
            self.__bairro           =self.campoBairro.GetValue()
            self.__cidade           =self.campoCidade.GetValue()
            self.__uf               =self.campoUF.GetValue()
            self.__matricula        =self.campoMatricula.GetValue()
            self.__departamento     =self.comboBoxDepartamento.GetValue() #nao sei fazer fazer com esse tambem mas tem que tranformar em alguma string para entrar no banco
            self.__curso            =self.comboBoxCursos.GetValue() #nao sei fazer tambem, mas eh string
            self.__ano_conclusao    =self.campoAnoConclusao.GetValue()
            
            
            if self.verificarEstagio.GetStringSelection() == 'Sim':
                self.__estagiando = 1
            else:
                self.__estagiando = 0
                
            if self.opcaoManha.GetValue() == False:
                self.__manha = 0
            else:
                self.__manha = 1
                
            
            if self.opcaoTarde.GetValue() == False:
                self.__tarde = 0
            else:
                self.__tarde = 1
                
            if self.opcaoNoite.GetValue() == False:
                self.__noite = 0
            else:
                self.__noite = 1
            self.__email            =self.campoEmail.GetValue()
            if self.__email == '':
                self.__email= None
            self.__telefone         =self.campoTelefone.GetValue()
            self.__celular          =self.campoCelular.GetValue()
            self.__senha            =self.campoSenha.GetValue()
            
            #DEPOIS DE DECLARAR TODO MUNDO EU INSIRO PELA FUNCAO
            Db.createAluno(self.__cpf , self.__data_nascimento, self.__sexo, self.__nome, self.__mae, self.__cep,\
                    self.__numero, self.__endereco, self.__bairro, self.__cidade, self.__uf, self.__matricula, \
                    self.__departamento , self.__curso, self.__ano_conclusao,\
                    self.__estagiando, self.__telefone, self.__celular, self.__senha, pai = self.__pai, \
                    complemento = self.__complemento, email= self.__email, manha = self.__manha, tarde = self.__tarde, noite = self.__noite)
        except MySQLdb.Error, e:
            self.ShowMessage(str(e[1]), str(e[0]))
예제 #12
0
ConnectfileData = File.Read(ConnectfileObject, empty)
if (ConnectfileData != empty):
    ConnectfileDataList = ConnectfileData.split(',')
else:
    Errormessage = 'No data in ' + Connectfilename
    File.Logerror(ErrorfileObject, module, Errormessage, error)

Errormessage = 'Could not close' + Connectfilename
if (File.Close(ConnectfileObject, failure) == failure):
    File.Logerror(ErrorfileObject, module, Errormessage, error)

# Progress update
File.Logerror(ErrorfileObject, module, 'Read database connection data', info)

# Open database connection.
DbObject = Db.Connect(ConnectfileDataList[0], ConnectfileDataList[1],
                      ConnectfileDataList[2], ConnectfileDataList[3], invalid)
Errormessage = 'Could not connect to database'
if (DbObject == invalid):
    File.Logerror(ErrorfileObject, module, Errormessage, error)

# Prepare a database cursor object.
DbCursor = Db.Initcursor(DbObject, invalid)
Errormessage = 'Unable to create database cursor'
if (DbCursor == invalid):
    File.Logerror(ErrorfileObject, module, Errormessage, error)

# Progress update
File.Logerror(ErrorfileObject, module, 'Connected to database', info)

# List all vacancy id's that have been applied for.
SQLcommand = 'select engine_id,vacancy_id from %s where vacancy_state = \'%s\'' % (
예제 #13
0
if debugPrint is False:
    blockPrint()
else:
    enablePrint()

if debugDb:
    exists = os.path.isfile("database.db")
    if exists:
        os.remove("database.db")

    exists = os.path.isfile("database.db-journal")
    if exists:
        os.remove("database.db-journal")

db = Db.Db()

# if debugDb:
#     dummy = Db.dummyDb()
#     dummy.dummyDB()

startConnection = db.startConnection()
connection = startConnection[0]
cursor = startConnection[1]

atexit.register(db.endConnection, connection)

app = QApplication(sys.argv)
window = MainWindow(cursor, connection)
# Having a fixed size for the windows makes it unable to be maximized
# window.setMaximumWidth(1380)
예제 #14
0
 def _setup_db(self):
     Db.drop_db(self.cfg, DB_NAME)
     Db.create_db(self.cfg, DB_NAME)
예제 #15
0
파일: Server.py 프로젝트: mru00/serial_rent
 def GET(self, key):
   log.info("get config: " + key)
   web.header('Content-type', "application/json")
   return json.dumps({"value": Db.get_config(key)})
예제 #16
0
def getInstance():
    instance = Db.Db(host='localhost',
                     user='******',
                     password='******',
                     dbname='tinyFirewall')
    return instance
예제 #17
0
 def __init__(self, parent, cursor):
     """Init."""
     self.db = Db.Db()
     self.cursor = cursor
     self.parent = parent
예제 #18
0
    def OnBotaoSalvarButton(self, event):  #pra já deixar maiusculo
        NomeAluno = self.campoNomeAluno.GetValue()
        NomeAluno = NomeAluno.upper()
        self.campoNomeAluno.SetValue(NomeAluno)

        NomeMae = self.campoNomeMae.GetValue()
        NomeMae = NomeMae.upper()
        self.campoNomeMae.SetValue(NomeMae)

        NomePai = self.campoNomePai.GetValue()
        NomePai = NomePai.upper()
        self.campoNomePai.SetValue(NomePai)

        Complemento = self.campoComplemento.GetValue()
        Complemento = Complemento.upper()
        self.campoComplemento.SetValue(Complemento)

        Endereco = self.campoEndereco.GetValue()
        Endereco = Endereco.upper()
        self.campoEndereco.SetValue(Endereco)

        Bairro = self.campoBairro.GetValue()
        Bairro = Bairro.upper()
        self.campoBairro.SetValue(Bairro)

        Matricula = self.campoMatricula.GetValue()
        Matricula = Matricula.upper()
        self.campoMatricula.SetValue(Matricula)

        Email = self.campoEmail.GetValue()
        Email = Email.upper()
        self.campoEmail.SetValue(Email)

        #Inserção no banco
        #Primeiro Declaro todo mundo:
        try:
            self.__cpf = self.campoCPF.GetValue()
            self.__data_nascimento = self.campoAniversario.GetValue()

            if self.selecionaSexo.GetStringSelection() == 'Feminino':
                self.__sexo = 0
            else:
                self.__sexo = 1

            self.__nome = self.campoNomeAluno.GetValue()
            self.__mae = self.campoNomeMae.GetValue()
            self.__pai = self.campoNomePai.GetValue()
            if self.__pai == '':  #caso seja vazio
                self.pai = None
            self.__cep = self.campoCEP.GetValue()
            self.__numero = self.campoNumero.GetValue()
            self.__complemento = self.campoComplemento.GetValue()
            if self.__complemento == '':
                self.__complemento = None
            self.__endereco = self.campoEndereco.GetValue()
            self.__bairro = self.campoBairro.GetValue()
            self.__cidade = self.campoCidade.GetValue()
            self.__uf = self.campoUF.GetValue()
            self.__matricula = self.campoMatricula.GetValue()
            self.__departamento = self.comboBoxDepartamento.GetValue(
            )  #nao sei fazer fazer com esse tambem mas tem que tranformar em alguma string para entrar no banco
            self.__curso = self.comboBoxCursos.GetValue(
            )  #nao sei fazer tambem, mas eh string
            self.__ano_conclusao = self.campoAnoConclusao.GetValue()

            if self.verificarEstagio.GetStringSelection() == 'Sim':
                self.__estagiando = 1
            else:
                self.__estagiando = 0

            if self.opcaoManha.GetValue() == False:
                self.__manha = 0
            else:
                self.__manha = 1

            if self.opcaoTarde.GetValue() == False:
                self.__tarde = 0
            else:
                self.__tarde = 1

            if self.opcaoNoite.GetValue() == False:
                self.__noite = 0
            else:
                self.__noite = 1
            self.__email = self.campoEmail.GetValue()
            if self.__email == '':
                self.__email = None
            self.__telefone = self.campoTelefone.GetValue()
            self.__celular = self.campoCelular.GetValue()
            self.__senha = self.campoSenha.GetValue()

            #DEPOIS DE DECLARAR TODO MUNDO EU INSIRO PELA FUNCAO
            Db.createAluno(self.__cpf , self.__data_nascimento, self.__sexo, self.__nome, self.__mae, self.__cep,\
                    self.__numero, self.__endereco, self.__bairro, self.__cidade, self.__uf, self.__matricula, \
                    self.__departamento , self.__curso, self.__ano_conclusao,\
                    self.__estagiando, self.__telefone, self.__celular, self.__senha, pai = self.__pai, \
                    complemento = self.__complemento, email= self.__email, manha = self.__manha, tarde = self.__tarde, noite = self.__noite)
        except MySQLdb.Error, e:
            self.ShowMessage(str(e[1]), str(e[0]))
예제 #19
0
def get_suggestion():
    jsdata = request.form['javascript_data']
    suggestion = json.loads(jsdata)
    Db.add_suggestion(suggestion)
    return 0
예제 #20
0
ConnectfileData = File.Read(ConnectfileObject, empty)
if (ConnectfileData != empty):
    ConnectfileDataList = ConnectfileData.split(',')
else:
    Errormessage = 'No data in ' + Connectfilename
    File.Logerror(ErrorfileObject, module, Errormessage, error)

Errormessage = 'Could not close' + Connectfilename
if (File.Close(ConnectfileObject, failure) == failure):
    File.Logerror(ErrorfileObject, module, Errormessage, error)

# Progress update
File.Logerror(ErrorfileObject, module, 'Read database connection data', info)

# Open database connection.
DbObject = Db.Connect(ConnectfileDataList[0], ConnectfileDataList[1],
                      ConnectfileDataList[2], ConnectfileDataList[3], invalid)
Errormessage = 'Could not connect to database'
if (DbObject == invalid):
    File.Logerror(ErrorfileObject, module, Errormessage, error)

# Prepare a database cursor object.
DbCursor = Db.Initcursor(DbObject, invalid)
Errormessage = 'Unable to create database cursor'
if (DbCursor == invalid):
    File.Logerror(ErrorfileObject, module, Errormessage, error)

# Progress update
File.Logerror(ErrorfileObject, module, 'Connected to database', info)

# Read fields in table 'vacancy'
SQLcommand = 'show columns from %s' % VacancyTable
예제 #21
0
 def __init__(self, var1, var2):
     self.db = Db.StockDb()
     self.change = NO_CHANGE
     self.reason = ""
     self.var1 = var1
     self.var2 = var2
예제 #22
0
    def enqueue(self, fn):

        download_dir = Db.get_config("download_dir")
        completed_dir = Db.get_config("completed_dir")

        # TODO: mkdir completed, download

        print "dl: ", download_dir
        print "cm: ", completed_dir

        def run(reactor, fn):
            global new_id

            log.info("should download " + str(fn))
            d = client.connect()
            reactor.resi = 5
            result = 5
            new_id = 5

            def on_set_1(new_id, result):
                c = client.core.set_torrent_move_completed(new_id, True)
                c.addCallback(lambda a: on_set_2(new_id, a))
                c.addErrback(on_add_fail)

            def on_set_2(new_id, result):
                client.disconnect()
                reactor.stop()

            def on_add_success(result):
                if not result:
                    log.info("add torrent successful, was already enqueued")
                    client.disconnect()
                    reactor.stop()
                else:
                    new_id = result
                    c = client.core.set_torrent_move_completed_path(
                        result, completed_dir)
                    c.addCallback(lambda a: on_set_1(result, a))
                    c.addErrback(on_add_fail)
                    log.info("added new torrent: " + repr(result))
                new_id = None

            def on_add_fail(result):
                log.info("add torrent failed: " + repr(result) + str(result))
                client.disconnect()
                reactor.stop()

            def on_connect_success(result):
                log.info("connection successful: " + repr(result))
                c = client.core.add_torrent_magnet(
                    fn, {
                        'download_location': download_dir,
                    })

                c.addCallback(on_add_success)
                c.addErrback(on_add_fail)

            def on_connect_fail(result):
                log.info("connection fail: " + repr(result))
                reactor.stop()

            d.addCallback(on_connect_success)
            d.addErrback(on_connect_fail)
            return new_id

        res = _run_deluge(run, fn)
        print "result:", res
예제 #23
0
ConnectfileData = File.Read(ConnectfileObject,empty)
if ( ConnectfileData != empty ) : 
    ConnectfileDataList = ConnectfileData.split(',')
else:
    Errormessage = 'No data in ' + Connectfilename
    File.Logerror(ErrorfileObject,module,Errormessage,error)

Errormessage = 'Could not close' + Connectfilename
if ( File.Close(ConnectfileObject,failure) == failure ) : File.Logerror(ErrorfileObject,module,Errormessage,error)

# Progress update
File.Logerror(ErrorfileObject,module,'Read database connection data',info)

# Open database connection.
DbObject = Db.Connect(ConnectfileDataList[0],ConnectfileDataList[1],ConnectfileDataList[2],ConnectfileDataList[3],invalid)
Errormessage = 'Could not connect to database'
if ( DbObject == invalid ) : File.Logerror(ErrorfileObject,module,Errormessage,error)

# Prepare a database cursor object.
DbCursor = Db.Initcursor(DbObject,invalid)
Errormessage = 'Unable to create database cursor'
if ( DbCursor == invalid ) : File.Logerror(ErrorfileObject,module,Errormessage,error)

# Progress update
File.Logerror(ErrorfileObject,module,'Connected to database',info) 

# Read fields in table 'vacancy'
SQLcommand = 'show columns from %s' % VacancyTable 
SQLresponse = ( Db.SQLload(DbObject,DbCursor,SQLcommand,failure) )
Errormessage = 'SQLresponse error for SQL command ' + '\"' + SQLcommand + '\"'
예제 #24
0
   def __init__(self, t_name, queue):  
 
       threading.Thread.__init__(self, name=t_name)  
       self.data=queue  
       self.conn = db.pre()
예제 #25
0
파일: Section.py 프로젝트: myglade/note
            {'id': 3, 'name': u'section 3', 'seqId': 2}, \
            {'id': 4, 'name': u'section 4', 'seqId': 3}, \
            {'id': 5, 'name': u'section 5', 'seqId': 4}, \
            {'id': 0, 'name': u'section 0', 'seqId': 5}, \
            ]
    assert (r == ex), "mismatch"

    prepare_reorder(sections)
    list = [0, 1, 2, 3, 4, 5]
    sections.reorderItem(list, 5)
    r = sections.getItems()
    ex = [  {'id': 0, 'name': u'section 0', 'seqId': 0}, \
            {'id': 1, 'name': u'section 1', 'seqId': 1}, \
            {'id': 2, 'name': u'section 2', 'seqId': 2}, \
            {'id': 3, 'name': u'section 3', 'seqId': 3}, \
            {'id': 4, 'name': u'section 4', 'seqId': 4}, \
            {'id': 5, 'name': u'section 5', 'seqId': 5}]
    assert (r == ex), "mismatch"

    print "done"


if __name__ == '__main__':
    db = Db("test.db")
    db.open()
    db.resetTables()
    db.createTable()

    test_section(db)

    print "done"
예제 #26
0
  def enqueue(self, fn):

    download_dir = Db.get_config("download_dir")
    completed_dir = Db.get_config("completed_dir")
    
    # TODO: mkdir completed, download

    print "dl: ", download_dir
    print "cm: ", completed_dir

    def run(reactor, fn):
      global new_id

      log.info("should download " + str(fn))
      d = client.connect()
      reactor.resi = 5
      result = 5
      new_id = 5


      def on_set_1(new_id, result):
        c = client.core.set_torrent_move_completed(new_id, True)
        c.addCallback(lambda a:on_set_2(new_id, a))
        c.addErrback(on_add_fail)

      def on_set_2(new_id, result):
        client.disconnect()
        reactor.stop()
      

      def on_add_success(result):
        if not result:
          log.info("add torrent successful, was already enqueued")
          client.disconnect()
          reactor.stop()
        else:
          new_id = result
          c = client.core.set_torrent_move_completed_path(result, completed_dir)
          c.addCallback(lambda a: on_set_1(result, a))
          c.addErrback(on_add_fail)
          log.info("added new torrent: " + repr(result))
        new_id=None

      def on_add_fail(result):
        log.info("add torrent failed: " + repr(result) + str(result))
        client.disconnect()
        reactor.stop()

      def on_connect_success(result):
        log.info("connection successful: " + repr(result))
        c = client.core.add_torrent_magnet(fn, 
            {
              'download_location':download_dir,
              })

        c.addCallback(on_add_success)
        c.addErrback(on_add_fail)

      def on_connect_fail(result):
        log.info("connection fail: " + repr(result))
        reactor.stop()

      d.addCallback(on_connect_success)
      d.addErrback(on_connect_fail)
      return new_id
 
    res = _run_deluge(run, fn)
    print "result:", res
예제 #27
0
파일: User.py 프로젝트: CCorazza/Intra42
 def save_location(self):
   if (self.connected):
     Db.update(self.username,
               {'latest_location': self.infos['location'], 'latest_activity': 1})
예제 #28
0
    return mctc1 #suma todos los elementos de la lista devolver como iterable

#connection configuration
cdata = {
    "host": "localhost",
    "username": "******",
    "password": "",
    "database": "simio"
}
#individual structure
#define fitness function, minimize in this case, weight negative stands for minimizing fitness
creator.create("FitnessMin", base.Fitness, weights=(-1.0,))
creator.create("Individual", list, fitness = creator.FitnessMin)

#trucks to create (6 in this test)
conn = Db.Connect(cdata)
truckTypes = conn.getTruckTypes()
for tt in truckTypes:
    N_TRUCKS += tt[5]

#population config
toolbox = base.Toolbox()
toolbox.register("attr_int", random.randint, MIN, N_SHOVELS) # define los tipos de un individuo
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_int, N_TRUCKS) # define individuo
toolbox.register("population", tools.initRepeat, list, toolbox.individual) #crea la poblacion

toolbox.register("evaluate", evalMin)
toolbox.register("mate", tools.cxTwoPoint)
toolbox.register("mutate", tools.mutUniformInt, low=1, up=N_SHOVELS, indpb=0.05)
toolbox.register("select", tools.selTournament, tournsize=3)
예제 #29
0
 def __init__(self):
   self.db = Db.get_db()