def report(self): r = Report() r.group_number = self.group r.type_analysis = self.type_analysis r.period = self.period r.session = self.stud_session r.header_table = self.table_header r.body_table = self.result name = "Группа: " + self.group + "/" + self.type_analysis if self.type_analysis == "Средняя оценка по итогам сессии": control = Control() proportional_result: np.ndarray = control.analysis_group_proportional( self.session, self.group, self.stud_session, self.period) r.proportional_result = proportional_result r.name = name list_of_report_object.append(r) list_of_report_name.append(name) msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("Отчет сформирован") msg.setInformativeText('Ваш отчет сформирован.') msg.setWindowTitle("Отчет сформирован") msg.exec_()
def main(argv=None): directory = '' if argv is None: argv = sys.argv try: try: opts, args = getopt.getopt(argv[1:], "hd:v", ["help", "directory="]) except getopt.error, msg: raise Usage(msg) # option processing for option, value in opts: if option == "-v": verbose = True if option in ("-h", "--help"): raise Usage(help_message) if option in ("-d", "--directory"): directory = value from attusage import AttUsage from report import Report, Directory usage = AttUsage() for filename in args: usage.process(filename) directory = Directory(directory) report = Report(usage, directory=directory) for line in report.text(): print line
def createReport(openbadgerDB, csolDB): cur = csolDB.cursor() queryString = ('SELECT ' 'CASE ' ' WHEN gender = "male" THEN "Male" ' ' WHEN gender = "female" THEN "Female" ' ' ELSE "Not Specified" ' 'END AS gender_readable, ' 'COUNT(*) as count ' 'FROM csol.Learners ' 'GROUP BY gender ' 'ORDER BY FIELD(gender_readable, "Female", "Male", "Not Specified");') cur.execute(queryString) report = Report('Learners by Gender', 2) for row in cur.fetchall(): gender = row[0] count = row[1] if gender is None or gender == '': gender = 'Not Specified' report.addRow([gender.title(), count]) return report
def run(self): Report().begin("NativeGen") for cls in SymbolTable().get_classes(): self.gen_class(cls) Report().end()
def test_get_report(make_stubber, stub_runner, error_code, stop_on_method): s3_resource = boto3.resource('s3') s3_stubber = make_stubber(s3_resource.meta.client) rekognition_client = boto3.client('rekognition') rekognition_stubber = make_stubber(rekognition_client) bucket = s3_resource.Bucket('test-bucket') report = Report(bucket, rekognition_client, None) photos = [f'photo-{index}' for index in range(3)] labels = {} for index, photo in enumerate(photos): label = MagicMock(confidence=index, instances=[], parents=[]) label.name = f'label-{index}' labels[photo] = [label] with stub_runner(error_code, stop_on_method) as runner: runner.add(s3_stubber.stub_list_objects, bucket.name, photos) for photo, label in zip(photos, labels): runner.add( rekognition_stubber.stub_detect_labels, {'S3Object': {'Bucket': bucket.name, 'Name': photo}}, None, labels[photo], raise_and_continue=True) got_report, result = report.get() if error_code is None: assert got_report[1:] == [ ','.join((photo, label[0].name, str(label[0].confidence))) for photo, label in labels.items()] assert result == 200 elif stop_on_method == 'stub_list_objects': assert result == 400
def createReport(openbadgerDB, csolDB): cur = csolDB.cursor() queryString = ("SELECT " "CASE " "WHEN age < 13 THEN 'Under 13' " "WHEN age BETWEEN 13 AND 17 THEN '13-17' " "WHEN age BETWEEN 18 AND 24 THEN '18-24' " "WHEN age > 24 THEN 'Over 24' " "END AS age_range, " "COUNT(*) AS count " "FROM (SELECT TIMESTAMPDIFF(YEAR, birthday, CURDATE()) AS age FROM csol.Learners) AS derived " "GROUP BY age_range " "ORDER BY FIELD(age_range, 'Under 13', '13-17', '18-24', 'Over 24'); ") cur.execute(queryString) report = Report('Learners by Age', 2) for row in cur.fetchall(): age = row[0] count = row[1] report.addRow([age, count]) return report
def test_post_report(make_stubber, monkeypatch, error_code): ses_client = boto3.client('ses') ses_stubber = make_stubber(ses_client) report = Report(None, None, ses_client) post_args = { 'sender': 'test-sender', 'recipient': 'test-recipient', 'subject': 'test-subject', 'message': 'test-message', 'analysis_labels': [ f'label{index}-1,label{index}-2,label{index}-3' for index in range(3)]} text_body = f"{post_args['message']}\n\n" + '\n'.join(post_args['analysis_labels']) mock_parser = MagicMock( name='mock_parser', return_value=MagicMock(parse_args=MagicMock( return_value=post_args))) monkeypatch.setattr(reqparse, 'RequestParser', mock_parser) html_body = 'test-html' monkeypatch.setattr('report.render_template', MagicMock(return_value=html_body)) ses_stubber.stub_send_email( post_args['sender'], {'ToAddresses': [post_args['recipient']]}, post_args['subject'], text_body, html_body, 'test-id', error_code=error_code) _, result = report.post() if error_code is None: assert result == 200 else: assert result == 400
def __init__(self): Report.__init__(self, 'OS') self.title = Div( text="DESI Nightly Intake - Observing Scientist", css_classes=['h1-title-style'], width=1000 ) # width=800, style={'font-size':'24pt','font-style':'bold'}) desc = """ To begin, connect to the observing night Night Log using the list of Existing Night Logs. Add information about the Observers and press the Update Tonight's Log. Throughout the night, enter information about the exposures, problems that occur, and observing conditions. Complete the OS Checklist at least once every hour. NOTE: If inputs are being made into a DNI for the OS at both KPNO and NERSC, the inputs made at KPNO for certain things (meta data, plan, milestones), will be prioritized over those made at NERSC. """ self.instructions = Div(text=desc, css_classes=['inst-style'], width=500) self.page_logo = Div(text="<img src='OS_Report/static/logo.png'>", width=350, height=300) self.os_checklist = [ "Did you check the weather?", "Did you check the guiding?", "Did you check the positioner temperatures?", "Did you check the FXC?", "Did you check the Spectrograph Cryostat?", "Did you check the FP Chiller?" ]
def getReportData(self, filters): """ Get data report data """ rep = Report() return rep.getReportData(filters)
def cv(X, y, clf): ''' 交叉验证 Cross-validation :param X: 训练集特征 :param y: 目标label :param clf: 分类器 :return: 交叉验证过程中的最佳模型 ''' model = None max_p = 0 # 记录实验中最好的模型 reporter = Report('train') # 定义评价器 for i in range(1, 10): # 10 logger.info("Folder {}".format(i)) x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=21 + i) if config.DEBUG: logger.info("Train x data: ({}, {}), Train y data: {}".format( len(x_train), len(x_train[0]), Counter(y_train))) logger.info("Test x data: ({}, {}), Test y data: {}".format( len(x_test), len(x_test[0]), Counter(y_test))) clf.fit(x_train, y_train) # 训练过程 predict_proba = clf.predict_proba(x_test) # 返回每个类别的概率值 # TODO 随机 看结果对比submission结果 p = reporter.report_one_folder(y_test, predict_proba, threshold=0.5) if p > max_p: max_p = p logger.info("Max result: {:.4f}".format(p)) model = clf reporter.report_final_result() return model, reporter
def __init__(self): Report.__init__(self, 'DQS') self.title = Div(text="DESI Nightly Intake - Data QA Scientist", css_classes=['h1-title-style'], width=1000) inst = """ The Data Quality Scientist (DQS) is responsible for analyzing all exposures for their quality. Submit problems as they arise throughout the night and complete the DQS checklist once an hour. Let the Lead Observer know if you encounter any issues. """ self.instructions = Div(text=inst, css_classes=['inst-style'], width=500) self.page_logo = Div(text="<img src='DQS_Report/static/logo.png'>", width=350, height=300) self.dqs_checklist = [ "Are all images being transferred to Night Watch?", "Did you check the observing conditions?", "Did you check the guiding?" ] self.quality_list = ['Good', 'Not Sure', 'No Data', 'Bad'] self.quality_btns = RadioButtonGroup(labels=self.quality_list, active=0)
class Worker(Thread): def __init__(self, worker_id, config, frontier): self.logger = get_logger(f"Worker-{worker_id}", "Worker") self.config = config self.frontier = frontier self.report = Report() super().__init__(daemon=True) def run(self): while True: tbd_url = self.frontier.get_tbd_url() report = self.report if not tbd_url: self.logger.info("Frontier is empty. Stopping Crawler.") break resp = download(tbd_url, self.config, self.logger) resp = download(tbd_url, self.config) self.logger.info( f"Downloaded {tbd_url}, status <{resp.status}>, " f"using cache {self.config.cache_server}.") scraped_urls = scraper(tbd_url, resp, report) for scraped_url in scraped_urls: self.frontier.add_url(scraped_url) self.frontier.mark_url_complete(tbd_url) time.sleep(self.config.time_delay) # print the result of report.py here self.report.print()
def run(self, symbol_list=None): if symbol_list == None: symbol_list = [] lines = open(config.TRADABLE_STOCKS, 'r').read().split('\n') for line in lines: if len(line) > 0: symbol_list.append(line) if len(symbol_list) == 0: print 'Symbol list is empty, so nothing is being done' return # --------------------------------------------------------------------- # Read in existing SPY quote file if exists # --------------------------------------------------------------------- if os.path.isfile(DATA_DIR + 'SPY.csv'): print 'read spy.csv' self.spy_df = pd.read_csv(DATA_DIR + 'SPY.csv', index_col=0) if self.spy_df is not None: self.latest_date = self.spy_df.index[-1] else: self.latest_date = None self.update_quotes(symbol_list) self.update_analysis(symbol_list) r = Report() r.report(symbol_list)
def main(*args, **kwargs): """Dovetail compliance test entry!""" build_tag = "daily-master-%s" % str(uuid.uuid1()) dt_cfg.dovetail_config['build_tag'] = build_tag if not get_result_path(): return clean_results_dir() if kwargs['debug']: os.environ['DEBUG'] = 'true' create_logs() logger = dt_logger.Logger('run').getLogger() logger.info('================================================') logger.info('Dovetail compliance: {}!'.format(kwargs['testsuite'])) logger.info('================================================') logger.info('Build tag: {}'.format(dt_cfg.dovetail_config['build_tag'])) parse_cli(logger, **kwargs) env_init(logger) copy_userconfig_files(logger) copy_patch_files(logger) dt_utils.check_docker_version(logger) dt_utils.get_openstack_endpoint(logger) check_hosts_file(logger) dt_utils.get_hardware_info(logger) testcase_list = get_testcase_list(logger, **kwargs) duration = run_test(testcase_list, logger) if (duration != "stop_on_fail"): Report.generate(testcase_list, duration) if (kwargs['report']): Report.save_logs()
def createReport(openbadgerDB, csolDB): badges = openbadgerDB.badges steamBadgeDocuments = openbadgerDB.badges.find( {'categoryAward' : { '$nin': ['', None] } }, fields=['_id']); steamBadges = [] for document in steamBadgeDocuments: steamBadges.append(document['_id']) badgeinstances = openbadgerDB.badgeinstances pipeline = [{'$match' : {'badge' : { '$in' : steamBadges } } }, {'$group' : {'_id' : '$user', 'count' : {'$sum' : 1}}}, {'$group' : {'_id' : '$count', 'count' : {'$sum' : 1}}}] results = badgeinstances.aggregate(pipeline)['result'] report = Report('Learners by STEAM Badges Earned', 2) countList = [0,0,0,0,0] for row in results: countList[row['_id']-1] = row['count'] for i in range(len(countList)): report.addRow([i+1, countList[i]]) return report
class People(QMainWindow): # signalKisiler = pyqtSignal(str) def __init__(self): super(People, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.btnKisiler.clicked.connect(self.clickKisilerAc) self.ui.btnKisiEkle.clicked.connect(self.clickKisiEkleAc) self.ui.btnOgrenciKontrol.clicked.connect(self.clickKapiKontrol) self.ui.btnRaporlar.clicked.connect(self.clickKisiRaporlar) self.ui.btnOnYukleme.clicked.connect(self.clickOnyukleyiciGuncelle) def clickKisilerAc(self): self.people_table_page = PeopleTable() self.people_table_page.show() #Kayıtlı kişileri açan fonksiyon def clickKisiEkleAc(self): self.people_add_page = PeopleAdd() self.people_add_page.show() #Kişi ekleme formunu açan fonksiyon. def clickKapiKontrol(self): self.door_check_page = DoorCheck() self.door_check_page.show() def clickKisiRaporlar(self): self.report_page = Report() self.report_page.show() def clickOnyukleyiciGuncelle(self): self.ui.btnOnYukleme.setEnabled(False) yuzTanima = YuzTanima() yuzTanima.SozlukCsvTumunuYenile(self)
def getIndicadores(self): """ Get data for indicadores MD """ rep = Report() return rep.getIndicadores()
def report(self, start, finish, report_type, report_format, locale=None): if start >= finish: raise errors.StartShouldBeEarlierFinish() if not Report.is_supported(report_type, report_format): raise errors.ReportFormatIsNotSupported() report_cache = ReportCache() report_task = ReportTask() report_id = ReportId(start, finish, report_type, report_format, locale) data = report_cache.get_report(report_id) if data: if report_format == "json": return {"status": "completed", "report": json.loads(data.decode("utf-8"))} filename = Report.generate_file_name(report_type, start, finish, report_format) content_disposition = make_content_disposition(filename, bottle.request.environ.get('HTTP_USER_AGENT')) return bottle.HTTPResponse(body=data, content_type=Report.content_types[report_format], content_disposition=content_disposition) status = report_task.task_status(report_id) if not status: result = report_file_generate.delay(report_id) logbook.info("Created report_file task {} for {}", result.id, report_id) report_task.set(report_id, result.id) status = "started" return {"status": status}
def _attack(self, army, report): if report: rep = Report() else: rep = None selfiter = iter(self) armyiter = iter(army) ours = advance_iter(selfiter) theirs = advance_iter(armyiter) while ours is not None and theirs is not None: if report: rep.start_round(ours, theirs) left1, left2 = ours.fight_with(theirs) if report: rep.end_round(left1, left2) if left1 == 0: ours = advance_iter(selfiter) if left2 == 0: theirs = advance_iter(armyiter) return (self.get_real_len() > army.get_real_len(), rep)
def main(): data = get_data() months, types, accounts = get_all_month_types(data) for month in months: month_transaction = filter_by_date(data, month) report = Report(month, month_transaction, accounts, types) report.print_report()
def console_report(): """Runs a report from the cli.""" args = parser.parse_args() conf = config.load(args.config_file) logger.setLevel(LOG_LEVELS.get(args.log_level.lower(), 'info')) manager = ClientManager(**conf.get('auth_kwargs', {})) ceilometer = manager.get_ceilometer() if args.mtd: start, stop = utils.mtd_range() elif args.today: start, stop = utils.today_range() elif args.last_hour: start, stop = utils.last_hour_range() else: start, stop = utils.mtd_range() r = Report( ceilometer, args.definition_filename, args.csv_filename, start=start, stop=stop ) r.run()
def submitReport(): if request.method == 'POST': reportData = request.get_json() product = reportData['productName'] company = reportData['companyName'] class_ = reportData['class_'] setup = reportData['setup'] data = reportData['dataLocation'] standard = reportData['standard'] equipment = {'SpecA': reportData['specA'], 'LISN': reportData['lisn']} print(reportData['productName']) print(reportData['companyName']) print(reportData['dataLocation']) print(reportData['standard']) print(reportData['setup']) print(reportData['power']) print(reportData['class_']) print(reportData['lisn']) print(reportData['specA']) output = '/Users/jadonbull/Documents/EMC Hub Output/EMC Reports/' + product + '.docx' report = Report(product, company, class_, setup, data, standard, equipment, output, PLCE=PLCE) report.reportOutput() return 'Finished'
def __init__(self): Report.__init__(self, 'OS') self.title = Div(text="DESI Nightly Intake - Operating Scientist", css_classes=['h1-title-style'], width=1000)# width=800, style={'font-size':'24pt','font-style':'bold'}) desc = """ The Operating Scientist (OS) is responsible for initializing the Night Log. Connect to an existing Night Log using the date or initialize tonight's log. Throughout the night, enter information about the exposures, weather, and problems. Complete the OS Checklist at least once every hour. """ self.instructions = Div(text=desc+self.time_note.text, css_classes=['inst-style'], width=500) self.line = Div(text='-----------------------------------------------------------------------------------------------------------------------------', width=1000) self.line2 = Div(text='-----------------------------------------------------------------------------------------------------------------------------', width=1000) self.init_bt = Button(label="Initialize Tonight's Log", css_classes=['init_button']) self.LO = Select(title='Lead Observer', value='Choose One', options=self.lo_names) self.OA = Select(title='Observing Assistant', value='Choose One', options=self.oa_names) self.page_logo = Div(text="<img src='OS_Report/static/logo.png'>", width=350, height=300) self.contributer_list = TextAreaInput(placeholder='Contributer names (include all)', rows=2, cols=3, title='Names of all Contributers') self.contributer_btn = Button(label='Update Contributer List', css_classes=['add_button'], width=300) self.connect_hdr = Div(text="Connect to Existing Night Log", css_classes=['subt-style'], width=800) self.init_hdr = Div(text="Initialize Tonight's Night Log", css_classes=['subt-style'], width=800) self.check_subtitle = Div(text="OS Checklist", css_classes=['subt-style']) self.checklist_inst = Div(text="Every hour, the OS is expected to monitor several things. After completing these tasks, record at what time they were completed. Be honest please!", css_classes=['inst-style'], width=1000) self.checklist.labels = ["Did you check the weather?", "Did you check the guiding?", "Did you check the positioner temperatures?","Did you check the FXC?", "Did you check the Cryostat?", "Did you do a connectivity aliveness check?","Did you check the Spectrograph Chiller?"] self.nl_submit_btn = Button(label='Submit NightLog & Publish Nightsum', width=300, css_classes=['add_button']) self.header_options = ['Startup','Calibration (Arcs/Twilight)','Focus','Observation','Other Acquisition','Comment']
def setUp(self): self.report = Report() self.bank_id = 1 self.bank = Bank(bank_id=self.bank_id) self.USER_ID = 3 self.SECOND_USER_ID = 2 self.PRODUCT_ID = 5 self.PRODUCT_ID_2 = 7
def generate_disturbing(self): self.NIVEL_ATUAL_PERT = random.randint(simconfig.BASE_DISTURBING_LEVEL-simconfig.INTERVAL_DISTURBING_LEVEL, simconfig.BASE_DISTURBING_LEVEL+simconfig.INTERVAL_DISTURBING_LEVEL) intervaloProximaPerturbacao = random.randint(simconfig.BASE_DISTURBING_PERIOD - simconfig.INTERVAL_DISTURBING_PERIOD, simconfig.BASE_DISTURBING_PERIOD + simconfig.INTERVAL_DISTURBING_PERIOD) Report.add_disturbing(str(self.NIVEL_ATUAL_PERT), str(intervaloProximaPerturbacao), self.simpyEnvironment.now) return intervaloProximaPerturbacao
def run(self): Report().begin("Translate") for cls in SymbolTable().get_classes(): Report().report('translate {}'.format(cls), lambda: self.translate(cls)) Report().end() Option().nodes = {}
def console_report(): """Runs a report from the cli.""" args = report_parser.parse_args() conf = config.load(args.config_file) logger.setLevel(LOG_LEVELS.get(args.log_level.lower(), 'info')) manager = ClientManager(**conf.get('auth_kwargs', {})) ceilometer = manager.get_ceilometer() out = output.Stream() if args.use_stdout else None if args.mtd: start, stop = utils.mtd_range() out = out or output.Mtd(args.output_directory, start, stop) elif args.today: start, stop = utils.today_range() out = out or output.Daily(args.output_directory, start, stop) elif args.last_hour: start, stop = utils.last_hour_range() out = out or output.Hourly(args.output_directory, start, stop) # If stop is provided, check for start elif args.stop: if not args.start: raise Exception('Provide --start if also using --stop') start = args.start stop = args.stop out = out or output.Other(args.output_directory, start, stop) # If start is provided, check for stop. If stop not provided, # default to now elif args.start: start = args.start _, now = utils.mtd_range() stop = args.stop or now out = out or output.Other(args.output_directory, start, stop) # Default to month to date else: start, stop = utils.mtd_range() out = out or output.Mtd(args.output_directory, start, stop) try: p_start = time.time() r = Report( ceilometer, args.definition_filename, out, start=start, stop=stop, max_samples=args.max_samples ) r.run() logger.debug("Finished in {} seconds".format(time.time() - p_start)) finally: out.close() if args.show_tags: print tag.all()
def console_report(): """Runs a report from the cli.""" args = report_parser.parse_args() conf = config.load(args.config_file) logger.setLevel(LOG_LEVELS.get(args.log_level.lower(), 'info')) manager = create_client_manager(**conf.get('auth_kwargs', {})) ceilometer = manager.get_ceilometer() out = output.Stream() if args.use_stdout else None if args.mtd: start, stop = utils.mtd_range() out = out or output.Mtd(args.output_directory, start, stop) elif args.today: start, stop = utils.today_range() out = out or output.Daily(args.output_directory, start, stop) elif args.last_hour: start, stop = utils.last_hour_range() out = out or output.Hourly(args.output_directory, start, stop) # If stop is provided, check for start elif args.stop: if not args.start: raise Exception('Provide --start if also using --stop') start = args.start stop = args.stop out = out or output.Other(args.output_directory, start, stop) # If start is provided, check for stop. If stop not provided, # default to now elif args.start: start = args.start _, now = utils.mtd_range() stop = args.stop or now out = out or output.Other(args.output_directory, start, stop) # Default to month to date else: start, stop = utils.mtd_range() out = out or output.Mtd(args.output_directory, start, stop) try: p_start = time.time() r = Report( ceilometer, args.definition_filename, out, start=start, stop=stop, max_samples=args.max_samples ) r.run() logger.debug("Finished in {} seconds".format(time.time() - p_start)) finally: out.close() if args.show_tags: print tag.all()
def stockreport(self): name=os.path.join(FILEPATH,'safety_shoes_stock_report.csv') temp_issue_worker_report=tkFileDialog.asksaveasfilename(defaultextension='.csv',filetypes=[('Excel Files','*.csv')],initialdir='C:\\',initialfile=name,title='Save') if os.path.exists(temp_issue_worker_report): os.remove(temp_issue_worker_report) x=Report('safety_shoes') x.stock_safetyshoes(temp_issue_worker_report) print "finished..." tkMessageBox.showinfo('Notice','The Report saved already!')
def run(self): Report().begin("ControlFlowAnalyse") for cls in SymbolTable().get_classes(): Report().report('analyse {}'.format(cls)) for method in cls.methods + cls.static_methods: self.analyse(method) Report().end()
def DrawShapefile(self, shapelygeoms, projection): Report("loading") geomstofeature = cartopy.feature.ShapelyFeature( geometries=shapelygeoms, crs=projection) Report("drawing") self.ax.add_feature(geomstofeature, facecolor="pink", edgecolor='green') self.ax.figure.canvas.draw()
def run(self): print "run()" dirname = path.dirname(path.abspath(__file__)) if self.tipo == 'txt': relatorio = Report(dirname+'/'+self.name+'.txt') relatorio.addTitle("Porous Structure") img = Image.open(self.img_name) #img = img.convert('L') img = binarizeImage(img) result = analysis(img) img.save('%s_test.jpg'%self.img_name) t_analise = Table(name = "Analise de estruturas porosas") #titulo das colunas da tabela title = [ "Cor do Poro","Area Poro","Comp. Max. Horiz.", "Comp. Max. Vert.","Comp. Max. Medio" ] for name in title: t_analise.addColumnName(name,[]) for path_img in result[0]: t_analise.addColumnValue(title[0], path_img.color) t_analise.addColumnValue(title[1], path_img.area) t_analise.addColumnValue(title[2], path_img.comprimentoHorizontal()) t_analise.addColumnValue(title[3], path_img.comprimentoVertical()) t_analise.addColumnValue(title[4], path_img.comprimentoMedio()) t_analise.legend = "obs.: comprimentos (px, um, mm)" #resultado do intercepto linerar inter = intercepto(img) #Tabela de intercepto linear t_inter = Table(name = "Intercepto Linear") t_inter.addColumnName("Poro Vertical", inter["porous_list_vertical"]) t_inter.addColumnName("Solido Vertical",inter["solid_list_vertical"]) t_inter.addColumnName("Poro Horizontal", inter["porous_list_horizontal"]) t_inter.addColumnName("Solido Horizontal",inter["solid_list_horizontal"]) table_continuo = Table(name = "Continuidade direcional") table_continuo.addColumnName("Vertical",inter["solid_list_vertical"]) table_continuo.addColumnName("Horizontal",inter["solid_list_horizontal"]) relatorio.addTable(t_analise) relatorio.addTable(t_inter) relatorio.addTable(table_continuo) report_output = relatorio.buildInColumns() report_output.close() print "fim report"
def testRegister7(self): print('first test is running...') self.testCase = TestCaseGenerator.generateTestCase( isValidFirstName=False, isValidLastName=False, isValidPhone=False, isValidEmail=False, isValidPassword=False, isValidConfirmedPassword=False, registeredEmail=self.registeredEmail) self.registeredEmail.append(self.testCase['email']) self.automateRegister.driver.get(self.url) HttpInterceptor.intercept(self.url) id = 7 bugName = '' summary = '' expectedResult = '' actualResult = '' try: self.assertIn('Register', self.automateRegister.driver.title) except: self.automateRegister.driver.save_screenshot( 'bugReports/screenshots/test' + str(id) + '.png') bugName = 'Unreachable site' summary = 'Trying to reach https://www.phptravels.net/register but failed' expectedResult = 'page tile should contain register' actualResult = 'page not found (400 HTTP Error)' Report.genrateBugReport(id, bugName, datetime.now(), summary, expectedResult, actualResult) self.automateRegister.driver.close() return for name in self.testCase: self.automateRegister.automateTextField(name, self.testCase[name]) self.automateRegister.automateButtonClick('signupbtn') try: self.assertIn('register', self.automateRegister.driver.current_url) except: self.automateRegister.driver.save_screenshot( 'bugReports/screenshots/test' + str(id) + '.png') bugName = 'Every field is wrong' summary = 'All fields have wrong formats or values at the same time' expectedResult = 'a prompt show that at least one field is in a wrong format' actualResult = 'the next page after registration' Report.genrateBugReport(id, bugName, datetime.now(), summary, expectedResult, actualResult) self.automateRegister.driver.close() return self.automateRegister.driver.close()
def add_worksheet(self, resp_list, building): header = Header(self.city, self.street, building) data = [] for resp in resp_list: for owner in resp.owner_objs: di = DataInstance(resp, owner) data.append(di) Report.add_worksheet(self, header, data, building)
def initialize(self, context): """ Initialize the driver session, this function is called everytime a new instance of the driver is created This is a good place to load and cache the driver configuration, initiate sessions etc. :param InitCommandContext context: the context the command runs on """ self.cs_session = self.start_cloudshell_api() self._start_temeva_session self.temeva_meth = Methodology(self.temeva_session) self.temeva_report = Report(self.temeva_session)
def test_add_row(): report = Report(4) report.add_row(Row("Fred", "Roberts", "MO")) # this is testing using and internal # implementation detail, which ou want to be careful of # but it will catch an error in the add_row, even when # the other methods are not yet written assert report.size() == 1
def __init__(self): Report.__init__(self, 'Other') self.title = Div(text="DESI Nightly Intake Form - Non Observer",css_classes=['h1-title-style'], width=1000) desc = """This Night Log is for Non-Observers. It should mainly be used for observing the ongoing Night Log. In special circumstances, if a non-observer has an important comment about an exposure or problem, it can be added here. Before doing so, make sure to communicate with the Observing Scientist. """ self.instructions = Div(text=desc+self.time_note.text, css_classes=['inst_style'], width=500) self.page_logo = Div(text="<img src='Other_Report/static/logo.png'>", width=350, height=300)
def createReport(openbadgerDB, csolDB): cur = csolDB.cursor() report = Report('Other Data', 2) queryString = ("SELECT COUNT(*) FROM Learners") cur.execute(queryString) learnerCount = cur.fetchone()[0] report.addRow(['Number of Learners', learnerCount]) badgeInstanceCount = openbadgerDB.badgeinstances.count() report.addRow(['Number of Badges Awarded', badgeInstanceCount]) steamBadgeDocuments = openbadgerDB.badges.find( {'categoryAward' : { '$nin': ['', None] } }, fields=['_id']); steamBadges = [] for document in steamBadgeDocuments: steamBadges.append(document['_id']) steamBadgeInstances = openbadgerDB.badgeinstances.aggregate([{'$match' : {'badge' : { '$in' : steamBadges } } }] ) steamBadgeInstanceCount = len(steamBadgeInstances['result']) report.addRow(['Number of STEAM Badges Awarded', steamBadgeInstanceCount]) queryString = ("SELECT COUNT(*) FROM Playlists") cur.execute(queryString) wishlistCount = cur.fetchone()[0] report.addRow(['Number of Badges Wishlisted', wishlistCount]) return report
def generate_reports(self, task_dir='./', no_file=False): for user in self.users: report = Report(str(f'{task_dir}{user["username"]}.txt.tmp')) # готовим содержимое файла в виде списка. if not report.prepare_content(user, self.tasks): continue # если отключен дебажный флаг if not no_file: if not os.path.exists(task_dir): try: os.makedirs(task_dir) except Exception as err: print(f'{err} Report cannot be saved.') break # сохраняем временный файл if not report.write_temp_file(report.file_name): break # валидируем временный файл if report.validate_output_file(report.file_name): # сохраняем изменения, переименовывая старый отчет report.commit() else: print("Report validation error. Changes not accepted.") # удаляем временный файл report.rollback()
def saveReport(self): rep = Report('D:\\Projects\\CC v2\\', 'Application Report - '+str(time.strftime("%B %d, %Y"))+'.docx') rep.addList(self.good_list, "1 - Applications which went through successfully:") rep.addList(self.complex_list, "2 - Applications which did NOT go through, but were close:") rep.addList(self.bad_list, "3 - Applications which cannot be automated:") rep.saveReport()
def post(self): data_dict = request.get_json() report = Report(**data_dict) report.position = [float(s) for s in data_dict["position"]] report.save() url = url_for(".report_detail", id=str(report.id)) response = { "report": report.as_dict(), "url": url } return JsonResponse(response, status=200)
def createReport(openbadgerDB, csolDB): learnersByZip = helper_queries.getLearnersByProperty('zipCode') report = Report('Top Zip Codes with Learners', 2) sortedLearnersByZip = sorted(learnersByZip.iteritems(), key=operator.itemgetter(1), reverse=True) for zip, count in sortedLearnersByZip: report.addRow([zip.title().decode('latin-1'), count]) return report
def createReport(openbadgerDB, csolDB): activeLearnersBySchool = helper_queries.getLearnersByProperty('school', badgeThreshold=1) report = Report('Top Schools with Active Learners', 2) sortedActiveLearnersBySchool = sorted(activeLearnersBySchool.iteritems(), key=operator.itemgetter(1), reverse=True) for school, count in sortedActiveLearnersBySchool: report.addRow([school.title().decode('latin-1'), count]) return report
def report(): conn = Report.get_connection(KeyChain.PG_KEY) index_page = None rpt = Report.factory(conn, dict(request.args)) if not rpt: index_page = render_template('index.html') else: rpt.request_data(conn) conn['cn'].close() return index_page if index_page else render_template(rpt.get_template(), rpt=rpt)
def run(self): Report().begin("RuntimeGen") table = SymbolTable() self.classes = sorted(table.get_classes(), key=lambda c: c.qualified_name) self.packages = sorted(table.get_packages(), key=lambda pkg: pkg.qualified_name) self.gen_global() Report().end()
def calculate_job_cost(disturbind_level, region_size): job_cost = disturbind_level - region_size erlang_cost = random.gammavariate(simconfig.ERLANG_SHAPE, 1) job_cost += int(erlang_cost) if job_cost < 1: job_cost = 1 Report.add_jobs_costs(job_cost, ControlFunctions.simpyEnvironment.now) return job_cost
def main(): report = Report(BEARER_TOKEN, BUDGET_ID, CATEGORY_ID) print('Building report...') message = report.build_report_string() dispatcher = Dispatcher(SENDER_EMAIL_ID, SENDER_EMAIL_PASSWORD, RECIPIENTS) print('Sending report...') print(message) dispatcher.email(REPORT_TITLE, message) print('Report sent to ' + RECIPIENTS)
def build(self, reporter=None): if self.built: return 0 if not self.tool.EMPTY: statistics.targets += 1 if reporter is None: from report import Report reporter = Report() reporter.title(self.pathname) rebuild_target = False rebuild_reason = None builds = 0 for tinput in self.inputs: builds += tinput.build(reporter.sub()) if os.path.islink(self.pathname): link = os.readlink(self.pathname) comake_shortname, comake_outdir, comake_pathname, comake_relname = self.filenames( ) if comake_relname != link: os.unlink(self.pathname) os.symlink(comake_relname, self.pathname) if not os.path.exists(self.pathname): rebuild_target = True rebuild_reason = "target requires creation" else: my_mtime = self.mtime() others_mtime = [tinput.mtime() for tinput in self.inputs] if others_mtime: max_others_mtime = max(others_mtime) if max_others_mtime > my_mtime: rebuild_target = True rebuild_reason = "target is older than dependencies" if not rebuild_target: if builds: rebuild_target = True rebuild_reason = "dependencies were rebuilt" if not rebuild_target: if self.tool.rebuild_needed(self): rebuild_target = True rebuild_reason = "rebuilding required by tool" if rebuild_target: if not self.tool.EMPTY: reporter.print_title() reporter.print_text("Building: %s" % (rebuild_reason, )) self._make(reporter) builds += 1 self.built = True return builds
def cmd_report(args, options): if len(args) != 1: logging.error('Missing bid') return 1 if not options.output: logging.error('Missing --output option') return 1 db = open_db(options) report = Report(db, options) report.buildReport(args[0]) db.close() return 0
def do_load_report(self, filename): report = Report() try: report.initFromFile(filename, self.storages) except Exception as ex: QMessageBox.critical(self, 'Error while loading report', 'Error while loading report: %s' % ex.message); return self.filters = [] for filter in report.filters: self.filters.extend(filter.get_trivial()) self.show_filters()
def scan(language, file_manifest, source_file_names): # Determine the files to scan. If no files are given, use a default manifest. if len(source_file_names) == 0 and file_manifest is None: file_manifest = manifest.default_manifest(language) source_file_names = set(source_file_names) if file_manifest is not None: source_file_names.update(set(manifest.contents(file_manifest))) supplier = ast_suppliers.abstract_syntax_tree_suppliers[language] # TODO: Configuration files! parameters = Parameters() parameters.distance_threshold = supplier.distance_threshold parameters.size_threshold = supplier.size_threshold source_files = [] report = Report(parameters) def parse_file(file_name): try: logging.info('Parsing ' + file_name + '...') source_file = supplier(file_name, parameters) source_file.getTree().propagateCoveredLineNumbers() source_file.getTree().propagateHeight() source_files.append(source_file) report.addFileName(file_name) logging.info('done') except: logging.warn('Can\'t parse "%s" \n: ' % (file_name,) + traceback.format_exc()) for file_name in source_file_names: parse_file(file_name) duplicates = clone_detection_algorithm.findDuplicateCode(source_files, report) n = 1 for duplicate in duplicates: distance = duplicate.calcDistance() summary = CloneSummary( "Clone #"+str(n), [ # TODO: This is a mess! Most of this info should be assembled on the fly and in member functions. Snippet( duplicate[i].getSourceFile()._file_name, duplicate[i].getCoveredLineNumbers(), '\n'.join([line for line in duplicate[i].getSourceLines()]) ) for i in [0, 1]], distance) report.addClone(summary) n += 1 report.sortByCloneSize() save_report(".orphanblack", report)
def executarTrabalho(self): if self.simulationEnvironment.jobs > 0: self.simulationEnvironment.jobs -= 1 self.jobsExecuted += 1 Report.add_jobs_executed_on_nodes(self.identificador) return ControlFunctions.calculate_job_cost(self.simulationEnvironment.NIVEL_ATUAL_PERT, self.simulationEnvironment.region._region_size) else: self.simulationEnvironment.idleLoops += 1 Report.add_idle_cycle() return 1
def createReport(openbadgerDB, csolDB): badgesByZip = helper_queries.getBadgesByProperty('zipCode') learnersByZip = helper_queries.getLearnersByProperty('zipCode') activeLearnersByZip = helper_queries.getLearnersByProperty('zipCode', badgeThreshold=1) report = Report('Statistics by Zip', 4) zips = sorted(learnersByZip.keys()) for zip in zips: report.addRow([zip, badgesByZip[zip], learnersByZip[zip], activeLearnersByZip[zip]]) return report
def createReport(openbadgerDB, csolDB): badgesBySchool = helper_queries.getBadgesByProperty('school') learnersBySchool = helper_queries.getLearnersByProperty('school') activeLearnersBySchool = helper_queries.getLearnersByProperty('school', badgeThreshold=1) report = Report('Statistics by School', 4) schools = sorted(learnersBySchool.keys()) for school in schools: report.addRow([school.title().decode('latin-1'), badgesBySchool[school], learnersBySchool[school], activeLearnersBySchool[school]]) return report
def render_data(self, request): from report import Report, Paragraph, Spacer, Table from django.http import HttpResponseRedirect from mysite.urls import tmpDir, tmp_url cells=[cell_format(a) for a in self.cells] rn=request.REQUEST.get("reportname",'') title=rn and rn or self.title if self.head=="": heads=[k for k in self.data[0].keys()] else: heads=self.head file_name=u"%s_%s.pdf"%(title, datetime.datetime.now().strftime("%Y%m%d%H%M%S")) filecode=request.REQUEST.get("fielcode",'gb18030') whs=colwidths = [len(i.encode(filecode)) for i in heads] wcells=[[len(item.encode("gb18030")) for item in line] for line in cells[:40]] wcells.insert(0, whs) chars_cnt=sum(wcs) page_size=get_page_size(chars_cnt) p=Report() p.set_page_size(page_size[1], page_size[2]) allws=min(6, max(3.7, 2.85*(p.width-23)/chars_cnt)) #计算每个字符的最大可能宽度 page_head=(Paragraph(title, p.style_title), ) grid_head=[Paragraph(col_text, p.style_grid_head) for col_text in heads] p.colwidths=[(allws*item or 20) for item in wcs] p.grid_head_height=20 p.row_height=15 p.print_report(cells, page_size[3], grid_head, page_head, file_name=u"%s/%s"%(tmpDir(), file_name)) f="/"+tmp_url()+file_name return HttpResponseRedirect(f.encode("utf-8"))
def run_report(self): Logger.debug('%s named %s with frequency %i' % (self.__class__.__name__, self.__name, int(self.__config["frequency"]))) Report.info('%s=%s %s="%s" %s %s' % ("checktype", self.__class__.__name__, "checkname", self.__name, " ".join(['%s=%s ' % (key, value) for (key, value) in self.__report.items()]), self.__group)) if self.__content != None: Report.info('%s=%s %s="%s" type=content %s\n%s' % ("checktype", self.__class__.__name__, "checkname", self.__name, self.__group, self.__content))
def run_report(self): status = {True: "succeed", False: "failed"}[self.__status is True] header = 'checktype=%s checkname="%s" checkstatus=%s' % ( \ self.__class__.__name__, self.__name, status) Logger.debug('%s named %s with frequency %i' % (self.__class__.__name__, self.__name, int(self.__config["frequency"]))) Logger.debug("Header %s" % header) Report.info( '%s group=%s environment=%s %s %s' % ( header, self.__config["group"], self.__config["environment"], "".join(['%s=%s ' % (key, value) \ for (key, value) in self.__report.items()]), self.__content))
def tunning(self): idleLoops = self.simulationEnvironment.idleLoops; if self.lastCountIdleLoops is not None: controlledVariable = idleLoops - self.lastCountIdleLoops actuation_value = self.update(controlledVariable) self.simulationEnvironment.region.increment_region_size(actuation_value) Report.add_actuation(actuation_value, controlledVariable, self.simpyEnvironment.now) self.lastCountIdleLoops = idleLoops return simconfig.CONTROLLER_FREQUENCY
def main(): # Where is our base folder (the one containing the auto_form.py file)? global base_dir base_dir = os.path.normpath(os.path.dirname(os.path.realpath(sys.argv[0]))) # Parsing arguments if len(sys.argv) > 2: print "Too many arguments" return elif len(sys.argv) == 2: if sys.argv[1] == "--setup-cron": setup_cron() return elif sys.arg[1] != "--run": print "invalid option: %s" % sys.argv[0] return # We are good to go! entities = import_entities() #entities = {"285000001": "Gobernacion"} current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M") if len(entities) == 0: print "%s:: No entities found. Are you sure the file is there?" % current_time elif len(entities) < 10: print "%s:: Will run against those entities %s" % (current_time,entities) else: print "%s:: Will run against %d entities" % (current_time,len(entities)) total = 0; report = Report(os.path.join(base_dir,REPORTS_FOLDER)) for entity_id, entity_name in entities.iteritems(): print "\n***** Entity %s (%s) *****" % (entity_name, entity_id) new_processes = do_one(entity_id) if len(new_processes) > 0: report.append(entity_id, entity_name, new_processes) total += len(new_processes) # Notify the result notif = None if report.created: text_body = "Hay %d nuevos contratos disponibles.\nAdjunto el reporte." % total notif = Notification(text_body, report.file_path); else: notif = Notification("No hay nada nuevo hoy.", None); notif.send() # Display summary print "\n" print "#############################################################" print "# Summary" print "# We found %d new processes" % total print "# Report avail. at %s" % report.file_path print "#############################################################"
def createReport(openbadgerDB, csolDB): cur = csolDB.cursor() queryString = ("SELECT DISTINCT cpsStudentId FROM Learners " "ORDER BY cpsStudentId ASC ") cur.execute(queryString) report = Report('Student IDs', 1) for row in cur.fetchall(): id = row[0] if id != '': report.addRow([id]) return report