question_id int64 59.5M 79.7M | creation_date stringdate 2020-01-01 00:00:00 2025-07-15 00:00:00 | link stringlengths 60 163 | question stringlengths 53 28.9k | accepted_answer stringlengths 26 29.3k | question_vote int64 1 410 | answer_vote int64 -9 482 |
|---|---|---|---|---|---|---|
71,099,818 | 2022-2-13 | https://stackoverflow.com/questions/71099818/websocket-not-working-when-trying-to-send-generated-answer-by-keras | I am implementing a simple chatbot using keras and WebSockets. I now have a model that can make a prediction about the user input and send the according answer. When I do it through command line it works fine, however when I try to send the answer through my WebSocket, the WebSocket doesn't even start anymore. Here is ... | I am devastated, I just wasted 2 days into the dumbest possible issue (and fix) I still had the while True: question = input("") ints = predict(question) answer = response(ints, json_data) print(answer) in my model file, so the server didn't start. The fix was to delete it and now it works fine. | 6 | 4 |
71,134,787 | 2022-2-15 | https://stackoverflow.com/questions/71134787/listing-objects-in-s3-with-suffix-using-boto3 | def get_latest_file_movement(**kwargs): get_last_modified = lambda obj: int(obj['LastModified'].strftime('%s')) s3 = boto3.client('s3') objs = s3.list_objects_v2(Bucket='my-bucket',Prefix='prefix')['Contents'] last_added = [obj['Key'] for obj in sorted(objs, key=get_last_modified, reverse=True)][0] return last_added A... | You can check if they end with .csv: def get_latest_file_movement(**kwargs): get_last_modified = lambda obj: int(obj['LastModified'].strftime('%s')) s3 = boto3.client('s3') objs = s3.list_objects_v2(Bucket='my-bucket',Prefix='prefix')['Contents'] last_added = [obj['Key'] for obj in sorted(objs, key=get_last_modified, r... | 5 | 1 |
71,111,005 | 2022-2-14 | https://stackoverflow.com/questions/71111005/modulenotfounderror-no-module-named-keras-applications-resnet50-on-google-cola | I am trying to run an image-based project on colab. I found the project on github. Everything runs fine till I reached the cell with the following code: import keras from keras.preprocessing.image import ImageDataGenerator from keras.applications.resnet50 import preprocess_input, ResNet50 from keras.models import Model... | from tensorflow.keras.applications.resnet50 import ResNet50 | 8 | 9 |
71,102,782 | 2022-2-13 | https://stackoverflow.com/questions/71102782/python-debugger-in-spyder-stops-at-line-2 | when i am trying to debug my code the debugger stops at line 2 and doenst respond to any commands (like go to next line). I am using python 3.9.7. This is what the console looks like: If I try to stop the debugger this happens: The only thing I can do then is close the console. | I had recently the same problem (using Python 3.8) and the solution was to revert an recent upgrade of qtconsole from 5.1.1 to 5.2.2. In case you use conda, the command to revert would be "conda install qtconsole=5.1.1". | 5 | 9 |
71,120,350 | 2022-2-15 | https://stackoverflow.com/questions/71120350/none-vs-nonetype-for-type-annotation | If a function can return None, shouldn't the type annotation use NoneType? For example, shouldn't we use this: from types import NoneType def my_function(num: int) -> int | NoneType: if num > 0: return num return None instead of: def my_function(num: int) -> int | None: if num > 0: return num return None ? | No. types.NoneType was removed in Python 3. Attempting to import NoneType from types will produce an ImportError in Python 3, before Python 3.10. (For Python 3.10, types.NoneType was reintroduced; however, for the purposes of type hinting, types.NoneType and None are equivalent, and you should prefer the latter for con... | 7 | 12 |
71,119,621 | 2022-2-14 | https://stackoverflow.com/questions/71119621/python-logging-in-aws-lambda | Something just doesn't click internally for me with pythons logging despite reading the documentation. I have this code import logging logging.basicConfig(level=logging.INFO,format='%(levelname)s::%(message)s') LOG = logging.getLogger("__name__") LOG.info("hey") If I run it from bash I get this: INFO::hey If I run it... | When your Lambda runs, a harness is running that does some basic bootstrap and then loads your module and invokes it. Part of that bootstrap in the AWS Lambda Python Runtime replaces the standard Python logger with its own: logger_handler = LambdaLoggerHandler(log_sink) logger_handler.setFormatter( logging.Formatter( ... | 6 | 7 |
71,059,123 | 2022-2-10 | https://stackoverflow.com/questions/71059123/pyreverse-not-showing-composition-relationships-in-the-umls-when-using-absolute | I am having trouble generating UMLs with pyreverse, in particular with composition relationships when classes are not part of the same module, and when using absolute imports. To illustrate the problem, I have the following two modules a.py and b.py in the same package: a.py: from b import B class A: def __init__(self,... | Edited answer following additional experimentation I'm not a python expert, but after a couple more experiments I think I get the information that you need First experiments : no package In my first experiment, I used several modules that were not in a package. It appeared when using different ways to do the imports th... | 6 | 4 |
71,117,478 | 2022-2-14 | https://stackoverflow.com/questions/71117478/vs-code-pylint-highlighting-the-whole-function-with-blue-underline-on-missing-fu | This just suddenly started happening where python pylint will highlight the whole function with blue squiggly lines when for a missing function docstring warning. How can I get it to only highlight the function definition or make a small indicator on the definition line. Its super annoying to get the whole file highlig... | A solution for this is being actively discussed and developed at the Pylint project. The workarounds until a fix is merged are either to use an earlier version of VS Code (before January 2022) or Pylint (below 2.12.2). If the latter is desired, you can download a local copy and specify a custom path to Pylint in the Py... | 6 | 7 |
71,113,116 | 2022-2-14 | https://stackoverflow.com/questions/71113116/modulenotfounderror-no-module-named-fastapi | Here is my file structure and requirements.txt: Getting ModuleNotFoundError, any help will be appreciated. main.py from fastapi import FastAPI from .import models from .database import engine from .routers import ratings models.Base.metadata.create_all(bind=engine) app = FastAPI() app.include_router(ratings.router) | The error comes from the fact that you were not using the right environment and python version on VSCODE. Your environment knew your different packages, but VSCode probably did not take them into account. The solution was, in VSCODE: CTRL + SHIFT + P then Python:select interpreter and choose the version of python linke... | 19 | 15 |
71,113,281 | 2022-2-14 | https://stackoverflow.com/questions/71113281/how-to-use-constructor-of-generic-type | How do I use the constructor of a python Generic typed class? T = typing.TypeVar('T') class MyClass(typing.Generic[T]): def __init__(self, initialValue: typing.Iterable): self.values: T = T(initialValue) test = MyClass[tuple[int]]([1, 2, 3]) In this case I am expecting T(initialValue) to be equivalent to tuple(initial... | You'll need to take an explicit factory method. Type annotations only exist for compile-time purposes, and at runtime that T is just a TypeVar. Consider class MyClass(Generic[T]): def __init__(self, initialValue: Iterable[int], factory: Callable[[Iterable[int]], T]): self.values: T = factory(initialValue) Then call it... | 5 | 2 |
71,106,529 | 2022-2-14 | https://stackoverflow.com/questions/71106529/cannot-import-pyi-file-in-stubs-package | I am trying to build a package of .pyi stub files, for use with type annotations. I have this structure: m/ __init__.pyi sub.pyi This works: >>> import m This does not (including in Python 3.10): >>> import m.sub ModuleNotFoundError: No module named 'm.sub' If I rename sub.pyi to sub.py, then I can import m.sub. Wha... | cf PEP 484 -- Type Hints : While stub files are syntactically valid Python modules, they use the .pyi extension to make it possible to maintain stub files in the same directory as the corresponding real module. This also reinforces the notion that no runtime behavior should be expected of stub files. The .pyi files a... | 5 | 5 |
71,079,342 | 2022-2-11 | https://stackoverflow.com/questions/71079342/how-can-i-take-comma-separated-inputs-for-python-anytree-module | Community. I need to accept multiple comma-separated inputs to produce a summary of information ( specifically, how many different employees participated in each group/project)? The program takes employees, managers and groups in the form of strings. I'm using anytree python library to be able to search/count the occur... | Leverage unpacking to extract elements. Then the if statement can be re-written this way. if io!='q': name, role, grp = io.upper(). split(',') lst_input.append([name,role, grp]) you also need to change lst.append(lst_input[i:i + 3]) in the for loop to this. lst.append(lst_input[0][i:i + 3]) | 6 | 5 |
71,104,319 | 2022-2-13 | https://stackoverflow.com/questions/71104319/postgresql-select-from-table-inside-docker-container-bash | I can access my postgresql db inside docker container and the see the postgresql bash with this command : docker exec -it <container-name> psql -U <dataBaseUserName> <dataBaseName> But I need to see the data I inserted to the table with the api. Is there a way to perform select statement here? | Whenever you access your container using the docker exec -it <container-name> psql -U <username> <database> you can run any PSQL-Query you like. To list all the tables within your database you can use \dt After you identified the table you want to query you can call any select, update or delete statement you like, e.... | 6 | 7 |
71,104,227 | 2022-2-13 | https://stackoverflow.com/questions/71104227/display-django-time-variable-as-full-hours-minutes-am-pm | I want to use a time variable instead of a CharField for a model, which displays multiple saved times. My issue is it displays as "9 am" instead of "9:00 am", and "noon" instead of "12:00 pm". Can anyone help? Thanks in advance. Relevant code below- models.py class Post(models.Model): time=models.TimeField() free=model... | You can achieve this by just using the built-in template datetime format like so: {{ post.time|date:"h:i A" }} This will display the datetime as: 09:00 AM. You can read more about this in the Django docs. | 5 | 4 |
71,102,012 | 2022-2-13 | https://stackoverflow.com/questions/71102012/python-how-to-solve-bracket-not-closed-error | following a tutorial I'm getting error "(" is not closed while using the exact same code: compiled_sol = compile_standard( { "language": "Solidity", "sources": {"SimpleStorage.sol": {"content" = simple_storage_file}} } ) don't know where it's going wrong getting these errors: "{" was not closedPylance Expected paramet... | try to replace "=" for ":" I hope this solves the problem. | 5 | 5 |
71,092,732 | 2022-2-12 | https://stackoverflow.com/questions/71092732/generating-new-unique-uuid4-in-django-for-each-object-of-factory-class | I have a Model Sector which has a id field (pk) which is UUID4 type. I am trying to populate that table(Sector Model) using faker and factory_boy. But, DETAIL: Key (id)=(46f0cf58-7e63-4d0b-9dff-e157261562d2) already exists. This is the error I am getting. Is it possible that the error is due to the fact that everytime... | just use like this: class SectorFactory(DjangoModelFactory): id = Faker('uuid4') name = Sequence(lambda n: f'Sector-{n}') class Meta: model = 'user.Sector' django_get_or_create = ['name'] | 6 | 10 |
71,086,270 | 2022-2-11 | https://stackoverflow.com/questions/71086270/no-module-named-virtualenv-activation-xonsh | I triyed to execute pipenv shell in a new environtment and I got the following error: Loading .env environment variables… Creating a virtualenv for this project… Using /home/user/.pyenv/shims/python3.9 (3.9.7) to create virtualenv… ⠋ModuleNotFoundError: No module named 'virtualenv.activation.xonsh' Error while trying t... | By github issue, the solution that works was the following: sudo apt-get remove python3-virtualenv | 32 | 20 |
71,053,839 | 2022-2-9 | https://stackoverflow.com/questions/71053839/vs-code-jupyter-not-connecting-to-python-kernel | Launching a cell will make this message appear: Connecting to kernel: Python 3.9.6 64-bit: Activating Python Environment 'Python 3.9.6 64-bit' This message will then stay up loading indefinitely, without anything happening. No actual error message. I've already tried searching for this problem, but every other post s... | Not sure what did the trick but downgrading VSCode to November version and after that reinstalling Jupyter extension worked for me. | 10 | 5 |
71,090,310 | 2022-2-12 | https://stackoverflow.com/questions/71090310/attributeerror-cant-get-attribute-unpickle-block | While using: with open("data_file.pickle", "rb") as pfile: raw_data = pickle.load(pfile) I get the error: AttributeError: Can't get attribute '_unpickle_block' on <module 'pandas._libs.internals' from '/opt/conda/lib/python3.8/site-packages/pandas/_libs/internals.cpython-38-x86_64-linux-gnu.so'> Another answer to a s... | I don't think the problem is pickle module but Pandas version. Your file was probably created with an older version of Pandas. Now you use a newer version, pickle can't "deserialize" the object because the API change. Try to downgrade your Pandas version and reload file. You can also try to use pd.read_pickle. | 30 | 26 |
71,087,163 | 2022-2-11 | https://stackoverflow.com/questions/71087163/screenshotting-the-windows-desktop-when-working-through-wsl | I'm primarily using Windows, where I run WSL2. So from a python script running in the subsystem, I would like to screenshot whatever is on windows monitor, as simple as such: v1 import mss import os os.environ['DISPLAY'] = ':0' with mss.mss() as sct: sct.shot() This gives only gives "Segmentation fault" error and no i... | The problem with your attempted solution is that the WSL/Linux Python's mss, as you've found, isn't able to capture the Windows desktop. Being the Linux version of MSS, it will only be able to communicate with Linux processes and protocols like X. Starting up VcXsrv might get you part of the way there, in that you migh... | 6 | 2 |
71,082,435 | 2022-2-11 | https://stackoverflow.com/questions/71082435/conversionerror-failed-to-convert-values-to-axis-units-2015-01-01 | I am trying to convert values to axis units. I checked codes with similar problems but none addressed this specific challenge. As can be seen in the image below, expected plot (A) was supposed to show month (Jan, Feb etc.) on the x-axis, but it was showing dates (2015-01 etc) in plot (B). Below is the source code, kin... | A wise way to draw the plot with datetime is to use datetime format in place of str; so, first of all, you should do this conversion: df = pd.read_csv(r'data/frankfurt_weather.csv') df['time'] = pd.to_datetime(df['time'], format = '%Y-%m-%d %H:%M') Then you can set up the plot as you please, preferably following Objec... | 6 | 8 |
71,075,798 | 2022-2-11 | https://stackoverflow.com/questions/71075798/include-one-yaml-file-inside-another | I want to have a base config file which is used by other config files to share common config. E.g if I have one file base.yml with foo: 1 bar: - 2 - 3 And then a second file some_file.yml with foo: 2 baz: "baz" What I'd want to end up with a merged config file with foo: 2 bar: - 2 - 3 baz: "baz" It's easy enough to ... | In YAML you cannot mix scalars, mapping keys and sequence elements. This is invalid YAML: - abc d: e and so is this some_file_name a: b and that you have that scalar quoted, and provide a tag does of course not change the fact that it is invalid YAML. As you can already found out, you can trick the loader into return... | 5 | 3 |
71,078,751 | 2022-2-11 | https://stackoverflow.com/questions/71078751/vs-code-python-formatting-change-max-line-length-with-autopep8-yapf-black | I am experimenting with different python formatters and would like to increase the max line length. Ideally without editing the settings.json file. Is there a way to achieve that? | For all three formatters, the max line length can be increased with additional arguments passed in from settings, i.e.: autopep8 args: --max-line-length=120 black args: --line-length=120 yapf args: --style={based_on_style: google, column_limit: 120, indent_width: 4} Hope that helps someone in the future! | 24 | 67 |
71,077,943 | 2022-2-11 | https://stackoverflow.com/questions/71077943/how-many-processors-should-be-used-with-multiprocessing-pool | I am trying to use multiprocessing.Pool to run my code in parallel. To instantiate Pool, you have to set the number of processes. I am trying to figure out how many I should set for this. I understand this number shouldn't be more than the number of cores you have but I've seen different ways to determine what your sys... | The difference between the two is clearly stated in the doc: multiprocessing.cpu_count() Return the number of CPUs in the system. This number is not equivalent to the number of CPUs the current process can use. The number of usable CPUs can be obtained with len(os.sched_getaffinity(0)). So even if you are on a 128-co... | 5 | 4 |
71,071,355 | 2022-2-10 | https://stackoverflow.com/questions/71071355/no-numeric-types-to-aggregate-while-using-pandas-expanding | In Pandas 1.1.4, I am receiving a DataError: No numeric types to aggregate when using an ExpandingGroupby. Example dataset: tmp = pd.DataFrame({'col1':['a','b','b','c','d','d'], 'col2': ['red','red','green','green','red','blue']}) print(tmp) col1 col2 a red b red b green c green d red d blue This works: tmp.groupby('c... | You can use accumulate from itertools module: from itertools import accumulate concat = lambda *args: ','.join(args) expand = lambda x: list(accumulate(x, func=concat)) df['col3'] = df.groupby('col1')['col2'].transform(expand) print(df) # Output col1 col2 col3 0 a red red 1 b red red 2 b green red,green 3 c green green... | 5 | 1 |
71,058,732 | 2022-2-10 | https://stackoverflow.com/questions/71058732/how-to-load-transformers-pipeline-from-folder | According to here pipeline provides an interface to save a pretrained pipeline locally with a save_pretrained method. When I use it, I see a folder created with a bunch of json and bin files presumably for the tokenizer and the model. But the documentation does not specify a load method. How does one initialize a pipel... | Apparently the default initialization works with local folders as well. So one can download a model like this: pipe = pipeline("text-classification") pipe.save_pretrained("my_local_path") And later load it like pipe = pipeline("text-classification", model = "my_local_path") | 13 | 18 |
71,058,888 | 2022-2-10 | https://stackoverflow.com/questions/71058888/zoneinfonotfounderror-no-time-zone-found-with-key-utc | While trying to load my webpage on the browser, I got the message. A server error occurred. Please contact the administrator And when I go back to check my termimal, I see the message zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key UTC' I have checked but don't know what's wrong. I even tried c... | Add tzdata to your requirements or pip install tzdata | 28 | 70 |
71,062,983 | 2022-2-10 | https://stackoverflow.com/questions/71062983/accessing-the-data-interval-of-a-dag-run-inside-a-task | I'm building an ETL pipeline with Apache Airflow. I have to extract the latest data added to a SQL database (say daily). Therefore, I want to construct a query as follows: SELECT foo FROM bar WHERE insert_date >= "DATA_INTERVAL_START_HERE" AND insert_date < "DATA_INTERVAL_END_HERE" To execute this query in a task (wit... | A similar question was asked here: Airflow ETL pipeline - using schedule date in functions? However, the answer is not updated to the TaskFlow API since Airflow 2.0. A concise way to access the data interval parameters: @dag(schedule_interval="@daily", start_date=datetime(2022, 2, 8), catchup=True) def tutorial_access_... | 6 | 6 |
71,043,378 | 2022-2-9 | https://stackoverflow.com/questions/71043378/unable-to-create-process-using-python-exe-error-in-virtual-environment | I'm unable to use python within the virtual environment. Python works fine outside of the virtual environment. I'm using Python 3.10.2 I keep on getting the error below when trying to run any python commands. 'C:\Users\User\AppData\Local\Programs\Python\Python310\python.exe' It might be relevant to mention that I was ... | Short answer, I bet you have a space in your Window's account name (say Your Account is where your account is saved so you have C:\Users\Your Account folder, and there is also a text file C:\Users\Your ("Your" being the first part of your user name). MSVS2022 (maybe earlier versions, too) is known to leave this log fil... | 6 | 27 |
71,050,697 | 2022-2-9 | https://stackoverflow.com/questions/71050697/transformers-how-to-use-cuda-for-inferencing | I have fine-tuned my models with GPU but inferencing process is very slow, I think this is because inferencing uses CPU by default. Here is my inferencing code: txt = "This was nice place" model = transformers.BertForSequenceClassification.from_pretrained(model_path, num_labels=24) tokenizer = transformers.BertTokenize... | You should transfer your input to CUDA as well before performing the inference: device = torch.device('cuda') # transfer model model.to(device) # define input and transfer to device encoding = tokenizer.encode_plus(txt, add_special_tokens=True, truncation=True, padding="max_length", return_attention_mask=True, return_t... | 9 | 13 |
71,050,098 | 2022-2-9 | https://stackoverflow.com/questions/71050098/how-is-cpython-implemented | So I lately came across an explanation for Python's interpreter and compiler (CPython specifically). Please correct me if I'm wrong. I just want to be sure I understand these specific concepts. So CPython gets both compiled (to bytecode) and then interpreted (in the PVM)? And what does the PVM do exactly? Does it read ... | Yes, CPython is compiled to bytecode which is then executed by the virtual machine. The virtual machine executes instructions one-by-one. It's written in C (but you can write it in another language) and looks like a huge if/else statement like "if the current instruction is this, do this; if the instruction is this, d... | 5 | 5 |
71,048,056 | 2022-2-9 | https://stackoverflow.com/questions/71048056/pandas-to-sql-create-table-permission-denied | I am trying to write a df to an existing table with pandas.to_sql with this code: import sqlalchemy #CREATE CONNECTION constring = "mssql+pyodbc://UID:PASSWORD@SERVER/DATABASE?driver=SQL Server" dbEngine = sqlalchemy.create_engine(constring, fast_executemany=True, connect_args={'connect_timeout':10}, echo=False) #WRITE... | You might need to add create permission to the SQL Server user. You can follow below steps from the link: To add a Windows user that has the login “domainname \username” to the sysadmin fixed server role a. Log on to the computer using the credentials for the domainname\username account. b. Click the Start button, poi... | 5 | 1 |
70,951,929 | 2022-2-2 | https://stackoverflow.com/questions/70951929/how-come-an-abstract-base-class-in-python-can-be-instantiated | It is very surprising to me that I can instantiate an abstract class in python: from abc import ABC class Duck(ABC): def __init__(self, name): self.name = name if __name__=="__main__": d = Duck("Bob") print(d.name) The above code compiles just fine and prints out the expected result. Doesn't this sort of defeat the pu... | If you have no abstract method, you will able to instantiate the class. If you have at least one, you will not. Consider the following code: from abc import ABC, abstractmethod class Duck(ABC): def __init__(self, name): self.name = name @abstractmethod def implement_me(self): ... if __name__=="__main__": d = Duck("Bob"... | 5 | 9 |
70,975,344 | 2022-2-3 | https://stackoverflow.com/questions/70975344/how-to-post-json-data-to-fastapi-and-retrieve-the-json-data-inside-the-endpoint | I would like to pass a JSON object to a FastAPI backend. Here is what I am doing in the frontend app: data = {'labels': labels, 'sequences': sequences} response = requests.post(api_url, data = data) Here is how the backend API looks like in FastAPI: @app.post("/api/zero-shot/") async def Zero_Shot_Classification(reque... | You should use the json parameter instead (which would change the Content-Type header to application/json): payload = {'labels': labels, 'sequences': sequences} r = requests.post(url, json=payload) not data which is used for sending form data with the Content-Type being application/x-www-form-urlencoded by default, or... | 8 | 7 |
70,952,692 | 2022-2-2 | https://stackoverflow.com/questions/70952692/how-to-customize-error-response-in-fastapi | I have the following FastAPI backend: from fastapi import FastAPI app = FastAPI class Demo(BaseModel): content: str = None @app.post("/demo") async def demoFunc(d:Demo): return d.content The issue is that when I send a request to this API with extra data like: data = {"content":"some text here"}aaaa or data = {"conte... | You are passing an invalid JSON, and hence, the server correctly responds with the 422 Unprocessable Entity error. Your test client shouldn't be able to run at all, without throwing an invalid syntax error. So, I'm guessing you posted the request through the interactive autodocs provided by Swagger UI at /docs, and rec... | 6 | 9 |
70,968,749 | 2022-2-3 | https://stackoverflow.com/questions/70968749/pandas-replace-equivalent-in-python-polars | Is there an elegant way how to recode values in polars dataframe. For example 1->0, 2->0, 3->1... in Pandas it is simple like that: df.replace([1,2,3,4,97,98,99],[0,0,1,1,2,2,2]) | Edit 2024-07-09 Polars has dedicated replace and replace_strict expressions. df = pl.DataFrame({ "a": [1, 2, 3, 4, 5] }) mapper = { 1: 0, 2: 0, 3: 10, 4: 10 } df.select( pl.all().replace(mapper) ) shape: (5, 1) ┌─────┐ │ a │ │ --- │ │ i64 │ ╞═════╡ │ 0 │ │ 0 │ │ 10 │ │ 10 │ │ 5 │ └─────┘ Before Edit In polars you can... | 16 | 29 |
71,029,876 | 2022-2-8 | https://stackoverflow.com/questions/71029876/how-can-i-perform-a-type-guard-on-a-property-of-an-object-in-python | PEP 647 introduced type guards to perform complex type narrowing operations using functions. If I have a class where properties can have various types, is there a way that I can perform a similar type narrowing operation on the property of an object given as the function argument? class MyClass: """ If `a` is `None` th... | TypeGuard annotations can be used to annotate subclasses of a class. If parameter types are specified for those classes, then MyPy will recognise the type narrowing operation successfully. class MyClass: a: Optional[int] b: Optional[str] # Some other things # Two hidden classes for the different types class _MyClassInt... | 13 | 10 |
70,977,935 | 2022-2-3 | https://stackoverflow.com/questions/70977935/why-do-i-receive-unable-to-get-local-issuer-certificate-ssl-c997 | When sending a request to a specific URL I get an SSL error and I am not sure why. First please see the error message I am presented with: requests.exceptions.SSLError: HTTPSConnectionPool(host='dicmedia.korean.go.kr', port=443): Max retries exceeded with url: /multimedia/naver/2016/40000/35000/14470_byeon-gyeong.wav ... | The problem was that not all certificates needed were included in Python's cacert.pem file. To tackle this I downloaded the certifi module at first. As this didn't work out as well I suppose as certifi also missed the necessary certificates. But I suppose not all certificates in the certificate where missing. As answer... | 10 | 14 |
71,011,161 | 2022-2-6 | https://stackoverflow.com/questions/71011161/compare-two-polars-dataframes-for-equality | How do I compare two polars DataFrames for value equality? It appears that == is only true if the two tables are the same object: import polars as pl pl.DataFrame({"x": [1,2,3]}) == pl.DataFrame({"x": [1,2,3]}) # False | It's the equals method of DataFrame: import polars as pl pl.DataFrame({"x": [1,2,3]}).frame_equal(pl.DataFrame({"x": [1,2,3]})) # True Before version 0.19.16, it was called frame_equals. | 12 | 7 |
70,953,357 | 2022-2-2 | https://stackoverflow.com/questions/70953357/how-to-verify-jwt-produced-by-azure-ad | Problem When I receive a JWK from Azure AD in Python, I would like to validate and decode it. I, however, keep getting the error "Signature verification failed". My Setup I have the following setup: Azure Setup In Azure I have created an app registration with the setting "Personal Microsoft accounts only". Python Setu... | There are at least 2 options to decode Microsoft Azure AD ID tokens: Option 1: Using jwt The code provided by OP gives me the exception InvalidIssuerError. Even replacing the issuer argument by https://login.microsoftonline.com/{your-tenant-id} did not work for me. However omitting this argument all together allowed me... | 11 | 2 |
70,966,298 | 2022-2-3 | https://stackoverflow.com/questions/70966298/python-black-code-formatter-doesnt-format-docstring-line-length | I am running the Black code formatter against a Python script however it doesn't reformat the line length for docstrings. For example, given the following code: def my_func(): """ This is a really long docstring. This is a really long docstring. This is a really long docstring. This is a really long docstring. This is ... | maintainer here! :wave: The short answer is no you cannot configure Black to fix line length issues in docstrings currently. It's not likely Black will split or merge lines in docstrings as it would be far too risky, structured data can and does exist in docstrings. While I would hope the added newlines wouldn't break ... | 33 | 48 |
71,031,816 | 2022-2-8 | https://stackoverflow.com/questions/71031816/how-do-you-properly-reuse-an-httpx-asyncclient-within-a-fastapi-application | I have a FastAPI application which, in several different occasions, needs to call external APIs. I use httpx.AsyncClient for these calls. The point is that I don't fully understand how I shoud use it. From httpx' documentation I should use context managers, async def foo(): """" I need to call foo quite often from diff... | You can have a global client that is closed in the FastApi shutdown event. import logging from fastapi import FastAPI import httpx logging.basicConfig(level=logging.INFO, format="%(levelname)-9s %(asctime)s - %(name)s - %(message)s") LOGGER = logging.getLogger(__name__) class HTTPXClientWrapper: async_client = None def... | 24 | 15 |
70,975,237 | 2022-2-3 | https://stackoverflow.com/questions/70975237/strange-autocomplete-suggestions-in-ipython-shell | I use the IPython shell fairly often and have just started to notice it giving me strange autocomplete suggestions without any prompting from me. In this example, I just typed "im" and it suggests importing matplotlib? This is very strange for several reasons: I've never seen this kind of grayed out code suggestion be... | Try this. import IPython terminal = IPython.get_ipython() terminal.pt_app.auto_suggest = None https://github.com/ipython/ipython/issues/13451 | 5 | 5 |
70,977,165 | 2022-2-3 | https://stackoverflow.com/questions/70977165/how-to-use-loguru-defaults-and-extra-information | I'm still reaseaching about Loguru, but I can't find an easy way to do this. I want to use the default options from Loguru, I believe they are great, but I want to add information to it, I want to add the IP of a request that will be logged. If I try this: import sys from loguru import logger logger.info("This is log i... | I made the same question in the Github Repository and this was the answer by Delgan (Loguru maintainer): I think you simply need to add() your handler using a custom format containing the extra information. Here is an example: logger_format = ( "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | " "<level>{level: <8}</lev... | 19 | 29 |
71,042,138 | 2022-2-8 | https://stackoverflow.com/questions/71042138/docker-and-playwright | I need to install playwright inside of docker. This is my dockerfile. FROM python:3.9 EXPOSE 8000 WORKDIR /fastanalytics COPY /requirements.txt /fastanalytics/requirements.txt RUN pip install --no-cache-dir --upgrade -r /fastanalytics/requirements.txt RUN playwright install RUN playwright install-deps RUN apt-get updat... | Microsoft released a python docker image for Playwright Dockerfile # Build Environment: Playwright FROM mcr.microsoft.com/playwright/python:v1.21.0-focal # Add python script to Docker COPY index.py / # Run Python script CMD [ "python", "index.py" ] Check Playwright - Docker docs for the latest playwright version. | 14 | 18 |
70,958,081 | 2022-2-2 | https://stackoverflow.com/questions/70958081/include-indices-in-pandas-groupby-results | With Pandas groupby, I can do things like this: >>> df = pd.DataFrame( ... { ... "A": ["foo", "bar", "bar", "foo", "bar"], ... "B": ["one", "two", "three", "four", "five"], ... } ... ) >>> print(df) A B 0 foo one 1 bar two 2 bar three 3 foo four 4 bar five >>> print(df.groupby('A')['B'].unique()) A bar [two, three, fiv... | You do not necessarily need to have a label in groupby, you can use a grouping object. This enables things like: df.index.to_series().groupby(df['A']).unique() output: A bar [1, 2, 4] foo [0, 3] dtype: object getting the indices of the unique B values: df[~df[['A', 'B']].duplicated()].index.to_series().groupby(df['A'... | 7 | 4 |
71,023,429 | 2022-2-7 | https://stackoverflow.com/questions/71023429/unexpected-result-when-using-list-append-what-am-i-doing-wrong | I can't understand the following two examples of behaviour of list.append() in Python: list_1 = ['A', 'B'] list_2 = ['C', 'D'] copy_l1 = list_1 copy_l1.append(list_2) Example print(copy_l1) result: ['A', 'B', ['C', 'D']] expected: ['A', 'B', 'C', 'D']. I kind of understand this, but how to get the expected result? ... | The first result is expected as you are adding the list itself, not its values, to copy_l1. To get the desired result, use either of the following: copy_l1 += list2 copy_l1.extend(list2) The second result is harder to understand, but it has to do with the fact that lists are mutable in Python. To understand this, yo... | 5 | 6 |
70,998,452 | 2022-2-5 | https://stackoverflow.com/questions/70998452/warning-ignoring-invalid-distribution-c-python310-lib-site-packages | Whenever I install a pip library in Python, I get a series of warnings. For example : WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages) WARNING: Ignoring invalid distribution - (c:\python310\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages) WARNING... | the warning below: can fix as follows. go to the lib\site-packages folder, then look for folders starting with ~ like what you see in the picture below and mentioned in that warning, then remove them this can be fixed this warning and no longer appears | 21 | 40 |
70,997,997 | 2022-2-5 | https://stackoverflow.com/questions/70997997/not-able-to-save-plotly-plots-using-to-image-or-write-image | fig.write_image("images/fig1.png",format='png',engine='kaleido') This makes my VSCode go bananas, the terminal hangs and the program stops then and there. Everything works fine if I remove just that line. I want to save the plots as pngs, but it is not working. I have kaleido installed. | Try this version of kaleido. pip install kaleido==0.1.0post1 It works for me | 24 | 37 |
70,958,434 | 2022-2-2 | https://stackoverflow.com/questions/70958434/unexpected-python-paths-in-conda-environment | In a Conda environment (base here), I'm surprised by the order of directories in the Python path: python -c "import sys; print(sys.path)" ['', '/export/projects/III-data/wcmp_bioinformatics/db291g/miniconda3/lib/python37.zip', '/export/projects/III-data/wcmp_bioinformatics/db291g/miniconda3/lib/python3.7', '/export/pro... | This is expected behavior (see PEP 370) and partially why Anaconda recommended against user-level package installations. The site module is responsible for setting the sys.path when Python is initializing. The code in site.py specifically appends the user site prior to appending the prefix site, which is what leads to ... | 9 | 12 |
70,967,266 | 2022-2-3 | https://stackoverflow.com/questions/70967266/what-exactly-is-python-typing-callable | I have seen typing.Callable, but I didn't find any useful docs about it. What exactly is typing.Callable? | typing.Callable is the type you use to indicate a callable. Most python types that support the () operator are of the type collections.abc.Callable. Examples include functions, classmethods, staticmethods, bound methods and lambdas. In summary, anything with a __call__ method (which is how () is implemented), is a call... | 50 | 55 |
71,027,763 | 2022-2-8 | https://stackoverflow.com/questions/71027763/how-to-open-a-new-mdi-sub-window-in-pyqt5 | What I want to do is to open a new Countrypage sub-window by clicking on the "New" button which is in Countrypage itself. For example, if I click the "New" button in a CountryPage window (window title: "Country page"), one more new Countrypage window will be opened in the MDI area (window title: "Country Page 1"). Now ... | The adding and closing of sub-windows is best handled by the main-window. The CountryPage class doesn't need to know anything about the sub-windows. The new/close buttons can be directly connected to methods of the main-window. This makes it easier to manage the sub-windows via the functions of the mdi-area. Below is a... | 6 | 3 |
70,964,954 | 2022-2-3 | https://stackoverflow.com/questions/70964954/filter-out-everything-before-a-condition-is-met-keep-all-elements-after | I was wondering if there was an easy solution to the the following problem. The problem here is that I want to keep every element occurring inside this list after the initial condition is true. The condition here being that I want to remove everything before the condition that a value is greater than 18 is true, but ke... | You could use enumerate and list slicing in a generator expression and next: out = next((p[i:] for i, item in enumerate(p) if item > 18), []) Output: [20, 13, 29, 3, 39] In terms of runtime, it depends on the data structure. The plots below show the runtime difference among the answers on here for various lengths of... | 26 | 23 |
71,039,820 | 2022-2-8 | https://stackoverflow.com/questions/71039820/retrieve-the-pytorch-model-from-a-pytorch-lightning-model | I have trained a PyTorch lightning model that looks like this: In [16]: MLP Out[16]: DecoderMLP( (loss): RMSE() (logging_metrics): ModuleList( (0): SMAPE() (1): MAE() (2): RMSE() (3): MAPE() (4): MASE() ) (input_embeddings): MultiEmbedding( (embeddings): ModuleDict( (LCLid): Embedding(5, 4) (sun): Embedding(5, 4) (day_... | You can manually save the weights of the torch.nn.Modules in the LightningModule. Something like: trainer.fit(model, trainloader, valloader) torch.save( model.input_embeddings.state_dict(), "input_embeddings.pt" ) torch.save(model.mlp.state_dict(), "mlp.pt") Then to load without needing Lightning: # create the "blank"... | 6 | 6 |
71,035,556 | 2022-2-8 | https://stackoverflow.com/questions/71035556/how-to-do-n-point-circular-convolution-for-1d-signal-with-numpy | I want a circular convolution function where I can set the number N as I like. All examples I looked at like here and here assume that full padding is required but that not what I want. I want to have the result for different values of N so input would N and and two different arrays of values the output should be the ... | I think that this should work: def conv(x1, x2, N): n, m = np.ogrid[:N, :N] return (x1[:N] * x2[(n - m) % N]).sum(axis=1) This is a direct translation of the formula posted in the question: To implement this formula, first we compute an array of indices used by x₂. This is done using the code n, m = np.ogrid[:N, :N] ... | 6 | 3 |
71,039,131 | 2022-2-8 | https://stackoverflow.com/questions/71039131/windows-python-3-10-2-fails-to-run-python-m-venv-venv | This issue has been solved, resulted in a bug report to Python.org. See the my self-answer below for the workaround until it's fixed in a future release of Python One of my PCs got bitten by this bug which no longer allows me to create venv with the error: Error: Command '['C:\\Users\\kesh\\test\\.venv\\Scripts\\python... | Bingo, the finding in the update #1 was the cause. The space in my username was the culprit. Although I have no idea what triggered this behavior change on my account... (anybody with an answer, please follow up.) Let's say the per-user python is installed at C:\Users\User Name\AppData\Local\Programs\Python\Python310 ... | 8 | 18 |
70,993,385 | 2022-2-4 | https://stackoverflow.com/questions/70993385/how-to-add-kaleido-package-to-poetry-lock-file | When attempting to install "kaleido" via Poetry, I receive the following error message: ~ poetry add kaleido Using version ^0.2.1 for kaleido Updating dependencies Resolving dependencies... (3.1s) Package operations: 1 install, 0 updates, 0 removals • Installing kaleido (0.2.1.post1): Failed RuntimeError Unable to find... | Firstly try to use a master version of poetry as advised in Github issue or upgrade it to the latest version pip3 install --upgrade poetry Then try to install with kaleido with locked version: poetry add kaleido==0.2.1 That worked in my case. | 11 | 30 |
70,993,316 | 2022-2-4 | https://stackoverflow.com/questions/70993316/get-feature-names-after-sklearn-pipeline | I want to match the output np array with the features to make a new pandas dataframe Here is my pipeline: from sklearn.pipeline import Pipeline # Categorical pipeline categorical_preprocessing = Pipeline( [ ('Imputation', SimpleImputer(missing_values=np.nan, strategy='most_frequent')), ('Ordinal encoding', OrdinalEncod... | Point is that, as of today, some transformers do expose a method .get_feature_names_out() and some others do not, which generates some problems - for instance - whenever you want to create a well-formatted DataFrame from the np.array outputted by a Pipeline or ColumnTransformer instance. (Instead, afaik, .get_feature_n... | 8 | 6 |
71,041,284 | 2022-2-8 | https://stackoverflow.com/questions/71041284/how-to-create-an-array-or-list-column-in-sqlalchemy-model | I know it's possible to create array of string in postgres but I want to create a model in sqlalchemy that contains a list or array column but I don't know how Please view the code below class Question(Base): __tablename__= 'questions' id = Column(Integer, nullable=False, primary_key=True) question = Column(String,null... | You need to use: from sqlalchemy.dialects.postgresql import ARRAY Here: from datetime import datetime from sqlalchemy import * from sqlalchemy.dialects.postgresql import ARRAY from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Question1(Base): __tablename__= 'questions' id = Column... | 5 | 5 |
71,041,586 | 2022-2-8 | https://stackoverflow.com/questions/71041586/typeerror-type-object-is-not-subscriptable | I’m trying to get the function below to run. However I’m getting an error saying TypeError: ‘type’ object is not subscriptable def dist(loc1: tuple[float], loc2: tuple[float]) -> float: dx = loc1[0] - loc2[0] dy = loc1[1] - loc2[1] return (dx**2 + dy**2)**0.5 | You need to use typing.Tuple, not the tuple class. from typing import Tuple def dist(loc1: Tuple[float], loc2: Tuple[float]) -> float: dx = loc1[0] - loc2[0] dy = loc1[1] - loc2[1] return (dx**2 + dy**2)**0.5 dist((1,2),(2,1)) # output 1.4142135623730951 | 8 | 14 |
71,034,111 | 2022-2-8 | https://stackoverflow.com/questions/71034111/how-to-set-default-python3-to-python-3-9-instead-of-python-3-8-in-ubuntu-20-04-l | I have installed Python 3.9 in the Ubuntu 20.04 LTS. Now the system has both Python 3.8 and Python 3.9. # which python # which python3 /usr/bin/python3 # which python3.8 /usr/bin/python3.8 # which python3.9 /usr/bin/python3.9 # ls -alith /usr/bin/python3 12583916 lrwxrwxrwx 1 root root 9 Jul 19 2021 /usr/bin/python3 ->... | You should be able to use python3.9 -m pip install <package> to run pip with a specific python version, in this case 3.9. The full docs on this are here: https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/ If you want python3 to point to python3.9 you could use the quick and dirty. alias ... | 31 | 28 |
71,029,800 | 2022-2-8 | https://stackoverflow.com/questions/71029800/how-to-dynamically-change-the-scale-ticks-of-y-axis-in-plotly-charts-upon-zoomin | I am trying to make a candle stick chart using plotly. I am using stock data spanning over 10 years. Due to this the candles appear very small as the y axis has a large scale. However if I zoom into a smaller time period (lets say any 1 month in the 10 years) I want the y axis scale to change so that the candle looks b... | This approach uses a callback with dash to set the range of y-axis based on values selected in range slider. A significant amount of the code is making your figure an MWE (calc RSI_14) import pandas_datareader as pdr from plotly.subplots import make_subplots import plotly.graph_objects as go import numpy as np import d... | 9 | 7 |
71,031,173 | 2022-2-8 | https://stackoverflow.com/questions/71031173/type-hinting-for-a-function-wrapping-another-function-accepting-the-same-argume | def function(a: int, b: str) -> None: pass def wrapper(extra: int, *args, **kwargs) -> None: do_something_with_extra(extra) function(*args, **kwargs) Is there an easy way for wrapper to inherit function()'s type hints without retyping all of them? Normally I'd write def wrapper(extra: int, a: int, b: str) -> None: Bu... | The best that you can do is to use a decorator for this purpose, and you can use Concatenate and ParamSpec. I use python 3.8 and I had to install typing_extensions for them. In the code below, if you type function in VSCode, it will show the int argument but without the "extra" name in front of it. from typing import C... | 11 | 6 |
71,024,254 | 2022-2-7 | https://stackoverflow.com/questions/71024254/jupyter-kernel-dies-when-importing-pipeline-function-from-transformers-class-on | I'm unable to import pipeline function of transformers class as my jupyter kernel keeps dying. Tried on transformers-4.15.0 and 4.16.2. Anyone faced this issue? I tried importing the class in a new notebook as you can see in the image and it keeps killing the kernel. | It works fine for me. You could try creating a fresh conda environment and reinstalling the app. You could also try using jupyterlab instead of jupyter-notebook. Are you on Mac OS? I couldn't get it to run at first using conda install transformers my jupyterlab kept hanging as well. Then I did this, conda install -c h... | 5 | 2 |
71,027,193 | 2022-2-8 | https://stackoverflow.com/questions/71027193/datetimeindex-get-loc-is-deprecated | I updated Pandas to 1.4.0 with yfinance 0.1.70. Previously, I had to stay with Pandas 1.3.5 as Pandas and yfinance did't play well together. These latest versions of Pandas and yfinance now work together, BUT Pandas now gives me this warning: Future Warning: Passing method to DatetimeIndex.get_loc is deprecated... Use ... | Should be pretty simple. Just change get_loc(XXX, ...) to get_indexer([XXX], ...)[0]: last_week = format((df.index[df.index.get_indexer([last_week], method='nearest')[0]]).strftime('%Y-%m-%d')) | 7 | 13 |
71,022,619 | 2022-2-7 | https://stackoverflow.com/questions/71022619/pre-commit-vs-tox-whats-the-difference-scope-of-use | Tox: https://tox.wiki/en/latest/ pre-commit: https://pre-commit.com/ I would like to understand the borders for both choices. I know that pre-commit creates a py environment - same as tox. To me, their architecture looks a bit the same. Some people use them in combination... what pre-commit can't do, that tox can? I sa... | In short, pre-commit is a linter/formatter runner, tox is a generic virtual env management and test command line tool. While tox could run linters too, it is tedious to manage the versions of the linters. In pre-commit you can just run pre-commit autoupdate, and all linters get updated. On the other hand tox can run e.... | 6 | 16 |
71,020,663 | 2022-2-7 | https://stackoverflow.com/questions/71020663/measuring-coverage-in-python-threads | I am trying to measure code coverage with a code that uses threads created by the python threading module. I am using coverage to measure coverage. However I can not get the code that is run within a thread to get measured. I tried following the suggestion on the coverage docs to measure coverage in subprocesses but no... | You need to specify "thread" as part of your concurrency setting: concurrency = multiprocessing,thread I'm not sure you need multiprocessing. Your sample program doesn't use it, maybe your real program doesn't either. | 5 | 6 |
71,022,591 | 2022-2-7 | https://stackoverflow.com/questions/71022591/pandas-replace-values-in-column-with-the-last-character-in-the-column-name | I have a dataframe as follows: import pandas as pd df = pd.DataFrame({'sent.1':[0,1,0,1], 'sent.2':[0,1,1,0], 'sent.3':[0,0,0,1], 'sent.4':[1,1,0,1] }) I am trying to replace the non-zero values with the 5th character in the column names (which is the numeric part of the column names), so the output should be, sent.1... | Since you're dealing with 1's and 0's, you can actually just use multiply the dataframe by a range: df = df * range(1, df.shape[1] + 1) Output: sent.1 sent.2 sent.3 sent.4 0 0 0 0 4 1 1 2 0 4 2 0 2 0 0 3 1 0 3 4 Or, if you want to take the numbers from the column names: df = df * df.columns.str.split('.').str[-1].as... | 5 | 3 |
71,019,671 | 2022-2-7 | https://stackoverflow.com/questions/71019671/vscode-python-debugger-stops-suddenly | after installing Windows updates today, debugging is not working anymore. This is my active debug configuration: "launch": { "version": "0.2.0", "configurations": [ { "name": "DEBUG CURR", "type": "python", "request": "launch", "program": "${file}", "console": "internalConsole", "justMyCode": false, "stopOnEntry": fals... | It's an issue with the latest Python Extension for VSCode. Downgrading the python extension to v2021.12.1559732655 fixes the problem. | 16 | 21 |
71,011,333 | 2022-2-6 | https://stackoverflow.com/questions/71011333/runtimeerror-stack-expects-each-tensor-to-be-equal-size-but-got-7-768-at-en | When running this code: embedding_matrix = torch.stack(embeddings) I got this error: RuntimeError: stack expects each tensor to be equal size, but got [7, 768] at entry 0 and [8, 768] at entry 1 I'm trying to get embedding using BERT via: split_sent = sent.split() tokens_embedding = [] j = 0 for full_token in split_... | As per PyTorch Docs about torch.stack() function, it needs the input tensors in the same shape to stack. I don't know how will you be using the embedding_matrix but either you can add padding to your tensors (which will be a list of zeros at the end till a certain user-defined length and is recommended if you will trai... | 6 | 6 |
70,953,743 | 2022-2-2 | https://stackoverflow.com/questions/70953743/reinterpreting-numpy-arrays-as-a-different-dtype | Say I have a large NumPy array of dtype int32 import numpy as np N = 1000 # (large) number of elements a = np.random.randint(0, 100, N, dtype=np.int32) but now I want the data to be uint32. I could do b = a.astype(np.uint32) or even b = a.astype(np.uint32, copy=False) but in both cases b is a copy of a, whereas I wa... | Is this legitimate? Can you point me to where this feature is documented? This is legitimate. However, using np.view (which is equivalent) is better since it is compatible with a static analysers (so it is somehow safer). Indeed, the documentation states: It’s possible to mutate the dtype of an array at runtime. [... | 9 | 11 |
71,012,012 | 2022-2-6 | https://stackoverflow.com/questions/71012012/modulenotfounderror-no-module-named-transformers | This is my first post and I am new to coding, so please let me know if you need more information. I have been running some AI to generate artwork and it has been working, but when I reloaded it the python script won't work and it is now saying "No module named 'transformers'". Can anyone help me out? It was when I upgr... | Probably it is because you have not installed in your (new, since you've upgraded to colabs pro) session the library transformers. Try to run as first cell the following: !pip install transformers (the "!" at the beginning of the instruction is needed to go into "terminal mode" ). This will download the transformers pa... | 31 | 32 |
71,010,343 | 2022-2-6 | https://stackoverflow.com/questions/71010343/cannot-load-swrast-and-iris-drivers-in-fedora-35 | Essentially, trying to write the following code results in the error below: Code from matplotlib import pyplot as plt plt.plot([1,2,3,2,1]) plt.show() Error libGL error: MESA-LOADER: failed to open iris: /home/xxx/.conda/envs/stat/lib/python3.8/site-packages/pandas/_libs/window/../../../../../libstdc++.so.6: version `... | Short answer: export LD_PRELOAD=/usr/lib64/libstdc++.so.6 Long answer: The underlying problem is that we have a piece of software that was built with an older C++ compiler. Part of the compiler is its implementation of libstdc++ which becomes part of the runtime requirements for anything built by the compiler. The soft... | 33 | 22 |
71,003,828 | 2022-2-6 | https://stackoverflow.com/questions/71003828/is-there-a-way-to-have-a-default-value-inside-a-dictionary-in-python | I want to know if there is a way to have a default value in a dictionary (without using the get function), so that: dict colors = { "Black":(0, 0, 0), "White":(255, 255, 255), default:(100, 100, 100) }; paint(colors["Blue"]); # Paints the default value (Grey) onto the screen Of course, the code above wouldn't work in ... | You can use a defaultdict. from collections import defaultdict colors = defaultdict(lambda: (100, 100, 100)) colors["Black"] = (0, 0, 0), colors["White"] = (255, 255, 255) # Prints (0, 0, 0), because "Black" is mapped to (0, 0, 0) in the dictionary. print(colors["Black"]) # Prints (100, 100, 100), because "Blue" is not... | 5 | 9 |
71,007,924 | 2022-2-6 | https://stackoverflow.com/questions/71007924/how-can-i-get-a-version-to-the-root-of-a-typer-typer-application | My CLI applications typically have subcommands. I want to have the --version flag at the root of my CLI applications, but with Typer I've only seen ways to put it to a command. I want to add it to the typer.Typer object (the root) itself. How can I do that? What I've tried import typer from typing import Optional __ver... | This is addressed in the documentation: But as those CLI parameters are handled by each of those commands, they don't allow us to create CLI parameters for the main CLI application itself. But we can use @app.callback() for that. It's very similar to @app.command(), but it declares the CLI parameters for the main CLI ... | 6 | 9 |
71,006,708 | 2022-2-6 | https://stackoverflow.com/questions/71006708/getting-sslv3-alert-handshake-failure-when-trying-to-connect-to-imap | i need to do a script for imap backup but when i'm trying to connect to the imap server with my script i'm getting that error: File "c:\Users\Lenovo\Desktop\python\progettoscuola.py", line 5, in <module> imapSrc = imaplib.IMAP4_SSL('mail.safemail.it') File "C:\Program Files\Python310\lib\imaplib.py", line 1323, in __i... | Python 3.10 increased the default security settings of the TLS stack by among other things prohibiting any ciphers which still use the RSA key exchange. RSA key exchange is long considered inferior since it does not provide forward secrecy and is therefore also no longer available in TLS 1.3. So in general the change i... | 7 | 21 |
71,004,414 | 2022-2-6 | https://stackoverflow.com/questions/71004414/numpy-dot-for-dimensions-2 | I am trying to understand how dot product works for dimensions more than 2. The documentation says: If a is an N-D array and b is an M-D array (where M>=2), it is a sum product over the last # axis of a and the second-to-last axis of b: dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m]) I don't understand this rule -- wh... | It may be easier to visualize this using the notation of np.einsum. Start with regular 2D matrix multiplication, which is pretty unambiguous, and follows "normal math" rules: a = np.ones((2, 3)) b = np.ones((3, 4)) np.einsum('ij,jk->ik', a, b) # Same as a.dot(b) Now prepend a few dimensions: a = np.ones((2, 3, 4, 5)) ... | 5 | 3 |
70,995,419 | 2022-2-5 | https://stackoverflow.com/questions/70995419/how-to-mock-an-async-instance-method-of-a-patched-class | (The following code can be run in Jupyter.) I have a class B, which uses class A, needs to be tested. class A: async def f(self): pass class B: async def f(self): a = A() x = await a.f() # need to be patched/mocked And I have the following test code. It seems it mocked the class method of A instead of the instance met... | In Python 3.8+, patching an async method gives you an AsyncMock, so providing a result is a little more straightforward. In the docs of the patch method itself: If new is omitted, then the target is replaced with an AsyncMock if the patched object is an async function or a MagicMock otherwise. AsyncMock lets you supp... | 7 | 7 |
70,987,896 | 2022-2-4 | https://stackoverflow.com/questions/70987896/why-is-this-task-faster-in-python-than-julia | I ran the following code in RStudio: exo <- read.csv('exoplanets.csv',TRUE,",") df <- data.frame(exo) ranks <- 570 files <- 3198 datas <- vector() for ( w in 2:files ) { listas <-vector() for ( i in 1:ranks) { name <- as.character(df[i,w]) listas <- append (listas, name) } datas <- append (datas, listas) } It reads a ... | NOTE: I wrote the below assuming you want the other column order (as in the Python and R examples). It is more efficient in Julia this way; to make it work equivalently to your original behaviour, permute the logic or your data at the right places (left as an exercise). Bogumił's anwer does the right thing already. Pu... | 7 | 8 |
70,988,235 | 2022-2-4 | https://stackoverflow.com/questions/70988235/make-bar-charts-x-axis-markers-horizontal-or-45-degree-readable-in-python-altai | I am trying to create a bar chart with year data on x-axis. It works but the year marker on x-xais are all in vertical direction and I want to make them more readable - either horizontal or 45 degree. I tried using the year:T in datatime format but it gave me the year and month markers (I just wanted to have the year m... | Set labelAngle: alt.Chart(source).mark_bar().encode( x=alt.X('year:O', axis=alt.Axis(labelAngle=-45)), y="wheat:Q" ) | 7 | 11 |
70,988,817 | 2022-2-4 | https://stackoverflow.com/questions/70988817/dealing-with-optional-python-dictionary-fields | I'm dealing with JSON data which I load into Python dictionaries. A lot of these have optional fields, which then may contain dictionaries, that kind of stuff. dictionary1 = {"required": {"value1": "one", "value2": "two"}, "optional": {"value1": "one"}} dictionary2 = {"required": {"value1": "one", "value2": "two"}} If... | First of all, you refer to " " as the empty string. This is incorrect; "" is the empty string. Second, if you're checking for membership, I don't see a reason to use the get method in the first place. I'd opt for something like the following. if "optional" in dictionary2: value1 = dictionary2["optional"].get("value1") ... | 6 | 1 |
70,987,818 | 2022-2-4 | https://stackoverflow.com/questions/70987818/what-does-the-svv-flag-mean-when-running-pytest-via-the-command-line-interfac | Can anyone explain what the -svv flag means/does when running pytest from command line? Such as: pytest -svv This is really driving me crazy, as I can't find it in pytest's official documentation, its code base or through a web search. | This is the same as passing pytest -s -vv where -s disables capturing of stdout/stderr (source) -vv enables verbose output (source) Specifically note that the increased verbosity specifier currently has no effect in base pytest above normal increased verbosity Using higher verbosity levels (-vvv, -vvvv, …) is support... | 6 | 8 |
70,986,620 | 2022-2-4 | https://stackoverflow.com/questions/70986620/combining-single-dispatch-and-protocols | I'm having some issues combining single-dispatch overloads with a protocol for structural typing based on having a specific attribute. I have constructed the following snippet to give an idea of what I'm attempting. from typing_extensions import Protocol from functools import singledispatch class HasFoo(Protocol): foo:... | That apparently doesn't work. Single dispatch uses the MRO (Method resolution order) to find out if a given instance matches a registered type. However, the protocol is not part of the MRO, hence python will not find it. To make it part of the MRO you could inherit from it, but that is not what Protocols are meant to b... | 5 | 4 |
70,984,947 | 2022-2-4 | https://stackoverflow.com/questions/70984947/efficient-way-to-generate-lime-explanations-for-full-dataset | Am working on a binary classification problem with 1000 rows and 15 features. Currently am using Lime to explain the predictions of each instance. I use the below code to generate explanations for full test dataframe test_indx_list = X_test.index.tolist() test_dict={} for n in test_indx_list: exp = explainer.explain_in... | From what the docs show, there isn't currently an option to do batch explain_instance, although there are plans for it. This should help a lot with speed on newer versions later on. What seems to be the most appropriate change to get better speed is decreasing the number of samples used to learn the linear model. expla... | 6 | 4 |
70,981,458 | 2022-2-4 | https://stackoverflow.com/questions/70981458/how-to-resolve-this-error-py4jjavaerror-an-error-occurred-while-calling-o70-sh | Currently I'm doing PySpark and working on DataFrame. I've created a DataFrame: from pyspark.sql import * import pandas as pd spark = SparkSession.builder.appName("DataFarme").getOrCreate() df = spark.createDataFrame([("Java", "20000"), ("Python", "100000"), ("Scala", "3000")]) df.printSchema() #Output:- root |-- _1: ... | The key is in this part of the error message: RuntimeError: Python in worker has different version 3.9 than that in driver 3.10, PySpark cannot run with different minor versions. Please check environment variables PYSPARK_PYTHON and PYSPARK_DRIVER_PYTHON are correctly set. You need to have exactly the same Python versi... | 6 | 4 |
70,977,131 | 2022-2-3 | https://stackoverflow.com/questions/70977131/flask-render-template-after-client-post-request | So, I'm working on a small web application that has a small canvas, the user is supposed to draw something and then I want to do some python with the image from that canvas. Like this: This is working fine. When I press "Click me!", I call a JS function that POST the image to my Flask server. And this is also working,... | The problem is that you are returning the page to view in response to the call that posts the image. Instead, you should return a response (for example in a json format) containing the information regarding the result of the call just made (i.e. the post of the image) and consequently, on the client side, you must redi... | 6 | 3 |
70,982,008 | 2022-2-4 | https://stackoverflow.com/questions/70982008/vscode-pytest-discovery-not-working-conda-error | I'm having a strange problem with VSCode's python testing functionality. When I try to discover tests I get the following error: > conda run -n sandbox --no-capture-output python ~/.vscode/extensions/ms-python.python-2022.0.1786462952/pythonFiles/get_output_via_markers.py ~/.vscode/extensions/ms-python.python-2022.0.17... | Two ways I've found to fix: Change the name of the conda environment. Just cloning sandbox to boxsand did the trick Add python.condaPath variable to VSCode's preferences | 10 | 6 |
70,964,740 | 2022-2-3 | https://stackoverflow.com/questions/70964740/explode-pandas-column-of-dictionary-with-list-of-tuples-as-value | I have the following dataframe where col2 is a dictionary with a list of tuples as values. The keys are consistantly 'added' and 'deleted' in the whole dataframe. Input df col1 col2 value1 {'added': [(59, 'dep1_v2'), (60, 'dep2_v2')], 'deleted': [(59, 'dep1_v1'), (60, 'dep2_v1')]} value 2 {'added': [(61, 'dep... | Well this certainly isn't elegant, but here's a potential solution that is at least easier to understand and reason about: def explode_records(df): new_records = [] def map_dict_to_row(value, col2_dict): temp = {} for number, added in col2_dict["added"]: temp[number] = {"value": value, "number": number, "added": added}... | 5 | 3 |
70,969,592 | 2022-2-3 | https://stackoverflow.com/questions/70969592/pytest-asserting-fixture-after-teardown | I have a test that makes a thing, validates it, deletes the thing and confirms it was deleted. def test_thing(): thing = Thing() # Simplified, it actually takes many lines to make a thing assert thing.exists thing.delete() # Simplified, it also takes a few lines to delete it assert thing.deleted Next I want to make ma... | If you want to test that a "thing" is deleted, make a fixture without teardown, delete it in the test, then assert if it is deleted. @pytest.fixture def thing_create(): # Perform all the creation steps thing = Thing() ... yield thing def thing_delete(thing): # Perform all the deletion steps ... thing.delete() @pytest.f... | 5 | 5 |
70,964,001 | 2022-2-2 | https://stackoverflow.com/questions/70964001/numpy-maxima-of-groups-defined-by-a-label-array | I have two arrays, one is a list of values and one is a list of IDs corresponding to each value. Some IDs have multiple values. I want to create a new array that contains the maximum value recorded for each id, which will have a length equal to the number of unique ids. Example using a for loop: import numpy as np valu... | np.lexsort sorts by multiple columns. However, this is not compulsory. You can sort ids first and then choose maximum item of each divided group using numpy.maximum.reduceat def mathfux(values, ids, return_groups=False): argidx = np.argsort(ids) #70% time ids_sort, values_sort = ids[argidx], values[argidx] #4% time div... | 5 | 4 |
70,953,643 | 2022-2-2 | https://stackoverflow.com/questions/70953643/how-to-turn-a-list-of-lists-into-columns-of-a-pandas-dataframe | I would like to ask how I can unnest a list of list and turn it into different columns of a dataframe. Specifically, I have the following dataframe where the Route_set column is a list of lists: Generation Route_set 0 0 [[20. 19. 47. 56.] [21. 34. 78. 34.]] The desired output is the following dataframe: route1 route... | You can try using df.explode and df.apply: import pandas as pd df = pd.DataFrame(data= {'Generation': 0, 'Route_set':[[[20., 19., 47., 56.], [21., 34., 78., 34.]]]}) df['route1']=df['Route_set'].apply(lambda x: x[0]) df['route2']=df['Route_set'].apply(lambda x: x[1]) df = df.explode(['route1', 'route2'], ignore_index=T... | 6 | 2 |
70,952,473 | 2022-2-2 | https://stackoverflow.com/questions/70952473/unicodedecodeerror-utf-8-can-t-decode-byte-0x90-in-position-4024984-invalid | I’m running a subprocess in full trace mode and displaying it using logger.info() > std = subprocess.run(subprocess_cmd, shell=True, > universal_newlines=True, stdout=subprocess.PIPE, > stderr=subprocess.PIPE) > > all_stdout = all_stdout + std.stdout + ‘\n’ all_stderr = all_stderr + > std.stderr + ‘\n’ > > logger.info... | Use the encoding encoding="unicode_escape" instead of encoding="utf-8" | 5 | 3 |
70,952,155 | 2022-2-2 | https://stackoverflow.com/questions/70952155/how-to-read-a-kubernetes-deployment-with-python-kubernetes-client | what is python kubernetes client equivalent for kubectl get deploy -o yaml CRUD python Client example i referred this example for getting python deployment but there is no read deployment option | read_namespaced_deployment() does the thing: from kubernetes import client, config config.load_kube_config() api = client.AppsV1Api() deployment = api.read_namespaced_deployment(name='foo', namespace='bar') | 6 | 11 |
70,891,687 | 2022-1-28 | https://stackoverflow.com/questions/70891687/how-do-i-get-my-fastapi-applications-console-log-in-json-format-with-a-differen | I have a FastAPI application where I would like to get the default logs written to the STDOUT with the following data in JSON format: App logs should look like this: { "XYZ": { "log": { "level": "info", "type": "app", "timestamp": "2022-01-16T08:30:08.181Z", "file": "api/predictor/predict.py", "line": 34, "threadId": 4... | You could do that by creating a custom Formatter, using the built-in logger module in Python. You could use the extra parameter when logging messages to pass contextual information, such as url and headers. Python's JSON module already implements pretty-printing JSON data, using the json.dumps() function and adjusting ... | 10 | 21 |
70,872,276 | 2022-1-27 | https://stackoverflow.com/questions/70872276/fastapi-python-how-to-run-a-thread-in-the-background | I'm making a server in python using FastAPI, and I want a function that is not related to my API, to run in background every 5 minutes (like checking stuff from an API and printing stuff depending on the response) I've tried to make a thread that runs the function start_worker, but it doesn't print anything. Does anyon... | Option 1 You should start your Thread before calling uvicorn.run, as uvicorn.run is blocking the thread. from fastapi import FastAPI import threading import uvicorn import time app = FastAPI() class BackgroundTasks(threading.Thread): def run(self,*args,**kwargs): while True: print('Hello') time.sleep(5) if __name__ == ... | 32 | 42 |
70,939,969 | 2022-2-1 | https://stackoverflow.com/questions/70939969/psycopg2-connect-to-postgresql-database-using-a-connection-string | I currently have a connection string in the format of: "localhost://username:password@data_quality:5432" What is the best method of using this to connect to my database using psycopg2? e.g.: connection = psycopg2.connect(connection_string) | You could make use of urlparse, creating a dictionary that matches psycopg's connection arguments: import psycopg2 from urllib.parse import urlparse conStr = "postgres://username:password@localhost:5432/data_quality" p = urlparse(conStr) pg_connection_dict = { 'dbname': p.path[1:], 'user': p.username, 'password': p.pas... | 13 | 15 |
70,879,159 | 2022-1-27 | https://stackoverflow.com/questions/70879159/get-datetime-format-from-string-python | In Python there are multiple DateTime parsers which can parse a date string automatically without providing the datetime format. My problem is that I don't need to cast the datetime, I only need the datetime format. Example: From "2021-01-01", I want something like "%Y-%m-%d" or "yyyy-MM-dd". My only idea was to try ca... | In pandas, this is achieved by pandas.tseries.api.guess_datetime_format from pandas.tseries.api import guess_datetime_format guess_datetime_format('2021-01-01') # '%Y-%m-%d' As there will always be an ambiguity on the day/month, you can specify the dayfirst case: guess_datetime_format('2021-01-01', dayfirst=True) # '%... | 7 | 6 |
70,891,435 | 2022-1-28 | https://stackoverflow.com/questions/70891435/dash-datatable-with-expandable-collapsable-rows | Similar to qtTree, I would like to have a drill down on a column of a datatable. I guess this is better illustrated with an example. Assume we have a dataframe with three columns: Country, City, Population like: Country City Population USA New-York 19MM China Shanghai 26MM China Beijing 20MM USA Los Angeles 12MM France... | Dynamic Python Dash app data_table with row-based dropdowns triggering callbacks This is a little tricky, but hopefully the following example might help achieve what you are attempting. The main drawback is probably the requirement for hard-coding the dropdown_conditional parameter (although, you probably wouldn't want... | 6 | 1 |
70,888,992 | 2022-1-28 | https://stackoverflow.com/questions/70888992/what-are-the-differences-between-unittest-mock-mock-mocker-and-pytest-mock | I am new to Python development, I am writing test cases using pytest where I need to mock some behavior. Googling best mocking library for pytest, has only confused me. I have seen unittest.mock, mock, mocker and pytest-mock. Not really sure which one to use. Can someone please explain me the difference between them an... | pytest-mock is a thin wrapper around mock. mock is since python 3.3. actually the same as unittest.mock. I don't know if mocker is another library, I only know it as the name of the fixture provided by pytest-mock to get mocking done in your tests. I personally use pytest and pytest-mock for my tests, which allows you ... | 29 | 16 |
70,929,777 | 2022-1-31 | https://stackoverflow.com/questions/70929777/type-annotations-tuple-type-vs-union-type | def func(df_a: pd.DataFrame, df_b: pd.DataFrame) -> (pd.DataFrame, pd.DataFrame): Pylance is advising to modify this line with two solution proposed. What would be the pros and cons of each one if there is any significant difference? Tuple expression not allowed in type annotation Use Tuple[T1, ..., Tn] to indicate a... | 2023 edit In newer versions of Python (>=3.10), you should use: tuple[A, B, C] instead of Tuple[A, B, C] (yes, that's the built-in tuple function) A | B instead of Union[A, B] The answer itself is still relevant, even if the newer style makes the difference between Tuple/tuple and Union/| more apparent. Original answ... | 5 | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.