def post(ctx, url, file_name, username, password): """Post file to Review Board. Args: ctx: RBTLIB context. url: Review Board URL. username: Review Board user name. password: Review Board password. Returns: The file_name argument to the RBT command. """ review_requests = Root(ctx.obj['session'], url)().review_requests() if 200 == login(ctx, url, username, password): create = review_requests.create({ 'file': (file_name, open(file_name, 'rb'), magic.from_file(file_name, mime=True), { 'Expires': '0' }) }) if 'ok' == create.stat: print >> sys.stderr, 'posted review {0}'.format( create.review_request.id) else: print >> sys.stderr, 'failed to post review' else: print >> sys.stderr, 'failed to login' sys.exit
def plot_distance_matrix(param_dir: str, names: List[str], ages: List[float], n_layers: int): assert len(names) == len(ages) roots = [] for name, age in zip(names, ages): rs = RootSystem() rs.readParameters(join(param_dir, f"{name}.xml")) rs.initialize() rs.simulate(age) pyroot = Root(rs) pyroot.rescale() roots.append(pyroot) n = len(roots) dist_matrix = np.zeros((n, n)) for i, root_i in enumerate(roots): for j, root_j in enumerate(roots[:i + 1]): dist_matrix[i, j] = lw_wasserstein(root_i, root_j, n_layers) cleaned_names = [" ".join(name.split("_")[:-2]) for name in names] #cleaned_names = ages heatmap = pd.DataFrame(dist_matrix, columns=cleaned_names, index=cleaned_names) ax = sns.heatmap(heatmap, square=True, cmap="Greens") ax.tick_params(axis='both', which='both', length=0) ax.xaxis.set_ticks_position('bottom') plt.xticks(rotation=45) plt.yticks(rotation=0) bottom, top = ax.get_ylim() ax.set_ylim(bottom + 0.5, top - 0.5) plt.savefig(join(os.environ["HOME"], "reportOTDendrit", "images", f"distance_matrix_Anagallis.pdf"), bbox_inches="tight")
def __init__(self, root=None): super().__init__() self.autosavestack = 0 self.setupUi(self) self.root = Root() if root is None else root self.root.setmainwin(self) """Match Control""" self.focus_single = False self.focusedmatch = None self.URL = None """Design""" self.tourbuttons = [] self.courtbuttons = [] self.buttonsize = (75, 75) self.pointsize = 9 self.drawdepth = 4 self.testB.clicked.connect(self.test) self.resetB.clicked.connect(self.unLockMatch) self.saveB.clicked.connect(self.saveFile) self.openB.clicked.connect(self.openFile) self.googleB.clicked.connect(self.googlesave) self.settingB.clicked.connect(self.settings) self.focusB.clicked.connect(self.changefocus) self.resettimeB.clicked.connect(self.resettime) self.changefocus() self.updateallui()
def post(ctx, url, file_name, username, password): """Post file to Review Board. Args: ctx: RBTLIB context. url: Review Board URL. username: Review Board user name. password: Review Board password. Returns: The file_name argument to the RBT command. """ review_requests = Root(ctx.obj['session'], url)().review_requests() if 200 == login(ctx, url, username, password): create = review_requests.create({ 'file': (file_name, open(file_name, 'rb'), magic.from_file(file_name, mime = True), {'Expires': '0'}) }) if 'ok' == create.stat: print >> sys.stderr, 'posted review {0}'.format(create.review_request.id) else: print >> sys.stderr, 'failed to post review' else: print >> sys.stderr, 'failed to login' sys.exit
class Main(App): def __init__(self): App.__init__(self) self._root = Root() def build(self): def _bool(value): if value == "1": return True else: return False parser = argparse.ArgumentParser() parser.add_argument( "-c", "--cars_count", help="display a square of a given number", type=int, default=_DEFAULT_CARS_COUNT, ) parser.add_argument( "-s", "--scale_factor", help="softmax scale factor", type=int, default=_SCALE_FACTOR, ) parser.add_argument( "-up", "--use_pytorch", help="Use pytorch framework for NN", type=_bool, default=True, ) parser.add_argument( "-ws", "--write_status_file", help="Write simple visualization in text file", type=_bool, default=False, ) args = parser.parse_args() if args.cars_count > _MAX_CARS_COUNT: Logger.warning( "zOrg app: maximum cars number exceeded, falling back to 6") args.cars_count = _MAX_CARS_COUNT self._root.build(args) Clock.schedule_interval(self._root.update, 1.0 / 30.0) return self._root
def plot_root(param_dir: str, name: str, age: float): rs = RootSystem() rs.readParameters(join(param_dir, f"{name}.xml")) rs.initialize() rs.simulate(age) pyroot = Root(rs) fig = pyroot.plot(draw_nodes=False) fig.update_layout(margin={"t": 0, "l": 0, "b": 0, "r": 0}) fig.write_image( join(os.environ["HOME"], "reportOTDendrit", "images", f"{name}_age_{age}.pdf"))
def __init__(self, obj_func=None, lb=None, ub=None, problem_size=50, verbose=True, epoch=750, pop_size=100, z=0.03): Root.__init__(self, obj_func, lb, ub, problem_size, verbose) self.epoch = epoch self.pop_size = pop_size self.z = z
def __init__(self, obj_func=None, lb=None, ub=None, problem_size=50, verbose=True, epoch=750, pop_size=100, z=0.03): Root.__init__(self, obj_func, lb, ub, problem_size, verbose) self.maxEpochs = epoch self.pop_size = pop_size self.z = z self.seed = 0 self.Rand, self.exception = rand.RandomState(self.seed), None
def main(): """ Runs the program """ config = get_config() scanners = [] if config['enabled']['openports']: scanners.append(OpenPorts(config)) if config['enabled']['root']: scanners.append(Root(config)) if config['enabled']['ssh']: scanners.append(Ssh(config)) if config['enabled']['umask']: scanners.append(Umask(config)) if config['enabled']['update']: scanners.append(Update(config)) if config['enabled']['worldwritable']: scanners.append(WorldWritable(config)) for scanner in scanners: print('-' * 79) print('Running:', scanner.__class__.__name__) result = scanner.scan() print('Status:', result[0]) print('Message:', result[1]) print()
def root_factory(request): doc = dbutil.get_collection(request, 'content').find_one(dict(_object_type='root')) if doc: root = Root(request, **(dbutil.encode_keys(doc))) else: data = dict( title="CMS Demo Site", description="This site is a demo of a CMS based on Pyramid, MongoDB and ElasticSearch.", _is_ordered=True, ) # Run data thru a schema serialize/deserialize to pick up default values for other schema fields. schema = Root.get_class_schema(request) data = schema.deserialize(schema.serialize(data)) root = Root(request, **data) root.save() return root
def review_requests(ctx, url, counts_only, time_added_from, time_added_to): """Print the Review Requests List Resource. The date and time format is YYYY-MM-DD HH:MM:SS or {yyyy}-{mm}-{dd}T{HH}:{MM}:{SS} with an optional timezone appended as -{HH:MM}. Args: ctx: RBTLIB context. url: Review Board URL. counts_only: set to True to obtain review request counts only; False otherwise. time_added_from: earliest date from which to select review requests. time__added_to: latest date from which to select review requests. Returns: Writes to standard output. """ query_dict = dict() if counts_only: query_dict['counts-only'] = True if time_added_from: query_dict['time-added-from'] = time_added_from if time_added_to: query_dict['time-added-to'] = time_added_to print beautify(Root(ctx.obj['session'], url)().review_requests(query_dict)) sys.exit
def build(self): student_list = self.get_students() skills = Skills(**self.get_skills()) root = Root(orientation='vertical', skills=skills, app=self, student_list=student_list) return root
def test_scan_when_getuid_is_other(self, mock_os): # Prepare data and mocks mock_os.getuid = MagicMock(return_value=1000) # Run test scenario result = Root(None).scan() # Assertions mock_os.getuid.assert_called_once_with() self.assertEqual(result[0], ScanStatus.success)
def umount(): global unidade, bitmap, fat, root bitmap.save(unidade) fat.save(unidade) root.save(unidade) unidade.close() unidade = None bitmap = BitMap() fat = Fat() root = Root()
class PurpApp(App): theme_cls = ThemeManager() def __init__(self, **kwargs): super().__init__(**kwargs) self.title = "Purp" self.icon = "assets/images/logo_w.png" self.theme_cls.theme_style = config.get_theme_style() Window.keyboard_anim_args = {"d": 0.2, "t": "linear"} Window.softinput_mode = "below_target" def build(self): self.root = Root() self.root.set_current("auth") def on_start(self): statusbar.set_color(self.theme_cls.primary_color)
def test_scan_when_getuid_is_0_and_environ_sudo_uid_is_set(self, mock_os): # Prepare data and mocks mock_os.getuid = MagicMock(return_value=0) mock_os.environ.get = MagicMock(return_value=1000) # Run test scenario result = Root(None).scan() # Assertions mock_os.getuid.assert_called_once_with() mock_os.environ.get.assert_called_once_with('SUDO_UID') self.assertEqual(result[0], ScanStatus.success)
def root(ctx, url): """Print the Root List Resource. Args: ctx: RBTLIB context. url: Review Board URL. Returns: Writes to standard output. """ print beautify(Root(ctx.obj['session'], url)()) sys.exit
def curses_wrapper(scr, config, options): curses.raw() curses.start_color() style.theme.init_pairs() curses.curs_set(0) root = Root(scr, config, options) root.refresh() try: keyhandler = keys.Keys(root) keyhandler.start() except: root.stop() raise try: mousehandler = mouse.Mouse(root.fadectrl) except Exception, e: has_mouse = False root.status.set_error(e[0])
def plot_barycenters(param_dir: str, names: List[str], ages: List[float]): roots = [] for name, age in zip(names, ages): rs = RootSystem() rs.readParameters(join(param_dir, f"{name}.xml")) rs.initialize() rs.simulate(age) pyroot = Root(rs) pyroot.rescale() roots.append(pyroot) for root in roots: print(root.n_nodes) pt_bar = point_cloud_barycenter(roots) fig = plot_barycenter_nodes(pt_bar) fig.write_image( join(os.environ["HOME"], "reportOTDendrit", "images", f"ptbar_{names[0]}_{names[1]}.pdf")) _, _, bar_nodes = lw_barycenter(roots, n_layers=100, reg=1e-1) fig = plot_barycenter_nodes(bar_nodes) fig.write_image( join(os.environ["HOME"], "reportOTDendrit", "images", f"lwbar_{names[0]}_{names[1]}.pdf"))
def __init__(self, options): cherrypy.tools.nocache = cherrypy.Tool('on_end_resource', set_no_cache) cherrypy.server.socket_host = options.host cherrypy.server.socket_port = options.port cherrypy.log.screen = True cherrypy.log.access_file = options.access_log cherrypy.log.error_file = options.error_log logLevel = LOGGING_LEVEL.get(options.log_level, logging.DEBUG) dev_env = options.environment != 'production' # Create handler to rotate access log file h = logging.handlers.RotatingFileHandler(options.access_log, 'a', 10000000, 1000) h.setLevel(logLevel) h.setFormatter(cherrypy._cplogging.logfmt) # Add access log file to cherrypy configuration cherrypy.log.access_log.addHandler(h) # Create handler to rotate error log file h = logging.handlers.RotatingFileHandler(options.error_log, 'a', 10000000, 1000) h.setLevel(logLevel) h.setFormatter(cherrypy._cplogging.logfmt) # Add rotating log file to cherrypy configuration cherrypy.log.error_log.addHandler(h) # Handling running mode if not dev_env: cherrypy.config.update({'environment': 'production'}) if hasattr(options, 'model'): model_instance = options.model elif options.test: model_instance = mockmodel.get_mock_environment() else: model_instance = model.Model() self.app = cherrypy.tree.mount(Root(model_instance, dev_env), config=self.CONFIG)
cherrypy.tools.auth = cherrypy.Tool( 'before_handler', redirect_if_authentication_is_required_and_session_is_not_authenticated) if __name__ == '__main__': cherrypy.config.update({'server.socket_port': 443}) #port 443 for https or port 80 for http # cherrypy.config.update({'server.socket_port': 80}) cherrypy.config.update({ 'server.socket_host': 'ec2-18-236-80-185.us-west-2.compute.amazonaws.com' }) #cherrypy.tree.mount(Root()) cherrypy.tree.mount( Root(), '/', { '/favicon.ico': { 'tools.staticfile.on': True, 'tools.staticfile.filename': '/home/ec2-user/server/favicon.ico' }, '/robots.txt': { 'tools.staticfile.on': True, 'tools.staticfile.filename': '/home/ec2-user/server/robots.txt' }, }) cherrypy.server.ssl_module = 'builtin' cherrypy.server.ssl_certificate = "/etc/letsencrypt/live/n-plat.com/fullchain.pem" cherrypy.server.ssl_private_key = "/etc/letsencrypt/live/n-plat.com/privkey.pem" cherrypy.server.ssl_certificate_chain = "/etc/letsencrypt/live/n-plat.com/fullchain.pem"
def setUpClass(self): self.data = Data() self.data, wb = ExcelReader.read(self.data, Root.path() + '/../resources/test0.xlsm') wb.close()
def load(self,args): fh = None try: fh = args['filehandle'] except: filename = args['filename'] fh = open(filename, 'r') fh = codecs.getreader('utf8')(fh) nodes = [] comment = '' for line in fh: if re.search('^#',line): comment = comment + line elif re.search('^\d+\-',line): # HACK: multiword tokens temporarily avoided pass elif line.strip(): if not nodes: bundle = Bundle() self.bundles.append(bundle) root = Root() # TODO: nahradit bundle.create_tree, az bude odladene root._aux['comment'] = comment # TODO: ulozit nekam poradne nodes = [root] bundle.trees.append(root) columns = line.strip().split('\t') node = Node() nodes.append(node) for index in xrange(0,len(Document.attrnames)): setattr( node, Document.attrnames[index], columns[index] ) try: # TODO: kde se v tomhle sloupecku berou podtrzitka node.head = int(node.head) except ValueError: node.head = 0 try: # TODO: poresit multitokeny node.ord = int(node.ord) except ValueError: node.ord = 0 else: # an empty line is guaranteed even after the last sentence in a conll-u file nodes[0]._aux['descendants'] = nodes[1:] for node in nodes[1:]: node.set_parent( nodes[node.head] ) nodes = [] comment = ''
from root import Root r = Root() r.find_sav_vulnerabilities() #asn = r.get_asn('195.66.224.201') #print(asn)
# for k in self.schoolDic.keys(): # values.append(self.schoolDic[k]) # if values[-1]=="Bye": # values=values[:-1] # dialogInput, ok = QInputDialog().getItem(self, "선수 검색", "검색할 선수의 학교를 선택하십시오", values, False) # if ok: # target=dialogInput # schoolCode="" # for x in self.schoolDic.keys(): # if self.schoolDic[x]==target: # schoolCode=x # players=self._findSchoolPlayer(schoolCode) # playerNames=[] # realPlayers=[] # for p in players: # if p.nickName(self.schoolDic, type="fullname") not in playerNames: # playerNames.append(p.nickName(self.schoolDic, type="fullname")) # realPlayers.append(p) # dialogInput, ok = QInputDialog().getItem(self, "선수 검색", "검색할 선수 이름을 선택하십시오", playerNames, False) # if ok: # lowestMatch=self._findPlayer(realPlayers[playerNames.index(dialogInput)].name, schoolCode) # self._popupForFindPlayer(realPlayers[playerNames.index(dialogInput)].name, lowestMatch) if __name__ == '__main__': app=QApplication(sys.argv) rt=Root() win=MainUI(rt) win.show() app.exec_()
from root import Root if __name__ == '__main__': app = Root() app.mainloop()
from root import Root from button import * from label import * from dragbar import * from textbox import TextBox from inputbox import InputBox from menu import Menu from servo import Servo def barker(msg): def bark(*args): print msg, args return bark root = Root(bgcolor=(0xef, 0xef, 0xff, 0xff), size=(800, 600)) # label = Label(root, text="hello", pos=(300, 200), size=(100, 30)) # label = Label(root, text="world", pos=(300, 250), size=(100, 30), # align=Label.ALIGN_LEFT) # label = Label(root, text="david", pos=(300, 300), size=(100, 30), # align=Label.ALIGN_RIGHT) # # button = Button(root, caption="Click Me", pos=(300, 400), size=(100, 30)) # button.bind_command(barker("How dare you!")) src = ( """ The textbox works! This is the third line. The fourth line with 4 leading spaces. def handle_event(self, event):
class MainWindow(QMainWindow, form_class): def __init__(self, root=None): super().__init__() self.autosavestack = 0 self.setupUi(self) self.root = Root() if root is None else root self.root.setmainwin(self) """Match Control""" self.focus_single = False self.focusedmatch = None self.URL = None """Design""" self.tourbuttons = [] self.courtbuttons = [] self.buttonsize = (75, 75) self.pointsize = 9 self.drawdepth = 4 self.testB.clicked.connect(self.test) self.resetB.clicked.connect(self.unLockMatch) self.saveB.clicked.connect(self.saveFile) self.openB.clicked.connect(self.openFile) self.googleB.clicked.connect(self.googlesave) self.settingB.clicked.connect(self.settings) self.focusB.clicked.connect(self.changefocus) self.resettimeB.clicked.connect(self.resettime) self.changefocus() self.updateallui() def autosave(self): if self.autosavestack == 20: self.root.save("./temp") print("Autosave") else: self.autosavestack += 1 def saveFile(self): dia = QFileDialog() filepath = dia.getSaveFileName(self)[0] if filepath != "": try: self.root.save(filepath) except: print("Error") def openFile(self): if len(sys.argv) != 2: dia = QFileDialog() filepath = dia.getOpenFileName(self)[0] if filepath != "": try: self.root.load(filepath) except: print("Error") self.root.start() self.updateallui() def resettime(self): self.root.set_strattime() self.updateallui() def settings(self): dia=SettingsDialog(self.buttonsize[0], self.buttonsize[1], \ self.pointsize, len(self.root.Courts), self.drawdepth) reply = dia.exec_() if reply == 1: dic = dia.data() self.buttonsize = (dic['width'], dic['height']) self.pointsize = dic['font'] self.drawdepth = dic['depth'] self.courtdraw(dic['courtnum']) self.updateallui() def unLockMatch(self): dia = CancelDialog() ret = dia.exec_() target = None if ret == 0: return if ret == 1: try: target = self.root.singlematchdic[dia.value()] except KeyError: target = None if ret == 2: try: target = self.root.doublematchdic[dia.value()] except KeyError: target = None if target is None: toshow = "There is no match {0} in Tournament".format(dia.value()) else: qm = QMessageBox() ret=qm.question(self,"Reset Match Information",\ match_general_info(target)+\ "초기화된 경기는 복구할 수 없습니다!!", qm.Yes | qm.No) if ret == qm.Yes: self.root._unLockMatchRec(target) else: pass self.updateallui() def changefocus(self): if self.root.SingleRoot is None: self.focus_single = False self.focusB.setText("Doubles") self.focusedmatch = self.root.DoubleRoot self.updateallui() elif self.root.DoubleRoot is None: self.focus_single = True self.focusB.setText("Singles") self.focusedmatch = self.root.SingleRoot self.updateallui() elif (self.focus_single): self.focus_single = False self.focusB.setText("Doubles") self.focusedmatch = self.root.DoubleRoot self.updateallui() elif (not self.focus_single): self.focus_single = True self.focusB.setText("Singles") self.focusedmatch = self.root.SingleRoot self.updateallui() def googlesave(self): dia = QInputDialog() if self.URL is not None: url, ok=dia.getText(self, "GoogleDocs Autosave Settings", \ "Google Docs URL", QLineEdit.Normal, self.URL) else: url, ok=dia.getText(self, "GoogleDocs Autosave Settings", \ "Google Docs URL") if ok: try: self.URL = url self.spreadSheetId = self.URL.split("/")[5] self.root.googlesave(self.spreadSheetId) except: print("Error at Googlesave") def updateallui(self): self.root.start() target = None if self.root.SingleRoot is not None: target = self.root.SingleRoot if self.root.DoubleRoot is not None: target = self.root.DoubleRoot if self.focusedmatch is not None: target = self.focusedmatch if target is not None: self.tourdraw(target) self.courtdraw(len(self.root.Courts)) self.update_waitingtable() def test(self): dia = QFileDialog() filepath = dia.getSaveFileName(self)[0] if filepath != "": self.root.save(filepath, option="slim") def tourdraw(self, target): if target is None: return depth = self.drawdepth self.focusedmatch = target #remove all existing tourButtons for x in self.tourbuttons: x.hide() self.tourbuttons = [] #find all target matches to draw udm = self.focusedmatch.undermatches() targets = [] for m in udm: if m.depth() < self.focusedmatch.depth() + depth: targets.append(m) xpos = 0 for mat in targets: #draw every match ypos = mat.depth() - self.focusedmatch.depth() todraw = MatchButton(self.root, mat, size=self.buttonsize, point=self.pointsize) todraw.move(self.tourGrid, ypos, xpos) todraw.show() self.tourbuttons.append(todraw) xpos += 1 #connect functions to tourButtons if mat.depth() == self.focusedmatch.depth(): todraw.linkedMatch=self.root.SingleRoot if self.focus_single\ else self.root.DoubleRoot else: todraw.linkedMatch = mat todraw.button.clicked.connect(todraw.popup) # todraw.button.doubleClicked.connect(lambda : self.tourDraw(todraw.linkedMatch)) if self.focusedmatch.underMatch == []: self.tourdraw(self.focusedmatch.upperMatch) elif self.focusedmatch.underMatch[ 0].underMatch == [] or self.focusedmatch.underMatch[ 1].underMatch == []: self.tourdraw(self.focusedmatch.upperMatch) def courtdraw(self, newcourtnum): for c in self.courtbuttons: c.hide() self.courtbuttons = [] try: self.root.changecourtnum(newcourtnum) except WrongActError as ex: QMessageBox.about(self, "WrongActError", ex) for i in range(len(self.root.Courts)): thisCourt=CourtButton(self.root, self.root.Courts[i],\ self.buttonsize, self.pointsize) self.courtbuttons.append(thisCourt) thisCourt.move(self.courtGrid, i % 2, i // 2) thisCourt.setlabel() self.autosave() def update_waitingtable(self): self.singlewaiting.clear() self.singlewaiting.setColumnCount(5) # waitingArray=waitingmatches(self.root.SingleRoot) self.singlewaiting.setHorizontalHeaderLabels( ["Match Level", "Player1", "player2", "UpperMatch", "MatchNum"]) if self.root is not None and self.root.SingleRoot is not None: waitingArray = self.root.waiting_tableform(single=True) self.singlewaiting.setRowCount(len(waitingArray)) for s in waitingArray: for j in range(5): self.singlewaiting.setItem(waitingArray.index(s), j, \ QTableWidgetItem(s[j])) self.doublewaiting.clear() self.doublewaiting.setColumnCount(5) # waitingArray=waitingmatches(self.root.SingleRoot) self.doublewaiting.setHorizontalHeaderLabels( ["Match Level", "Player1", "player2", "UpperMatch", "MatchNum"]) if self.root is not None and self.root.DoubleRoot is not None: waitingArray = self.root.waiting_tableform(single=False) self.doublewaiting.setRowCount(len(waitingArray)) for s in waitingArray: for j in range(5): self.doublewaiting.setItem(waitingArray.index(s), j, \ QTableWidgetItem(s[j])) self.autosave()
from root import Root import sys from games import Match from filecontrol import google_writeall import random rt = Root() rt.load("./Realtest/test05.tr") rt.start() rt.changecourtnum(14) while True: order = int(input("Enter next order (1 : next result, 2 : court set) : ")) if order == 1: cn = random.randint(0, len(rt.Courts) - 1) tc = rt.Courts[cn] t = 0 while tc.empty(): cn = random.randint(0, len(rt.Courts) - 1) tc = rt.Courts[cn] t += 1 if t == 100: print("No courts are on play") break if tc.game is not None: g = tc.game if max(g.score[0], g.score[1]) == 4: winning = random.randint(0, 10) % 2 g.score[winning] = 6 g.score[(winning + 1) % 2] = random.randint( g.score[(winning + 1) % 2], 7)
class MainWindow(QMainWindow, form_class): def __init__(self, root=None): super().__init__() self.setupUi(self) self.root = Root() if root is None else root self.root.setmainwin(self) """Match Control""" self.focus_single = False self.focusedmatch = None self.URL = None """Design""" self.tourbuttons = [] self.courtbuttons = [] self.buttonsize = (75, 75) self.pointsize = 9 self.drawdepth = 4 self.testB.clicked.connect(self.test) self.saveB.clicked.connect(self.saveFile) self.openB.clicked.connect(self.openFile) self.googleB.clicked.connect(self.googlesave) self.updateallui() def saveFile(self): dia = QFileDialog() filepath = dia.getSaveFileName(self)[0] if filepath != "": try: self.root.save(filepath) except: print("Error") def openFile(self): if len(sys.argv) != 2: dia = QFileDialog() filepath = dia.getOpenFileName(self)[0] if filepath != "": try: self.root.load(filepath) except: print("Error") self.updateallui() def googlesave(self): dia = QInputDialog() if self.URL is not None: url, ok=dia.getText(self, "GoogleDocs Autosave Settings", \ "Google Docs URL", QLineEdit.Normal, self.URL) else: url, ok=dia.getText(self, "GoogleDocs Autosave Settings", \ "Google Docs URL") if ok: self.URL = url self.spreadSheetId = self.URL.split("/")[5] self.root.googlesave(self.spreadSheetId) def updateallui(self): self.root.start() target = None if self.root.SingleRoot is not None: target = self.root.SingleRoot if self.root.DoubleRoot is not None: target = self.root.DoubleRoot if self.focusedmatch is not None: target = self.focusedmatch if target is not None: self.tourdraw(target) self.courtdraw(len(self.root.Courts)) self.update_waitingtable() def test(self): self.focusedmatch = self.root.DoubleRoot if self.focus_single else self.root.SingleRoot self.focus_single = False if self.focus_single else True self.updateallui() if self.courtbuttons == []: self.courtdraw(14) def tourdraw(self, target): if target is None: return depth = self.drawdepth self.focusedmatch = target #remove all existing tourButtons for x in self.tourbuttons: x.hide() self.tourbuttons = [] #find all target matches to draw udm = self.focusedmatch.undermatches() targets = [] for m in udm: if m.depth() < self.focusedmatch.depth() + depth: targets.append(m) xpos = 0 for mat in targets: #draw every match ypos = mat.depth() - self.focusedmatch.depth() todraw = MatchButton(self.root, mat, size=self.buttonsize, point=self.pointsize) todraw.move(self.tourGrid, ypos, xpos) todraw.show() self.tourbuttons.append(todraw) xpos += 1 #connect functions to tourButtons if mat.depth() == self.focusedmatch.depth(): todraw.linkedMatch=self.root.SingleRoot if self.focus_single\ else self.root.DoubleRoot else: todraw.linkedMatch = mat todraw.button.clicked.connect(todraw.popup) # todraw.button.doubleClicked.connect(lambda : self.tourDraw(todraw.linkedMatch)) if self.focusedmatch.underMatch == []: self.tourdraw(self.focusedmatch.upperMatch) elif self.focusedmatch.underMatch[ 0].underMatch == [] or self.focusedmatch.underMatch[ 1].underMatch == []: self.tourdraw(self.focusedmatch.upperMatch) def courtdraw(self, newcourtnum): for c in self.courtbuttons: c.hide() self.courtbuttons = [] try: self.root.changecourtnum(newcourtnum) except WrongActError as ex: QMessageBox.about(self, "WrongActError", ex) for i in range(len(self.root.Courts)): thisCourt=CourtButton(self.root, self.root.Courts[i],\ self.buttonsize, self.pointsize) self.courtbuttons.append(thisCourt) thisCourt.move(self.courtGrid, i % 2, i // 2) thisCourt.setlabel() def update_waitingtable(self): self.singlewaiting.clear() self.singlewaiting.setColumnCount(5) # waitingArray=waitingmatches(self.root.SingleRoot) self.singlewaiting.setHorizontalHeaderLabels( ["Match Level", "Player1", "player2", "UpperMatch", "MatchNum"]) if self.root is not None and self.root.SingleRoot is not None: waitingArray = self.root.waiting_tableform(single=True) self.singlewaiting.setRowCount(len(waitingArray)) for s in waitingArray: for j in range(5): self.singlewaiting.setItem(waitingArray.index(s), j, \ QTableWidgetItem(s[j])) self.doublewaiting.clear() self.doublewaiting.setColumnCount(5) # waitingArray=waitingmatches(self.root.SingleRoot) self.doublewaiting.setHorizontalHeaderLabels( ["Match Level", "Player1", "player2", "UpperMatch", "MatchNum"]) if self.root is not None and self.root.DoubleRoot is not None: waitingArray = self.root.waiting_tableform(single=False) self.doublewaiting.setRowCount(len(waitingArray)) for s in waitingArray: for j in range(5): self.doublewaiting.setItem(waitingArray.index(s), j, \ QTableWidgetItem(s[j]))
def build(self): students, classes = self.get_students() skills, skill_sets = self.get_skills() self.root = Root(students, classes, skills, skill_sets) return self.root
def main(*args): t0 = time() # EXCEL-bol hivva if len(args) == 0: data = ExcelReader.read(Data())[0] ExcelWriter.clear(data) # ECLIPSE-bol hivva elif len(args) == 1: filename = args[0] data, wb = ExcelReader.read(Data(), Root.path() + filename) t1 = time() if len(args)==0: ExcelWriter.excelTime(t1-t0) model = Initialiser.init(data) opt = SolverFactory("asl", executable="xpress") opt.options["logfile"] = Root.resources() + "xpress_log.txt" Tools.Logger(Root.resources() + "xpress_log.txt", model.name) #opt = SolverFactory("gurobi") #opt.options["LogFile"] = Root.resources() + "gurobi_log.txt" t2 = time() if len(args)==0: ExcelWriter.pyomoTime(t2-t1) if Tools.Debug: model.write(Root.resources() + 'problem.lp', io_options={'symbolic_solver_labels':True}) results = opt.solve(model) try: pass except Exception as e: if type(e) == ZeroDivisionError: ExcelWriter.exception("Division by zero: 'alpha' should be < 1.") elif type(e) == Tools.OutOfHedgingPeriodException: ExcelWriter.exception("Empty planning horizon: T should be no more than the number of time periods.") elif type(e) == Tools.EpsilonIsZeroException: ExcelWriter.exception("Unbounded problem: epsilon should not equal 0.") elif type(e) == ApplicationError: ExcelWriter.exception("Unfeasible problem.") traceback.format_exc() # @UndefinedVariable #ExcelWriter.exception("Unhandled exception:", e) return model.solutions.load_from(results) t3 = time() if len(args)==0: ExcelWriter.gurobiTime(t3-t2) if Tools.Debug: print "Excel read: {0:0.3f} seconds".format(t1-t0) print "Model build: {0:0.3f} seconds".format(t2-t1) print "Solve: {0:0.3f} seconds".format(t3-t2) if len(args) == 0: if Tools.Debug: f = open(Root.resources() + "/yxc.txt", 'w') print >>f, results Plotter.plotTotalEnergy(data, model).show() ExcelWriter.write(model, results) elif len(args) == 1: wb.close() return (model, results, data)
def run_process(simulation_datas, parameters, seed): """Runs a process (window) and appends its simulation datas to the list""" root = Root(parameters=parameters, seed=seed) simulation_datas.extend(root.simulation_datas)
from root import Root """ TODO: - experiment with trying to keep big districts more cohesive/clumped/less strung out - stop at best possible - don't stall ui on sleep between draws - add 'precincts' or 'neighborhoods' that represent a certain number of people that vote different ways but are swapped as one person - add incrementer parameter adjuster type - improve favor_tie (allow a not tied district to flip to tie if a tied district flips to not tied) - implement get_district2_weight in District class - better performance by different drawing method (not tkinter.Canvas), maybe website (flask) - district hover information - custom people ratios and grids - line smoothing (spline, make districts look more organic) - multiple parties? make red and blue into other non american colors? """ if __name__ == '__main__': Root()
singles_err=0 doubles_err=0 filename="" path="" """open file""" playersFileName=input("Enter Filename of players : ") while not os.path.exists("./"+playersFileName): if playersFileName=="?": print(os.system("dir")) else: print("Invalid Filename") playersFileName=input("Enter Filename of players : ") read_excel("./"+playersFileName) rt=Root() """Make Singles""" while warnings==True: trial+=1 if trial>MAXTRY: print("Fail To Make Tournament at Singles!!") break print("Try {0:>2d} : ".format(trial), end="") rt.maketour_single() rt._start_single() warnings_single = rt.haveproblem_single (singles_err) singles_err+=1 if warnings_single else 0 warnings=warnings_single
def root(session, server): """Construct a Root List Resource object.""" return Root(session, server.url)
import cherrypy from root import Root ### Definições da aplicação ################## cherrypy.tree.mount(Root(), '/', config="projeto.conf") cherrypy.config.update({ 'server.socket_host': '0.0.0.0', 'server.socket_port': 3127, }) cherrypy.engine.start() cherrypy.engine.block() ##############################################