Best Python code snippet using avocado_python
app.py
Source:app.py  
1# <-------------------------- TERRORISM ANALYSIS------------------------------>2# Importing required libraries3import pandas as pd4import dash 5import dash_html_components as html6import webbrowser7import dash_core_components as dcc8from dash.dependencies import Input,Output9import plotly.graph_objects as go10import plotly.express as px   11from dash.exceptions import PreventUpdate1213# Creating a global Dash type object 14app=dash.Dash()1516# Defining required variables17def load_data():18    dataset_name = "global_terror.csv"19    global df20    df=pd.read_csv(dataset_name)21    22    month={"January":1,"February":2,"March":3,"April":4,"May":5,"June":6,"July":7,"August":8,"September":9,"October":10,"November":11,"December":12}23    global month_list24    month_list=[{'label':key,'value':values} for key,values in month.items()]25    26    global region_list27    region_list=[{'label':str(i),'value':str(i)} for i in sorted(df['region_txt'].unique().tolist())]28    29    global country_data30    country_data=df.groupby("region_txt")["country_txt"].unique().apply(list).to_dict()31    32    global state_data33    state_data=df.groupby("country_txt")["provstate"].unique().apply(list).to_dict()34    35    global city_data36    city_data=df.groupby("provstate")["city"].unique().apply(list).to_dict()37    38    global attack_list39    attack_list=[{'label':str(i),'value':str(i)} for i in sorted(df['attacktype1_txt'].unique().tolist())]  40    41    global year_list42    year_list=sorted(df['iyear'].unique().tolist())43    global year_dict44    year_dict={str(year):str(year) for year in year_list}45    46    global chart_dropdown_data,chart_dropdown_values47    chart_dropdown_data={'Terrorist Organisation':'gname','Target Nationality':'natlty1_txt','Target Type':'targtype1_txt','Attack Type':'attacktype1_txt','Weapon Type':'weaptype1_txt','Region':'region_txt','Country Attacked':'country_txt'}48    chart_dropdown_values=[{'label':key,'value':val} for key,val in chart_dropdown_data.items()]4950# Creating a UI having 2 tabs ie Map Tool and Chart Tool51# Both the tabs have respective subtabs for world and india scenario52def create_app_ui():53    main_layout=html.Div(54    [55     html.H1(children="Terrorism Analysis with Insights",id='Main_heading',style={'textAlign':'center'}),      56     57     html.Hr(),58     html.Br(),  59     60     dcc.Tabs(id='Tabs', value='map', children=[61         dcc.Tab(label='Map Tool',id='MapT', value='map', children=[62         dcc.Tabs(id='Subtabs_map',value='worldmap',children=[63                 dcc.Tab(label='World Map',id='WorldM',value='worldmap'),64                 dcc.Tab(label='India Map',id='IndiaM',value='indiamap')65                 ]66                 )]),67         68         dcc.Tab(label='Chart Tool',id='ChartT',value='chart',children=[69         dcc.Tabs(id='Subtabs_chart',value='worldchart',children=[70                 dcc.Tab(label='World Chart',id='WorldC',value='worldchart'),71                 dcc.Tab(label='India Chart',id='IndiaC',value='indiachart')]),72                 ])        73     ]),74     html.Div(id='dropdowns') # Here the screen will fill with either map-specifications or the chart-specifications as returned by update_data callback75    ])76    return main_layout7778@app.callback(79Output('dropdowns','children'),80[Input('Tabs','value')]81)82def update_data(tab): # To show dropdowns based on id='Tabs' value83    data=None84    if tab=='map':  # When user selects Map Tool tab85        data=html.Div([86        dcc.Dropdown(87        id='dropdown-month',88        options=month_list,89        placeholder='Select Month',90        multi=True       91        ),92     93        dcc.Dropdown(94        id='dropdown-date',95        placeholder='Select Date',      96        multi=True97        ),98     99        dcc.Dropdown(100        id='dropdown-region',101        options=region_list,102        placeholder='Select Region',        103        multi=True104        ),105            106        dcc.Dropdown(id='dropdown-country',   107        options=[{'label':'All','value':'All'}],   108        placeholder='Select Country',109        multi=True110        ),111                  112        dcc.Dropdown(113        id='dropdown-state',114        options=[{'label':'All','value':'All'}],115        placeholder='Select State',        116        multi=True117        ),118             119        dcc.Dropdown(120        id='dropdown-city',121        options=[{'label':'All','value':'All'}],122        placeholder='Select City',        123        multi=True124        ),125             126        dcc.Dropdown(127        id='dropdown-attack',128        options=attack_list,129        placeholder='Select Attack Type',        130        multi=True131        ),132             133        html.Br(),134        html.H4("Select Year", id='year-title'),135     136        dcc.RangeSlider(137        id='year-slider',138        min=min(year_list),139        max=max(year_list),140        value=[min(year_list),max(year_list)],141        marks=year_dict        142        ),143             144        html.Br(),145     146        html.Div(id='map-initials',children=["World map loading..."])147        ])148    else:  # When user selects Chart Tool tab149        data=html.Div([150        html.Br(),151        html.Br(),152        153        dcc.Dropdown(154        id='dropdown-chart',155        options=chart_dropdown_values,156        placeholder='Select Your Option',157        value='region_txt'158        ),159                160        html.Br(),161        html.Br(),162        163        dcc.Input(id='search-box',placeholder='Search Filter'),164        165        html.Br(),166        html.Br(),167        168        dcc.RangeSlider(169        id='chart-year-slider',170        min=min(year_list),171        max=max(year_list),172        value=[min(year_list),max(year_list)],173        marks=year_dict,174        step=None        175        ),176        177        html.Br(),178        179        html.Div(id='chart-initials',children=["World chart loading..."])180        ])181    return data182183# To update the map(world map or india map) according to user selected values184@app.callback(185        dash.dependencies.Output('map-initials','children'),186        [187        dash.dependencies.Input('dropdown-month','value'),188        dash.dependencies.Input('dropdown-date','value'),189        dash.dependencies.Input('dropdown-region','value'),190        dash.dependencies.Input('dropdown-country','value'),191        dash.dependencies.Input('dropdown-state','value'),192        dash.dependencies.Input('dropdown-city','value'),193        dash.dependencies.Input('dropdown-attack','value'),194        dash.dependencies.Input('year-slider','value'),195        dash.dependencies.Input('Tabs','value')196        ]197        )198def update_app_ui_map(month_value,date_value,region_value,country_value,state_value,city_value,attack_value,year_value,tab):199    # Printing is just for debugging purpose200    print(type(month_value))201    print(month_value)202    print(type(date_value))203    print(date_value)204    print(type(region_value))205    print(region_value)206    print(type(country_value))207    print(country_value)208    print(type(state_value))209    print(state_value)210    print(type(city_value))211    print(city_value)212    print(type(attack_value))213    print(attack_value)214    print(type(year_value))215    print(year_value)216   217    figure_map=go.Figure()  218        219    if tab=='map':  # When map is to be implemented220        year_range=range(year_value[0],year_value[1]+1)221        map_df=df[df['iyear'].isin(year_range)]222    223        if month_value==[] or month_value is None:224            pass225        else:226            if date_value==[] or date_value is None:227                map_df=map_df[map_df["imonth"].isin(month_value)]228            else:229                map_df=map_df[map_df['imonth'].isin(month_value) & map_df['iday'].isin(date_value)]  # here () not needed for expressions on either side of &230        231        if region_value==[] or region_value is None:232            pass233        else: 234            if country_value==[] or country_value is None: 235                map_df=map_df[map_df['region_txt'].isin(region_value)]236            else: 237                if state_value==[] or state_value is None:238                    map_df=map_df[map_df['region_txt'].isin(region_value) & map_df['country_txt'].isin(country_value)]239                else: 240                    if city_value==[] or city_value is None:241                        map_df=map_df[map_df['region_txt'].isin(region_value) & map_df['country_txt'].isin(country_value) & map_df['provstate'].isin(state_value)]242                    else:243                        map_df=map_df[map_df['region_txt'].isin(region_value) & map_df['country_txt'].isin(country_value) & map_df['provstate'].isin(state_value) & map_df['city'].isin(city_value)]244    245        if attack_value==[] or attack_value is None:246            pass247        else:248            map_df=map_df[map_df['attacktype1_txt'].isin(attack_value)]249    250        if map_df.shape[0]:251            pass252        else: 253            map_df = pd.DataFrame(columns = ['iyear', 'imonth', 'iday', 'country_txt', 'region_txt', 'provstate', 'city', 'latitude', 'longitude', 'attacktype1_txt', 'nkill'])254            map_df.loc[0] = [0, 0 ,0, None, None, None, None, None, None, None, None]255    256        figure_map=px.scatter_mapbox(257            map_df,258            lat='latitude',259            lon='longitude',260            color='attacktype1_txt',  261            hover_name="city",262            hover_data=['region_txt','country_txt','provstate','city','attacktype1_txt','nkill','iyear'],263            zoom=1  264            )265    266        figure_map.update_layout(267            mapbox_style='open-street-map',268            autosize=True,  269            margin=dict(l=0,r=0,t=25,b=20)                     270            )271    272        return dcc.Graph(figure=figure_map)273    else:274        pass275    276# To update the chart(world chart/india chart) according to user selected values277@app.callback(278        dash.dependencies.Output('chart-initials','children'),279        [280        dash.dependencies.Input('dropdown-chart','value'),281        dash.dependencies.Input('search-box','value'),282        dash.dependencies.Input('chart-year-slider','value'),283        dash.dependencies.Input('Tabs','value'),284        dash.dependencies.Input('Subtabs_chart','value')285        ]286        )287def update_app_ui_chart(chart_value,search_value,chart_year_value,tab,subtab): 288    figure_chart=go.Figure() 289        290    if tab=='chart':   # When chart is to be implemented291        year_range=range(chart_year_value[0],chart_year_value[1]+1)292        chart_df=df[df['iyear'].isin(year_range)]293        294        # Following if-else block would filter the output according to world chart or india chart295        if subtab=='worldchart':  296            pass297        else:  298            chart_df=chart_df[(chart_df["region_txt"]=="South Asia") & (chart_df["country_txt"]=="India")]299        300        if chart_value is not None:301            if search_value is not None:302                chart_df=chart_df=chart_df.groupby('iyear')[chart_value].value_counts().reset_index(name='count')303                chart_df=chart_df[chart_df[chart_value].str.contains(search_value,case=False)]304            else:305                chart_df=chart_df.groupby('iyear')[chart_value].value_counts().reset_index(name='count')306        else:307            raise PreventUpdate308        309        if chart_df.shape[0]:310            pass311        else: 312            chart_df = pd.DataFrame(columns = ['count', 'iyear','chart_value'])313            chart_df.loc[0] = [0, 0, "No Data"]314        315        figure_chart=px.area(chart_df,x='iyear',y='count',color=chart_value)316        317        return dcc.Graph(figure=figure_chart)318    else:319        pass320321# Updating the date dropdown options according to the value selected from month dropdown322@app.callback(323Output('dropdown-date','options'),324[Input('dropdown-month','value')]        325)326def update_date_options_acc_to_month_selected(month_value):327    dates=[x for x in range(1,32)]328    options=[]329    if month_value:330        options=[{'label':m,'value':m} for m in dates]331    return options332    333# 'dropdown_update_acc_to_world_or_india_map' callback is for providing india map tool facility (here we need to fix the values for region and country dropdowns)334@app.callback(335[336Output('dropdown-region','value'),337Output('dropdown-region','disabled'),338Output('dropdown-country','value'),339Output('dropdown-country','disabled')340],341[Input('Subtabs_map','value')]        342)343def dropdown_update_acc_to_world_or_india_map(subtab):344    region=None345    disable_region=False346    country=None347    disable_country=False348    if subtab=='worldmap':349        pass350    else:351        region=['South Asia']352        disable_region=True353        country=['India']354        disable_country=True355    return region, disable_region, country, disable_country356357# Chained callbacks to filter country,state,city options based on region,country,state values respectively358@app.callback(359Output('dropdown-country','options'),360[Input('dropdown-region','value')]     361)362def update_country_options_acc_to_region_selected(region_value):363    options=[]364    if region_value is None:365        raise PreventUpdate366    else: 367        for reg in region_value:368            if reg in country_data.keys():369                options.extend(country_data[reg])370    return [{'label':country,'value':country} for country in options]371@app.callback(372Output('dropdown-state','options'),373[Input('dropdown-country','value')]        374)375def update_state_options_acc_to_region_country_selected(country_value):376    options=[]377    if country_value is None:378        raise PreventUpdate379    else:380        for country in country_value:381            if country in state_data.keys():382                options.extend(state_data[country])383    return [{'label':state,'value':state} for state in options]384@app.callback(385Output('dropdown-city','options'),386[Input('dropdown-state','value')]         387)388def update_city_options_acc_to_region_country_state_selected(state_value):389    options=[]390    if state_value is None:391        raise PreventUpdate392    else:393        for state in state_value:394            if state in city_data.keys():395                options.extend(city_data[state])396    return [{'label':city,'value':city} for city in options]397398# Automatically opening the web app on running the script399def open_browser():400    url='http://127.0.0.1:8050/'401    webbrowser.open_new(url)402403# Program flow404def main():405    load_data()406    open_browser() 407    global app,df 408    app.layout=create_app_ui()409    app.title="Terrorism Analysis"410    app.run_server()411    df=None412    app=None413    414if __name__=='__main__':415    print('Project starting ... ')416    main()
...extract_info.py
Source:extract_info.py  
1from gensim.models.phrases import Phraser2from gensim.models import Word2Vec3from scipy.spatial.distance import cosine4from nltk import pos_tag5from collections import defaultdict6from ..nlp_utils.common import *7from ..nlp_utils.pos_tag import *8from ..nlp_utils.time import *9from ..nlp_utils.synonym import *10import numpy as np11init_tagger = Tagger(locations)12time_tagger = TimeTagger()13e_tag = ElementTagger()14bigram_phraser = Phraser.load(f"{COMMON_PATH}/bigram_phraser.pkl")15def process_for_ocr(text):16    final_text = defaultdict(lambda : defaultdict(float))17    for word in text:18        final_text[word][word] = 119        for i in range(0, len(word)-1):20            if len(word[:i+1]) > 1:21                final_text[word][word[:i+1]] += (i+1) / len(word)22            if len(word[i+1:]) > 1:23                final_text[word][word[i+1:]] += 1 - (i+1)/len(word)24    return final_text25def search(wordset, text):26    results = []27    text = " " + text + " "28    for keyword in wordset:29        if keyword:30            if " " + keyword + " " in text:31                results.append(keyword)32            # if re.search(r'\b' + re.escape(keyword) + r'\b', text, re.IGNORECASE):33                # results.append(keyword)34    return results35# Partial match only36def search_possible_location(text):37    results = []38    for location in locations:39        for i, extra in enumerate(locations[location]):40            if re.search(r'\b' + re.escape(extra) + r'\b', text, re.IGNORECASE):41                if extra not in results:42                    results.append(location)43    return results44# gps_location_sets = {location: set([pl for pl in location.lower().replace(',', ' ').split() if pl not in stop_words]) for location, gps in map_visualisation}45gps_not_lower = {}46for loc in locations:47    for origin_doc, (lat, lon) in map_visualisation:48        if loc == origin_doc.lower():49            gps_not_lower[loc] = origin_doc50def rreplace(s, old, new, occurrence):51    li = s.rsplit(old, occurrence)52    return new.join(li)53class Query:54    def __init__(self, text, shared_filters=None):55        self.negative = ""56        self.disable_region = False57        if "âdisable_region" in text:58            print("Disabling region")59            self.disable_region = True60            text = text.replace("âdisable_region", "")61        self.disable_location = False62        if "âdisable_location" in text:63            print("Disabling location")64            self.disable_location = True65            text = text.replace("âdisable_location", "")66        if "NOT" in text:67            text, self.negative = text.split("NOT")68            self.negative = self.negative.strip(". \n").lower()69            self.negative = [word for word in self.negative.split() if word in all_keywords]70        text = text.strip(". \n").lower()71        self.time_filters = None72        self.date_filters = None73        self.ocr_queries = []74        self.location_queries = []75        self.query_visualisation = defaultdict(list)76        self.location_filters = []77        self.country_to_visualise = []78        self.extract_info(text, shared_filters)79    def extract_info(self, text, shared_filters=None):80        def search_words(wordset):81            return search(wordset, text)82        self.original_text = text83        quoted_text = " ".join(re.findall(r'\"(.+?)\"', text))84        text = text.replace(f'"{quoted_text}"', "") #TODO!85        self.ocr = process_for_ocr(quoted_text.split())86        if not self.disable_location:87            self.locations = search_words(locations)88            self.place_to_visualise = [gps_not_lower[location] for location in self.locations]89            if self.locations:90                self.query_visualisation["LOCATION"].extend(self.locations)91            else:92                possible_locations = search_possible_location(text)93                if possible_locations:94                    self.query_visualisation["POSSIBLE LOCATION(S)"].extend(possible_locations)95        else:96            self.locations = []97            self.place_to_visualise = []98        print("Locations:", self.locations)99        for loc in self.locations:100            text = rreplace(text, loc, "", 1) #TODO!101        if not self.disable_region:102            self.regions = search_words(regions)103        else:104            self.regions = []105        for reg in self.regions:106            self.query_visualisation["REGION"].append(reg)107            for country in countries:108                if reg == country.lower():109                    self.country_to_visualise.append({"country": country, "geojson": countries[country]})110        for region in self.regions:111            text = rreplace(text, region, "", 1) #TODO!112        # processed = set([w.strip(",.") for word in self.regions +113                        #  self.locations for w in word.split()])114        # if not full_match:115        #     # self.locations.extend(search_words(116        #         # [w for w in ["hotel", "restaurant", "airport", "station", "cafe", "bar", "church"] if w not in self.locations]))117        #     for loc in self.locations[len(self.gps_results):]:118        #         for place, _ in map_visualisation:119        #             if loc in place.lower().split():120        #                 self.place_to_visualise.append(place)121        # if full_match:122        #     for loc in self.locations:123        #         self.query_visualisation["LOCATION"].append(loc)124        # else:125        #     for loc in self.locations:126        #         self.query_visualisation["POSSIBLE LOCATION"].append(loc)127        self.weekdays = []128        self.dates = None129        self.start = (0, 0)130        self.end = (24, 0)131        tags = time_tagger.tag(text)132        processed = set()133        for i, (word, tag) in enumerate(tags):134            if word in processed:135                continue136            if tag in ["WEEKDAY", "TIMERANGE", "TIMEPREP", "DATE", "TIME"]:137                processed.add(word)138                # self.query_visualisation["TIME" if "TIME" in tag else tag].append(word)139            if tag == "WEEKDAY":140                self.weekdays.append(word)141            elif tag == "TIMERANGE":142                s, e = word.split("-")143                self.start = adjust_start_end(144                    "start", self.start, *am_pm_to_num(s))145                self.end = adjust_start_end("end", self.end, *am_pm_to_num(e))146            elif tag == "TIME":147                if word in ["2019", "2020"]:148                    self.dates = get_day_month(word)149                else:150                    timeprep = ""151                    if i > 1 and tags[i-1][1] == 'TIMEPREP':152                        timeprep = tags[i-1][0]153                    if timeprep in ["before", "earlier than", "sooner than"]:154                        self.end = adjust_start_end(155                            "end", self.end, *am_pm_to_num(word))156                    elif timeprep in ["after", "later than"]:157                        self.start = adjust_start_end(158                            "start", self.start, *am_pm_to_num(word))159                    else:160                        h, m = am_pm_to_num(word)161                        self.start = adjust_start_end(162                            "start", self.start, h - 1, m)163                        self.end = adjust_start_end("end", self.end, h + 1, m)164            elif tag == "DATE":165                self.dates = get_day_month(word)166            elif tag == "TIMEOFDAY":167                if word not in ["lunch", "breakfast", "dinner", "sunrise", "sunset"]:168                    processed.add(word)169                # self.query_visualisation["TIME" if "TIME" in tag else tag].append(word)170                timeprep = ""171                if i > 1 and tags[i-1][1] == 'TIMEPREP':172                    timeprep = tags[i-1][0]173                if "early" in timeprep:174                    if "early; " + word in timeofday:175                        word = "early; " + word176                elif "late" in timeprep:177                    if "late; " + word in timeofday:178                        word = "late; " + word179                if word in timeofday:180                    s, e = timeofday[word].split("-")181                    self.start = adjust_start_end(182                        "start", self.start, *am_pm_to_num(s))183                    self.end = adjust_start_end(184                        "end", self.end, *am_pm_to_num(e))185                else:186                    print(187                        word, f"is not a registered time of day ({timeofday})")188        print(processed)189        print(tags)190        if shared_filters:191            if not self.weekdays:192                self.weekdays.extend(shared_filters.weekdays)193            if self.dates is None:194                self.dates = shared_filters.dates195        unprocessed = [(word, tag) for (word, tag) in tags if word not in processed]196        last_non_prep = 0197        self.clip_text = ""198        for i in range(1, len(unprocessed)  + 1):199            if unprocessed[-i][1] not in ["DT", "IN"] and unprocessed[-i][0] not in stop_words:200                last_non_prep = i201                break202        if last_non_prep > 1:203            self.clip_text = " ".join([word for word, tag in unprocessed[:-(last_non_prep - 1)]])204        else:205            self.clip_text = " ".join(206                [word for word, tag in unprocessed])207        self.clip_text = self.clip_text.strip(", ")208        print("CLIP:", self.clip_text)209        # self.query_visualisation[self.clip_text] = "CLIP"210    def get_info(self):211        return {"query_visualisation": [(hint, ", ".join(value)) for hint, value in self.query_visualisation.items()],212                "country_to_visualise": self.country_to_visualise,213                "place_to_visualise": self.place_to_visualise}214    def time_to_filters(self):215        if not self.time_filters:216            # Time217            self.time_filters = {218                                    "range":219                                    {220                                        "hour":221                                        {222                                            "gte": self.start[0],223                                            "lte": self.end[0]224                                        }225                                    }226                                }227            # Date228            self.date_filters = []229            if self.dates:230                y, m, d = self.dates231                if y:232                    self.date_filters.append({"term": {"year": str(y)}})233                if m:234                    self.date_filters.append(235                        {"term": {"month": str(m).rjust(2, "0")}})236                if d:237                    self.date_filters.append(238                        {"term": {"date": str(d).rjust(2, "0")}})239            if self.start[0] != 0 and self.end[0] != 24:240                self.query_visualisation["TIME"] = [f"{self.start[0]}:00 - {self.end[0]}:00"]241            if str(self.dates) != "None":242                self.query_visualisation["DATE"] = [str(self.dates)]243        return self.time_filters, self.date_filters244    def make_ocr_query(self):245        if not self.ocr_queries:246            self.ocr_queries = []247            for ocr_word in self.ocr:248                dis_max = []249                for ocr_word, score in self.ocr[ocr_word].items():250                    dis_max.append(251                        {"rank_feature": {"field": f"ocr_score.{ocr_word}", "boost": 200 * score, "linear": {}}})252                self.ocr_queries.append({"dis_max": {253                    "queries": dis_max,254                    "tie_breaker": 0.0}})255        return self.ocr_queries256        #TODO: multiple word in OCR257    def make_location_query(self):258        if not self.location_filters:259            for loc in self.locations:260                place = gps_not_lower[loc]261                place = gps_not_lower[loc]262                dist = "0.5km"263                pivot = "5m"264                if "airport" in loc or "home" in loc:265                    dist = "2km"266                    pivot = "200m"267                elif "dcu" in loc:268                    dist = "1km"269                    pivot = "100m"270                for place_iter, (lat, lon) in map_visualisation:271                    if place == place_iter:272                        # self.location_queries.append({273                        #         "distance_feature": {274                        #             "field": "gps",275                        #             "pivot": pivot,276                        #             "origin": [lon, lat],277                        #             "boost": score * 50278                        #         }279                        #     })280                        self.location_filters.append({281                            "geo_distance": {282                                "distance": dist,283                                "gps": [lon, lat]284                            }285                        })286                        break287            # # General:288            # if len(self.gps_results) < len(self.locations):289            #     for loc in self.locations[len(self.gps_results):]:290            #         loc_set = set(loc.split())291            #         for place, (lat, lon) in map_visualisation:292            #             set_place = gps_location_sets[place]293            #             if loc_set.issubset(set_place):294            #                 pivot = "5m"295            #                 if "airport" in set_place:296            #                     pivot = "200m"297            #                     self.location_filters.append({298            #                         "geo_distance": {299            #                             "distance": "2km",300            #                             "gps": [lon, lat]301            #                         }302            #                     })303            #                 elif "dcu" in set_place:304            #                     pivot = "100m"305            #                 self.location_queries.append({306            #                     "distance_feature": {307            #                         "field": "gps",308            #                         "pivot": pivot,309            #                         "origin": [lon, lat],310            #                         "boost": len(loc_set) / len(set_place) * 50311            #                     }312            #                 })313        # if self.location_queries:314            # return {"dis_max": {"queries": self.location_queries, "tie_breaker": 0.0}}...test_cell.py
Source:test_cell.py  
...110        assert widget._center_btn is not None111        assert widget._center_btn.icon == "map-marker"112        assert widget._centered == False113        assert widget._can_select == True114    def test_disable_region(self, widget):115        """Tests `disable_region`."""116        widget.disable_region(True)117        assert widget._region_checkbox.disabled == True118        assert widget._center_btn.disabled == True119        widget.disable_region(False)120        assert widget._region_checkbox.disabled == False121        assert widget._center_btn.disabled == False122    def test_center_region(self, widget):123        """Tests `center_region`."""124        widget.center_region(True)125        assert widget._centered == True126        assert widget._center_btn.icon == "map-pin"127        widget.center_region(False)128        assert widget._centered == False129        assert widget._center_btn.icon == "map-marker"130    def test_remove_center(self, widget):131        """Tests `remove_center`."""132        widget.remove_center()133        assert widget._centered == False...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!!
