def leave(self): # get the end time self.end_time = now() # update the parent state time to actual elapsed time if necessary if self.duration < 0: if isinstance(self, ParentState): # advance the duration the children moved the this parent duration = self.state_time-self.start_time else: # advance the duration of this state duration = self.end_time-self.start_time self.advance_parent_state_time(duration) # remove the callback from the schedule clock.unschedule(self.callback) # notify the parent that we're done self.active = False self.done = True if self.parent: self.parent.check = True # call custom leave code self._leave() # write log to the state log #print self.get_log() if self.save_log: dump([self.get_log()],self.get_log_stream()) pass
def _callback(self, dt): if self.check: self.check = False # check the outcome each time if not self.outcome: # we should stop now #self.interval = 0 self.leave() return # process the children # start those that are not active and not done reset_next = False num_done = 0 for i,c in enumerate(self.children): if c.done: num_done += 1 # set whether we should reset the next reset_next = c.reset_next continue if not c.active: if i > 0 and \ not self.children[i-1].done and \ self.children[i-1].duration < 0: # we have to wait until it's done break # start the next one if reset_next: c.reset_clock = True c.enter() break # set whether we should reset the next reset_next = c.reset_next if num_done == len(self.children): # we're done with this sequence finished = False if not self.iterable is None: # see if we're done with the loop if self.i+1 >= len(val(self.iterable,recurse=False)): # we're really done finished = True self.leave() # reset to start if inside another loop self.i = 0 else: # dump log dump([self.get_log()],self.get_log_stream()) # set to next self.i += 1 self.current.item = val(self.iterable[self.i]) # update everything for the next loop if not finished: self._enter() pass
def _callback(self, dt): # eval the log_items and write the log keyvals = [(k, val(v)) for k, v in self.log_items.iteritems()] log = dict(keyvals) # log it to the correct file dump([log], self._get_stream()) pass
def leave(self): # get the end time self.end_time = now() # update the parent state time to actual elapsed time if necessary if self.duration < 0: if issubclass(self.__class__, ParentState): #isinstance(self, ParentState): # advance the duration the children moved the this parent duration = self.state_time - self.start_time else: # advance the duration of this state duration = self.end_time - self.start_time self.advance_parent_state_time(duration) # remove the callback from the schedule clock.unschedule(self.callback) # notify the parent that we're done self.active = False self.done = True if self.parent: self.parent.check = True # call custom leave code self._leave() # write log to the state log #print self.get_log() if self.save_log: dump([self.get_log()], self.get_log_stream()) pass
def _callback(self, dt): # eval the log_items and write the log keyvals = [(k, val(v)) for k, v in self.log_items.iteritems()] log = dict(keyvals) if self.log_dict: log.update(val(self.log_dict)) # log it to the correct file dump([log], self._get_stream()) pass
def _callback(self, dt): if self.check: self.check = False # check the outcome each time if not self.outcome: # we should stop now #self.interval = 0 self.leave() return # process the children # start those that are not active and not done num_done = 0 for i, c in enumerate(self.children): if c.done: num_done += 1 continue if not c.active: if i > 0 and \ not self.children[i-1].done and \ self.children[i-1].duration < 0: # we have to wait until it's done break # start the next one c.enter() break if num_done == len(self.children): # we're done with this sequence finished = False if not self.iterable is None: # see if we're done with the loop if self.i + 1 >= len(val(self.iterable, recurse=False)): # we're really done finished = True self.leave() # reset to start if inside another loop self.i = 0 else: # dump log dump([self.get_log()], self.get_log_stream()) # set to next self.i += 1 # update everything for the next loop if not finished: self._enter() pass
def mdlsearch(name, year, mediatypes, max_episodes, year_affects_match_score): Log.Info("Handling search for `%s (%s)` in %s", name, year, mediatypes) fetched = mdlfetchsearch(name) Log.Debug("Fetched search results len=%s entries=%s", len(fetched), dump(fetched)) results = [ mdlsearchresult(name, year, entry, year_affects_match_score) for entry in fetched if entry["type"] in mediatypes and entry.get("episodes", 1) <= max_episodes ] Log.Info("Populated metadata search results len=%s entries=%s", len(results), dump(results)) return results
def search(self, results, media, lang, manual): Log.Debug("Handling search lang=%s manual=%s, media:\n%s ", lang, manual, dump(media)) for result in mdlsearch(self.searchname(media), media.year, self.media_types, self.max_episodes, self.year_affects_match_score): results.Append(result)
def mdlupdate(metadata, media): Log.Debug("Handling request to update metadata\n%s\nusing media\n%s", dump(metadata.attrs), dump(media)) fetched = mdlfetchdetail(metadata.id) if hasattr(metadata, "year"): metadata.year = fetched.get("year") if Prefs["TRANSLATED_TITLES"]: metadata.title = fetched["title"] else: metadata.title = fetched["original_title"] metadata.original_title = fetched["original_title"] metadata.summary = fetched["synopsis"] metadata.duration = int(fetched["runtime"]) * MILLISECONDS_PER_MINUTE metadata.content_rating = fetched["certification"] metadata.rating = float(fetched["rating"]) metadata.originally_available_at = mdlairdate(fetched) # [metadata.collections.add(entry) for entry in fetched[]] [ metadata.genres.add(entry) for entry in fetched["genres"] if entry not in metadata.genres ] [ metadata.tags.add(entry) for entry in fetched["tags"] if entry not in metadata.tags ] country = fetched["country"] if country not in metadata.countries: metadata.countries.add(country) fetchedtype = fetched["type"] if fetchedtype not in metadata.collections: metadata.collections.add(fetchedtype) credits = mdlfetchcredits(metadata.id) Log.Debug("Fetched credits %s", credits) for person in credits["crew"]: Log.Debug("Handling credits for %s", person) job = person["job"] for property in mdlcreditsprops(job): # Only Movies have top-level cast properties collection = getattr(metadata, property, None) if collection is None: Log.Debug("Property '%s' does not exist, skipping", property) continue name = person["name"] if any(entry.name == name for entry in collection): Log.Debug( "Person %s already exists in property '%s', skipping", person, property) continue entry = collection.new() entry.name = name entry.role = job entry.photo = person["images"]["poster"] Log.Debug("Added person %s to property '%s'", person, property) posterURL = fetched["images"]["poster"] metadata.posters[posterURL] = Proxy.Media( HTTP.Request(posterURL, immediate=False)) Log.Debug("Updated metadata to have contents %s", dump(metadata.attrs))
def nsga_2(task_names, type_names, type_info_price, type_info_ecu, task_base_time, task_preds, comm_speeds, comm_sizes, task_seccs, archive_name=None): n_tasks = len(task_names) n_nodes = n_tasks n_types = len(type_names) creator.create("FitnessMulti", base.Fitness, weights=(-1.0, -1.0)) creator.create("Individual", array.array, typecode='I', fitness=creator.FitnessMulti) toolbox = base.Toolbox() toolbox.register("task2node", random.randint, 0, n_tasks-1) toolbox.register("node2type", random.randint, 0, n_types-1) toolbox.register("individual", tools.initCycle, creator.Individual, (toolbox.task2node, toolbox.node2type), n=n_tasks) toolbox.register("population", tools.initRepeat, list, toolbox.individual) toolbox.register("evaluate", evaluate, type_info_price=type_info_price, type_info_ecu=type_info_ecu, task_base_time=task_base_time, task_preds=task_preds, comm_speeds=comm_speeds, comm_sizes=comm_sizes, n_tasks=n_tasks, n_nodes=n_nodes, n_types=n_types) toolbox.register("mate", cross_tool, n_tasks=n_tasks, inplace=True) toolbox.register("mutate", mutate_tool, n_tasks=n_tasks, n_types=n_types, multi=True) toolbox.register("select", tools.selNSGA2) # pool = multiprocessing.Pool() # toolbox.register("map", pool.map) pop = toolbox.population(50) _, loc, ts = heft2(type_info_price, type_info_ecu, task_base_time,\ task_preds, comm_speeds, comm_sizes, task_seccs) pop[0][:] = get_chromosome(loc, ts) # hof = tools.ParetoFront() # hof.update(pop) fits = toolbox.map(toolbox.evaluate, pop) for fit, ind in zip(fits, pop): ind.fitness.values = fit for gen in range(100000): offspring = tools.selTournament(pop, 50, 2) offspring = toolbox.map(toolbox.clone, offspring) for ind1, ind2 in zip(offspring[::2], offspring[1::2]): if random.random() <= 0.5: toolbox.mate(ind1, ind2) del ind1.fitness.values, ind2.fitness.values for ind in offspring: if random.random() <= 0.3: toolbox.mutate(ind) del ind.fitness.values invalid_ind = [ind for ind in offspring if not ind.fitness.valid] fitnesses = toolbox.map(toolbox.evaluate, invalid_ind) for ind, fit in zip(invalid_ind, fitnesses): ind.fitness.values = fit pop = toolbox.select(pop + offspring, 50) # hof.update(offspring) # pop = hof s = set() ar = [] for i in pop: if tuple(i.fitness.values) not in s: s.add(tuple(i.fitness.values)) ar.append(i) ar.sort(key=lambda x: x.fitness.values[0]) if archive_name: dump(archive_name, ar, task_names, type_names, type_info_price, type_info_ecu, task_base_time, task_preds, comm_speeds, comm_sizes, n_tasks, n_nodes, n_types) return ar
pidLoop() micLoop() micLedLoop() try: while True: # main loop #image bug detection #print("threads: " + str(threading.active_count())) I2C.setLed(I2C.YELLOW, True) filename = detect.saveImage() I2C.setLed(I2C.YELLOW, False) bugs = 0 if ENABLE_MULTIPLE_BUGS: bugs = detect.detectMultiple(filename) else: bugs = detect.detectBug(filename) I2C.setBugCount(bugs) if bugs > 0: log.append('cam') print("[" + log.getTimestamp() + "] Image: Cockroach Detected") if ENABLE_MULTIPLE_BUGS: print('Number of bugs: ' + str(bugs)) except KeyboardInterrupt: print('Termination signal received, quitting...') GPIO.cleanup() log.dump() print('Cleanup finished') quit(0)