def on_set_template_clicked(self): # Create the specified template ## @var selected_filter # String value. Indicates the filter type selected for the template self.selected_filter = self.filterTypeComboBox.currentText() ## @var template # Template insatance with the specified parameters. self.template = Template(self.selected_filter, omega_p1=self.passBand1DoubleSpinBox.value(), omega_s1=self.stopBand1DoubleSpinBox.value(), omega_p2=self.passBand2DoubleSpinBox.value(), omega_s2=self.stopBand2DoubleSpinBox.value(), att_p=self.maxAttnDoubleSpinBox.value(), att_s=self.minAttnDoubleSpinBox.value(), final=True) # remove all plots widgets. in plotLayout self.clear_plot_layout() # plot template in specified axes self.template_axes = self.template_fig.add_subplot(211) self.template_axes_norm = self.template_fig.add_subplot(212) self.template.plot_template_in_axes(self.template_axes, self.template_axes_norm) # add template_canas to plotLayout self.plotsLayout.addWidget(self.template_canvas) # show template_canvas self.template_canvas.show() # redraw template_canvas self.template_canvas.draw() # set template submitted to True self.template_submited = True self.validate_approximation() pass
def __init__(self): self.templates = [] self.extra_templates = [] self.category_nums = {} os.chdir('Template') #for e in glob.glob('*.txt'): for e in TemplateFileNames: cnt_e = 0 file = open(e + ".txt") for line in file: if line != '\n' and not Utl.startswith(line, '%%%%%'): t = Template(line) t.category = e cnt_e += 1 if t.extra: self.extra_templates.append(t) else: self.templates.append(t) self.category_nums[e] = cnt_e file.close() self.templates.sort( key=lambda x: x.num_match * 100 + x.num_restriction, reverse=True) os.chdir('..') pass # __init__
def validate_template(self): selected_filter = self.filterTypeComboBox.currentText() template = Template(selected_filter, omega_p1=self.passBand1DoubleSpinBox.value(), omega_s1=self.stopBand1DoubleSpinBox.value(), omega_p2=self.passBand2DoubleSpinBox.value(), omega_s2=self.stopBand2DoubleSpinBox.value(), att_p=self.maxAttnDoubleSpinBox.value(), att_s=self.minAttnDoubleSpinBox.value(), final=False) valid = template.is_valid() self.setTemplateButton.setEnabled(valid)
def __init__(self): self.mth = datetime.now().month self.sheetName = 'interface1' self.path = '' self.pres = Template() # pres.getDataWithTemplateOrder(templateWorkSheet, self.repos) #self.google_cres="E:/downloads/JaneProject-f472d80e0028.json" self.google_cres = "E:/downloads/JaneProject-f472d80e0028.json" self.google = False self.fileName = 'entityConfig.xlsx' #self.fileName='/Users/pengwang/Downloads/entityConfig.xlsx' self.googleFile = 'entityConfig' #self.outputFile='/Users/pengwang/Downloads/output.xlsx' self.outputFile = 'output.xlsx'
def automatic_cut_button(self, event): Template.template_match() ''' 读入模版匹配后的图,消除之前的图,展示模版匹配的图 ''' image = wx.Image('picture\\match.png') image_bitmap = image.ConvertToBitmap() self.choose_image_bitmap.Destroy() self.automatic_cut_bitmap = wx.StaticBitmap( self, -1, image_bitmap, pos=(100, 0), size=(image_bitmap.GetWidth(), image_bitmap.GetHeight()))
def extractInfo(inTextFile): stories = [] story_objects = [] with open(inTextFile) as inputFile: text = "" for line in inputFile: p = re.match('^((DEV-MUC3|TST1-MUC3|TST2-MUC4)-[0-9]{4})', line) if p: if len(text) != 0: stories.append(text) text = "" obj = Template(p.group(), '-', '-', '-', '-', '-', '-') story_objects.append(obj) else: text += line.replace('\n', ' ').replace('\r', '') if len(text) != 0: stories.append(text) for i in range(len(stories)): findIncident(stories[i], story_objects[i]) test = findWeapon(stories[i], story_objects[i]) FindTarget(stories[i], story_objects[i]) FindVictim(stories[i], story_objects[i]) FindPerp(stories[i], story_objects[i]) FindOrg(stories[i], story_objects[i]) return story_objects
def readFile(self, filename): template = configparser.ConfigParser() template.optionxform = lambda option: option template.read(self.path + filename) template.sections() # Control set value if not 'MAIN' in template: return 0 if not 'FIELDS' in template: return 0 if not template['MAIN'].getboolean('Enable'): return 0 templateName = template['MAIN']['TemplateName'] tableName = template['MAIN']['TableName'] fmt = [] fields = template['FIELDS'] for name in fields: fmt.append(AttrObject(fields[name], name, None)) self.logger.info("INIT Template " + templateName) return Template(templateName, tableName, fmt)
def list_comments(self, query, *args): with Repository(db_file, table_name) as repository: comments_tuple = repository.find_all() comments = [ Comment(item[0], item[1], item[2]) for item in comments_tuple ] return Template.render('comments.tpl', {"comments": comments})
def loadSkarphedChildren(self): self.loadPublicKey() self.getMaintenanceMode() self.loadRendermode() if 'skarphed.users.view' in self.serverRights: self.users = Users(self) self.addChild(self.users) if 'skarphed.modules.install' in self.serverRights or 'skarphed.modules.uninstall' in self.serverRights: self.modules = Modules(self) self.addChild(self.modules) if 'skarphed.roles.view' in self.serverRights: self.roles = Roles(self) self.addChild(self.roles) if True: #'skarphed.sites.view' in self.serverRights self.sites = Sites(self) self.addChild(self.sites) if True: self.views = Views(self) self.addChild(self.views) if True: #'skarphed.template.modify' in self.serverRights self.template = Template(self) self.addChild(self.template) if True: #'skarphed.operation.modify' in self.serverRights self.operationManager = OperationManager(self) #TODO: restliche implementieren self.pokethread = PokeThread(self) self.pokethread.start()
class PageEmpty(Container): """ Widget for minimalistic web pages. Simplified variant with less arguments, but otherwise similar to Page. Arguments: headers: list of entries for the <head> section. Example: page = CTK.PageEmpty () page += CTK.RawHTML ('<p>Nothing to see here.</p>') return page.Render() """ def __init__(self, headers=[], **kwargs): Container.__init__(self, **kwargs) self.headers = headers[:] self.template = Template(content=PAGE_TEMPLATE_MINI) def Render(self): # Get the content render render = Container.Render(self) # Build the <head> text self.headers += render.headers head = "\n".join(uniq(self.headers)) self.template['head'] = head self.template['body'] = render.html # Render txt = self.template.Render() return Postprocess(txt)
def __init__(self, template=None, headers=None, helps=None, **kwargs): Container.__init__(self, **kwargs) self.js_header_end = True if headers: self._headers = HEADERS[:] + headers[:] else: self._headers = HEADERS[:] if template: self._template = template else: self._template = Template(content=PAGE_TEMPLATE_DEFAULT) self._helps = [] for entry in helps or []: self._helps.append(HelpEntry(entry[1], entry[0]))
def renderTemplate(template_path, template_parameters, result_path): """ Renders template with given data. template_path - Path to template .odt file; template_parameters - Parsed data to fill the template; result_path - Path to result .odt file Term "render" means creating new document by filling template with data. Function perfoms following steps: 1) Extract content of template to temporary directory; 2) Render file styles.xml; 3) Render file content.xml; 4) Copy used pictures to "Pictures" directory; 5) Remove unused pictures from "Pictures" directory; 6) Update "META-INF/manifest.xml" with new pictures; 7) Pack temporary directory to result_path. """ temp_dir = basefilename(result_path) extractAll(template_path, temp_dir) styles_xml_path = os.path.join(temp_dir, 'styles.xml') styles_xml = open(styles_xml_path, 'r').read() t = Template(styles_xml, template_parameters) rendered_styles_xml = t.render() codecs.open(styles_xml_path, 'w', 'utf-8').write(rendered_styles_xml) content_xml_path = os.path.join(temp_dir, 'content.xml') content_xml = open(content_xml_path, 'r').read() t = Template(content_xml, template_parameters) rendered_content_xml = t.render() codecs.open(content_xml_path, 'w', 'utf-8').write(rendered_content_xml) image_replacements = t.imageUrls() for key in image_replacements.iterkeys(): value = image_replacements[key] for flow_chart_path in value: dest_path = os.path.join(temp_dir, 'Pictures', os.path.basename(flow_chart_path)) shutil.copy2(flow_chart_path, dest_path) replaceManifest(temp_dir, image_replacements) cleanPictures(temp_dir, image_replacements.keys()) packAll(temp_dir, result_path) if os.path.exists('Pictures'): shutil.rmtree('Pictures') if os.path.exists(temp_dir): shutil.rmtree(temp_dir)
def load_template(file_path, chain_name='A'): """*load_template(file_path, chain_name='A')* Loads a template structure from a PDB file. Produces a Template object that can be saved in a variable. Each template in ModeRNA has only one chain. By default, the chain with id 'A' is loaded. Another chain id can be specified optionally :Arguments: * path+filename of a PDB structure file * chain id (by default 'A') """ file_path = validate_filename(file_path) t = Template(file_path, 'file', chain_name) log.write_message('Template loaded from %s.\nTemplate sequence:\n%s\n' % (file_path, t.get_sequence().seq_with_modifications)) return t
def add_missing_3p(self): """ """ if self.alignment and len(self.recipe.add_fragment_3p)>0: anchor5 = [r for r in self][-1] ap_list = self.recipe.add_fragment_3p[0] seq = Sequence(''.join([ap.target_letter.short_abbrev for ap in ap_list])) all_resis = [r for r in Template(SINGLE_STRAND,'file', 'A')] while len(all_resis)-1 <len(ap_list): all_resis=self._elongate_strand(all_resis) frag_resis = all_resis[:len(ap_list)+1] struc = ModernaStructure('residues',frag_resis) frag = ModernaFragment5(struc, anchor5=anchor5, new_sequence=seq, keep=keep_first) self.insert_fragment(frag)
class PageEmpty (Container): def __init__ (self, headers=[], **kwargs): Container.__init__ (self, **kwargs) self.headers = headers[:] self.template = Template (content = PAGE_TEMPLATE_MINI) def Render(self): # Get the content render render = Container.Render(self) # Build the <head> text self.headers += render.headers head = "\n".join (uniq(self.headers)) self.template['head'] = head self.template['body'] = render.html # Render txt = self.template.Render() return Postprocess (txt)
def __init__(self, the_packet_area, iserver): Gtk.Box.__init__(self, spacing=10, orientation=Gtk.Orientation.VERTICAL) self.set_homogeneous(False) # components of the MessageTypeArea self.msgtype_view = MessageType(iserver, the_packet_area) self.dependency_view = Dependency(iserver, the_packet_area) self.page_num = 0 title = Gtk.Label() title.set_markup("<u><b><big> Message Type Area </big></b></u>") title.set_xalign(0.05) self.pack_start(title, True, True, 0) notebook = Gtk.Notebook() notebook.connect("switch_page", self.update_page) pages = [('New/Modify', self.msgtype_view), ('Dependency', self.dependency_view), ('Template', Template()), ('Equivalency', Equivalency()), ('Generation', Generation())] self.append_pages(notebook, pages) self.pack_start(notebook, True, True, 0)
def process_word(self, tree_id: int, this_word_ind: int, root_id: int): # если слова закончились if this_word_ind == len(self.word_sequence.seq_basic): return # первое слово пропускаем if this_word_ind == 0: this_word_ind += 1 tree = self.tree_versions[tree_id] word_basic = self.word_sequence.seq_basic[this_word_ind] word = self.word_sequence.seq_normal[this_word_ind] prev_word_basic = self.word_sequence.seq_basic[this_word_ind - 1] template_info_arr = get_template_info_by_word(word_basic, prev_word=prev_word_basic) # print(word + ' -> ' + word_basic + ':', str(len(template_info_arr)), 'options') for template_info in template_info_arr: # если это второе слово, у корня шаблончика color=1, name=root_name, если нужно if this_word_ind == 1: template_info['relatives'][0][1] = self.word_sequence.seq_normal[0] template_info['relatives'][0][2] = 1 # если это последнее слово, у целевого слова в шаблончике color=1 if this_word_ind == len(self.word_sequence.seq_basic) - 1: template_info['relatives'][len(template_info['relatives']) - 1][2] = 1 # добавляем остальные варианты for template_info in template_info_arr[1:]: new_tree = TreeVersion(id=len(self.tree_versions)) new_tree.relatives = copy.deepcopy(tree.relatives) template = Template(template_info, word) new_tree.add_template(template, root_id) new_root_id = template.get_target_word_id() self.tree_versions.append(new_tree) self.process_word(new_tree.id, this_word_ind + 1, new_root_id) # добавляем первый вариант шаблончика template = Template(template_info_arr[0], word) tree.add_template(template, root_id) new_root_id = template.get_target_word_id() self.process_word(tree_id, this_word_ind + 1, new_root_id)
def render(self, path, context, out): liteCode = self.load(path,out); template = Template(liteCode); template.render(context,out);
args = vars(ap.parse_args()) ##################################################################################### input_image_path = args["input_image"] template_directory = args["template_directory"] output_directory = args["output_directory"] non_max_suppression_threshold = args["NMS_Threshold"] match_threshold = args["match_threshold"] colors = get_color_codes() templates = [] label = 1 for template_image in glob(template_directory + "/*.png"): templates.append( Template(image_path=template_image, label=label, color=colors[label - 1], match_threshold=match_threshold)) label += 1 input_image = cv2.imread(input_image_path) ######################################################################## detection = predict(templates, input_image) filtered_detection = get_filtered_detection( detections=detection, non_max_suppression_threshold=non_max_suppression_threshold) cv2.imwrite(output_directory + "/image_with_detection.png", plot_detection(input_image.copy(), filtered_detection)) print("Output Image saved to ", output_directory)
class FilterTool(QtWidgets.QMainWindow, FilterToolDesign.Ui_MainWindow): def __init__(self, parent=None): super(FilterTool, self).__init__(parent) self.setupUi(self) # configure to use latex interpreter if find_executable('latex'): mpl.rc('font', **{'family': 'serif', 'serif': ['Palatino']}) mpl.rc('text', usetex=True) # array containing approximation types self.approx_types = [ 'butterworth', 'bessel', 'cheby_1', 'cheby_2', 'legendre', 'gauss', 'cauer' ] # connect 'preview approximation' button to handler self.previewApproxButton.clicked.connect(self.on_preview_clicked) # connect clear approximation button to handler self.clearApproxButton.clicked.connect(self.on_clear_previews_clicked) # connect approximation type combo box to handler self.approximationComboBox.currentIndexChanged.connect( self.validate_approximation) # connect 'Compute' button to handler. self.computePushButton.clicked.connect(self.on_compute_clicked) # connect 'Set Template' button to handler self.setTemplateButton.clicked.connect(self.on_set_template_clicked) # connect filter type combo box selection changed to handler self.filterTypeComboBox.currentIndexChanged.connect( self.on_filter_type_changed) # connect spinboxes valueChanged to handlers self.minAttnDoubleSpinBox.valueChanged.connect(self.validate_template) self.maxAttnDoubleSpinBox.valueChanged.connect(self.validate_template) self.passBand1DoubleSpinBox.valueChanged.connect( self.validate_template) self.passBand2DoubleSpinBox.valueChanged.connect( self.validate_template) self.stopBand1DoubleSpinBox.valueChanged.connect( self.validate_template) self.stopBand2DoubleSpinBox.valueChanged.connect( self.validate_template) # connect approximation input config parameters widgets to handler self.approximationComboBox.currentIndexChanged.connect( self.validate_approximation) self.minMaxRadioButton.clicked.connect(self.validate_approximation) self.minOrderSpinBox.valueChanged.connect(self.validate_approximation) self.maxOrderSpinBox.valueChanged.connect(self.validate_approximation) self.maxQRadioButton.clicked.connect(self.validate_approximation) self.maxQdoubleSpinBox.valueChanged.connect( self.validate_approximation) self.customOrderRadioButton.clicked.connect( self.validate_approximation) self.customOrderSpinBox.valueChanged.connect( self.validate_approximation) # connect plot settings to handlers self.attenuationCurvesCheckBox.clicked.connect( self.validate_approximation) self.phaseCheckBox.clicked.connect(self.validate_approximation) self.groupDelayCheckBox.clicked.connect(self.validate_approximation) self.stepResponseCheckBox.clicked.connect(self.validate_approximation) self.sPlaneCheckBox.clicked.connect(self.validate_approximation) self.freqResponseCheckBox.clicked.connect(self.validate_approximation) # connect current approximation in stages page changed self.current_approx_comboBox.currentIndexChanged.connect( self.on_current_approx_changed) # connect stage plot type to handler self.stage_plot_comboBox.currentIndexChanged.connect( self.on_current_stage_plot_type_changed) # connect current stage combobox to handler self.current_stage_comboBox.currentIndexChanged.connect( self.on_current_stage_changed) # connect appoximation selected pole changed self.poles_listWidget.currentItemChanged.connect( self.on_selected_approx_pole_changed) # connect approximation slected zero changed self.zeros_listWidget.currentItemChanged.connect( self.on_selected_approx_zero_changed) # connect remove pole from stage button to handler self.remove_poleButton.clicked.connect(self.on_remove_stage_pole) # connect remove zero from stage button to handler self.remove_zeroButton.clicked.connect(self.on_remove_stage_zero) # connect add pole to stage to handler self.add_poleButton.clicked.connect(self.on_add_pole) # connect add zero to stage to handler self.add_zeroButton.clicked.connect(self.on_add_zero) # connect stage gain spin box to handler self.gain_spinBox.valueChanged.connect(self.on_stage_gain_changed) # connect remove stage button to handler self.delete_stageButton.clicked.connect(self.on_remove_stage) # hide stopband2 & passband2 widgets self.hide_pass_stop_2() # validate template parameters self.validate_template() # set template_submited to False ## @var template_submited # Bool variable indicatign whether the template has been submitted self.template_submited = False # validate approximation settings self.validate_approximation() ## @var validation_computed # Bool variable indicating whether the approximation has been computed self.validation_computed = False # Disable save pushbutton self.saveResultsPushButton.setEnabled(False) # setup figures and canvases self.set_mpl() # array containing every preview ploted self.plotted_previews = [] # initialize plot options self.any_plots_checked() ## @var current_stage # vriable containing the current selected stage in stages tab self.current_stage = None # indica si alguna vez se ploteo esto self.att_plotted = False self.phase_plotted = False self.step_plotted = False self.s_plane_plotted = False self.freq_response_plotted = False self.group_delay_plotted = False self.preview_already_plotted = False self.currentApproximation = None self.approximations = [] self.zerosGroupBoxes = [] self.polesGroupBoxes = [] self.stages = [] self.mainStageFigure = None ## Helper to hide unused GUI widgets. # Hides unused frequency input fields when 'Low-pass' or 'High-pass' # @details filter type is selected. # @param self The object pointer def hide_pass_stop_2(self): self.stopBand2_label.hide() self.stopBand2DoubleSpinBox.hide() self.passBand2_label.hide() self.passBand2DoubleSpinBox.hide() ## Helper to show hided GUI widgets # @details Shows hided frequency input fields when needed. # @param self The object pointer def show_pass_stop_2(self): self.stopBand2_label.show() self.stopBand2DoubleSpinBox.show() self.passBand2_label.show() self.passBand2DoubleSpinBox.show() ## Helper to instantiate figures and canvas # @details Instantiates every figure and canvas to be used by de program # @param self The object pointer def set_mpl(self): self.template_fig = Figure() self.template_canvas = FigureCanvas(self.template_fig) self.att_fig = Figure() self.att_canvas = FigureCanvas(self.att_fig) self.phase_fig = Figure() self.phase_canvas = FigureCanvas(self.phase_fig) self.group_fig = Figure() self.group_canvas = FigureCanvas(self.group_fig) self.step_fig = Figure() self.step_canvas = FigureCanvas(self.step_fig) self.s_plane_fig = Figure() self.s_plane_canvas = FigureCanvas(self.s_plane_fig) self.freq_fig = Figure() self.freq_canvas = FigureCanvas(self.freq_fig) self.composition_figure = Figure() self.composition_canvas = FigureCanvas(self.composition_figure) self.stage_figure = Figure() self.stage_canvas = FigureCanvas(self.stage_figure) self.stage_layout.addWidget(self.stage_canvas) self.template_toolbar = NavigationToolbar(self.template_canvas, self) self.plotsLayout.addWidget(self.template_canvas) self.plotsLayout.addWidget(self.template_toolbar) ## Handles a filter type combo box index change. # @details Executes whenever the selected index in filter type combo box changes. # @param self The object pointer def on_filter_type_changed(self): self.validate_template() selectedText = self.filterTypeComboBox.currentText() if selectedText == 'Low-pass': self.hide_pass_stop_2() if selectedText == 'High-pass': self.hide_pass_stop_2() if selectedText == 'Band-pass': self.show_pass_stop_2() if selectedText == 'Band-reject': self.show_pass_stop_2() return ## Handler that validates a new template parameter setting. # @details Whenever a template parameter is changed, the new configuration is # validated to determine if the user can submit it. # @param self The object pointer def validate_template(self): selected_filter = self.filterTypeComboBox.currentText() template = Template(selected_filter, omega_p1=self.passBand1DoubleSpinBox.value(), omega_s1=self.stopBand1DoubleSpinBox.value(), omega_p2=self.passBand2DoubleSpinBox.value(), omega_s2=self.stopBand2DoubleSpinBox.value(), att_p=self.maxAttnDoubleSpinBox.value(), att_s=self.minAttnDoubleSpinBox.value(), final=False) valid = template.is_valid() self.setTemplateButton.setEnabled(valid) ## Helper to clear all figures # @details Deletes every canvas contained in the plotslayout # @param self The object pointer def clear_plot_layout(self): for i in reversed(range(self.plotsLayout.count())): if isinstance(self.plotsLayout.itemAt(i), FigureCanvas): self.plotsLayout.itemAt(i).widget().figure.clf() self.plotsLayout.itemAt(i).widget().draw() self.plotsLayout.itemAt(i).widget().setParent(None) ## Set template handler # @details Executes when a new template is submitted (previously validated) # and plots it to the specified axes. # @param self The object pointer def on_set_template_clicked(self): # Create the specified template ## @var selected_filter # String value. Indicates the filter type selected for the template self.selected_filter = self.filterTypeComboBox.currentText() ## @var template # Template insatance with the specified parameters. self.template = Template(self.selected_filter, omega_p1=self.passBand1DoubleSpinBox.value(), omega_s1=self.stopBand1DoubleSpinBox.value(), omega_p2=self.passBand2DoubleSpinBox.value(), omega_s2=self.stopBand2DoubleSpinBox.value(), att_p=self.maxAttnDoubleSpinBox.value(), att_s=self.minAttnDoubleSpinBox.value(), final=True) # remove all plots widgets. in plotLayout self.clear_plot_layout() # plot template in specified axes self.template_axes = self.template_fig.add_subplot(211) self.template_axes_norm = self.template_fig.add_subplot(212) self.template.plot_template_in_axes(self.template_axes, self.template_axes_norm) # add template_canas to plotLayout self.plotsLayout.addWidget(self.template_canvas) # show template_canvas self.template_canvas.show() # redraw template_canvas self.template_canvas.draw() # set template submitted to True self.template_submited = True self.validate_approximation() pass ## Validates the approximation settings # @details Verifies if the approximation settings are valid and whether a template is # submitted. # @param self The object pointer # @return A boolean value. True if approximation is ready to compute. False otherwise def validate_approximation(self): valid = False approx_index = self.approximationComboBox.currentIndex() self.approx_type = self.approx_types[approx_index] if approx_index == 4 or approx_index == 5: # Bessel, Legendre y Gauss self.minMaxRadioButton.setEnabled(False) else: self.minMaxRadioButton.setEnabled(True) if self.customOrderRadioButton.isChecked(): self.restriction = 'custom_order' valid = self.customOrderSpinBox.value() > 0 elif self.maxQRadioButton.isChecked(): self.restriction = 'max_q' valid = self.maxQdoubleSpinBox.value() > 0 elif self.minMaxRadioButton.isChecked(): self.restriction = 'min_max_order' valid = self.minOrderSpinBox.value() < self.maxOrderSpinBox.value() valid = valid and self.minOrderSpinBox.value() > 0 valid = valid and self.maxOrderSpinBox.value() > 0 else: valid = False can_compute = valid and self.any_plots_checked() self.computePushButton.setEnabled(can_compute and self.template_submited) self.previewApproxButton.setEnabled(valid and self.template_submited) ## Checks if any plot option selected # @details Verifies if any of the plots option check-boxes is checked # @param self The object pointer # @return A boolean value. True if any check-box checked. False otherwise def any_plots_checked(self): ret = False ## @var plot_attenuation # Boolean variable that indicates whether the attenuation curve ust be plotted self.plot_attenuation = self.attenuationCurvesCheckBox.isChecked() ## @var plot_phase # Boolean variable that indicates whether the phase response must be plotted self.plot_phase = self.phaseCheckBox.isChecked() ## @var plot_group_delay # Boolean variable that indicates whether the group delay must be plotted self.plot_group_delay = self.groupDelayCheckBox.isChecked() ## @var plot_step_response # Boolean variable that indicates whether the step response must be plotted self.plot_step_response = self.stepResponseCheckBox.isChecked() ## @var plot_s_plane # Boolean variable that indicates whether the S plane must be plotted self.plot_s_plane = self.sPlaneCheckBox.isChecked() ## @var plot_freq_resp # Boolean varialbe that indicates whether the frequency response must be plotted self.plot_freq_resp = self.freqResponseCheckBox.isChecked() ret = self.plot_attenuation or self.plot_phase or self.plot_group_delay or self.plot_step_response or self.plot_s_plane or self.plot_freq_resp return ret ## Active approx selection changed handler # @details Handles the selection of a different active approximation # in the stages tab. def on_current_approx_changed(self): selection = str(self.current_approx_comboBox.currentText()) if selection == 'None': self.currentApproximation = None else: for approximation in self.approximations: if selection == approximation.legend: self.currentApproximation = approximation # Clear Stage Figure self.stage_figure.clf() # clear poles list self.poles_listWidget.clear() # clear zeros list self.zeros_listWidget.clear() # clear stage combobox self.current_stage_comboBox.clear() # if current approx is not None: if self.currentApproximation != None: # clear poles list self.poles_listWidget.clear() # Add all poles to list for pole_pair in self.currentApproximation.poles_pairs: self.poles_listWidget.addItem( QtWidgets.QListWidgetItem(pole_pair.label)) # Add all zeros to list for zero_pair in self.currentApproximation.zeros_pairs: self.zeros_listWidget.addItem( QtWidgets.QListWidgetItem(zero_pair.label)) # disable add pole and zeros buttons if list are empty self.add_poleButton.setEnabled(self.poles_listWidget.count() > 0) self.add_zeroButton.setEnabled(self.zeros_listWidget.count() > 0) selected_stage_plot = str(self.stage_plot_comboBox.currentText()) for stage in self.currentApproximation.stages_2: self.current_stage_comboBox.addItem('Stage {}'.format( str(stage.id))) # set first stage by defult self.current_stage_comboBox.setCurrentIndex(0) # Stages poles and zeros if selected_stage_plot == 'Poles & Zeros': self.currentApproximation.stages_2[0].plot_s_plane_to_figure( self.stage_figure) self.stage_polesList.setVisible(True) self.stage_zerosList.setVisible(True) # list stage poles and zeros self.stage_zerosList.clear() for zero_pair in self.current_stage.zero_pairs: self.stage_zerosList.addItem( QtWidgets.QListWidgetItem(zero_pair.label)) self.stage_polesList.clear() for pole_pair in self.current_stage.pole_pairs: self.stage_polesList.addItem( QtWidgets.QListWidgetItem(pole_pair.label)) else: # else hide self.stage_polesList.setVisible(False) self.stage_zerosList.setVisible(False) self.update_composition() self.stage_canvas.draw() ## New stage plot type handler # @details Handles the selection of a different plot for the stage def on_current_stage_plot_type_changed(self): selected_stage_plot = str(self.stage_plot_comboBox.currentText()) if selected_stage_plot == 'Transfer': self.current_stage.plot_transfer_to_figure(self.stage_figure) elif selected_stage_plot == 'Poles & Zeros': self.current_stage.plot_s_plane_to_figure(self.stage_figure) # list stage poles and zeros self.stage_zerosList.clear() for zero_pair in self.current_stage.zero_pairs: self.stage_zerosList.addItem( QtWidgets.QListWidgetItem(zero_pair.label)) self.stage_polesList.clear() for pole_pair in self.current_stage.pole_pairs: self.stage_polesList.addItem( QtWidgets.QListWidgetItem(pole_pair.label)) self.stage_canvas.draw() ## Stage selector handler # @details Handles the selection of a different 'active' stage def on_current_stage_changed(self): # TODO: en vez de limpiar el canvas, borrar la figure. # Clear figure self.stage_figure.clf() # get the stage index index = self.current_stage_comboBox.currentIndex() self.current_stage = self.currentApproximation.stages_2[index] selected_stage_plot = str(self.stage_plot_comboBox.currentText()) # Stages poles and zeros if selected_stage_plot == 'Poles & Zeros': # list stage poles and zeros self.stage_zerosList.clear() self.current_stage.plot_s_plane_to_figure(self.stage_figure) for zero_pair in self.current_stage.zero_pairs: self.stage_zerosList.addItem( QtWidgets.QListWidgetItem(zero_pair.label)) self.stage_polesList.clear() for pole_pair in self.current_stage.pole_pairs: self.stage_polesList.addItem( QtWidgets.QListWidgetItem(pole_pair.label)) elif selected_stage_plot == 'Transfer': self.current_stage.plot_transfer_to_figure(self.stage_figure) self.stage_canvas.draw() empty_stages = self.current_stage_comboBox.count() == 0 if empty_stages: self.stage_figure.clf() self.composition_figure.clear() ## Handles te selection of a new approx pole def on_selected_approx_pole_changed(self): # if pair is already used disable add pole button. index = self.poles_listWidget.currentRow() if self.currentApproximation.poles_pairs[ index].used or self.current_stage.pole_pairs: self.add_poleButton.setEnabled(False) else: self.add_poleButton.setEnabled(True) ## Handles te selection of a new approx zero def on_selected_approx_zero_changed(self): # if pair is already used disable add pole button. index = self.zeros_listWidget.currentRow() if self.currentApproximation.zeros_pairs[ index].used or self.current_stage.zero_pairs: self.add_zeroButton.setEnabled(False) else: self.add_zeroButton.setEnabled(True) ## Handles the click on remove stage pole def on_remove_stage_pole(self): index = self.stage_polesList.currentRow() pole_pair = self.current_stage.pole_pairs[index] self.current_stage.remove_pole_pair(pole_pair) # update stage poles and zeros list self.stage_zerosList.clear() for zero_pair in self.current_stage.zero_pairs: self.stage_zerosList.addItem( QtWidgets.QListWidgetItem(zero_pair.label)) self.stage_polesList.clear() for pole_pair in self.current_stage.pole_pairs: self.stage_polesList.addItem( QtWidgets.QListWidgetItem(pole_pair.label)) self.current_stage.plot_s_plane_to_figure(self.stage_figure) self.stage_canvas.draw() self.update_composition() self.on_selected_approx_pole_changed() ## Handles the click on remove stage zero def on_remove_stage_zero(self): index = self.stage_zerosList.currentRow() zero_pair = self.current_stage.zero_pairs[index] self.current_stage.remove_zero_pair(zero_pair) # update stage poles and zeros list self.stage_zerosList.clear() for zero_pair in self.current_stage.zero_pairs: self.stage_zerosList.addItem( QtWidgets.QListWidgetItem(zero_pair.label)) self.stage_polesList.clear() for pole_pair in self.current_stage.pole_pairs: self.stage_polesList.addItem( QtWidgets.QListWidgetItem(pole_pair.label)) self.current_stage.plot_s_plane_to_figure(self.stage_figure) self.stage_canvas.draw() self.update_composition() self.on_selected_approx_zero_changed() ## Handles the click on add pole to stage def on_add_pole(self): index = self.poles_listWidget.currentRow() pair = self.currentApproximation.poles_pairs[index] self.current_stage.add_pole_pair(pair) selected_plot = str(self.stage_plot_comboBox.currentText()) if selected_plot == 'Poles & Zeros': self.current_stage.plot_s_plane_to_figure(self.stage_figure) self.stage_canvas.draw() # list stage poles and zeros self.stage_zerosList.clear() for zero_pair in self.current_stage.zero_pairs: self.stage_zerosList.addItem( QtWidgets.QListWidgetItem(zero_pair.label)) self.stage_polesList.clear() for pole_pair in self.current_stage.pole_pairs: self.stage_polesList.addItem( QtWidgets.QListWidgetItem(pole_pair.label)) self.on_selected_approx_pole_changed() self.update_composition() ## Handles the click on add zero to stage def on_add_zero(self): index = self.zeros_listWidget.currentRow() pair = self.currentApproximation.zeros_pairs[index] self.current_stage.add_zero_pair(pair) selected_plot = str(self.stage_plot_comboBox.currentText()) if selected_plot == 'Poles & Zeros': self.current_stage.plot_s_plane_to_figure(self.stage_figure) self.stage_canvas.draw() # list stage poles and zeros self.stage_zerosList.clear() for zero_pair in self.current_stage.zero_pairs: self.stage_zerosList.addItem( QtWidgets.QListWidgetItem(zero_pair.label)) self.stage_polesList.clear() for pole_pair in self.current_stage.pole_pairs: self.stage_polesList.addItem( QtWidgets.QListWidgetItem(pole_pair.label)) self.on_selected_approx_zero_changed() self.update_composition() ## Handles the gain change def on_stage_gain_changed(self): self.current_stage.gain = self.gain_spinBox.value() self.update_composition() ## Updates the transfer generated by the stages def update_composition(self): zeros = [] poles = [] gain = 1 for stage in self.currentApproximation.stages_2: for zero_pair in stage.zero_pairs: for zero in zero_pair.points: zeros.append(zero) for pole_pair in stage.pole_pairs: for pole in pole_pair.points: poles.append(pole) gain *= stage.gain title = '{0} Accumulated Stages'.format( self.currentApproximation.legend) legend = 'Stage Composition Freq. Response' self.composition_figure.clear() axes = self.composition_figure.add_subplot(111) sys = signal.TransferFunction(signal.ZerosPolesGain( zeros, poles, gain)) w, mag, phase = signal.bode(sys) axes.semilogx(w, mag, label=legend) axes.set_xlabel(r'$\omega [rad/seg]$') axes.set_ylabel(r'Mag') axes.set_title('') axes.legend() axes.grid(True, which='minor', axis='both') axes.yaxis.grid() self.clearLayout(self.composition_layout) self.composition_layout.addWidget(self.composition_canvas) self.composition_canvas.draw() ## Handles the deletion of a stage def on_remove_stage(self): if self.current_stage_comboBox.count() > 1: # remove stage from stage combo box # should generate currentSelected changed index = self.current_stage_comboBox.currentIndex() self.current_stage_comboBox.removeItem(index) # eliminarle los polos y ceros self.current_stage.clear() # remove from list if self.current_stage is not None: self.currentApproximation.stages_2.remove(self.current_stage) # rearrange ids for i in range(0, len(self.currentApproximation.stages_2)): self.currentApproximation.stages_2[i].change_id(i) # update stage names in combobox for i in range(0, self.current_stage_comboBox.count()): self.current_stage_comboBox.setItemText( i, self.currentApproximation.stages_2[i].label) self.update_composition() self.stage_canvas.draw() self.composition_canvas.draw() def on_preview_clicked(self): index = self.approximationComboBox.currentIndex() approximation = Approximation( self, self.template, restriction=self.restriction, min_order=self.minOrderSpinBox.value(), max_order=self.maxOrderSpinBox.value(), max_q=self.maxQdoubleSpinBox.value(), custom_order=self.customOrderSpinBox.value(), approx_type=self.approx_type) left, right = self.template_axes.get_xlim() left_N, right_N = self.template_axes_norm.get_xlim() limits = { 'left': left, 'right': right, 'left_N': left_N, 'right_N': right_N } preview_lines = approximation.plot_preview_to_axes( self.template_axes, self.template_axes_norm, limits) # Add approx to combo box (LICHA) self.current_approx_comboBox.addItem(approximation.legend) self.approximations.append(approximation) for line in preview_lines: if line != None: self.plotted_previews.append(line) # show template_canvas self.template_canvas.show() # redraw template_canvas self.template_canvas.draw() self.preview_already_plotted = True # self.initStages() def on_clear_previews_clicked(self): if self.preview_already_plotted: for line in self.plotted_previews: line.pop(0).remove() self.template_canvas.draw() self.plotted_previews = [] self.template_axes.get_legend().remove() self.template_axes_norm.get_legend().remove() self.template_canvas.draw() self.preview_already_plotted = False # redraw template to sclae properly # remove all plots widgets. in plotLayout self.clear_plot_layout() # plot template in specified axes self.template_axes = self.template_fig.add_subplot(211) self.template_axes_norm = self.template_fig.add_subplot(212) self.template.plot_template_in_axes(self.template_axes, self.template_axes_norm) # add template_canvas to plotLayout self.plotsLayout.addWidget(self.template_canvas) # show template_canvas self.template_canvas.show() # redraw template_canvas self.template_canvas.draw() # set template submitted to True self.template_submited = True self.approximations.clear() # empty currentComboBox list self.currentApproxComboBox.setCurrentIndex(0) self.currentApproxComboBox.clear() self.currentApproxComboBox.addItem("None") self.currentApproxComboBox.setCurrentIndex(0) # set current approx to None self.currentApproximation = None # validate approximation for GUI porpuses self.validate_approximation() self.currentApproxComboBox.update() return def on_compute_clicked(self): # eliminar los plots de plotsLayout compute_options = [ self.plot_attenuation, self.plot_phase, self.plot_group_delay, self.plot_step_response, self.plot_s_plane, self.plot_freq_resp ] count = 0 for opt in compute_options: if opt: count = count + 1 self.plots_axes = [] if self.plot_attenuation: # if previously plotted, clear if self.att_plotted: self.att_axes.clear() # create axes in figure self.att_axes = self.att_fig.add_subplot(111) for approximation in self.approximations: left, right = approximation.plot_attenuation_to_axes( self.att_axes) t_left, t_right = self.template_axes.get_xlim() if t_left > left: left = t_left if t_right < right: right = t_right self.att_axes.set_xlim(left, right) self.att_axes.set_ylim(auto=True) self.att_axes.grid(True, which='minor', axis='both') self.att_axes.yaxis.grid() self.att_plotted = True self.att_canvas.draw() self.att_canvas.show() if self.plot_phase: # if previously plotted, clear if self.phase_plotted: self.phase_axes.clear() # create axes in figure self.phase_axes = self.phase_fig.add_subplot(111) left, right = self.template_axes.get_xlim() limits = {'left': left, 'right': right} for approximation in self.approximations: p_left, p_right = approximation.plot_phase_to_axes( self.phase_axes, limits) if p_left > left: left = p_left if p_right < right: right = p_right self.phase_axes.set_xlim(left, right) self.phase_axes.set_ylim(auto=True) self.phase_axes.legend() self.phase_axes.grid(True, which='minor', axis='both') self.phase_axes.yaxis.grid() self.phase_plotted = True self.phase_canvas.draw() self.phase_canvas.show() if self.plot_group_delay: # if previously plotted, clear if self.group_delay_plotted: self.group_axes.clear() # create axes in figure self.group_axes = self.group_fig.add_subplot(111) left, right = self.template_axes.get_xlim() limits = {'left': left, 'right': right} for approximation in self.approximations: p_left, p_right = approximation.plot_group_delay_to_axes( self.group_axes, limits) self.group_axes.set_ylim(auto=True) self.group_axes.legend() self.group_axes.grid(True, which='minor', axis='both') self.group_axes.xaxis.grid() self.group_axes.yaxis.grid() self.group_delay_plotted = True self.group_canvas.draw() self.group_canvas.show() if self.plot_step_response: # if previously plotted, clear if self.step_plotted: self.step_axes.clear() # create axes in figure self.step_axes = self.step_fig.add_subplot(111) left, right = self.template_axes.get_xlim() limits = {'left': left, 'right': right} for approximation in self.approximations: approximation.plot_step_response_to_axes(self.step_axes) self.step_axes.set_ylim(auto=True) self.step_axes.legend() self.step_axes.grid(True, which='minor', axis='both') self.step_axes.xaxis.grid() self.step_axes.yaxis.grid() self.step_plotted = True self.step_canvas.draw() self.step_canvas.show() if self.plot_s_plane: # if previously plotted, clear if self.s_plane_plotted: self.s_plane_axes.clear() # create axes in figure self.s_plane_axes = self.s_plane_fig.add_subplot( 111, projection='polar') left, right = self.template_axes.get_xlim() limits = {'left': left, 'right': right} for approximation in self.approximations: approximation.plot_s_plane_to_axes(self.s_plane_axes) self.s_plane_axes.set_ylim(auto=True) self.s_plane_axes.legend() self.s_plane_plotted = True self.s_plane_canvas.draw() self.s_plane_canvas.show() if self.plot_freq_resp: # if previously plotted, clear if self.freq_response_plotted: self.freq_axes.clear() # create axes in figure self.freq_axes = self.freq_fig.add_subplot(111) left, right = self.template_axes.get_xlim() limits = {'left': left, 'right': right} for approximation in self.approximations: p_left, p_right = approximation.plot_freq_response_to_axes( self.freq_axes, limits) if p_left > left: left = p_left if p_right < right: right = p_right self.freq_axes.set_xlim(left, right) self.freq_axes.set_ylim(auto=True) self.freq_axes.legend() self.freq_axes.grid(True, which='minor', axis='both') self.freq_axes.yaxis.grid() self.freq_response_plotted = True self.freq_canvas.draw() self.freq_canvas.show() return def on_set_current_approx_clicked(self): selectedLegend = str(self.currentApproxComboBox.currentText()) if selectedLegend == '': return if selectedLegend != "None": for approximation in self.approximations: if approximation.legend == selectedLegend: selectedApproximation = approximation self.setCurrentApproximation(selectedApproximation) else: self.setCurrentApproximation(None) class groupBoxPar(QtWidgets.QGroupBox): radioButtons = [] par = None class stageRadioButton(QtWidgets.QRadioButton): stage = None def updateStages(self): self.currentApproximation.updateStages() def clearLayout(self, layout): if layout.count() != 0: for i in reversed(range(layout.count())): tempWidget = layout.itemAt(i).widget() if tempWidget is not None and str( tempWidget.accessibleName()) != "scroll": tempWidget.setParent(None) return def setCurrentApproximation(self, approximation): self.clearLayout(self.horizontalLayout_30) self.clearLayout(self.horizontalLayout_29) self.clearLayout(self.paresGroupBoxLayout) self.currentApproximation = approximation if approximation is not None: self.setStagesPushButton.show() self.horizontalLayout_30.addWidget( approximation.mainStageFigureCanvas) approximation.plotToStagesTab() for stage in approximation.stages: self.horizontalLayout_29.addWidget(stage.figurecanvas) stage.plotStage() for pairList in [approximation.poles, approximation.zeros]: for pair in pairList: self.paresGroupBoxLayout.addWidget(pair.groupBox) # currentItem=[self.currentApproxComboBox.itemText(count) for count in range(self.currentApproxComboBox.count())] else: self.setStagesPushButton.hide()
(opts, args) = parser.parse_args() if not opts.s_template_file and not opts.t_template_file: print "No templates specified at all. Please give a torrent and/or summary template." parser.print_help() sys.exit(1) transmission = Transmission(options=opts) torrents, summary = transmission.get_simple_torrent_data(active_only=opts.activeonly) color_code = ColorCode(color_filename=opts.colorfile) # Summary if opts.s_template_file: s_template = Template(opts.s_template_file) s_template.set_data(summary) s_info = s_template.get_string() print s_info # Torrents if opts.t_template_file: t_template = Template(opts.t_template_file, short_status=False) if opts.limit > 0: # Limit the number of displayed torrents del torrents[opts.limit:] for t in torrents: t_template.set_data(t) t_info = t_template.get_string()
def main(): addressees, theme, files, text_path = parse_config() letter_template = Template(text_path, files, theme) for addressee in addressees: letter_template.send_to(addressee)
def run(videoFile, template1, advert1, minmatch1, ratio1, template2=None, advert2=None, minmatch2=0, ratio2=0, outputFile=None, show=True): MAX_FRAMES = 100000000 frame_count = 0 start_from = 0 cap = cv2.VideoCapture(videoFile) templates = [] template1 = Template(template1, advert1, minmatch1, ratio1) templates.append(template1) if template2 is not None: template2 = Template(template2, advert2, minmatch2, ratio2) templates.append(template2) if outputFile is not None: fourcc = cv2.VideoWriter_fourcc(*'MP4V') out = cv2.VideoWriter(outputFile, fourcc, 30.0, (1280, 720)) while (1): ret, frame = cap.read() frame_count += 1 if ret == True: if frame_count < start_from: continue # if frame_count % 2 == 0: # continue for template in templates: frame = template.processFrame(frame, frame_count) if outputFile is None: if show is True: cv2.imshow("img3", cv2.flip(frame, -1)) if cv2.waitKey(1) & 0xFF == ord('q'): break else: out.write(cv2.flip(frame, -1)) if frame_count > MAX_FRAMES: print("Exiting...") break else: break # Release everything if job is finished cap.release() if outputFile is not None: out.release() cv2.destroyAllWindows() return frame_count
#!/usr/bin/env python """ Author: Manpreet Singh 2016 Headless mode for raspberry pi. This program only returns the X and Y position of an object if it is found in the image """ import cv2 as cv import numpy as np from networktables import NetworkTable from Template import Template nt = NetworkTable.getTable("VISION") template = Template() cap = cv.VideoCapture(1) while True: _, im = cap.read() im = np.array(im, dtype=np.uint8) hsv = cv.cvtColor(im, cv.COLOR_BGR2HSV) # HSV Ranges, hard coded values lower_limit = np.array([78, 176, 0]) upper_limit = np.array([119, 255, 255]) mask = cv.inRange(hsv, lower_limit, upper_limit) _, contours, hierarchy = cv.findContours(mask, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
def getPintuUrl(self, pintu): t = Template(pintu.templNo) t.setTitle(pintu.title) t.setDescription(pintu.description) for i in range(1, 6): t.setShowbox(i, eval("pintu.showbox%d.cost" % i), eval("pintu.showbox%d.sale" % i), eval("pintu.showbox%d.name" % i), eval("pintu.showbox%d.url" % i)) t.setPicbox(pintu.bigpic) t.output() return path.join("cache", "output.svg.png")
class Page(Container): """ Base widget for web pages. Typically an instance of this class (or a class inheriting from it) is used as top level container to which every other CTK widget is added. Arguments: template: custom CTK Template for the pages headers: list of entries for the <head> section. helps: parameters for CTK HelpMenu, if any. Example: page = CTK.Page () page += CTK.RawHTML ('<p>Nothing to see here.</p>') return page.Render() """ def __init__(self, template=None, headers=None, helps=None, **kwargs): Container.__init__(self, **kwargs) self.js_header_end = True if headers: self._headers = HEADERS[:] + headers[:] else: self._headers = HEADERS[:] if template: self._template = template else: self._template = Template(content=PAGE_TEMPLATE_DEFAULT) self._helps = [] for entry in helps or []: self._helps.append(HelpEntry(entry[1], entry[0])) def AddHeaders(self, headers): if type(headers) == list: self._headers += headers else: self._headers.append(headers) def Render(self): # Get the content render render = Container.Render(self) # Build the <head> text self._headers += render.headers if self.js_header_end: head = "\n".join( filter(lambda l: not '<script' in l, uniq(self._headers))) else: head = "\n".join(uniq(self._headers)) # Helps all_helps = self._helps all_helps += render.helps render_helps = HelpMenu(all_helps).Render().html # Javascript js = '' if self.js_header_end: js += "\n".join( filter(lambda l: '<script' in l, uniq(self._headers))) if render.js: js += formatter(HTML_JS_ON_READY_BLOCK, render.js) # Build the <body> body = render.html + render_helps if render.js: body += js # Set up the template self._template['head'] = head self._template['html'] = render.html self._template['js'] = js self._template['body'] = body self._template['helps'] = render_helps if not self._template['body_props']: self._template['body_props'] = '' txt = self._template.Render() return Postprocess(txt)
def getTemplates(self): if self.debug: print(self.seq) result_handle = NCBIWWW.qblast("blastp", "pdb", str(self.seq), expect=0.01) blast_records = NCBIXML.parse(result_handle) if self.debug: print("BLAST Request Finished") print() for record in blast_records: for alignment in record.alignments: id = alignment.accession fasta = self.getFastaFromId(id) title = alignment.title length = alignment.length template = Template(id=id, fasta=fasta, sequence=title, length=length, alignments=[]) self.templates[id] = template self.fastas[id] = fasta for hsp in alignment.hsps: a = Alignment(id=id, title=title, expect=hsp.expect, score=hsp.score, identities=hsp.identities, similarity=(100 * hsp.identities / len(self.seq)), target=hsp.query, targetstart=hsp.query_start, match=hsp.match, template=hsp.sbjct, templatestart=hsp.sbjct_start, length=length) targetfront = str(self.seq[:a.targetstart - 1]) targetend = str(self.seq[(a.targetstart + a.length):]) a.target = ''.join(targetfront) + a.target + ''.join( targetend) a.length = len(a.target) templatefront = ['-'] * (a.targetstart - 1) templateend = ['-'] * (len(self.seq) - (a.targetstart + a.length)) a.template = ''.join(templatefront) + a.template + ''.join( templateend) self.templates[id].alignments.append(a) self.alignments.append(a) for id, fasta in self.fastas.items(): fname = '%s/%s.fasta' % (self.fastasfolder, id) if not os.path.exists(fname): f = open(fname, 'w') SeqIO.write(fasta, f, 'fasta') f.close() for i, a in enumerate(self.alignments): fname = '%s/%s-%s.alignment' % (self.alignmentsfolder, a.id, str(i)) if not os.path.exists(fname): f = open(fname, 'w') json.dump(a.toJSON(), f) f.close() return self.templates.keys()
def __init__(self, headers=[], **kwargs): Container.__init__(self, **kwargs) self.headers = headers[:] self.template = Template(content=PAGE_TEMPLATE_MINI)
def list_comments(self, query, *args): with Repository(db_file, table_name) as repository: comments_tuple = repository.find_all() comments = [Comment(item[0], item[1], item[2]) for item in comments_tuple] return Template.render('comments.tpl', {"comments": comments})
class JaneP(object): def __init__(self): self.mth = datetime.now().month self.sheetName = 'interface1' self.path = '' self.pres = Template() # pres.getDataWithTemplateOrder(templateWorkSheet, self.repos) #self.google_cres="E:/downloads/JaneProject-f472d80e0028.json" self.google_cres = "E:/downloads/JaneProject-f472d80e0028.json" self.google = False self.fileName = 'entityConfig.xlsx' #self.fileName='/Users/pengwang/Downloads/entityConfig.xlsx' self.googleFile = 'entityConfig' #self.outputFile='/Users/pengwang/Downloads/output.xlsx' self.outputFile = 'output.xlsx' def doProcess(self): self.fileName = 'entityConfig.xlsx' if (self.google): self.io = GoogleExcel() self.io.loadSheet(self.google_cres) else: self.io = MicroExcel() self.io.loadSheet(self.path, self.fileName) self.repos = self.io.repos def createTemplate(self): templateDFs = pd.DataFrame( self.io.templates.values ) # convert worksheets to dataFrame structure for i in range(1, len(templateDFs)): #loop all templates path = templateDFs.iloc[i][0] if (pd.isnull(path)): fileName = self.path + templateDFs.iloc[i][1] else: fileName = path + templateDFs.iloc[i][1] sheet = templateDFs.iloc[i][2] #self.writeToSheet(fileName, sheet,outputData, template) self.templateWorkSheet = self.io.loadTemplateWorkSheet(sheet) self.outputData = self.pres.getDataWithTemplateOrder( self.templateWorkSheet, self.repos) self.io.writeToSheet(fileName, sheet, self.outputData, self.templateWorkSheet) # self.io.writeToSheet(self.outputFile, self.sheetName,self.outputData, self.templateWorkSheet) def main(self, argv): #if argv == []: # print("Usage: " + sys.argv[0] + " -h for help") #return try: # opts, args = getopt.getopt(argv,"hf:o:",["ifile=","ofile="]) opts, args = getopt.getopt(argv, "hgf:t:o:n", [ "help", "google Drive", "file=", "templateWorkSheet=", "output=", "noTemplate" ]) except getopt.GetoptError: print("Usage: " + sys.argv[0] + " -h for help") #sys.exit(2) for opt, arg in opts: if opt == '-h': print( 'Syntax: ' + sys.argv[0] + ' \n\n -h help.\n -g google Drive. cres Path and Name \n -f file path and name.\n -p presentation name.\n -o output path and file name.\n' ) sys.exit() elif opt in ("-g", "-google"): self.google = True self.google = True #self.google_cres=arg elif opt in ("-f", "-file"): self.path = arg elif opt in ("-t", "-template"): self.sheetName = arg.lower() elif opt in ("-o", "-output"): self.outputName = arg if opt in ("-n", "-noTemplate"): self.doProcess() else: self.doProcess() self.createTemplate()
def say(self, name = 'World'): return Template.render('hello.tpl', {'name': name})
def say(self, name='World'): return Template.render('hello.tpl', {'name': name})
def hello(self, query, *args): return Template.render('hello.tpl', {"name": args[0]})
Gradebook Type Cohort Period ID ------------------------------------ Academic D 1 114 TEKS Mastery D 1 13 Academic C 2 113 TEKS Mastery C 2 12 Academic B 5 115 TEKS Mastery B 5 11 Academic A 6 6 """ gradebook_choice = str(raw_input("What type of gradebook? ")) gradebook_id_choice = str(raw_input("What is the gradebook ID? ")) cohort_choice = str(raw_input("Which cohort? ")) top = Template(gradebook_choice, gradebook_id_choice, cohort_choice) top.generate_gb_string() file_string = gradebook_choice + cohort_choice + ".csv" f = open(file_string, 'w') f.write(top.print_header()) def create_assignment(assignment, assignment_id, due_date): a = Assignment(assignment, assignment_id, due_date) return a.print_assignment_subheader() def create_event(event, event_id, skill, due_date): e = Event(event, event_id, skill, due_date)
class Page (Container): def __init__ (self, template=None, headers=None, helps=[], **kwargs): Container.__init__ (self, **kwargs) self.js_header_end = True if headers: self._headers = HEADERS + headers else: self._headers = HEADERS if template: self._template = template else: self._template = Template (content = PAGE_TEMPLATE_DEFAULT) self._helps = [] for entry in helps: self._helps.append (HelpEntry (entry[1], entry[0])) def AddHeaders (self, headers): if type(headers) == list: self._headers += headers else: self._headers.append (headers) def Render(self): # Get the content render render = Container.Render(self) # Build the <head> text self._headers += render.headers if self.js_header_end: head = "\n".join (filter (lambda l: not '<script' in l, uniq(self._headers))) else: head = "\n".join (uniq(self._headers)) # Helps all_helps = self._helps all_helps += render.helps render_helps = HelpMenu(all_helps).Render().html # Javascript js = '' if self.js_header_end: js += "\n".join (filter (lambda l: '<script' in l, uniq(self._headers))) if render.js: js += formater (HTML_JS_ON_READY_BLOCK, render.js) # Build the <body> body = render.html + render_helps if render.js: body += js # Set up the template self._template['head'] = head self._template['html'] = render.html self._template['js'] = js self._template['body'] = body self._template['helps'] = render_helps if not self._template['body_props']: self._template['body_props'] = '' txt = self._template.Render() return Postprocess (txt)
def writeToSheet(self, outputFile, sheetName, outputData, templateWorkSheet): self.getSheet(outputFile) sheet = self.workbook.create_sheet(title=sheetName) #print head months row = 1 col = 1 sheet.cell(row, col, ci.INDEX_NAME) col = col + 1 for mon in ci.COLUMNS_WITHOUT_INDEXES: end_col = col + 6 sheet.merge_cells(start_row=row, start_column=col, end_row=row, end_column=end_col) sheet.cell(1, col, mon) col = end_col + 1 # print sub Head as A17,B18... row = 2 col = 1 for column in outputData.columns.tolist(): sheet.cell(row, col, column) col = col + 1 # a blank line # print data row = 4 templateClass = Template() for templateRow in templateWorkSheet.iterrows(): d = outputData.query(ci.INDEX_NAME + "=='" + templateRow[1][ci.CONFIG_ACCOUNT] + "'") if (~d.empty and len(d) > 0): # templateWorkSheet row is not percentages of other row sheet.cell(row, 1, d.iloc[0][0]) for j in range(1, len(d.columns)): col = j + 1 if (d.columns[j] in ci.INDEX_PERCENTAGES): sheet.cell(row, col, "{:1.0%}".format(d.iloc[0][j])) else: sheet.cell(row, col, "{:,.0f}".format(d.iloc[0][j])) else: if (templateRow[1][ci.CONFIG_LEVEL] == 10): percent = templateClass.getPercentages( templateRow[1][ci.CONFIG_ACCOUNT], templateRow[1][ci.CONFIG_PRECENTAGES], templateRow[1][ci.CONFIG_DENOMINATOR], outputData) sheet.cell(row, 1, percent.iloc[0][0]) for j in range(1, len(percent.columns)): col = j + 1 #format to % sheet.cell(row, col, "{:1.0%}".format(percent.iloc[0][j])) else: sheet.cell(row, 1, templateRow[1][ci.CONFIG_ACCOUNT]) # if(templateRow[1][ci.CONFIG_LEVEL!='1']): # rowA=sheet.row_dimensions[row] # rowA.font=Font(b="border") row = row + 1 #self.wb.save(self.fileName) self.workbook.save(outputFile)
def render(template,**kwargs): from Template import Template t = Template(template,searchList=kwargs) return t.respond()