def on_delete_event(self, window, event, data=None): """Handle a window close request""" maker = Factory() if maker.isinstance(self.get_child(), 'Terminal'): if self.get_property('term_zoomed') == True: return (self.confirm_close(window, _('window'))) else: dbg('Window::on_delete_event: Only one child, closing is fine') return (False) elif maker.isinstance(self.get_child(), 'Container'): return (self.confirm_close(window, _('window'))) else: dbg('unknown child: %s' % self.get_child())
def get_tab_title(self, uuid=None): """Return the title of a parent tab of a given terminal""" maker = Factory() terminal = self.terminator.find_terminal_by_uuid(uuid) window = terminal.get_toplevel() root_widget = window.get_children()[0] if maker.isinstance(root_widget, 'Notebook'): for tab_child in root_widget.get_children(): terms = [tab_child] if not maker.isinstance(terms[0], 'Terminal'): terms = enumerate_descendants(tab_child)[1] if terminal in terms: return root_widget.get_tab_label(tab_child).get_label()
def propagate_title_change(self, widget, title): """Pass a title change up the widget stack""" maker = Factory() parent = self.get_parent() title = widget.get_window_title() if maker.isinstance(self, 'Notebook'): self.update_tab_label_text(widget, title) elif maker.isinstance(self, 'Window'): self.title.set_title(widget, title) if maker.isinstance(parent, 'Container'): parent.propagate_title_change(widget, title)
def __init__(self, www_path): self.factory = Factory() self.factory.register('DateTimeWrapper', DateTimeWrapper()) self.factory.register('FsWrapper', FsWrapper()) self.filepathhandler = FilePathHandler(www_path) daily_log_writer = DailyFileWriter(self.factory, DAILY_LOG_NAME, DAILY_LOG_EXT) daily_err_writer = DailyFileWriter(self.factory, DAILY_LOG_NAME, DAILY_ERR_EXT) daily_logger = Logger(self.factory, daily_log_writer, daily_err_writer) self.logger = LogChainer(daily_logger) self.logger.chain(ConsoleLogger(True))
def main(): args = parse_args() if not os.path.exists(args.checkpoint_dir): os.mkdir(args.checkpoint_dir) if not os.path.exists(args.record_dir): os.mkdir(args.record_dir) num_logfile = 0 logfile_detail = '%s/PFAN_%s_%s_to_%s_%d_detail.log' % ( args.record_dir, args.base_net, args.source, args.target, num_logfile) logfile_brief = '%s/PFAN_%s_%s_to_%s_%d_brief.log' % ( args.record_dir, args.base_net, args.source, args.target, num_logfile) while os.path.exists(logfile_detail): num_logfile += 1 logfile_detail = '%s/PFAN_%s_%s_to_%s_%d_detail.log' % ( args.record_dir, args.base_net, args.source, args.target, num_logfile) logfile_brief = '%s/PFAN_%s_%s_to_%s_%d_brief.log' % ( args.record_dir, args.base_net, args.source, args.target, num_logfile) logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger('record') # sh = logging.StreamHandler(sys.stdout) fh_detail = logging.FileHandler(filename=logfile_detail) fh_brief = logging.FileHandler(filename=logfile_brief) # sh.setLevel(logging.DEBUG) fh_detail.setLevel(logging.DEBUG) fh_brief.setLevel(logging.INFO) # logger.addHandler(sh) logger.addHandler(fh_detail) logger.addHandler(fh_brief) logger.debug('log test') logger.info(args) factory = Factory(logger, args.data_dir, args.checkpoint_dir, base_net=args.base_net, batch_size=args.batch_size, source=args.source, target=args.target, num_classes=args.num_classes, u=args.u, base_lr=args.base_lr, alpha=args.alpha, beta=args.beta, max_iter=args.max_iter, max_step=args.max_step, interval=args.interval) factory.transfer_learning()
def split_axis(self, widget, vertical=True, cwd=None, sibling=None, widgetfirst=True): """Split the axis of a terminal inside us""" dbg('called for widget: %s' % widget) order = None page_num = self.page_num(widget) if page_num == -1: err('Notebook::split_axis: %s not found in Notebook' % widget) return label = self.get_tab_label(widget) self.remove(widget) maker = Factory() if vertical: container = maker.make('vpaned') else: container = maker.make('hpaned') self.get_toplevel().set_pos_by_ratio = True if not sibling: sibling = maker.make('terminal') sibling.set_cwd(cwd) sibling.spawn_child() if widget.group and self.config['split_to_group']: sibling.set_group(None, widget.group) if self.config['always_split_with_profile']: sibling.force_set_profile(None, widget.get_profile()) self.insert_page(container, None, page_num) self.child_set_property(container, 'tab-expand', True) self.child_set_property(container, 'tab-fill', True) self.set_tab_reorderable(container, True) self.set_tab_label(container, label) self.show_all() order = [widget, sibling] if widgetfirst is False: order.reverse() for terminal in order: container.add(terminal) self.set_current_page(page_num) self.show_all() while Gtk.events_pending(): Gtk.main_iteration_do(False) self.get_toplevel().set_pos_by_ratio = False GObject.idle_add(terminal.ensure_visible_and_focussed)
def set_rough_geometry_hints(self): """Walk all the terminals along the top and left edges to fake up how many columns/rows we sort of have""" if self.ismaximised == True: return if not hasattr(self, 'cached_maker'): self.cached_maker = Factory() maker = self.cached_maker if maker.isinstance(self.get_child(), 'Notebook'): dbg("We don't currently support geometry hinting with tabs") return terminals = self.get_visible_terminals() column_sum = 0 row_sum = 0 for terminal in terminals: rect = terminal.get_allocation() if rect.x == 0: cols, rows = terminal.get_size() row_sum = row_sum + rows if rect.y == 0: cols, rows = terminal.get_size() column_sum = column_sum + cols if column_sum == 0 or row_sum == 0: dbg('column_sum=%s,row_sum=%s. No terminals found in >=1 axis' % (column_sum, row_sum)) return # FIXME: I don't think we should just use whatever font size info is on # the last terminal we inspected. Looking up the default profile font # size and calculating its character sizes would be rather expensive # though. font_width, font_height = terminal.get_font_size() total_font_width = font_width * column_sum total_font_height = font_height * row_sum win_width, win_height = self.get_size() extra_width = win_width - total_font_width extra_height = win_height - total_font_height dbg('setting geometry hints: (ewidth:%s)(eheight:%s),\ (fwidth:%s)(fheight:%s)' % (extra_width, extra_height, font_width, font_height)) geometry = Gdk.Geometry() geometry.base_width = extra_width geometry.base_height = extra_height geometry.width_inc = font_width geometry.height_inc = font_height self.set_geometry_hints(self, geometry, Gdk.WindowHints.BASE_SIZE | Gdk.WindowHints.RESIZE_INC)
def split_axis(self, widget, vertical=True, cwd=None, sibling=None, widgetfirst=True): """Split the window""" if self.get_property('term_zoomed') == True: err("You can't split while a terminal is maximised/zoomed") return order = None maker = Factory() self.remove(widget) if vertical: container = maker.make('VPaned') else: container = maker.make('HPaned') self.set_pos_by_ratio = True if not sibling: sibling = maker.make('Terminal') sibling.set_cwd(cwd) # TODO (dank): is widget ever not a Terminal? if self.config['always_split_with_profile']: sibling.force_set_profile(None, widget.get_profile()) sibling.spawn_child( orientation='vertical' if vertical else 'horizontal', active_pane_id=getattr(widget, 'pane_id', None)) if widget.group and self.config['split_to_group']: sibling.set_group(None, widget.group) elif self.config['always_split_with_profile']: sibling.force_set_profile(None, widget.get_profile()) self.add(container) container.show_all() order = [widget, sibling] if widgetfirst is False: order.reverse() for term in order: container.add(term) container.show_all() while Gtk.events_pending(): Gtk.main_iteration_do(False) sibling.grab_focus() self.set_pos_by_ratio = False
def closetab(self, widget, label): """Close a tab""" tabnum = None try: nb = widget.notebook except AttributeError: err('TabLabel::closetab: called on non-Notebook: %s' % widget) return for i in xrange(0, nb.get_n_pages() + 1): if label == nb.get_tab_label(nb.get_nth_page(i)): tabnum = i break if tabnum is None: err('TabLabel::closetab: %s not in %s. Bailing.' % (label, nb)) return maker = Factory() child = nb.get_nth_page(tabnum) if maker.isinstance(child, 'Terminal'): dbg('Notebook::closetab: child is a single Terminal') del nb.last_active_term[child] child.close() # FIXME: We only do this del and return here to avoid removing the # page below, which child.close() implicitly does del (label) return elif maker.isinstance(child, 'Container'): dbg('Notebook::closetab: child is a Container') result = self.construct_confirm_close(self.window, _('tab')) if result == Gtk.ResponseType.ACCEPT: containers = None objects = None containers, objects = enumerate_descendants(child) while len(objects) > 0: descendant = objects.pop() descendant.close() while Gtk.events_pending(): Gtk.main_iteration() return else: dbg('Notebook::closetab: user cancelled request') return else: err('Notebook::closetab: child is unknown type %s' % child) return
def test_resolve_bombs(self): # (Factory, bombs_arriving, expt_stock) test_bombs = [ # Bombs take out half of the factory's stock (Factory(0, 1, 0, 33, (0, 0)), 1, 17), # Bombs take out minimum 10 stock (Factory(0, -1, 0, 13, (0, 0)), 1, 3), # Multiple bombs stack properly (Factory(0, 0, 0, 33, (0, 0)), 2, 7), # Can't go below zero (Factory(0, 1, 0, 5, (0, 0)), 2, 0), ] for factory, bombs_arriving, expt_stock in test_bombs: orig_team = factory.team factory.bombs_arriving = bombs_arriving factory.resolve_bombs() self.assertEqual(factory.team, orig_team) self.assertEqual(factory.stock, expt_stock) self.assertEqual(factory.disabled_turns, 5) self.assertEqual(factory.bombs_arriving, 0)
def new_window(self, cwd=None, profile=None): """Create a window with a Terminal in it""" maker = Factory() window = maker.make('Window') terminal = maker.make('Terminal') if cwd: terminal.set_cwd(cwd) if profile and self.config['always_split_with_profile']: terminal.force_set_profile(None, profile) window.add(terminal) window.show(True) terminal.spawn_child() return (window, terminal)
def tab_new(self, widget=None, debugtab=False, _param1=None, _param2=None): """Make a new tab""" cwd = None if self.get_property('term_zoomed') == True: err("You can't create a tab while a terminal is maximised/zoomed") return if widget: cwd = widget.get_cwd() maker = Factory() if not self.is_child_notebook(): dbg('Making a new Notebook') notebook = maker.make('Notebook', window=self) self.get_child().newtab(debugtab, cwd=cwd)
def tab_title_action(self, uuid, action, label): maker = Factory() terminal = self.terminator.find_terminal_by_uuid(uuid) window = terminal.get_toplevel() root_widget = window.get_children()[0] if maker.isinstance(root_widget, "Notebook"): for tab_child in root_widget.get_children(): terms = [tab_child] if not maker.isinstance(terms[0], "Terminal"): terms = enumerate_descendants(tab_child)[1] if terminal in terms: if action == 'get': return root_widget.get_tab_label(tab_child).get_label() elif action == 'set': root_widget.get_tab_label(tab_child).set_label(label)
def __init__(self, sfs_path, csv_file): os.chdir(sfs_path) self.ud = Factory(csv_file) self.sfs = subprocess.Popen(shsplit("java -jar sfs.jar")) os.chdir("..") tries = 0 success = False while tries < self.MAX_TRIES: try: xdt = subprocess.run( shsplit( 'xdotool search --onlyvisible --name "{}"'.format( "Shop Floor Simulator" ) ), stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) if xdt.stdout is None: tries += 1 else: win = int(xdt.stdout) # print(win) xdt = subprocess.run( shsplit("xdotool windowmove {} 1500 300".format(win)), stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) success = True break except Exception: tries += 1 # print(e) if not success: print("Could not reposition SFS window!") else: print("SFS window repositioned!") self.mb_client = ModbusTcpClient("127.0.0.1", 5502) if self.mb_client.connect(): print("Connected to server!") else: print("Could not connect to server!")
def getAABB(self): aabb = AABB() lastX = 0 lastY = 0 # to acces values with simplepath format (x, y) = range(-2, 0) if self.tag == addNS('path', 'svg'): blocks = Factory().create('path_parser').parse(self.get('d')) for vertex in blocks: for (cmd, values) in vertex: if values is not None: if cmd == 'C': aabb.addBezier((lastX, lastY), values) elif cmd == 'A': aabb.addArc((lastX, lastY), values) else: aabb.addPoint(values[x], values[y]) lastX = values[x] lastY = values[y] elif self.tag in [addNS('rect', 'svg'), addNS('image', 'svg')]: x = float(self.get('x')) y = float(self.get('y')) width = float(self.get('width')) height = float(self.get('height')) aabb.addPoint(x, y) aabb.addPoint(x + width, y + height) elif self.tag == addNS('use', 'svg'): x = float(self.get('x')) y = float(self.get('y')) # the first character of an href is a # imageId = self.get(addNS('href', 'xlink'))[1:] image = self.svg.getImage(imageId) width = float(image.get('width')) height = float(image.get('height')) aabb.addPoint(x, y) aabb.addPoint(x + width, y + height) else: raise Exception("Can't get AABB of a node which is neither a path \ nor a rect.\nnode tag:%s" % self.tag) return aabb
def rotate_recursive(self, parent, w, h, clockwise): """ Recursively rotate "self" into a new paned that'll have "w" x "h" size. Attach it to "parent". As discussed in LP#1522542, we should build up the new layout (including the separator positions) in a single step. We can't rely on Gtk+ computing the allocation sizes yet, so we have to do the computation ourselves and carry the resulting paned sizes all the way down the widget tree. """ maker = Factory() handle_size = self.get_handlesize() if isinstance(self, HPaned): container = VPaned() reverse = not clockwise else: container = HPaned() reverse = clockwise container.ratio = self.ratio children = self.get_children() if reverse: container.ratio = 1 - container.ratio children.reverse() if isinstance(self, HPaned): w1 = w2 = w h1 = pos = self.position_by_ratio(h, handle_size, container.ratio) h2 = max(h - h1 - handle_size, 0) else: h1 = h2 = h w1 = pos = self.position_by_ratio(w, handle_size, container.ratio) w2 = max(w - w1 - handle_size, 0) container.set_pos(pos) parent.add(container) if maker.isinstance(children[0], 'Terminal'): children[0].get_parent().remove(children[0]) container.add(children[0]) else: children[0].rotate_recursive(container, w1, h1, clockwise) if maker.isinstance(children[1], 'Terminal'): children[1].get_parent().remove(children[1]) container.add(children[1]) else: children[1].rotate_recursive(container, w2, h2, clockwise) self.terminator.layout_changed(self)
def group_tab(self, widget): """Group all terminals in the current tab""" maker = Factory() notebook = self.get_child() if not maker.isinstance(notebook, 'Notebook'): dbg('not in a notebook, refusing to group tab') return pagenum = notebook.get_current_page() while True: group = _('Tab %d') % pagenum if group not in self.terminator.groups: break pagenum += 1 self.set_groups(group, self.get_visible_terminals())
def __init__(self, location): super(ProjectManager, self).__init__() logger = logging.getLogger("pm.ProjectManager") logger.info( "Constructing ProjectManager with location: {0}".format(location)) self.projdir = location self.usersdirs = {} # Hold a list of 'UserDir' objects self.factory = Factory() self.factory.addClass('Download', DownloadWorker) self.factory.addWorkers('Download') self.factory.addClass('DownloadThumbnails', DownloadThumbnailsWorker) self.factory.addWorkers('DownloadThumbnails', 5) self.updateUsersDir() logger.info("Finish constructing ProjectManager")
def get_tab(self, uuid=None): """Return the UUID of the parent tab of a given terminal""" maker = Factory() terminal = self.terminator.find_terminal_by_uuid(uuid) window = terminal.get_toplevel() root_widget = window.get_children()[0] if maker.isinstance(root_widget, 'Notebook'): #return root_widget.uuid.urn for tab_child in root_widget.get_children(): terms = [tab_child] if not maker.isinstance(terms[0], "Terminal"): terms = enumerate_descendants(tab_child)[1] if terminal in terms: # FIXME: There are no uuid's assigned to the the notebook, or the actual tabs! # This would fail: return root_widget.uuid.urn return ""
def split_axis(self, widget, vertical=True, cwd=None, sibling=None, widgetfirst=True): """Split the axis of a terminal inside us""" dbg('called for widget: %s' % widget) order = None page_num = self.page_num(widget) if page_num == -1: err('Notebook::split_axis: %s not found in Notebook' % widget) return label = self.get_tab_label(widget) self.remove(widget) maker = Factory() if vertical: container = maker.make('vpaned') else: container = maker.make('hpaned') if not sibling: sibling = maker.make('terminal') sibling.set_cwd(cwd) sibling.spawn_child() if widget.group and self.config['split_to_group']: sibling.set_group(None, widget.group) if self.config['always_split_with_profile']: sibling.force_set_profile(None, widget.get_profile()) self.insert_page(container, None, page_num) self.set_tab_reorderable(container, True) self.set_tab_label(container, label) self.show_all() order = [widget, sibling] if widgetfirst is False: order.reverse() for terminal in order: container.add(terminal) self.set_current_page(page_num) self.show_all() terminal.grab_focus()
def _do_redistribute(self, recurse_up=False, recurse_down=False): maker = Factory() #2 Make a list of self + all children of same type tree = [self, [], 0, None] toproc = [tree] number_splits = 1 while toproc: curr = toproc.pop(0) for child in curr[0].get_children(): if type(child) == type(curr[0]): childset = [child, [], 0, curr] curr[1].append(childset) toproc.append(childset) number_splits = number_splits + 1 else: curr[1].append([None, [], 1, None]) p = curr while p: p[2] = p[2] + 1 p = p[3] # (1c) If Shift modifier, redistribute lower sections too if recurse_down and \ (maker.isinstance(child, 'VPaned') or \ maker.isinstance(child, 'HPaned')): GObject.idle_add(child.do_redistribute, False, True) #3 Get ancestor x/y => a, and handle size => hs avail_pixels = self.get_length() handle_size = self.get_handlesize() #4 Math! eek (a - (n * hs)) / (n + 1) = single size => s single_size = (avail_pixels - (number_splits * handle_size)) / (number_splits + 1) arr_sizes = [single_size] * (number_splits + 1) for i in range(avail_pixels % (number_splits + 1)): arr_sizes[i] = arr_sizes[i] + 1 #5 Descend down setting the handle position to s # (Has to handle nesting properly) toproc = [tree] while toproc: curr = toproc.pop(0) for child in curr[1]: toproc.append(child) if curr[1].index(child) == 0: curr[0].set_position((child[2] * single_size) + ((child[2] - 1) * handle_size)) GObject.idle_add(curr[0].set_position, child[2] * single_size)
def get_points(self, query, count=10, scope='*'): # type: (str, int, str) -> osisoftpy.structures.TypedList[Point] """ :param query: :param count: :param scope: :return: """ payload = {'q': query, 'count': count, 'scope': scope} log.debug( 'Executing Query against PI Web WebAPI Indexed Search with ' 'the following parameters: Query: "%s", Count: "%s". Payload: %s', query, count, payload) r = self.session.get(self.url + '/search/query', params=payload) if r.status_code != requests.codes.ok: r.raise_for_status() else: data = r.json() log.debug('HTTP %s - Instantiating %s PI points', r.status_code, get_count(data.get('Items', None))) factory = Factory(Point) items = list(map(lambda x: create(factory, x), data.get('Items', None))) points = TypedList(Point) for point in items: points.append(point) log.debug('PI Point retrieval success! %s PI ' 'point(s) were ' 'found and instantiated.', get_count(points)) if len(data['Errors']) != 0: for error in data['Errors']: try: log.warning('The PI Web WebAPI returned the ' 'following error while instantiating ' 'PI points. ' 'ErrorCode: {0}, Source: {1}, ' 'Message {2}'.format( error['ErrorCode'], error['Source'], error['Message'])) except Exception as e: log.error('Exception encounted while ' 'instantiating ' 'PI points!', exc_info=True) return points
def do_redistribute(self, recurse_up=False, recurse_down=False): """Evenly divide available space between sibling panes""" maker = Factory() #1 Find highest ancestor of the same type => ha highest_ancestor = self while type(highest_ancestor.get_parent()) == type(highest_ancestor): highest_ancestor = highest_ancestor.get_parent() # (1b) If Super modifier, redistribute higher sections too if recurse_up: grandfather = highest_ancestor.get_parent() if maker.isinstance(grandfather, 'VPaned') or \ maker.isinstance(grandfather, 'HPaned') : grandfather.do_redistribute(recurse_up, recurse_down) GObject.idle_add(highest_ancestor._do_redistribute, recurse_up, recurse_down)
def random_vs_ttc(n_courses, n_students, min_cap, max_cap, iters): """ Compare RandomLottery outcome with RL+TTC outcome. """ f = Factory(n_courses, n_students, min_cap, max_cap) student_diffs = [] total_diffs = [] mean_student_diffs = [] for i in xrange(iters): courses, students = f.generate() # Run the RandomLottery rl = RandomLottery(courses, students) rl_students = rl.run() rl_utils = [s.get_studycard_value() for s in rl.students] rl_welfare = sum(rl_utils) # Run TTC on the output of RandomLottery ttc = TTC(deepcopy(rl_students)) ttc.run() ttc_utils = [s.get_studycard_value() for s in ttc.students] ttc_welfare = sum(ttc_utils) # Compute summary statistics total_diff = (ttc_welfare - rl_welfare) / float(ttc_welfare + rl_welfare) * 100 total_diffs.append(total_diff) student_diff = [(t - r) / float(t + r) * 100 if t + r else 0 for t, r in zip(ttc_utils, rl_utils)] student_diffs.append(student_diff) mean_student_diff = np.mean(student_diff) mean_student_diffs.append(mean_student_diff) print print "==========================================" print "Overall Welfare Improvement (%): " print "mean: ", np.mean(total_diffs), "std: ", np.std(total_diffs) print "==========================================" print "Mean Individual Welfare Improvement (%):" print "mean: ", np.mean(mean_student_diffs), "std: ", np.std(mean_student_diffs) print "==========================================" print return student_diffs, total_diffs, mean_student_diffs
def new_window(self, cwd=None, profile=None): """Create a window with a Terminal in it""" maker = Factory() window = maker.make('Window') terminal = maker.make('Terminal') if cwd: terminal.set_cwd(cwd) # new window gets terminal with defaults terminal.apply_new(self.config.get_defstub()) window.add(terminal) window.show(True) terminal.spawn_child() if len(self.windows) > 1: dbg('~MORE WINDOWS') else: dbg('~FIX NOCONFIg HEISENBUG') terminal.describe_layout('n', {'_': 1}) return (window, terminal)
def main(wf): log.debug('Started workflow') factory = Factory(find_omnifocus_icons()) args = parse_args() if SHOW_UPDATES and workflow.update_available: workflow.add_item('A new version is available', 'Action this item to install the update', autocomplete='workflow:update', icon=ICON_SYNC) if args.type != PERSPECTIVE: sql = populate_query(args) get_results(sql, args.type, factory) else: get_perspectives(args, factory) workflow.send_feedback()
def describe_layout(self, count, parent, global_layout, child_order): """Describe our current layout""" layout = {} maker = Factory() mytype = maker.type(self) if not mytype: err('unable to detemine own type. %s' % self) return ({}) layout['type'] = mytype layout['parent'] = parent layout['order'] = child_order if hasattr(self, 'get_position'): position = self.get_position() if hasattr(position, '__iter__'): position = ':'.join([str(x) for x in position]) layout['position'] = position if hasattr(self, 'get_size'): layout['size'] = self.get_size() labels = [] if mytype == 'Notebook': for tabnum in xrange(0, self.get_n_pages()): page = self.get_nth_page(tabnum) label = self.get_tab_label(page) labels.append(label.get_custom_label()) if len(labels) > 0: layout['labels'] = labels name = 'child%d' % count count = count + 1 global_layout[name] = layout child_order = 0 for child in self.get_children(): if hasattr(child, 'describe_layout'): count = child.describe_layout(count, name, global_layout, child_order) child_order = child_order + 1 return (count)
def get_visible_terminals(self): """Walk the widget tree to find all of the visible terminals. That is, any terminals which are not hidden in another Notebook pane""" if not hasattr(self, 'cached_maker'): self.cached_maker = Factory() maker = self.cached_maker terminals = {} for child in self.get_offspring(): if not child: continue if maker.isinstance(child, 'Terminal'): terminals[child] = child.get_allocation() elif maker.isinstance(child, 'Container'): terminals.update(child.get_visible_terminals()) else: err('Unknown child type %s' % type(child)) return (terminals)
def run_all(): start = time.time() for mode in modes: for order in orders: for sort in sorting.__all__: for n in sizes: factory = Factory(n, order=order, mode=mode) data = test.run_test(sort, factory) try: test.write_result_line(data) except Exception: print('data: \n', data) print('%s concluido' % str(sort).split(' ')[1]) print('%s concluido' % order) print('%s concluido' % mode) end = time.time() - start print('Concluído') print("Tempo total: %s segundos ---" % end)
def _start_task(self, taskName: str): self.curTask = taskName log.info(f'Start task {taskName}') try: lg = create_task_logger(taskName, console) ts = TaskStore(taskName, lg, self.taskList[taskName]['overwriteTaskstore']) taskId = self._mark_task_start(taskName) # [total ,seen, new, differ, delete, task error, export error, last doc id] self.syncCount[taskId] = [-1, 0, 0, 0, 0, 0, 0, ''] cf = self.taskList[taskName] fc = Factory(taskName, lg, cfg['exporters'][cf['exporter']], self.syncCount[taskId]) picker = self.Picker(taskId, taskName, cf, lg, ts, fc, self.syncCount[taskId]) picker.run() tab = '\n' + '\t' * 5 lg.info(f"Task done" f"{tab}Total objects: {self.syncCount[taskId][0]}" f"{tab}Seen: {self.syncCount[taskId][1]}" f"{tab}New: {self.syncCount[taskId][2]}" f"{tab}Differ: {self.syncCount[taskId][3]}" f"{tab}Deleted: {self.syncCount[taskId][4]}" f"{tab}Task errors: {self.syncCount[taskId][5]}" f"{tab}Export errors: {self.syncCount[taskId][6]}") if self.syncCount[taskId][5] != 0: lg.warning('Task done with some errors. Check logs') if self.syncCount[taskId][6] != 0: log.warning( 'Task had errors with sending documents. ' f'Documents that were not sent are saved in a folder {picker.factory.failPath}' ) self.check_point(taskId, 'complete') except Exception as e: if log.level == 10: e = traceback.format_exc() log.error(f"Fail with task {taskName}: {e}")