eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: Example code: import os import asyncio from contextlib import asynccontextmanager from fastapi import FastAPI, Request @asynccontextmanager async def lifespan(app: FastAPI): print(f'Lifetime ON {os.getpid()=}') app.state.global_rw = 0 _ = asyncio.create_task(infinite_1(app.state), name='my_task') yield app = FastAPI(lifespan=lifespan) @app.get("/state/") async def inc(request: Request): return {'rw': request.app.state.global_rw} async def infinite_1(app_rw_state): print('infinite_1 ON') while True: app_rw_state.global_rw += 1 print(f'infinite_1 {app_rw_state.global_rw=}') await asyncio.sleep(10)  This is all working fine, every 10 seconds app.state.global_rw is increased by one. Test code: from fastapi.testclient import TestClient def test_all(): from a_10_code import app client = TestClient(app) response = client.get("/state/") assert response.status_code == 200 assert response.json() == {'rw': 0}  Problem that I have found is that TestClient(app) will not start async def lifespan(app: FastAPI):. Started with pytest -s a_10_test.py  So, how to start lifespan in FastAPI TestClient ? P.S. my real code is more complex, this is just simple example for demonstration purposes.

Answer: The main reason that the written test fails is that it doesn't handle the asynchronous nature of the FastAPI app's lifespan context properly. In fact, the global_rw is not set due to improper initialization. If you don't want to utilize an AsyncClient like the one by httpx you can use pytest_asyncio and the async fixture, ensuring that the FastAPI app's lifespan context correctly works and global_rw is initialized properly. Here's the workaround: import pytest_asyncio import pytest import asyncio from fastapi.testclient import TestClient from fastapi_lifespan import app @pytest_asyncio.fixture(scope="module") def client(): with TestClient(app) as client: yield client @pytest.mark.asyncio async def test_state(client): response = client.get("/state/") assert response.status_code == 200 assert response.json() == {"rw": 1} await asyncio.sleep(11) response = client.get("/state/") assert response.status_code == 200 assert response.json() == {'rw': 2}  You can also define a conftest.py to place the fixture there to have a clean test files.
Question: I want to draw a rectangle in matplotlib and I want only the top edge to show. I tried to draw a line on top of the rectangle to make it work, but I was not satisfied with the result. Here's my code: import matplotlib.pyplot as plt from matplotlib.axes import Axes from matplotlib.figure import Figure from matplotlib.patches import Rectangle LIM = 5 def configure_plot(lim: float, **kwargs) -> tuple[Figure, Axes]: fig: Figure ax: Axes fig, ax = plt.subplots(**kwargs) ax.axis("equal") ax.set_axis_off() ax.set_xlim(-lim, lim) ax.set_ylim(-lim, lim) fig.tight_layout() return fig, ax def main() -> None: fig: Figure ax: Axes fig, ax = configure_plot(LIM) width = 8 height = 3.5 color = "tab:blue" rect = Rectangle( (-width / 2, -height), width, height, facecolor=color, alpha=0.8, linewidth=3, ) ax.add_patch(rect) ax.plot([-width / 2, width / 2], [0, 0], color=color) plt.show() if __name__ == "__main__": main()  This gives me this output:  It's almost the result I am looking for, but the line of the edge continues slightly beyond the rectangle's corners which makes it look worse in my opinion. I could play with the line end points to shorten it and make it fit, but this doesn't sound like an ideal solution. Is there a way to draw a rectangle and only one of its edges in matplotlib?

