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
70,811,065
2022-1-22
https://stackoverflow.com/questions/70811065/how-to-schedule-code-execution-in-python
I have a function that is running inside a for loop. My goal is to run it every day at a specific time, such as 10 am. My code is: def get_sql_backup_transfer(ip, folder,path_sec_folder,sec_folder,path): call(["robocopy",f'{ip}\\{folder}', f'{path_sec_folder}{sec_folder}',"/tee","/r:5","/w:120","/S","/MIR",f"/LOG:{path...
There are some ways to do this , but the best way is using 'schedule' package, i guess However, in the first step install the package : pip install schedule And then use it in your code like the following codes : import schedule schedule.every().day.at("10:00").do(yourFunctionToDo,'It is 10:00')
5
2
70,809,437
2022-1-22
https://stackoverflow.com/questions/70809437/why-if-statement-does-not-pick-the-specific-row-for-condition-from-a-data-fram
writing a function that should meet a condition on a row basis and return the expected results def bt_quantity(df): df = bt_level(df) df['Marker_change'] = df['Marker'] - df['Marker'].shift(1).fillna(0).round(0).astype(int) df['Action'] = np.where(df['Marker_change'] > 0, "BUY", "") def turtle_split(row): if df['Action...
As you said, this is really a common problem, you will find the answers from Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() But to address your particular case, this is not a very efficient way of doing it as the dataset is huge. You should use Numpy. That will shorten the run...
5
5
70,789,297
2022-1-20
https://stackoverflow.com/questions/70789297/apache-beam-performance-between-python-vs-java-running-on-gcp-dataflow
We have Beam data pipeline running on GCP dataflow written using both Python and Java. In the beginning, we had some simple and straightforward python beam jobs that works very well. So most recently we decided to transform more java beam to python beam job. When we having more complicated job, especially the job requi...
Yes, this is a very normal performance factor between Python and Java. In fact, for many programs the factor can be 10x or much more. The details of the program can radically change the relative performance. Here are some things to consider: Profiling the Dataflow job (official docs) Profiling a Dataflow pipeline (med...
6
6
70,805,036
2022-1-21
https://stackoverflow.com/questions/70805036/why-are-python-sets-sorted-in-ascending-order
Let's run the following code: st = {3, 1, 2} st >>> {1, 2, 3} st.pop() >>> 1 st.pop() >>> 2 st.pop() >>> 3 Although sets are said to be unordered, this set behaves as if it was sorted in ascending order. The method pop(), that should return an 'arbitrary element', according to the documentation, returns elements in as...
The order correlates to the hash of the object, size of the set, binary representation of the number, insertion order and other implementation parameters. It is completely arbitrary and shouldn't be relied upon: >>> st = {3, 1, 2,4,9,124124,124124124124,123,12,41,15,} >>> st {1, 2, 3, 4, 9, 41, 12, 15, 124124, 123, 124...
5
6
70,802,550
2022-1-21
https://stackoverflow.com/questions/70802550/pyinstaller-executable-is-not-working-if-using-multiprocessing-in-pyqt5
I was working in my project related to pyqt5 GUI. I used multiprocessing to make it faster. When I run my program in editor, it works fine. But when I converted my program into executable using pyinstaller, then while running the program through this executable, it's not working. GUI opens, but close once it comes to t...
I had the same problem a while ago, and I recommend using Nuitka hence it supports Multiprocessing. If the problem lasts, try to use the threading library: from threading import Thread def worker(a,b): while True: print(a+b) a+=1 my_thread = Thread(target = worker, args = [10,20]) my_thread.start() You can also setup ...
5
1
70,792,216
2022-1-20
https://stackoverflow.com/questions/70792216/count-number-of-retries-for-each-request
I use package requests together with urllib3.util.retry.Retry() to send tens of thousands of queries. I seek to count the number of queries and the number of necessary attempts until I successfully retrieve the desired data. My goal is to construct a measure for the reliability of the API. To fix ideas, let's assume th...
This is a rather verbose solution along the lines of this answer. It counts requests and retries on the session level (which, however, was not my preferred approach). import requests from urllib3.util.retry import Retry class RequestTracker: """ track queries and retries """ def __init__(self): self._retries = 0 self._...
7
2
70,799,600
2022-1-21
https://stackoverflow.com/questions/70799600/how-exactly-does-python-find-new-and-choose-its-arguments
While trying to implement some deep magic that I'd rather not get into here (I should be able to figure it out if I get an answer for this), it occurred to me that __new__ doesn't work the same way for classes that define it, as for classes that don't. Specifically: when you define __new__ yourself, it will be passed a...
The issues you're seeing aren't related to how Python finds __new__ or chooses its arguments. __new__ receives every argument you're passing. The effects you observed come from specific code in object.__new__, combined with a bug in the logic for updating the C-level tp_new slot. There's nothing special about how Pyth...
5
5
70,794,535
2022-1-20
https://stackoverflow.com/questions/70794535/selenium-unable-to-find-session-with-id-after-a-few-minutes-of-idling
I started a Docker container with: docker run -d --shm-size="4g" --hostname selenium_firefox selenium/standalone-firefox In another container with Python: ... >>> driver = webdriver.Remote(command_executor="http://" +selenium_host+":4444/w d/hub", desired_capabilities=DesiredCapabilities.FIREFOX, keep_alive=True) >>> d...
Option 1: Override Docker Selenium Grid default session timeout From docker/selenium documentation: Grid has a default session timeout of 300 seconds, where the session can be on a stale state until it is killed. You can use SE_NODE_SESSION_TIMEOUT to overwrite that value in seconds. docker run -d -e SE_NODE_SESSION_...
6
7
70,795,755
2022-1-21
https://stackoverflow.com/questions/70795755/how-to-resolve-dash-bootstrap-no-gutter-type-error
When I run this code, I get an error message saying "Error: The dash_bootstrap_components.Row component (version 1.0.2) received an unexpected keyword argument: no_gutters Allowed arguments: align, children, className, class_name, id, justify, key, loading_state, style" I believe it's because of the dash bootstrap vers...
As of Version 1.0 for Dash-bootstrap-components, the no_gutters attribute for the Row component has been deprecated. You are probably using code from a version <= 0.13, read this migration guide for the full details of the changes. You have a couple of options here: Reading that migration guide will suggest the new wa...
5
4
70,794,199
2022-1-20
https://stackoverflow.com/questions/70794199/use-of-colon-in-type-hints
When type annotating a variable of type dict, typically you'd annotate it like this: numeralToInteger: dict[str, int] = {...} However I rewrote this using a colon instead of a comma: numeralToInteger: dict[str : int] = {...} And this also works, no SyntaxError or NameError is raised. Upon inspecting the __annotations...
If you have a dictionary whose keys are strings and values are integers, you should do dict[str, int]. It's not optional. IDEs and type-checkers use these type hints to help you. When you say dict[str : int], it is a slice object. Totally different things. Try these in mypy playground: d: dict[str, int] d = {'hi': 20} ...
12
9
70,792,058
2022-1-20
https://stackoverflow.com/questions/70792058/how-can-i-change-the-default-pager-for-pythons-help-debugger-command
I'm currently doing some work in a server (Ubuntu) without admin rights nor contact with the administrator. When using the help(command) in the python command line I get an error. Here's an example: >>> help(someCommand) /bin/sh: most: command not found So, this error indicates that most pager is not currently install...
This one is annoyingly difficult to research, but I think I found it. The built-in help generates its messages using the standard library pydoc module (the module is also intended to be usable as a standalone script). In that documentation, we find: When printing output to the console, pydoc attempts to paginate the o...
5
1
70,782,902
2022-1-20
https://stackoverflow.com/questions/70782902/best-way-to-navigate-a-nested-json-in-python
I have tried different for loops trying to iterate through this JSON and I cant figure out how to do it. I have a list of numbers and want to compare it to the "key" values under each object of "data" (For example, Aatrox, Ahri, Akali, and so on) and if the numbers match store the "name" value in another list. Example:...
You simply iterate over the values of the dictionary, check whether the value of the 'key' item is in your list and if that's the case, append the value of the 'name' item to your output list. Let jsonObj be your JSON object presented in your question. Then this code should work: listOfNumbers = [266, 166, 123, 283] na...
5
4
70,780,369
2022-1-20
https://stackoverflow.com/questions/70780369/valueerror-only-one-element-tensors-can-be-converted-to-python-scalars-when-con
I have the following: type of X is: <class 'list'> X: [tensor([[1.3373, 0.5666, 0.2337, ..., 0.4899, 0.1876, 0.5892], [0.0320, 0.0797, 0.0052, ..., 0.3405, 0.0000, 0.0390], [0.1305, 0.1281, 0.0021, ..., 0.6454, 0.1964, 0.0493], ..., [0.2635, 0.0237, 0.0000, ..., 0.6635, 0.1376, 0.2988], [0.0241, 0.5464, 0.1263, ..., 0....
Use torch.stack(): X = torch.stack(X)
4
11
70,779,984
2022-1-20
https://stackoverflow.com/questions/70779984/python-tuple-is-not-defined-warning
I'm writing a function that returns a tuple and using type annotations. To do so, I've written: def foo(bar) -> Tuple[int, int]: pass This runs, but I've been getting a warning that says: "Tuple" is not defined Pylance report UndefinedVariable Given that I'm writing a number of functions that return a tuple type, I'...
Depending on your exact python version there might be subtle differences here, but what's bound to work is from typing import Tuple def foo(bar) -> Tuple[int, int]: pass Alternatively I think since 3.9 or 3.10 you can just outright say tuple[int, int] without importing anything.
13
19
70,773,695
2022-1-19
https://stackoverflow.com/questions/70773695/how-are-python-closures-implemented
I am interested in how python implements closures? For the sake of example, consider this def closure_test(): x = 1 def closure(): nonlocal x x = 2 print(x) return closure closure_test()() Here, the function closure_test has a local x which the nested function closure captures. When I run the program, I get the follow...
Overview Python doesn't directly use variables the same way one might expect coming from a statically-typed language like C or Java, rather it uses names and tags instances of objects with them In your example, closure is simply an instance of a function with that name It's really nonlocal here which causes LOAD_CLOSUR...
7
6
70,776,558
2022-1-19
https://stackoverflow.com/questions/70776558/pytube-exceptions-regexmatcherror-init-could-not-find-match-for-w-w
So my issue is I run this simple code to attempt to make a pytube stream object... from pytube import YouTube yt = YouTube('https://www.youtube.com/watch?v=aQNrG7ag2G4') stream = yt.streams.filter(file_extension='mp4') And end up with the error in the title. Full error: Traceback (most recent call last): File ".\test....
As juanchosaravia suggested on https://github.com/pytube/pytube/issues/1199, in order to solve the problem, you should go in the cipher.py file and replace the line 30, which is: var_regex = re.compile(r"^\w+\W") With that line: var_regex = re.compile(r"^\$*\w+\W") After that, it worked again.
13
74
70,773,879
2022-1-19
https://stackoverflow.com/questions/70773879/fastapi-starlette-redirectresponse-redirect-to-post-instead-get-method
I have encountered strange redirect behaviour after returning a RedirectResponse object events.py router = APIRouter() @router.post('/create', response_model=EventBase) async def event_create( request: Request, user_id: str = Depends(get_current_user), service: EventsService = Depends(), form: EventForm = Depends(Event...
When you want to redirect to a GET after a POST, the best practice is to redirect with a 303 status code, so just update your code to: # ... return RedirectResponse(redirect_url, status_code=303) As you've noticed, redirecting with 307 keeps the HTTP method and body. Fully working example: from fastapi import FastAPI...
12
17
70,773,526
2022-1-19
https://stackoverflow.com/questions/70773526/why-do-we-need-a-dict-update-method-in-python-instead-of-just-assigning-the-va
I have been working with dictionaries that I have to modify within different parts of my code. I am trying to make sure if I do not miss anything about there is no need for dict_update() in any scenario. So the reasons to use update() method is either to add a new key-value pair to current dictionary, or update the val...
1. You can update many keys on the same statement. my_dict.update(other_dict) In this case you don't have to know how many keys are in the other_dict. You'll just be sure that all of them will be updated on my_dict. 2. You can use any iterable of key/value pairs with dict.update As per the documentation you can use an...
22
37
70,773,518
2022-1-19
https://stackoverflow.com/questions/70773518/fail-to-install-module-pil-error-could-not-find-a-version-that-satisfies-the
when trying to import - from PIL import Image this error occurs: ERROR: Could not find a version that satisfies the requirement PIL (from versions: none) ERROR: No matching distribution found for PIL
the solution: pip install Pillow after that make sure it works: from PIL import Image
5
7
70,773,090
2022-1-19
https://stackoverflow.com/questions/70773090/printstring1-or-string2-in-string-does-not-give-boolean-result
why does print("Lorem" and "aliqua" in string ) Gives True. A Boolean, But print("Lorem" or "aliqua" in string ) Gives 'Lorem'. A String string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua" print("Lorem" and "aliqua" in string ) >>> True p...
Try: print("Lorem" in string and "aliqua" in string ) And print("Lorem" in string or "aliqua" in string ) Explanation: The condition in string will always be true as it checks string is non empty. >>> if "harsha": ... print("hi") ... hi >>> if "": ... print("hi") ... <<No output>>
4
5
70,768,547
2022-1-19
https://stackoverflow.com/questions/70768547/how-to-pass-date-and-id-through-url-in-django
I am trying to pass date and id through url, but getting an error, I have passed just id before and I usually do it like this. path('user_payment_menu/<int:pk>/',user_payment_menu, name='user_payment_menu'), but now I want date to pass after int:pk/ but when I add date after a slash I am getting an error.
Probably the easiest way to define a date is with a custom path converter. You can implement this with: # app_name/converters.py class DateConverter: regex = '\d{4}-\d{1,2}-\d{1,2}' format = '%Y-%m-%d' def to_python(self, value): return datetime.strptime(value, self.format).date() def to_url(self, value): return value....
4
13
70,766,215
2022-1-19
https://stackoverflow.com/questions/70766215/problem-with-memory-allocation-in-julia-code
I used a function in Python/Numpy to solve a problem in combinatorial game theory. import numpy as np from time import time def problem(c): start = time() N = np.array([0, 0]) U = np.arange(c) for _ in U: bits = np.bitwise_xor(N[:-1], N[-2::-1]) N = np.append(N, np.setdiff1d(U, bits).min()) return len(*np.where(N==0)),...
The original code can be re-written in the following way: function problem2(c) N = zeros(Int, c+2) notseen = falses(c+1) for lN in 1:c+1 notseen .= true @inbounds for i in 1:lN-1 b = N[i] ⊻ N[lN-i] b <= c && (notseen[b+1] = false) end idx = findfirst(notseen) isnothing(idx) || (N[lN+1] = idx-1) end return count(==(0), ...
14
17
70,690,454
2022-1-13
https://stackoverflow.com/questions/70690454/how-to-redirect-the-user-back-to-the-home-page-using-fastapi-after-submitting-a
I have a page with a table of students. I added a button that allows you to add a new row to the table. To do this, I redirect the user to a page with input forms. The problem is that after submitting the completed forms, the user goes to a new empty page. How to transfer data in completed forms and redirect the user b...
To start with, in cases where you return Jinja2 templates, you should return a TemplateResponse, as shown in the documentation. To redirect the user to a specific page, you could use RedirectResponse. Since you do that through a POST (and not GET) method, as shown in your example, a 405 (Method Not Allowed) error would...
8
7
70,744,477
2022-1-17
https://stackoverflow.com/questions/70744477/prometheus-how-to-expose-metrics-in-multiprocess-app-with-start-http-server
How expose metrics in multiprocess app use start_http_server I found many examples with gunicorn in internet but i want use start_http_server what should i do with code below to make it work properly? from multiprocessing import Process import time, os from prometheus_client import start_http_server, multiprocess, Coll...
I was figuring out the same thing, and the solution was as simple as you would imagine. Updated your example code to work: from multiprocessing import Process import shutil import time, os from prometheus_client import start_http_server, multiprocess, CollectorRegistry, Counter COUNTER1 = Counter('counter1', 'Incremen...
6
14
70,682,613
2022-1-12
https://stackoverflow.com/questions/70682613/update-env-variable-on-notebook-in-vscode
I’m working on a python project with a notebook and .env file on VsCode. I have problem when trying to refresh environment variables in a notebook (I found a way but it's super tricky). My project: .env file with: MY_VAR="HELLO_ALICE" test.ipynb file with one cell: from os import environ print('MY_VAR = ', environ.get(...
The terminal you open in VSC is not the same terminal ipython kernel is running. The kernel is already running in an environment that is not affected by you changing variables in another terminal. You need to set the variables in the correct environment. You can do that with dotenv, but remember to use override=True. T...
9
11
70,711,245
2022-1-14
https://stackoverflow.com/questions/70711245/changing-schema-name-in-openapi-docs-generated-by-fastapi
I'm using FastAPI to create backend for my project. I have a method that allows to upload a file. I implemented it as follows: from fastapi import APIRouter, UploadFile, File from app.models.schemas.files import FileInResponse router = APIRouter() @router.post("", name="files:create-file", response_model=FileInResponse...
In case someone is interested into renaming auto generated fields from FastAPI in openapi.json file, you should add an operation_id param to your route. This will allow FastAPI to use this id to generate a clearer attribute name for the generated schema. Before: @router.post( "/{opportunity_id}/files", status_code=stat...
5
2
70,714,622
2022-1-14
https://stackoverflow.com/questions/70714622/why-is-colab-still-running-python-3-7
I saw on this tweet that Google Colab move to Python 3.7 on February 2021. As of today however (January 2022), Python 3.10 is out, but Colab still runs Python 3.7. My (voluntarily) naive take is that this is quite a significant lag. Why are they not at least on Python 3.8 or even 3.9? Is it simply to make sure that som...
The only reason is that they want to have the most compatible version of Python worldwide. According to the Python Readiness report (Python 3.7 Readiness), version 3.7 supports almost 80.6% of the most used packages so far. Still, this coverage is 78.3% for version 3.8, 70.6% for version 3.9, and 49.7% for version 3.10...
4
7
70,693,647
2022-1-13
https://stackoverflow.com/questions/70693647/how-can-i-decode-a-json-string-into-a-pydantic-model-with-a-dataframe-field
I am using MongoDB to store the results of a script into a database. When I want to reload the data back into python, I need to decode the JSON (or BSON) string into a pydantic basemodel. With a pydantic model with JSON compatible types, I can just do: base_model = BaseModelClass.parse_raw(string) But the default json...
Pydantic V2: You can define a custom data type and specify a serializer which will automatically handle conversions: from typing import Annotated, Any from pydantic import BaseModel, GetCoreSchemaHandler import pandas as pd from pydantic_core import CoreSchema, core_schema class myDataFrame(pd.DataFrame): @classmethod ...
8
2
70,759,514
2022-1-18
https://stackoverflow.com/questions/70759514/how-to-show-geopandas-interactive-map-with-explore
I made a geopandas dataframe and I want to use geopandas_dataframe.explore() to create an interactive map. Here is my code. First I create the geopandas dataframe, I check the dtypes and I try to map the dataframe with gdf.explore(). Unfortunately, my code just finishes without errors and no map is shown. code: geometr...
What IDE are you using? In Jupyter Notebook your code (slightly modified) works for me. However, when I run it in PyCharm I get, "Process finished with exit code 0" with no plot. import geopandas as gpd import pandas as pd from shapely.geometry import Point data_dict = {'x': {0: -110.1, 1: -110.2, 2: -110.3, 3: -110.4,...
6
7
70,694,787
2022-1-13
https://stackoverflow.com/questions/70694787/fastapi-fastapi-users-with-database-adapter-for-sqlmodel-users-table-is-not-crea
I was trying to use fastapi users package to quickly Add a registration and authentication system to my FastAPI project which uses the PostgreSQL database. I am using asyncio to be able to create asynchronous functions. In the beginning, I used only sqlAlchemy and I have tried their example here. And I added those line...
By the time I posted this question that was the answer I received from one of the maintainer of fastapi-users that made me switch to sqlAlchemy that time, actually I do not know if they officially released sqlModel DB adapter or not My guess is that you didn't change the UserDB model so that it inherits from the SQLMo...
7
2
70,727,291
2022-1-16
https://stackoverflow.com/questions/70727291/how-do-i-know-whether-a-sklearn-scaler-is-already-fitted-or-not
For example, ss is an sklearn.preprocessing.StandardScaler object. If ss is fitted already, I want to use it to transform my data. If ss is not fitted yet, I want to use my data to fit it and transform my data. Is there a way to know whether ss is already fitted or not?
Sklearn implements the check_is_fitted function to check if any generic estimator is fitted, which works with StandardScaler: from sklearn.preprocessing import StandardScaler from sklearn.utils.validation import check_is_fitted ss = StandardScaler() check_is_fitted(ss) # Raises error ss.fit([[1,2,3]]) check_is_fitted(s...
7
4
70,754,841
2022-1-18
https://stackoverflow.com/questions/70754841/how-to-adjust-the-color-bar-size-in-geopandas
I've created this map using geopandas, but I can't make the color bar have the same size as the figure. ax = covid_death_per_millon_geo.plot(column = 'total_deaths_per_million', legend = True, cmap = 'RdYlGn_r', figsize=(20,15)) ax.set_title('Covid deaths per Million', size = 20) ax.set_axis_off() https://i.sstatic.ne...
The colorbars on GeoPandas plots are Matplotlib colorbar objects, so it's worth checking those docs. Add a legend_kwds option and define the shrink value to change the colorbar's size (this example will shrink it to 50% of the default): ax = covid_death_per_millon_geo.plot( column="total_deaths_per_million", legend=Tru...
5
4
70,710,874
2022-1-14
https://stackoverflow.com/questions/70710874/how-to-send-base64-image-using-python-requests-and-fastapi
I am trying to implement a code for image style transfer based on FastAPI. I found it effective to convert the byte of the image into base64 and transmit it. So, I designed my client codeto encode the image into a base64 string and send it to the server, which received it succesfully. However, I face some difficulties ...
Option 1 As previously mentioned here, as well as here and here, one should use UploadFile, in order to upload files from client apps (for async read/write have a look at this answer). For example: server side: @app.post("/upload") def upload(file: UploadFile = File(...)): try: contents = file.file.read() with open(fil...
5
6
70,753,768
2022-1-18
https://stackoverflow.com/questions/70753768/jupyter-notebook-access-to-the-file-was-denied
I'm trying to run a Jupyter notebook on Ubuntu 21.10. I've installed python, jupyter notebook, and all the various prerequisites. I added export PATH=$PATH:~/.local/bin to my bashrc so that the command jupyter notebook would be operational from the terminal. When I call jupyter notebook from the terminal, I get the fol...
I had the same problem. Ubuntu 20.04.3 LTS Chromium Version 96.0.4664.110 This was the solution in my case: Create the configuration file with this command: jupyter notebook --generate-config Edit the configuration file ~/.jupyter/jupyter_notebook_config.py and set: c.NotebookApp.use_redirect_file = False Make sure t...
25
44
70,743,246
2022-1-17
https://stackoverflow.com/questions/70743246/django-db-with-ssh-tunnel
Is there a python native way to connect django to a database through an ssh tunnel? I have seen people using ssh port forwarding in the host machine but I would prefer a solution that can be easily containerized.
It is pretty seamless. Requirements: The sshtunnel package https://github.com/pahaz/sshtunnel In the django settings.py create an ssh tunnel before the django DB settings block: from sshtunnel import SSHTunnelForwarder # Connect to a server using the ssh keys. See the sshtunnel documentation for using password authen...
4
13
70,757,953
2022-1-18
https://stackoverflow.com/questions/70757953/pygame-display-init-fails-for-non-root-user
Tl;dr I need to use pygame but it can't initialize the screen as a normal user because of the permissions for the framebuffer driver. root can do pygame.display.init() but not the user. User is in the group 'video' and can write on /dev/fb0. What permission is missing to the user so pygame.display.init() would work. Er...
Solution to the problem OpenVT So it appears that the best solution, which meet all requirement I listed, is to use openvt. How ? The procedure holds in a few bullet points : 1. Add User to tty group As root, add your user to the group named tty, that will allow us to give it access to the TTYs. # As root: usermod -a -...
5
2
70,713,838
2022-1-14
https://stackoverflow.com/questions/70713838/can-someone-explain-the-logic-behind-xarray-polyfit-coefficients
I am trying to fit a linear regression to climate data from a Netcdf file. The data look like the following.. print(dsloc_lvl) <xarray.DataArray 'sla' (time: 10227)> array([0.0191, 0.0193, 0.0197, ..., 0.0936, 0.0811, 0.0695]) Coordinates: latitude float32 21.62 * time (time) datetime64[ns] 1993-01-01 1993-01-02 ... 20...
While the results of numpy's polyfit are the regression coefficients with respect to an array of x values you pass in manually, xarray's polyfit gives coefficients in units of the coordinate labels. In the case of datetime coordinates, this often means the coefficient result is in the units of the array per nanosecond....
4
6
70,705,250
2022-1-14
https://stackoverflow.com/questions/70705250/how-to-install-local-package-with-conda
I have a local python project called jive that I would like to use in an another project. My current method of using jive in other projects is to activate the conda env for the project, then move to my jive directory and use python setup.py install. This works fine, and when I use conda list, I see everything installed...
The immediate error is that the build is generating a Python 3.10 version, but when testing Conda doesn't recognize any constraint on the Python version, and creates a Python 3.9 environment. I think the main issue is that python >=3.5 is only a valid constraint when doing noarch builds, which this is not. That is, onc...
6
2
70,762,856
2022-1-18
https://stackoverflow.com/questions/70762856/error-importing-plugin-sqlmypy-no-module-named-sqlmypy
I have sqlalchemy-stubs installed via my Pipfile: [dev-packages] sqlalchemy-stubs = {editable = true, git = "https://github.com/dropbox/sqlalchemy-stubs.git"} Verified by running pipenv graph: sqlalchemy-stubs==0.4 - mypy [required: >=0.790, installed: 0.910] - mypy-extensions [required: >=0.4.3,<0.5.0, installed: 0.4...
I fixed by removing the editable = true from the pipfile.
5
0
70,750,396
2022-1-18
https://stackoverflow.com/questions/70750396/how-to-generate-a-rank-5-matrix-with-entries-uniform
I want to generate a rank 5 100x600 matrix in numpy with all the entries sampled from np.random.uniform(0, 20), so that all the entries will be uniformly distributed between [0, 20). What will be the best way to do so in python? I see there is an SVD-inspired way to do so here (https://math.stackexchange.com/questions/...
I just couldn't take the fact the my previous solution (the "selection" method) did not really produce strictly uniformly distributed entries, but only close enough to fool a statistical test sometimes. The asymptotical case however, will almost surely not be distributed uniformly. But I did dream up another crazy idea...
8
1
70,738,211
2022-1-17
https://stackoverflow.com/questions/70738211/run-pytest-classes-in-custom-order
I am writing tests with pytest in pycharm. The tests are divided into various classes. I would like to specify certain classes that have to run before other classes. I have seen various questions on stackoverflow (such as specifying pytest tests to run from a file and how to run a method before all other tests). The...
Approach You can use the pytest_collection_modifyitems hook to modify the order of collected tests (items) in place. This has the additional benefit of not having to install any third party libraries. With some custom logic, this allows to sort by class. Full example Say we have three test classes: TestExtract TestTra...
7
8
70,761,481
2022-1-18
https://stackoverflow.com/questions/70761481/how-to-stop-pycharms-break-stop-halt-feature-on-handled-exceptions-i-e-only-b
I have that PyCharm is halting on all my exceptions, even the ones I am handling in a try except block. I do not want it to break there - I am handling and perhaps expecting an error. But every other exception I do want it to halt and suspend execution (e.g. so that I have the program state and debug it). How does one ...
I think it is already working actually, but you are in fact not catching the correct error. In your code you have: try: pickle.dumps(obj) except pickle.PicklingError: return False But the error thrown is AttributeError. So to avoid that you need something like this: try: pickle.dumps(obj) except (pickle.PicklingError,...
5
2
70,696,761
2022-1-13
https://stackoverflow.com/questions/70696761/python-nsfw-detection-module-nudenet-not-longer-working
I have been using the python module nudenet for my final degree project. I'm using google colab to run it. It worked correctly and without any problem during this last months until yesterday, when I tried to import it, this error happenend: !pip install --upgrade nudenet from nudenet import NudeClassifier ImportError: ...
replace the rile classifier_model.onnx with nudenet classifier and file classifier_lite.onnx with nudenet lite classifier
4
9
70,753,091
2022-1-18
https://stackoverflow.com/questions/70753091/why-does-object-not-support-setattr-but-derived-classes-do
Today I stumbled upon the following behaviour: class myobject(object): """Should behave the same as object, right?""" obj = myobject() obj.a = 2 # <- works obj = object() obj.a = 2 # AttributeError: 'object' object has no attribute 'a' I want to know what is the logic behind designing the language to behave this way, ...
Because derived classes do not necessarily support setattr either. class myobject(object): """Should behave the same as object!""" __slots__ = () obj = myobject() obj.a = 2 # <- works the same as for object Since all types derive from object, most builtin types such as list are also examples. Arbitrary attribute assig...
7
4
70,704,285
2022-1-13
https://stackoverflow.com/questions/70704285/can-no-longer-fold-python-dictionaries-in-vs-code
I used to be able to collapse (fold) python dictionaries just fine in my VS Code. Randomly I am not able to do that anymore. I can still fold classes and functions just fine, but dictionaries cannot fold, the arrow on the left hand side just isn't there. I've checked my settings but I can't figure out what would've cha...
It's caused by Pylance v2022.1.1. Use v2022.1.0 instead. Issue #2248
8
6
70,763,542
2022-1-18
https://stackoverflow.com/questions/70763542/pandas-dataframe-mypy-error-slice-index-must-be-an-integer-or-none
The following line pd.DataFrame({"col1": [1.1, 2.2]}, index=[3.3, 4.4])[2.5:3.5] raises a mypy linting error of on the [2.5 Slice index must be an integer or None This is valid syntax and correctly returns col1 3.3 1.1 Without # type: ignore, how can I resolve this linting error? versions: pandas 1.3.0 mypy 0.931...
This is by design for now, I fear, but if you have to, you can silence mypy by slicing with a callable, like this: import pandas as pd df = pd.DataFrame({"col1": [1.1, 2.2]}, index=[3.3, 4.4])[ lambda x: (2.5 <= x.index) & (x.index < 3.5) ] print(df) # Ouput col1 3.3 1.1 And so mypy reports no issues found on this cod...
8
5
70,723,757
2022-1-15
https://stackoverflow.com/questions/70723757/arch-x86-64-and-arm64e-is-available-but-python3-is-saying-incompatible-architect
I am trying to run this reading-text-in-the-wild on Mac M1. When I attempt to run this code python3 make_keras_charnet_model.py I get the error Using Theano backend. Traceback (most recent call last): File "/Users/name/miniforge3/envs/ocr_env/lib/python3.8/site-packages/theano/gof/cutils.py", line 305, in <module> ...
I found that i need to specify the architecture so instead of python3 make_keras_charnet_model.py i now use this arch -arm64 python3 make_keras_charnet_model.py
7
6
70,759,112
2022-1-18
https://stackoverflow.com/questions/70759112/one-to-one-relationships-with-sqlmodel
After working through the tutorial of SQLModel, I don't remember seeing anything on how to implement 1:1 relationships using Relationship attributes. I found documentation for SQLAlchemy, but it's not immediately clear how this applies to SQLModel. Code example: How to enforce that User and ICloudAccount have a 1:1 rel...
You can turn off the list functionality to allow SQLModel to foreign key as a one-to-one. You do this with the SQLalchemy keyword uselist class User(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str icloud_account_id: Optional[int] = Field(default=None, foreign_key="icloudaccoun...
11
23
70,739,858
2022-1-17
https://stackoverflow.com/questions/70739858/how-to-create-a-brand-new-virtual-environment-or-duplicate-an-existing-one-in-po
I have a project and an existing virtual environment created with poetry (poetry install/init). So, as far as I know, the purpouse of a virtual environment is avoiding to modify the system base environment and the possibility of isolation (per project, per development, per system etc...). How can I create another brand...
Poetry seems to be bound to one virtualenv per python interpreter. Poetry is also bound to the pyproject.toml file and its path to generate a new environment. So there are 2 tricky solutions: 1 - change your deps in the pyproject.toml and use another python version (installed for example with pyenv) and then: poetry en...
25
26
70,730,831
2022-1-16
https://stackoverflow.com/questions/70730831/whats-the-mathematical-reason-behind-python-choosing-to-round-integer-division
I know Python // rounds towards negative infinity and in C++ / is truncating, rounding towards 0. And here's what I know so far: |remainder| -12 / 10 = -1, - 2 // C++ -12 // 10 = -2, + 8 # Python 12 / -10 = -1, 2 // C++ 12 // -10 = -2, - 8 # Python 12 / 10 = 1, 2 // Both 12 // 10 = 1, 2 -12 / -10 = 1, - 2 // Both = 2,...
But why Python // choose to round towards negative infinity? I'm not sure if the reason why this choice was originally made is documented anywhere (although, for all I know, it could be explained in great length in some PEP somewhere), but we can certainly come up with various reasons why it makes sense. One reason i...
88
97
70,761,764
2022-1-18
https://stackoverflow.com/questions/70761764/pytest-html-not-displaying-image
I am trying to generate a self contained html report using pytest-html and selenium. I have been trying to imbedded screenshots into the report but they are not being displayed. My conftest.py looks like this @pytest.fixture() def chrome_driver_init(request, path_to_chrome): driver = webdriver.Chrome(options=opts, exe...
I have learned so much in this painful journey. Mostly I have learned I am an idiot. The problem was that I wanted to make a self contained HTML. Pytest-html does not work as expected with adding images to a self contained report. Before you can you have to convert the image into its text base64 version first. So the a...
4
10
70,760,723
2022-1-18
https://stackoverflow.com/questions/70760723/walrus-assignment-expression-in-list-comprehension-generator
I am trying to pass each element of foo_list into a function expensive_call, and get a list of all the items whose output of expensive_call is Truthy. I am trying to do it with list comprehensions, is it possible? Something like: Something like this: result_list = [y := expensive_call(x) for x in foo_list if y] or......
Quoting from above: result_list = [y for x in foo_list if y := expensive_call(x)] It should work almost exactly as how you have it; just remember to parenthesize the assignment with the := operator, as shown below. foo_list = [1, 2, 3] def check(x): return x if x != 2 else None result_list = [y for x in foo_list if (...
7
8
70,751,892
2022-1-18
https://stackoverflow.com/questions/70751892/error-in-pip-install-transformers-building-wheel-for-tokenizers-pyproject-toml
I'm building a docker image on cloud server via the following docker file: # base image FROM python:3 # add python file to working directory ADD ./ / # install and cache dependencies RUN pip install --upgrade pip RUN pip install RUST RUN pip install transformers RUN pip install torch RUN pip install slack_sdk RUN pip i...
The logs say error: can't find Rust compiler You need to install a rust compiler. See https://www.rust-lang.org/tools/install. You can modify the installation instructions for a docker image like this (from https://stackoverflow.com/a/58169817/5666087): RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | s...
9
7
70,757,783
2022-1-18
https://stackoverflow.com/questions/70757783/how-to-make-a-specific-instance-of-a-class-immutable
Having an instance c of a class C, I would like to make c immutable, but other instances of C dont have to. Is there an easy way to achieve this in python?
You can't make Python classes fully immutable. You can however imitate it: class C: _immutable = False def __setattr__(self, name, value): if self._immutable: raise TypeError(f"Can't set attribute, {self!r} is immutable.") super().__setattr__(name, value) Example: >>> c = C() >>> c.hello = 123 >>> c.hello 123 >>> c._i...
5
8
70,733,261
2022-1-16
https://stackoverflow.com/questions/70733261/joining-dataframes-using-rust-polars-in-python
I am experimenting with polars and would like to understand why using polars is slower than using pandas on a particular example: import pandas as pd import polars as pl n=10_000_000 df1 = pd.DataFrame(range(n), columns=['a']) df2 = pd.DataFrame(range(n), columns=['b']) df1p = pl.from_pandas(df1.reset_index()) df2p = p...
A pandas join uses the indexes, which are cached. A comparison where they do the same: # pandas # CPU times: user 1.64 s, sys: 867 ms, total: 2.5 s # Wall time: 2.52 s df1.merge(df2, left_on="a", right_on="b") # polars # CPU times: user 5.59 s, sys: 199 ms, total: 5.79 s # Wall time: 780 ms df1p.join(df2p, left_on="a",...
5
12
70,751,249
2022-1-18
https://stackoverflow.com/questions/70751249/which-are-safe-methods-and-practices-for-string-formatting-with-user-input-in-py
My Understanding From various sources, I have come to the understanding that there are four main techniques of string formatting/interpolation in Python 3 (3.6+ for f-strings): Formatting with %, which is similar to C's printf The str.format() method Formatted string literals/f-strings Template strings from the standa...
It doesn't matter which format you choose, any format and library can have its own downsides and vulnerabilities. The bigger questions you need to ask yourself is what is the risk factor and the scenario you are facing with, and what are you going to do about it. First ask yourself: will there be a scenario where a use...
7
1
70,755,030
2022-1-18
https://stackoverflow.com/questions/70755030/reading-environment-variables-from-more-than-one-env-file-in-python
I have environment variables that I need to get from two different files in order to keep user+pw outside of the git repo. I download the sensitive user+pass from another location and add it to .gitignore. I am using from os import getenv from dotenv import load_dotenv ... load_dotenv() DB_HOST=getenv('DB_HOST') # from...
You can add file path as an argument in load_dotenv function from dotenv import load_dotenv import os load_dotenv(<file 1 path>) load_dotenv(<file 2 path>)
9
14
70,731,492
2022-1-16
https://stackoverflow.com/questions/70731492/the-transaction-declared-chain-id-5777-but-the-connected-node-is-on-1337
I am trying to deploy my SimpleStorage.sol contract to a ganache local chain by making a transaction using python. It seems to have trouble connecting to the chain. from solcx import compile_standard from web3 import Web3 import json import os from dotenv import load_dotenv load_dotenv() with open("./SimpleStorage.sol"...
Had this issue myself, apparently it's some sort of Ganache CLI error but the simplest fix I could find was to change the network id in Ganache through settings>server to 1337. It restarts the session so you'd then need to change the address and private key variable. If it's the same tutorial I'm doing, you're likely t...
13
37
70,745,252
2022-1-17
https://stackoverflow.com/questions/70745252/how-to-extract-column-names-from-sql-query-using-python
I would like to extract the column names of a resulting table directly from the SQL statement: query = """ select sales.order_id as id, p.product_name, sum(p.price) as sales_volume from sales right join products as p on sales.product_id=p.product_id group by id, p.product_name; """ column_names = parse_sql(query) # co...
I've done something like this using the library sqlparse. Basically, this library takes your SQL query and tokenizes it. Once that is done, you can search for the select query token and parse the underlying tokens. In code, that reads like import sqlparse def find_selected_columns(query) -> list[str]: tokens = sqlparse...
5
5
70,729,329
2022-1-16
https://stackoverflow.com/questions/70729329/are-generators-with-context-managers-an-anti-pattern
I'm wondering about code like this: def all_lines(filename): with open(filename) as infile: yield from infile The point of a context manager is to have explicit control over the lifetime of some form of state, e.g. a file handle. A generator, on the other hand, keeps its state until it is exhausted or deleted. I do kn...
While it does indeed extend the lifetime of the object until the generator exits or is destroyed, it also can make the generators clearer to work with. Consider creating the generators under an outer with and passing the file as an argument instead of them opening it. Now the file is invalid for use after the context m...
5
1
70,739,677
2022-1-17
https://stackoverflow.com/questions/70739677/sphinx-html-static-path-entry-does-not-exist
I am working with Sphinx and I want to set the html_static_path variable in the config.py file. The default was: html_static_path = ['_static'] My project setup is: docs/ build/ doctrees html/ _static/ source/ conf.py The sphinx documentation says that I need to set the path relative to this directory, i.e. relative p...
The build directory is created after you build the docs, which is why you get that error. When you make your docs, Sphinx will copy the static directory from your source location as defined by html_static_path to the build location. Create a new directory source/_static and place any static assets inside of it. Change ...
11
13
70,738,783
2022-1-17
https://stackoverflow.com/questions/70738783/json-serialize-python-enum-object
While serializing Enum object to JSON using json.dumps(...), python will throw following error: >>> class E(enum.Enum): ... A=0 ... B=1 >>> import json >>> json.dumps(E.A) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\guptaaman\Miniconda3\lib\json\__init__.py", line 231, in dumps...
We can make the class which is inheriting Enum to also inherit str class as following: >>> class E(str, enum.Enum): ... A="0" ... B="1" ... >>> json.dumps(E.A) '"0"' Reference: https://hultner.se/quickbits/2018-03-12-python-json-serializable-enum.html
6
10
70,709,406
2022-1-14
https://stackoverflow.com/questions/70709406/import-matplotlib-could-not-be-resolved-from-source-pylancereportmissingmodul
whenever I try to import matplotlib or matplotlib.pyplot in VS Code I get the error in the title: Import "matplotlib" could not be resolved from source Pylance(reportMissingModuleSource) or Import "matplotlib.pyplot" could not be resolved from source Pylance(reportMissingModuleSource) The hyperlink of the reportMissi...
I can reproduce your question when I select a python interpreter where doesn't exist matplotlib: So, the solution is opening an integrated Terminal then run pip install matplotlib. After it's installed successfully, please reload window, then the warning should go away.
17
29
70,729,502
2022-1-16
https://stackoverflow.com/questions/70729502/f2-rename-variable-doesnt-work-in-vscode-jupyter-notebook-python
I can use the normal F2 rename variable functionality in regular python files in vscode. But not when editing python in a jupyter notebook. When I press F2 on a variable in a jupyter notebook in vscode I get the familiar change variable window but when I press enter the variable is not changed and I get this error mess...
Notice that you put up a bug report in GitHub and see this issue: Renaming variables didn't work, the programmer replied: Some language features are currently not supported in notebooks, but we are making plans now to hopefully bring more of those online soon. So please wait for this feature.
10
6
70,723,487
2022-1-15
https://stackoverflow.com/questions/70723487/sqlalchemy-get-child-count-without-reading-all-the-children
Here are my Parent and Child classes: class Parent(Base): id = Column(...) ... children = relationship("Child", backref="parent", lazy="select") class Child(Base): id = Column(...) parent_id = Column(...) active = Column(Boolean(), ...) The reason behind the loading technique of children of Parent being lazy is that t...
I think you unnecessary iterate over children within active_count hybrid_property definition. This should works for you: class Parent(Base): ... children = relationship("Child", backref="parent", lazy="dynamic") @hybrid_property def active_count(self): return self.children.filter_by(active=True).with_entities(func.coun...
7
5
70,721,360
2022-1-15
https://stackoverflow.com/questions/70721360/python-selenium-web-scrap-how-to-find-hidden-src-value-from-a-links
Scrapping links should be a simple feat, usually just grabbing the src value of the a tag. I recently came across this website (https://sunteccity.com.sg/promotions) where the href value of a tags of each item cannot be found, but the redirection still works. I'm trying to figure out a way to grab the items and their c...
By reverse-engineering the Javascript that takes you to the promotions pages (seen in https://sunteccity.com.sg/_nuxt/d4b648f.js) that gives you a way to get all the links, which are based on the HappeningID. You can verify by running this in the JS console, which gives you the first promotion: window.__NUXT__.state.Pr...
6
3
70,722,545
2022-1-15
https://stackoverflow.com/questions/70722545/draw-circle-in-console-using-python
I want to draw a circle in the console using characters instead of pixels, for this I need to know how many pixels are in each row. The diameter is given as input, you need to output a list with the width in pixels of each line of the picture For example: input: 7 output: [3, 5, 7, 7, 7, 5, 3] input: 12 output: [4, 8,...
This was a good reminder for me to be careful when mixing zero-based and one-based computations. In this case, I had to account for the for loops being zero-based, but the quotient of the diameter divided by 2 being one-based. Otherwise, the plots would have been over or under by 1. By the way, while I matched your ans...
7
3
70,723,165
2022-1-15
https://stackoverflow.com/questions/70723165/pandas-groupby-get-value-from-previous-element-of-a-group-based-on-value-of-ano
I have a data frame with 4 columns. I have sorted this data frame by 'group' and 'timestamp' beforehand. df = pd.DataFrame( { "type": ['type0', 'type1', 'type2', 'type3', 'type1', 'type3', 'type0', 'type1', 'type3', 'type3'], "group": [1, 1, 1, 1, 1, 1, 2, 2, 2, 2], "timestamp": ["20220105 07:52:46", "20220105 07:53:11...
We can mask the price with type3 then ffill s = df.price.mask(df.type.isin(['type0','type3'])) df['new'] = np.where(df.type.eq('type3'),s.groupby(df['group']).ffill(),df['price']) df type group timestamp price new 0 type0 1 20220105 07:52:46 0 0 1 type1 1 20220105 07:53:11 1.5 1.5 2 type2 1 20220105 07:53:55 2.5 2.5 3 ...
4
4
70,719,806
2022-1-15
https://stackoverflow.com/questions/70719806/outlier-removal-techniques-from-an-array
I know there's a ton resources online for outlier removal, but I haven't yet managed to obtain what I exactly want, so posting here, I have an array (or DF) of 4 columns. Now I want to remove the rows from the DF based on a column's outlier values. The following is what I have tried, but they are not perfect. def outli...
You could use scipy's median_filter: import pandas as pd from matplotlib import pyplot as plt from scipy.ndimage import median_filter b = pd.read_csv("test.csv") x = b.copy() x.orig_w = median_filter(b.orig_w, size=15) #Plot plt.rcParams['figure.figsize'] = [10,8] #Original plt.plot(b.t,b.orig_w,'o',label='Original',al...
4
3
70,714,809
2022-1-14
https://stackoverflow.com/questions/70714809/iterate-variables-over-binary-combinations
Is there a simple way to loop variables through all possible combinations of true/false? For example, say we have a function: def f(a, b, c): return not (a and (b or c)) Is there a way to loop a,b,c through 000, 001, 010, 011, 100, etc.? My first thought was to loop through the integers and get the bit that correspond...
Use itertools.product: from itertools import product for a, b, c in product([True, False], repeat=3): print(f(a,b,c), " ", a,b,c) If you really want integers 1 and 0, just replace [True, False] with [1, 0]. There's little reason to treat integers as bit arrays here.
4
5
70,698,407
2022-1-13
https://stackoverflow.com/questions/70698407/huggingface-autotokenizer-valueerror-couldnt-instantiate-the-backend-tokeniz
Goal: Amend this Notebook to work with albert-base-v2 model Error occurs in Section 1.3. Kernel: conda_pytorch_p36. I did Restart & Run All, and refreshed file view in working directory. There are 3 listed ways this error can be caused. I'm not sure which my case falls under. Section 1.3: # define the tokenizer tokeni...
First, I had to pip install sentencepiece. However, in the same code line, I was getting an error with sentencepiece. Wrapping str() around both parameters yielded the same Traceback. --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-1...
6
7
70,708,036
2022-1-14
https://stackoverflow.com/questions/70708036/how-to-get-a-terraform-object-into-an-aws-lambda-environment
Lambda functions support the environment parameter and make it easy to define a key-value pair. But what about getting an object (defined by a module variable eg) into the function's environment? Quick example of what I'm trying to accomplish in python 3.7: Terraform: # variable definition variable foo { type = map(any...
In python, you will have to get json string and convert it to dict: import json def bar: for k in json.loads(os.environ["foo"]): print(k)
4
5
70,704,749
2022-1-14
https://stackoverflow.com/questions/70704749/type-hint-for-class-method-return-error-name-is-not-defined
The following class has a class method create(), which as a type hint for return type, for creating an instance of the class. class X: @classmethod def create(cls) -> X: pass However, it got the following error? NameError: name 'X' is not defined
The name X doesn't exist until the class is fully defined. You can fix this by importing a __future__ feature called annotations. Just put this at the top of your file. from __future__ import annotations This wraps all annotations in quotation marks, to suppress errors like this. It's the same as doing this class X: @...
7
9
70,696,896
2022-1-13
https://stackoverflow.com/questions/70696896/how-to-add-already-created-figures-to-a-subplot-figure
I created this function that generates the ROC_AUC, then I returned the figure created to a variable. from sklearn.metrics import roc_curve, auc from sklearn.preprocessing import label_binarize import matplotlib.pyplot as plt def plot_multiclass_roc(clf, X_test, y_test, n_classes, figsize=(17, 6)): y_score = clf.decisi...
You need exactly the same as in the linked solution. You can't store plots for later use. Note that in matplotlib a figure is the surrounding plot with one or more subplots. Each subplot is referenced via an ax. Function plot_multiclass_roc needs some changes: it needs an ax as parameter, and the plot should be create...
8
8
70,701,672
2022-1-13
https://stackoverflow.com/questions/70701672/how-can-i-scale-deployment-replicas-in-kubernetes-cluster-from-python-client
I have Kubernetes cluster set up and managed by AKS, and I have access to it with the python client. Thing is that when I'm trying to send patch scale request, I'm getting an error. I've found information about scaling namespaced deployments from python client in the GitHub docs, but it was not clear what is the body n...
The body argument to the patch_namespaced_deployment_scale can be a JSONPatch document, as @RakeshGupta shows in the comment, but it can also be a partial resource manifest. For example, this works: >>> api_response = api_instance.patch_namespaced_deployment_scale( ... name, namespace, ... [{'op': 'replace', 'path': '/...
4
11
70,698,738
2022-1-13
https://stackoverflow.com/questions/70698738/two-walrus-operators-in-one-if-statement
Is there a correct way to have two walrus operators in 1 if statement? if (three:= i%3==0) and (five:= i%5 ==0): arr.append("FizzBuzz") elif three: arr.append("Fizz") elif five: arr.append("Buzz") else: arr.append(str(i-1)) This example works for three but five will be "not defined".
The logical operator and evaluates its second operand only conditionally. There is no correct way to have a conditional assignment that is unconditionally needed. Instead use the "binary" operator &, which evaluates its second operand unconditionally. arr = [] for i in range(1, 25): # v force evaluation of both operand...
6
2
70,688,858
2022-1-12
https://stackoverflow.com/questions/70688858/how-to-continuously-read-from-stdin-not-just-once-input-file-is-done
I have these two scripts: clock.py #!/usr/bin/env python3 import time while True: print("True", flush=True) time.sleep(1) continuous_wc.py #!/usr/bin/env python3 import sys def main(): count = 0 for line in sys.stdin: sys.stdout.write(str(count)) count += 1 if __name__=='__main__': main() And I run them like so: ./cl...
In addition to print(x, flush=True) you must also flush after sys.stdout.write. Note that the programs would technically work without flush, but they would print values very infrequently, in very large chunks, as the Python IO buffer is many kilobytes. Flushing is there to make it work more real-time. sys.stdout.write(...
5
4
70,697,906
2022-1-13
https://stackoverflow.com/questions/70697906/split-text-into-smaller-paragraphs-of-a-minimal-length-without-breaking-the-sent
Is there a better way to do this task? For the pre-processing of an NLP task, I was trying to split large pieces of text into a list of strings of even length. By splitting the text at every "." I would have very uneven sentences in length. By using an index/number I would cut off sentences in the middle. The goal was ...
IIUC, you want to split the text on dot, but try to keep a minimal length of the chunks to avoid having very short sentences. What you can do is to split on the dots and join again until you reach a threshold (here 200 characters): out = [] threshold = 200 for chunk in text.split('. '): if out and len(chunk)+len(out[-1...
5
2
70,679,571
2022-1-12
https://stackoverflow.com/questions/70679571/how-do-i-set-a-wildcard-for-csrf-trusted-origins-in-django
After updating from Django 2 to Django 4.0.1 I am getting CSRF errors on all POST requests. The logs show: "WARNING:django.security.csrf:Forbidden (Origin checking failed - https://127.0.0.1 does not match any trusted origins.): /activate/" I can't figure out how to set a wildcard for CSRF_TRUSTED_ORIGINS? I have a ser...
The Django app is running using Gunicorn behind NGINX. Because SSL is terminated after NGINX request.is_secure() returns false which results in Origin header not matching the host here: https://github.com/django/django/blob/3ff7f6cf07a722635d690785c31ac89484134bee/django/middleware/csrf.py#L276 I resolved the issue by ...
11
6
70,688,159
2022-1-12
https://stackoverflow.com/questions/70688159/using-plt-annotate-how-to-adjust-arrow-color
I want to add some annotations and arrows to my plots using plt.annotate() and I am not sure how to change the arrow parameters. import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({'weight': [10, 10, 20, 5, 10, 15]}) print(df) Dummy Data: weight 0 10 1 10 2 20 3 5 4 10 5 15 Plot Line: ax = df.plot...
In arrowprops you should be able to set arrow color and other properties , something like this: arrowprops=dict(arrowstyle= '->', color='red', lw=3, ls='--')
4
5
70,685,203
2022-1-12
https://stackoverflow.com/questions/70685203/how-to-get-the-origin-url-in-fastapi
Is it possible to get the URL that a request came from in FastAPI? For example, if I have an endpoint that is requested at api.mysite.com/endpoint and a request is made to this endpoint from www.othersite.com, is there a way that I can retrieve the string "www.othersite.com" in my endpoint function?
The premise of the question, which could be formulated as a server can identify the URL from where a request came is misguided. True, some HTTP requests (especially some of the requests issued by browsers) carry an Origin header and/or a Referer [sic] header. Also, the Forwarded header, if present, contains informati...
5
5
70,686,557
2022-1-12
https://stackoverflow.com/questions/70686557/python-googlesearch-module-error-typeerror-search-got-an-unexpected-keywor
Here is my code, it was working properly before I was not getting an error while using it. I don't understand how it happened even though I didn't change with it. : results = [] for query in my_list: results.append(search(query, tld="com", num=1, stop=1, pause=2)) Error: results.append(search(query, tld="com", num=1,...
It is from the google python package. it is still working of all the versions. version parameters : query : query string that we want to search for. tld : tld stands for top level domain which means we want to search our result on google.com or google.in or some other domain. lang : lang stands for language. num : Num...
4
10
70,682,654
2022-1-12
https://stackoverflow.com/questions/70682654/comparing-pandas-map-and-merge
I have the following df: df = pd.DataFrame({'key': {0: 'EFG_DS_321', 1: 'EFG_DS_900', 2: 'EFG_DS_900', 3: 'EFG_Q_900', 4: 'EFG_DS_1000', 5: 'EFG_DS_1000', 6: 'EFG_DS_1000', 7: 'ABC_DS_444', 8: 'EFG_DS_900', 9: 'EFG_DS_900', 10: 'EFG_DS_321', 11: 'EFG_DS_900', 12: 'EFG_DS_1000', 13: 'EFG_DS_900', 14: 'EFG_DS_321', 15: '...
map will be faster than a merge If your goal is simply to assign a numerical category to each unique value in df['AB'], you could use pandas.factorize that should be a bit faster than map: res = df['AB'].factorize()[0]+1 output: array([1, 1, 1, 2, 2, 3, 3, 3]) test on 800k rows: factorize 28.6 ms ± 153 µs map 32.1 ms ...
6
5
70,680,363
2022-1-12
https://stackoverflow.com/questions/70680363/structural-pattern-matching-using-regex
I have a string that I'm trying to validate against a few regex patterns and I was hoping since Pattern matching is available in 3.10, I might be able to use that instead of creating an if-else block. Consider a string 'validateString' with possible values 1021102,1.25.32, string021. The code I tried would be something...
It is not possible to use regex-patterns to match via structural pattern matching (at this point in time). From: PEP0643: structural-pattern-matching PEP 634: Structural Pattern Matching Structural pattern matching has been added in the form of a match statement and case statements of patterns with associated actions....
27
4
70,678,304
2022-1-12
https://stackoverflow.com/questions/70678304/removing-signs-and-repeating-numbers
I want to remove all signs from my dataframe to leave it in either one of the two formats: 100-200 or 200 So the salaries should either have a single hyphen between them if a range of salaries if given, otherwise a clean single number. I have the following data: import pandas as pd import re df = {'salary':['£26,768 - ...
Another way using pandas.Series.str.partition with replace: data["salary"].str.partition("/")[0].str.replace("[^\d-]+", "", regex=True) Output: 0 26768-30136 1 26000-28000 2 21000 3 26768-30136 4 33 5 18500-20500 6 27500-30000 7 35000-40000 8 24000-27000 9 19000-24000 10 30000-35000 11 44000-66000 12 75-90 Name: 0, dt...
5
5
70,675,453
2022-1-12
https://stackoverflow.com/questions/70675453/django-app-runs-locally-but-i-get-csrf-verification-failed-on-heroku
My app runs fine at heroku local but after deployed to Heroku, every time I try to login/register/login as admin, it returns this error shown below. I have tried to put @csrf_exempt on profile views, but that didn't fix the issue. What can I do?
The error message is fairly self-explanatory (please excuse typos as I can't copy from an image): Origin checking failed - https://pacific-coast-78888.herokuapp.com does not match any trusted origins The domain you are using is not a trusted origin for CSRF. There is then a link to the documentation, which I suspect g...
4
11
70,658,748
2022-1-10
https://stackoverflow.com/questions/70658748/using-fastapi-in-a-sync-way-how-can-i-get-the-raw-body-of-a-post-request
Using FastAPI in a sync, not async mode, I would like to be able to receive the raw, unchanged body of a POST request. All examples I can find show async code, when I try it in a normal sync way, the request.body() shows up as a coroutine object. When I test it by posting some XML to this endpoint, I get a 500 "Interna...
Using async def endpoint If an object is a co-routine, it needs to be awaited. FastAPI is actually Starlette underneath, and Starlette methods for returning the request body are async methods (see the source code here as well); thus, one needs to await them (inside an async def endpoint). For example: from fastapi impo...
26
33
70,648,645
2022-1-10
https://stackoverflow.com/questions/70648645/create-a-field-which-is-immutable-after-being-set
Is it possible to create a Pydantic field that does not have a default value and this value must be set on object instance creation and is immutable from then on? e.g. from pydantic import BaseModel class User(BaseModel): user_id: int name: str user = User(user_id=1, name='John') user.user_id = 2 # raises immutable err...
Pydantic already has the option you want. You can customize specific field by specifying allow_mutation to false. This raises a TypeError if the field is assigned on an instance. from pydantic import BaseModel, Field class User(BaseModel): user_id: int = Field(..., allow_mutation=False) name: str class Config: validate...
9
12
70,660,854
2022-1-11
https://stackoverflow.com/questions/70660854/how-to-check-if-a-bot-can-dm-a-user
If a user has the privacy setting "Allow direct messages from server members" turned off and a discord bot calls await user.dm_channel.send("Hello there") You'll get this error: discord.errors.Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user I would like to check whether I can message a...
Explanation You can send an invalid message, which would raise a 400 Bad Request exception, to the dm_channel. This can be accomplished by setting content to None, for example. If it raises 400 Bad Request, you can DM them. If it raises 403 Forbidden, you can't. Code async def can_dm_user(user: discord.User) -> bool: t...
10
11
70,597,020
2022-1-5
https://stackoverflow.com/questions/70597020/lower-latency-from-webcam-cv2-videocapture
I'm building an application using the webcam to control video games (kinda like a kinect). It uses the webcam (cv2.VideoCapture(0)), AI pose estimation (mediapipe), and custom logic to pipe inputs into dolphin emulator. The issue is the latency. I've used my phone's hi-speed camera to record myself snapping and found l...
Welcome to the War-on-Latency ( shaving-off ) The experience you have described above is a bright example, how accumulated latencies could devastate any chances to keep a control-loop tight-enough, to indeed control something meaningfully stable, as in a MAN-to-MACHINE-INTERFACE system we wish to keep: User's-motion | ...
5
10
70,597,896
2022-1-5
https://stackoverflow.com/questions/70597896/check-if-conda-env-exists-and-create-if-not-in-bash
I have a build script to run a simple python app. I am trying to set it up that it will run for any user that has conda installed and in their PATH. No other prerequisites. I have that pretty much accomplished but would like to make it more efficient for returning users. build_run.sh conda init bash conda env create --...
update 2022 i've been receiving upvotes recently. so i'm going to bump up that this method overall is not natively "conda" and might not be the best approach. like i said originally, i do not use conda. take my advice at your discretion. rather, please refer to @merv's comment in the question suggesting the use of the ...
8
9
70,587,544
2022-1-5
https://stackoverflow.com/questions/70587544/brew-install-python-installs-3-9-why-not-3-10
My understanding is that "brew install python" installs the latest version of python. Why isn't it pulling 3.10? 3.10 is marked as a stable release. I can install 3.10 with "brew install python@3.10 just fine and can update my PATH so that python and pip point to the right versions. But I am curious why "brew install p...
As Henry Schreiner have specified now Python 3.10 is the new default in Brew. Thx for pointing it --- Obsolete --- The "python3" formula is still 3.9 in the brew system check the doc here: https://formulae.brew.sh/formula/python@3.9#default The latest version of the formula for 3.9 also support apple silicon. If you wa...
18
32
70,624,413
2022-1-7
https://stackoverflow.com/questions/70624413/how-to-read-from-dev-stdin-with-asyncio-create-subprocess-exec
Backround I am calling an executable from Python and need to pass a variable to the executable. The executable however expects a file and does not read from stdin. I circumvented that problem previously when using the subprocess module by simply calling the executable to read from /dev/stdin along the lines of: # with ...
I'll briefly wrap up the question and summarize the outcome of the discussion. In short: The problem is related to a bug in Python's asyncio library that has been fixed by now. It should no longer occur in upcoming versions. Bug Details: In contrast to the Python subprocess library, asyncio uses a socket.socketpair() a...
6
2
70,645,074
2022-1-9
https://stackoverflow.com/questions/70645074/tensorflow-setup-on-rstudio-r-centos
For the last 5 days, I am trying to make Keras/Tensorflow packages work in R. I am using RStudio for installation and have used conda, miniconda, virtualenv but it crashes each time in the end. Installing a library should not be a nightmare especially when we are talking about R (one of the best statistical languages) ...
Update on 29 July, 2022 After months of solving this problem, I feel so stupid to have wasted time coding R on CentOS. The most popular and stable OS to code R is Ubuntu. By default, CentOS supports only the 3.6 version of R while the most stable current version of R is 4.2. With the default 3.6 version of R on CentOS,...
6
3
70,588,185
2022-1-5
https://stackoverflow.com/questions/70588185/warning-the-script-pip3-8-is-installed-in-usr-local-bin-which-is-not-on-path
When running pip3.8 i get the following warning appearing in my terminal WARNING: The script pip3.8 is installed in '/usr/local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. Successfully installed pip-21.1.1 setuptools-56.0.0...
This question has been answered on the serverfaults forum: Here is a link to the question. You need to add the following line to your ~/.bash_profile or ~/.bashrc file. export PATH="/usr/local/bin:$PATH" You will then need to profile, do this by either running the command: source ~/.bash_profile Or by simply closing...
49
72
70,641,660
2022-1-9
https://stackoverflow.com/questions/70641660/how-do-you-get-and-use-a-refresh-token-for-the-dropbox-api-python-3-x
As the title says, I am trying to generate a refresh token, and then I would like to use the refresh token to get short lived Access tokens. There is a problem though, in that I'm not smart enough to understand the docs on the dropbox site, and all the other information I've found hasn't worked for me (A, B, C) or is i...
Here is how I did it. I'll try to keep it simple and precise Replace <APP_KEY> with your dropbox app key in the below Authorization URL https://www.dropbox.com/oauth2/authorize?client_id=<APP_KEY>&token_access_type=offline&response_type=code Complete the code flow on the Authorization URL. You will receive an AUTHORIZA...
15
37
70,639,556
2022-1-9
https://stackoverflow.com/questions/70639556/is-it-possible-to-use-pydantic-instead-of-dataclasses-in-structured-configs-in-h
Recently I have started to use hydra to manage the configs in my application. I use Structured Configs to create schema for .yaml config files. Structured Configs in Hyda uses dataclasses for type checking. However, I also want to use some kind of validators for some of the parameter I specify in my Structured Configs ...
For those of you wondering how this works exactly, here is an example of it: import hydra from hydra.core.config_store import ConfigStore from omegaconf import OmegaConf from pydantic.dataclasses import dataclass from pydantic import validator @dataclass class MyConfigSchema: some_var: float @validator("some_var") def ...
12
12
70,669,213
2022-1-11
https://stackoverflow.com/questions/70669213/gyp-err-stack-error-command-failed-python-c-import-sys-print-s-s-s-s
I'm trying to npm install in a Vue project, and even if I just ran vue create (name) it gives me this err: npm ERR! gyp verb check python checking for Python executable "c:\Python310\python.exe" in the PATH npm ERR! gyp verb `which` succeeded c:\Python310\python.exe c:\Python310\python.exe npm ERR! gyp ERR! configure e...
As @MehdiMamas pointed out in the comments, downgrading Node to v14 should solve the problem nvm install 14 nvm use 14
10
16
70,648,404
2022-1-10
https://stackoverflow.com/questions/70648404/syntaxerror-multiple-exception-types-must-be-parenthesized
I am a beginner and have a problem after installing pycaw for the audio control using python, on putting the basic initialization code for pycaw, i get the following error:- Traceback (most recent call last): File "c:\Users\...\volumeControl.py", line 7, in <module> from comtypes import CLSCTX_ALL File "C:\...\env\lib\...
After a time searching I found that comtypes uses a tool to be compatible with both python 2 and 3 and that is no longer works in new versions. I had to downgrade two packages and reinstall comtypes: pip install setuptools==57.0.0 --force-reinstall pip install wheel==0.36.2 --force-reinstall pip uninstall comtypes pip ...
18
6
70,622,426
2022-1-7
https://stackoverflow.com/questions/70622426/centos-8-firewalld-error-command-failed-python-nftables-failed
when I try to reload firewalld, it tells me Error: COMMAND_FAILED: 'python-nftables' failed: internal:0:0-0: Error: Could not process rule: Numerical result out of range JSON blob: {"nftables": [{"metainfo": {"json_schema_version": 1}}, {"add": {"chain": {"family": "inet", "table": "firewalld", "name": "filter_IN_polic...
I had the same error message. I enabled verbose debugs on firewalld and tailed the logs to file for a deeper dive. In my case the exception was originally happening in "nftables.py" on line "361". Exception: 2022-01-23 14:00:23 DEBUG3: <class 'firewall.core.nftables.nftables'>: calling python-nftables with JSON blob: ...
8
2