Best Python code snippet using pytest-benchmark
plotting.py
Source:plotting.py  
2import matplotlib.pyplot as plt3from matplotlib.patches import Rectangle4import cv25import os6def handle_saving(plotting_function):7    def wrapper_function(*args, **kwargs):8        plotting_function(*args, **kwargs)9        # save_args: save, folder_path, overwrite_path10        save_args = [x for x in kwargs.values()]11        if not save_args[0]:12            plt.show()13        else:14            if len(save_args) == 3:15                img_path = f"{save_args[1]}{os.path.sep}{plotting_function.__name__}.png"16                if not os.path.exists(17                        f"{save_args[1]}{os.path.sep}{plotting_function.__name__}.png"18                ):19                    plt.savefig(img_path)20                    print(...__init__.py
Source:__init__.py  
...106            self.ids.title.text = 'Save file'107            if not hasattr(self, 'save_widget'):108                self.save_widget = Factory.SaveWidget_()109                self.save_widget.ids.input.bind(on_text_validate=self.handle_saving)110                func = lambda *args: self.handle_saving(self.save_widget.ids.input)111                self.save_widget.ids.save_btn.bind(on_release=func)112            self.ids.saving_container.add_widget(self.save_widget)113        else:114            if self.mode == 'open_file':115                self.ids.title.text = 'Open file'116            elif self.mode == 'choose_dir':117                self.ids.title.text = 'Open folder'118                if not hasattr(self, 'folder_btn'):119                    self.folder_btn = Factory.DirButton_(text='Select')120                    self.folder_btn.bind(on_release=self.folder_selected)121                self.ids.saving_container.add_widget(self.folder_btn)122    123    def folder_selected(self, *args):124        path=self.ids.file_chooser.ids.stacklayout.current_highlighted_child.path125        self.dispatch('on_finished', path)126    def handle_escape(self):127        if self.new_bub in Window.children:128            Window.remove_widget(self.new_bub)129        else:130            self.dismiss()        131    def handle_bubble(self, btn):132        if self.new_bub in Window.children:133            Window.remove_widget(self.new_bub)134        else:135            self.new_bub.pos = (btn.x - (self.new_bub.width-btn.width), btn.y - self.new_bub.height)136            Window.add_widget(self.new_bub)137    def create_new_folder(self, textinput):138        path = os.path.join(self._file_chooser.path, textinput.text)139        if not os.path.exists(path):140            print('making folder ', path)141            try:142                os.mkdir(path)143                # a simple trick to force the file chooser to recompute the files144                former_path = self._file_chooser.path145                self._file_chooser.path = 'eeraef7h98fwb38rh3f8h23yr8i'  # change to an invaid path146                self._file_chooser.path = former_path       # then change back147                Window.remove_widget(self.new_bub)148            except OSError:149                print('error making dir')150        else:151            print('already exists')152    def handle_saving(self, textinput):153        path = os.path.join(self._file_chooser.path, textinput.text)154        if not os.path.exists(path):155            self.dispatch('on_finished', path)156        else:157            print('file already exist')158    def file_selected(self, obj, path):159        if self.mode == 'open_file':160            self.dispatch('on_finished', path)161            self.dismiss()162    def on_finished(self, path):163        self.on_selection([path])164        self.dismiss()165    def open_file(self, path='', on_selection=None):166        self.mode = 'open_file'...routes.py
Source:routes.py  
...43        else:44            save_form.is_saved.render_kw = {'checked': False}45        save_forms[article["url"]] = save_form46    return save_forms47def handle_saving(forms, reload = False):48    # Check each form for49    for form_url in forms:50        if request.method=='POST' and request.form['form_name']==form_url:51            saved_article = db.session.query(ArticleAction).filter_by(article_url=request.form['form_name']).first()52            # If the article is already saved, remove it and update its form.53            if saved_article:54                db.session.query(ArticleAction).filter_by(article_url=request.form['form_name']).delete()55                forms[form_url].is_saved.render_kw = {'checked': False}56            else:57                db.session.add(ArticleAction(article_url=request.form['form_name'], action="saved", last_update_time=datetime.now()))58                forms[form_url].is_saved.render_kw = {'checked': True}59            db.session.commit()60            # This is for the saved articles page. Requires a reload in order to61            # reflect changes to saved articles.62            if reload:63                return True64    return False65@app.route('/', methods=['GET', 'POST'])66@app.route('/home', methods=['GET', 'POST'])67def home():68    # select only articles that have confirmed tags and were added in the last 3 days:69    articles = [a.__dict__ for a in db.session.query(Article70                                                    ).join(ArticleTag).join(Tag71                                                    ).filter(and_(Tag.is_confirmed==True,72                                                                  Article.time_added>datetime.now()-timedelta(days=3))73                                                    ).order_by(Article.time_added.desc()74                                                    ).all()]75    theme = DisplayPref.query.filter_by(attribute='theme').first()76    dark_toggle_form = DarkToggleForm()77    handle_dark_toggle(theme, dark_toggle_form)78    save_articles_forms = create_save_articles(articles)79    handle_saving(save_articles_forms)80    return render_template('home.html', articles=articles, theme=theme.value,81                            dark_toggle_form=dark_toggle_form, save_articles_forms=save_articles_forms, **jinja_helpers_map)82@app.route('/saved', methods=['GET', 'POST'])83def saved_articles():84    #select only articles that are in the saved article list, regardless of tag85    articles = [a.__dict__ for a in db.session.query(Article86                                                    ).join(ArticleAction87                                                    ).filter(and_(ArticleAction.action=="saved")88                                                    ).order_by(ArticleAction.last_update_time.desc()89                                                    ).all()]90    #------------------------91    # HANDLE DARK THEME FORM:92    theme = DisplayPref.query.filter_by(attribute='theme').first()93    dark_toggle_form = DarkToggleForm()94    handle_dark_toggle(theme, dark_toggle_form)95    # -----------------------------96    # HANDLE ARTICLE SAVING FORMS:97    save_articles_forms = create_save_articles(articles)98    #checks for changes in save-status and reloads the page when there are to99    #reflect those changes100    if handle_saving(save_articles_forms,True):101        return redirect(url_for('saved_articles'))102    return render_template('home.html', articles=articles, theme=theme.value,103                            dark_toggle_form=dark_toggle_form, save_articles_forms=save_articles_forms, **jinja_helpers_map)104@app.route('/about')105def about():106    return render_template('about.html', title='About')107@app.route('/tag-manager', methods=['GET', 'POST'])108def tag_manager():109    # ------------------------110    # HANDLE TAG INPUT FORM:111    old_confirmed_tags = {tag.text for tag in Tag.query.filter_by(is_confirmed=True).all()}112    tag_manager_form = TagManagerForm()113    # set the preselected to the currently confirmed tags:114    # note that this accepts a list of tuples: (value, label)...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