Answer: You can set the CapStyle for the ax.plot line to butt (instead of the default, which is projecting). You can use the solid_capstyle kwarg for this. To demonstrate, I increased the line width to make the differences more obvious: solid_capstyle='projecting' ax.plot([-width / 2, width / 2], [0, 0], color=color, solid_capstyle='projecting', linewidth=5)   solid_capstyle='butt' ax.plot([-width / 2, width / 2], [0, 0], color=color, solid_capstyle='butt', linewidth=5)
Question: I basically just want to use the transformers pipeline() to classify data, but independent of which model I try to use, it returns the same error, stating Numpy is not available Code I'm running: pipe = pipeline("text-classification", model="AdamLucek/roberta-llama3.1405B-twitter-sentiment") sentiment_pipeline('Today is a great day!') # other model i've tried: sentiment_pipeline = pipeline(model="cardiffnlp/twitter-roberta-base-sentiment-latest", tokenizer="cardiffnlp/twitter-roberta-base-sentiment-latest") sentiment_pipeline('Today is a great day!')  Error I receive: RuntimeError Traceback (most recent call last) Cell In[49], line 1 ----> 1 sentiment_pipeline('Today is a great day!') File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\transformers\pipelines\text_classification.py:156, in TextClassificationPipeline.__call__(self, inputs, **kwargs) 122 """ 123 Classify the text(s) given as inputs. 124 (...) 153 If `top_k` is used, one such dictionary is returned per label. 154 """ 155 inputs = (inputs,) --> 156 result = super().__call__(*inputs, **kwargs) 157 # TODO try and retrieve it in a nicer way from _sanitize_parameters. 158 _legacy = "top_k" not in kwargs File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\transformers\pipelines\base.py:1257, in Pipeline.__call__(self, inputs, num_workers, batch_size, *args, **kwargs) 1249 return next( 1250 iter( 1251 self.get_iterator( (...) 1254 ) 1255 ) 1256 else: -> 1257 return self.run_single(inputs, preprocess_params, forward_params, postprocess_params) File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\transformers\pipelines\base.py:1265, in Pipeline.run_single(self, inputs, preprocess_params, forward_params, postprocess_params) 1263 model_inputs = self.preprocess(inputs, **preprocess_params) 1264 model_outputs = self.forward(model_inputs, **forward_params) -> 1265 outputs = self.postprocess(model_outputs, **postprocess_params) 1266 return outputs File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\transformers\pipelines\text_classification.py:208, in TextClassificationPipeline.postprocess(self, model_outputs, function_to_apply, top_k, _legacy) 204 outputs = model_outputs["logits"][0] 206 if self.framework == "pt": 207 # To enable using fp16 and bf16 --> 208 outputs = outputs.float().numpy() 209 else: 210 outputs = outputs.numpy() RuntimeError: Numpy is not available  I already tried simply un- and reinstalling transformers and numpy and for both the most recent versions are installed (and should be compatible). Anyone has an idea on how to solve this?

Answer: Try: pip install "numpy<2"  then restart the kernel.
Question: I'm following Head First Python (3ed). I'm at the last chapter and have a bug I can't get past. I've got an sqlite3 database that I need to port to MariaDB. I've got the schema and data in separate files: sqlite3 CoachDB.sqlite3 .schema > schema.sql sqlite3 CoachDB.sqlite3 '.dump swimmers events times --data-only' > data.sql  I've installed MariaDB via apt, granted privileges to a user, and logged in to get MariaDB prompt: mariadb -u swimuser -p swimDB source schema.sql; source data.sql;  Now I run my python app locally that connects to the MariaDB but, and I'm not sure where exactly, the call fails with: mysql.connector.errors.DatabaseError: 1273 (HY000): Unknown collation: 'utf8mb4_0900_ai_ci' Back at MariaDB prompt: show collation like 'utf8%'; # shows no collation 'utf8mb4_0900_ai_ci' select * from INFORMATION_SCHEMA.SCHEMATA; # shows default is is utf8mb4 / utf8mb4_uca1400_ai_ci At shell prompt, file -i schema.sql shows it's plain-text in us-ascii. I tried opening schema.sql and data.sql in notepadqq and saving them as utf8 but I still got the same error. I dropped the database and recreated it with: CREATE DATABASE swimDB DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_unicode_520_ci;  ...then again sourced schema.sql and data.sql and still got the same error. I saw a post where someone asked for this so... MariaDB [swimDB]> SHOW VARIABLES WHERE VALUE LIKE 'utf%'; +--------------------------+-------------------------------+ | Variable_name | Value | +--------------------------+-------------------------------+ | character_set_client | utf8mb3 | | character_set_collations | utf8mb4=utf8mb4_uca1400_ai_ci | | character_set_connection | utf8mb3 | | character_set_database | utf8mb4 | | character_set_results | utf8mb3 | | character_set_server | utf8mb4 | | character_set_system | utf8mb3 | | collation_connection | utf8mb3_general_ci | | collation_database | utf8mb4_uca1400_ai_ci | | collation_server | utf8mb4_uca1400_ai_ci | | old_mode | UTF8_IS_UTF8MB3 | +--------------------------+-------------------------------+  So I guess there's a character set or encoding problem with the data (?). At this point I'm lost, madly searching the interwebs for clues. Any help appreciated and sorry for the long post :)

Answer: MySQL Connector appears to be forcing a collation that does not exist in MariaDB (utf8mb4_0900_ai_ci). Per comments it appears that attempting to force a later MariaDB collation utf8mb4_uca1400_ai_ci on the connection appears to not resolve the connection. MariaDB Connector/Python its actually tested with MariaDB server. Conforming to the Python Database API Specification v2.0 (PEP 249) it should be compatible with the MySQL (Python) Connector as a replacement connection module for your MariaDB server and application.
Question: I have this piece of code that appends two parts of the same data to a PyArrow table. The second write fails because the column gets assigned null type. I understand why it is doing that. Is there a way to force it to use the type in the table's schema, and not use the inferred one from the data in second write? import pandas as pd import pyarrow as pa import pyarrow.parquet as pq data = { 'col1': ['A', 'A', 'A', 'B', 'B'], 'col2': [0, 1, 2, 1, 2] } df1 = pd.DataFrame(data) df1['col3'] = 1 df2 = df1.copy() df2['col3'] = pd.NA pat1 = pa.Table.from_pandas(df1) pat2 = pa.Table.from_pandas(df2) writer = pq.ParquetWriter('junk.parquet', pat1.schema) writer.write_table(pat1) writer.write_table(pat2)  My error on second write above: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/opt/anaconda3/lib/python3.10/site-packages/pyarrow/parquet/core.py", line 1094, in write_table raise ValueError(msg) ValueError: Table schema does not match schema used to create file: table: col1: string col2: int64 col3: null -- schema metadata -- pandas: '{"index_columns": [{"kind": "range", "name": null, "start": 0, "' + 578 vs. file: col1: string col2: int64 col3: int64 -- schema metadata -- pandas: '{"index_columns": [{"kind": "range", "name": null, "start": 0, "' + 577 

Answer: The problem is that the assignment of pd.NA leads to the incorrect dtype (object): df2 = df1.copy() df2['col3'] = pd.NA print(df2.dtypes) col1 object col2 int64 col3 object dtype: object  Simply change it to Int64 first, using Series.astype: df2['col3'] = pd.NA df2['col3'] = df2['col3'].astype('Int64')  Or in one statement, using pd.Series: df2['col3'] = pd.Series(pd.NA, dtype='Int64')  Both leading to: pat2.schema col1: string col2: int64 col3: int64 -- schema metadata -- pandas: '{"index_columns": [{"kind": "range", "name": null, "start": 0, "' + 577  pat1.schema == pat2.schema # True
Question: I need to set a flag to 1 for every employee in the group (groupby MNGR, YEAR) if any of the employees in the group has any of the columns V1 or V2 or V3 or V4 is greater than 14. I can make it work if only checking 1 column but the V columns can be more than 10 columns. I have this code: DF1['flg'] = [1 for i in range(1, 5) if DF1[f'V{i}'].gt(14).any().groupby(by=['MNGR', 'YEAR']).replace({True: 1, False: 0}).reindex_like(DF1) ]  But I got error: AttributeError: 'numpy.bool_' object has no attribute 'groupby'  sample dataframes DF1 = pd.DataFrame({'EMPLID': [12, 13, 14, 15, 16, 17, 18], 'MNGR': ['BOB', 'JIM', 'RHONDA', 'RHONDA', 'JIM', 'RHONDA', 'RHONDA'], 'YEAR': [2012, 2013, 2012, 2012, 2012, 2013, 2012], 'V1': [1,2,3,4,5,6,7], 'V2': [2,3,4,50,6,7,8], 'V3': [3,3,3,3,3,3,3], 'V4': [7,15,8,9,10,11,12]})  Expected output:  EMPLID MNGR YEAR V1 V2 V3 V4 flg 0 12 BOB 2012 1 2 3 7 NaN 1 13 JIM 2013 2 3 3 15 1 2 14 RHONDA 2012 3 4 3 8 1 3 15 RHONDA 2012 4 50 3 9 1 4 16 JIM 2012 5 6 3 10 NaN 5 17 RHONDA 2013 6 7 3 11 NaN 6 18 RHONDA 2012 7 8 3 12 1 

Answer: You can break this transformation into two discrete steps:  Find the rows where ANY V{1..4} columns are greater than 14 transform the groups ['MNGR', 'YEAR'] where ANY row meets the above  import pandas as pd import numpy as np df = pd.DataFrame({ 'EMPLID': [12, 13, 14, 15, 16, 17, 18], 'MNGR': ['BOB', 'JIM', 'RHONDA', 'RHONDA', 'JIM', 'RHONDA', 'RHONDA'], 'YEAR': [2012, 2013, 2012, 2012, 2012, 2013, 2012], 'V1': [1,2,3,4,5,6,7], 'V2': [2,3,4,50,6,7,8], 'V3': [3,3,3,3,3,3,3], 'V4': [7,15,8,9,10,11,12] }) df['flag'] = ( df.filter(regex=r'^V.+').gt(14).any(axis=1) # 1. .groupby([df['MNGR'], df['YEAR']]).transform('any') # 2. .astype(int) ) print(df) # EMPLID MNGR YEAR V1 V2 V3 V4 flag # 0 12 BOB 2012 1 2 3 7 0 # 1 13 JIM 2013 2 3 3 15 1 # 2 14 RHONDA 2012 3 4 3 8 1 # 3 15 RHONDA 2012 4 50 3 9 1 # 4 16 JIM 2012 5 6 3 10 0 # 5 17 RHONDA 2013 6 7 3 11 0 # 6 18 RHONDA 2012 7 8 3 12 1
Question: I want to convert a list of zip codes into a DataFrame of latitude and longitude using data from this website: Free Map Tools. https://www.freemaptools.com/convert-us-zip-code-to-lat-lng.htm#google_vignette Here’s my code, but it’s not returning the latitude and longitude data. How can I improve it ? import requests from bs4 import BeautifulSoup def get_lat_lng(zip_code): # URL of the form processing page url = 'https://www.freemaptools.com/convert-us-zip-code-to-lat-lng.htm' # Create a session to handle cookies and headers session = requests.Session() # Send a GET request to get the initial form and any hidden data response = session.get(url) response.raise_for_status() # Parse the page with BeautifulSoup soup = BeautifulSoup(response.text, 'html.parser') # Find form data (if needed) # Note: The actual form data extraction depends on how the website is structured # For simplicity, assume there's no hidden form data to worry about # Prepare the data to send in the POST request data = { 'zip': zip_code # Include any other required form fields here if necessary } # Send a POST request with the zip code data response = session.post(url, data=data) response.raise_for_status() # Parse the resulting page soup = BeautifulSoup(response.text, 'html.parser') # Extract latitude and longitude (you need to adjust these selectors based on the website's structure) lat = soup.find('span', {'id': 'latitude'}).text.strip() lng = soup.find('span', {'id': 'longitude'}).text.strip() return lat, lng # Example zip_code = ['97048','63640','63628'] latitude, longitude = get_lat_lng(zip_code) print(f'Latitude: {latitude}, Longitude: {longitude}')   query latitude and longitude data from https://www.freemaptools.com/convert-us-zip-code-to-lat-lng.htm#google_vignette  Querying a list of zip code,i.e. ['97048','63640','63628'], and obtain the latitude and longitude for each zip.  It results in error message.  

Answer: Try: import requests api_url = ( "https://api.promaptools.com/service/us/zip-lat-lng/get/?zip={}&key=17o8dysaCDrgvlc" ) zips = ["97048", "63640", "63628"] headers = { "Origin": "https://www.freemaptools.com", } for z in zips: url = api_url.format(z) data = requests.get(url, headers=headers).json() print(z, data)  Prints: 97048 {'status': 1, 'output': [{'zip': '97048', 'latitude': '46.053228', 'longitude': '-122.971330'}]} 63640 {'status': 1, 'output': [{'zip': '63640', 'latitude': '37.747435', 'longitude': '-90.363484'}]} 63628 {'status': 1, 'output': [{'zip': '63628', 'latitude': '37.942778', 'longitude': '-90.484430'}]}
Question: I came upon a bit of third party Python code that read: count = [remaining, readlen][remaining > readlen]  After staring at it for a bit, I have to ask: are there any cases where this construct is NOT equivalent to: count = min(readlen, remaining)  i.e. are there there any functional differences between the two?

Answer: Let's assume a == b. In this case, [a,b][a>b] returns a, since a>b evaluates to False, which is then cast to 0. But min(b, a) returns b (first argument). This is not relevant for numbers, but it may matter if a and b are mutable objects, like lists: >>> a = [1, 2] >>> b = [1, 2] >>> c = [a, b][a>b] >>> c is a True >>> c is b False >>> c.append(3) >>> a [1, 2, 3] >>> b [1, 2]  With lists, it matters which of two equal objects get picked. Note that just switching the min arguments to min(a, b) would remove this difference.
Question: In pandas I can calculate the centered grouped columns as follows for a dataframe with columns ['a','b','c']: df[['b','c']] = df[['b','c']].sub(df.groupby('a')['b','c'].transform(mean))  What is the equivalent code in Polars? I tried implementing it with sub in polars but it expects expression and not dataframe. I need the original dataframe as output and not the grouped version.

Answer: TLDR. In polars, this is achieved with the window function pl.Expr.over. Concretely, your pandas code would look as follows. df.with_columns( pl.col("b", "c") - pl.col("b", "c").mean().over("a") )   Applied to some sample data, this could look as follows. import polars as pl df = pl.DataFrame({ "a": [0, 0, 0, 1, 1, 1], "b": [2, 2, 2, 3, 3, 3], "c": range(6), })  shape: (6, 3) ┌─────┬─────┬─────┐ │ a ┆ b ┆ c │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪═════╡ │ 0 ┆ 2 ┆ 0 │ │ 0 ┆ 2 ┆ 1 │ │ 0 ┆ 2 ┆ 2 │ │ 1 ┆ 3 ┆ 3 │ │ 1 ┆ 3 ┆ 4 │ │ 1 ┆ 3 ┆ 5 │ └─────┴─────┴─────┘  df.with_columns( pl.col("b", "c") - pl.col("b", "c").mean().over("a") )  shape: (6, 3) ┌─────┬─────┬──────┐ │ a ┆ b ┆ c │ │ --- ┆ --- ┆ --- │ │ i64 ┆ f64 ┆ f64 │ ╞═════╪═════╪══════╡ │ 0 ┆ 0.0 ┆ -1.0 │ │ 0 ┆ 0.0 ┆ 0.0 │ │ 0 ┆ 0.0 ┆ 1.0 │ │ 1 ┆ 0.0 ┆ -1.0 │ │ 1 ┆ 0.0 ┆ 0.0 │ │ 1 ┆ 0.0 ┆ 1.0 │ └─────┴─────┴──────┘
Question: I'm working with a Polars DataFrame, and I want to combine two columns into a dictionary format, where the values from one column become the keys and the values from the other column become the corresponding values. Here's an example DataFrame: import polars as pl df = pl.DataFrame({ "name": ["Chuck", "John", "Alice"], "surname": ["Dalliston", "Doe", "Smith"] })  I want to transform this DataFrame into a new column that contains dictionaries, where name is the key and surname is the value. The expected outcome should look like this: shape: (3, 3) ┌───────┬─────────┬──────────────────────────┐ │ name │ surname │ name_surname │ │ --- │ --- │ --- │ │ str │ str │ dict[str, str] │ ├───────┼─────────┼──────────────────────────┤ │ Chuck │ Dalliston│ {"Chuck": "Dalliston"} │ │ John │ Doe │ {"John": "Doe"} │ │ Alice │ Smith │ {"Alice": "Smith"} │ └───────┴─────────┴──────────────────────────┘  I've tried the following code: df.with_columns( json = pl.struct("name", "surname").map_elements(json.dumps) )  But the result is not as expected. Instead of creating a dictionary with key-value, it produces: {name:Chuck,surname:Dalliston} 

Answer: You can try this code snippet, This seems to be the closest you can get has pl does not have a naive dict. See reference : data_types_polaris import polars as pl df = pl.DataFrame( {"name": ["Chuck", "John", "Alice"], "surname": ["Dalliston", "Doe", "Smith"]} ) df = df.select( [ "name", "surname", ( pl.struct(["name", "surname"]).map_elements( lambda row: {row["name"]: row["surname"]}, return_dtype=pl.Object ) ).alias("name_surname"), ] ) print(df)  ┌───────┬───────────┬────────────────────────┐ │ name ┆ surname ┆ name_surname │ │ --- ┆ --- ┆ --- │ │ str ┆ str ┆ object │ ╞═══════╪═══════════╪════════════════════════╡ │ Chuck ┆ Dalliston ┆ {'Chuck': 'Dalliston'} │ │ John ┆ Doe ┆ {'John': 'Doe'} │ │ Alice ┆ Smith ┆ {'Alice': 'Smith'} │ └───────┴───────────┴────────────────────────┘
Question: I am trying to replace null values in my dataframe column by a prefix and ascending numbers(to make each unique).ie df = pl.from_repr(""" ┌──────────────┬──────────────┐ │ name ┆ asset_number │ │ --- ┆ --- │ │ str ┆ str │ ╞══════════════╪══════════════╡ │ Office Chair ┆ null │ │ Office Chair ┆ null │ │ Office Chair ┆ null │ │ Office Chair ┆ CMP - 001 │ │ Office Chair ┆ CMP - 005 │ │ Office Chair ┆ null │ │ Table ┆ null │ │ Table ┆ CMP - 007 │ └──────────────┴──────────────┘ """)  the null values should be replaced to something like PREFIX - 001,PREFIX - 002,...

Answer: df = df.with_columns( pl.col("asset_number").fill_null( "PREFIX - " + pl.int_range(pl.len()).cast(pl.String) ) )
Question: I have created a figure with two subplots. On the left is a 3D surface plot and on the right side is 2D projection of the 3D plot with imshow. I want the colormap of the imshow plot to be linked to the 3D plot. But the scale does not fit. import numpy as np import matplotlib.pyplot as plt id = np.arange(-600,750,150) iq = np.arange(-600,750,150) xx,yy = np.meshgrid(id,iq) T = np.array([[-8988, -8697.5, -7847, -6923, -5610.5, -4536, -3374.35, -2572.85, -1987.65], [-8162, -7910, -7206.5, -6160, -4798.5, -3476.55, -2479.4, -1711.5, -1374.45], [-6513.5, -6814.5, -6398, -5218.5, -3706.5, -2362.15, -1414.7, -1013.6,-883.05], [-4224.5,-4669, -4686.5, -3755.5, -2217.6, -1079.4, -591.85, -313.005,-211.925], [0, 0, 0, 0, 0, 0, 0, 0, 0], [4420.5, 4833.5, 4749.5, 3787, 2221.1, 1054.55, 567.35, 280.42, 146.51], [6793.5, 7017.5, 6510, 5260.5, 3692.5, 2295.3, 1360.45, 914.55, 806.4], [8421, 8008, 7287, 6160, 4725, 3400.25, 2318.4, 1628.2, 1285.55], [9170, 8750, 7864.5, 6874, 5498.5, 4413.5, 3206.7, 2351.3, 1865.5]]) m = plt.cm.ScalarMappable() m.set_array(T) m.set_clim(-9000, 9000) # optional fig = plt.figure(1, figsize=(12,6)) ax = fig.add_subplot(121, projection='3d') ax.set_xlabel(r'$I_d$', fontsize=15) ax.set_ylabel(r'$I_q$', fontsize=15) ax.set_zlabel(r'$T$', fontsize=15) ax.plot_surface(xx, yy, T, cmap=m.cmap, norm = m.norm) ax2 = fig.add_subplot(122) ax2.imshow(T, cmap=m.cmap, norm=m.norm, extent=(np.min(xx), np.max(xx), np.min(yy), np.max(yy)), interpolation=None) cbar = fig.colorbar( plt.cm.ScalarMappable(), ax=ax2 ) plt.tight_layout() plt.show()   I added a mappable to the plot but unfortunately the colormap is not linked to values of the z axis of the surface plot. The scale only shows values between 0 and 1. How can I connect the values of the T Matix to the colormap ?

Answer: There are two things here:  The default origin for imshow (on your 2D plot) is "upper", meaning the vertical axis points downwards by default. Since you have the lower numbers at the bottom of your axis, you want to set origin="lower".  You can use the mappable object that is created by imshow to create the colorbar, which will then make the colorbar limits match the data. Below I give the mappable returned by ax2.imshow the name im, which you can then use in fig.colorbar.   im = ax2.imshow(T, cmap=m.cmap, norm=m.norm, origin='lower', extent=(np.min(xx), np.max(xx), np.min(yy), np.max(yy)), interpolation=None) cbar = fig.colorbar(im, ax=ax2)
Question: I have a python script that uses images from a folder. The script might work on Windows and Android as well. The problem is I should indicate different file path for the same images (included in the folder where the script is). Is there a format I can use valid for both? For Android I am using "./image.png", but this does not work on Windows.

Answer: If you want some dynamic path, you can use os: import os path = os.path.join('folder1', 'folder2', '...', 'image.png')  You can use as many as you need, or just image.png.