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
72,764,417
2022-6-26
https://stackoverflow.com/questions/72764417/looping-through-rows-of-pandas-when-the-equation-also-changes
I need to ignore timestamps and loop through rows this way. import pandas as pd import numpy as np time = ['11:50', '12:50', '13:50'] data_1 = {'time': time, 'n1': [1, 5, 8], 'n2': [2, 6 ,7], 'n3': [3, 7 ,6], 'n4': [4, 8, 5], } df1 = pd.DataFrame(data = data_1) df1 I am trying to multiply: row 1 * (10^0) row 2 * (1...
You can use mul on index axis: df1.iloc[:, 1:] = df1.iloc[:, 1:].mul(10**df1.index, axis=0) print(df1) # Output time n1 n2 n3 n4 0 11:50 1 2 3 4 1 12:50 50 60 70 80 2 13:50 800 700 600 500 You can replace df1.index by np.arange(len(df1)) if your index is not a RangeIndex.
4
5
72,762,251
2022-6-26
https://stackoverflow.com/questions/72762251/create-a-pytorch-tensor-of-sequences-which-excludes-specified-value
I have a 1d PyTorch tensor containing integers between 0 and n-1. Now I need to create a 2d PyTorch tensor with n-1 columns, where each row is a sequence from 0 to n-1 excluding the value in the first tensor. How can I achieve this efficiently? Ex: n = 3 a = torch.Tensor([0, 1, 2, 1, 2, 0]) # desired output b = [ [1, 2...
We can construct a tensor with the desired sequences and index with tensor a. import torch n = 3 a = torch.Tensor([0, 1, 2, 1, 2, 0]) # using torch.tensor is recommended def exclude_gather(a, n): sequences = torch.nonzero(torch.arange(n) != torch.arange(n)[:,None], as_tuple=True)[1].reshape(-1, n-1) return sequences[a....
4
1
72,738,301
2022-6-24
https://stackoverflow.com/questions/72738301/best-way-to-read-aws-credentials-file
In my python code I need to extract AWS credentials AWS_SECRET_ACCESS_KEY and AWS_ACCESS_KEY_ID which are stored in the plain text file as described here: https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html I know the name of the file: AWS_SHARED_CREDENTIALS_FILE and the name of profile: AWS_PROFILE. My cu...
Would something like this work for you, or am I misunderstanding the question? Basically start a session for the appropriate profile (or the default, I guess), and then query those values from the credentials object: session = boto3.Session(profile_name=<...your-profile...>) credentials = session.get_credentials() pri...
7
8
72,754,426
2022-6-25
https://stackoverflow.com/questions/72754426/gui-freezing-in-python-pyside6
I am developing a software as part of my work, as soon as I make a call to the API to fetch data the GUI freezes, at first I understood the problem and transferred the functions to threads, the problem is that once I used the join() function the app froze again. What I would like is to wait at the same point in the fun...
One possible option would be to use QThreads finished signal it emits that you can connect to with a slot that contains the remaining logic from your get_all_tickets method. threads = [] def call_api(self, query, index, return_dict): thread = QThread() worker = Worker(query, index, return_dict) worker.moveToThread(thre...
4
3
72,754,331
2022-6-25
https://stackoverflow.com/questions/72754331/webdriver-object-has-no-attribute-find-element-by-link-text-selenium-scrip
This is a weird issue I have ran into and I can't find any solution for this across the internet. I was using selenium in google colab to scrape a website and my code was working completely fine. I woke up the next day and ran the code again without changing a single line and don't know how/why my code starting giving ...
Selenium just removed that method in version 4.3.0. See the CHANGES: https://github.com/SeleniumHQ/selenium/blob/a4995e2c096239b42c373f26498a6c9bb4f2b3e7/py/CHANGES Selenium 4.3.0 * Deprecated find_element_by_* and find_elements_by_* are now removed (#10712) * Deprecated Opera support has been removed (#10630) * Fully ...
8
25
72,753,000
2022-6-25
https://stackoverflow.com/questions/72753000/what-is-the-most-suitable-efficient-pandas-data-type-for-ids
Probably obvious, but just wanted to confirm: What would be the best suited data type for a numerical ID in pandas? Let's say that I have a sequential numerical ID type user_id, which would be better: an int64 type (that would seem to be the most obvious choice given the numerical representation of the field) a catego...
Operating on object-typed dataframes/arrays is slow because Pandas needs to operate on each item using the inefficient CPython interpreter. This causes a high overhead due to reference counting, internal pointer indirections, type checks, internal function calls, etc. Pandas often uses Numpy internally which can be muc...
7
6
72,743,499
2022-6-24
https://stackoverflow.com/questions/72743499/regex-alternative-to-expression-to-define-word-sequence
i am currently trying to match specific sentences based on the words they contain and their order. I am doing this mostly with the lookahead assertion based on this structure: [^>.\]]*(?="The desired Words)[^<.\]]* So i am for example looking for sentences that talk about Vacation in the Maledives. To match the sentenc...
You can try something like this. (?:^|\.)\s*([^.]*[Vv]acation[^.]*[Mm]aledives[^.]*(?:\.|$)) See demo. https://regex101.com/r/97UvCH/1 There is no need for lookahead .It will slow things down.
4
2
72,741,663
2022-6-24
https://stackoverflow.com/questions/72741663/argument-parser-from-a-pydantic-model
How do I create an argument parser (argparse.ArgumentParser) from a Pydantic model? I have a Pydantic model: from pydantic import BaseModel, Field class MyItem(BaseModel): name: str age: int color: str = Field(default="red", description="Color of the item") And I want to create an instance of MyItem using command line...
I found an answer myself. Just: create an argument parser, turn the fields of the model as arguments of the parser, parse the command-line arguments, turn the arguments as dict and pass them to the model and process the instance of the model import argparse from pydantic import BaseModel, Field class MyItem(BaseModel...
11
14
72,738,553
2022-6-24
https://stackoverflow.com/questions/72738553/how-can-i-run-an-ffmpeg-command-in-a-python-script
I want to overlay a transparent video over top of an image using ffmpeg and python I am able to do this successfully through terminal, but I cannot get ffmpeg commands to work in python. The following command produces the result that I want in terminal when I am in the directory with the files there. ffmpeg -i head1.pn...
In Windows one line with spaces should work, but in Linux we have to pass the arguments as list. We can build the command as a list: command = ['ffmpeg', '-i', 'head1.png', '-i', 'hdmiSpitting.mov', '-filter_complex', '[0:v][1:v]overlay=0:0', '-pix_fmt', 'yuv420p', '-c:a', 'copy', 'output3.mov'] We may also use shl...
4
10
72,737,853
2022-6-24
https://stackoverflow.com/questions/72737853/get-values-after-idxmin1
I apply idxmin() to get the index of the minimum absolute value of two columns: rep["OffsetFrom"] = rep[["OffsetDates", "OffsetDays"]].abs().idxmin(axis=1).dropna() OffsetDates OffsetDays OffsetFrom 0 0.0 0.0 OffsetDates 1 1.0 1.0 OffsetDates 2 4.0 -3.0 OffsetDays 3 4.0 -3.0 OffsetDays 4 6.0 -1.0 OffsetDays ... ... ....
First idea is use lookup by column Offset: rep["Offset"] = rep[["OffsetDates", "OffsetDays"]].abs().idxmin(axis=1) idx, cols = pd.factorize(rep['Offset']) rep["OffsetVal"] = rep.reindex(cols, axis=1).to_numpy()[np.arange(len(rep)), idx] Another numpy solution is use numpy.argmin for positions by absolute values, then ...
4
1
72,736,760
2022-6-23
https://stackoverflow.com/questions/72736760/making-abstract-property-in-python-3-results-in-attributeerror
How do you make an abstract property in python? import abc class MyClass(abc.ABC): @abc.abstractmethod @property def foo(self): pass results in the error AttributeError: attribute '__isabstractmethod__' of 'property' objects is not writable
It turns out that order matters when it comes to python decorators. @abc.abstractmethod @property is not the same as @property @abc.abstractmethod The correct way to create an abstract property is: import abc class MyClass(abc.ABC): @property @abc.abstractmethod def foo(self): pass
28
37
72,736,116
2022-6-23
https://stackoverflow.com/questions/72736116/could-not-interpret-value-in-scatterplot
I have a dataset with 2 features with the name pos_x and pos_y and I need to scatter plot the clustered data done with DBScan. Here is what I have tried for it: dataset = pd.read_csv(r'/Users/file_name.csv') Data = dataset[["pos_x","pos_y"]].to_numpy() dbscan=DBSCAN() clusters =dbscan.fit(Data) p = sns.scatterplot(data...
I think the error is caused by this part of the code: Data = dataset[["pos_x","pos_y"]].to_numpy() When you convert the dataframe to numpy, seaborn cannot access the columns as it should. Try this: dataset = pd.read_csv(r'/Users/file_name.csv') Data = dataset[["pos_x","pos_y"]] dbscan = DBSCAN() clusters = dbscan.fit(...
4
3
72,723,928
2022-6-23
https://stackoverflow.com/questions/72723928/how-to-combine-several-images-to-one-image-in-a-grid-structure-in-python
I have several images (PNG format) that I want to combine them into one image file in a grid structure (in such a way that I can set the No. of images shown in every row). Also, I want to add small empty space between images. For example, assume that there are 7 images. And I want to set the No. of images shown in ever...
You can pass to the combine_images function number of expected columns, space between images in pixels and the list of images: from PIL import Image def combine_images(columns, space, images): rows = len(images) // columns if len(images) % columns: rows += 1 width_max = max([Image.open(image).width for image in images]...
7
7
72,710,695
2022-6-22
https://stackoverflow.com/questions/72710695/controlling-context-manager-in-a-meta-class
I would like to know if it's possible to control the context automatically in a metaclass and decorator. I have written a decorator function that creates the stub from the grpc insecure channel: def grpc_factory(grpc_server_address: str): print("grpc_factory") def grpc_connect(func): print("grpc_connect") def grpc_conn...
You have a problem in this part of the code, that your are not setting an expected proto object instead you are setting string class AnalyserClient(AC, metaclass=Client, grpc_server_address="localhost:50051"): def grpc_analyse(self, text, stub) -> str: print("Analysing text: {}".format(text)) print("Stub is ", stub) st...
6
2
72,722,768
2022-6-22
https://stackoverflow.com/questions/72722768/why-does-super-not-do-the-same-as-super-init
I have been wondering this for a while now, and I hope this isn't a stupid question with an obvious answer I'm not realizing: Why can't I just call the __init__ method of super() like super()()? I have to call the method like this instead: super().__init__() Here is an example that gets a TypeError: 'super' object is n...
super() objects can't intercept most special method calls, because they bypass the instance and look up the method on the type directly, and they don't want to implement all the special methods when many of them won't apply for any given usage. This case gets weirder, super()() would try to lookup a __call__ method on ...
4
6
72,714,112
2022-6-22
https://stackoverflow.com/questions/72714112/what-is-the-difference-between-engine-begin-and-engine-connect
i go first straight for my questions: Why would one rather use engine.connect() instead of engine.begin(), if the second is more reliable? Then, why is it still on the tutorial page of SQLAlchemy and everywhere in stackoverflow? Performance? Why does engine.connect() work so inconsistently? Is the problem withing the a...
the scope of with engine.connect() does an autocommit as well No, it doesn't. That's the most striking difference between with engine.connect() and with engine.begin() with engine.connect() as conn: # do stuff # on exit, the transaction is automatically rolled back with engine.begin() as conn: # do stuff # on exit, t...
8
16
72,715,121
2022-6-22
https://stackoverflow.com/questions/72715121/how-to-restart-a-python-script
In a program I am writing in python I need to completely restart the program if a variable becomes true, looking for a while I found this command: while True: if reboot == True: os.execv(sys.argv[0], sys.argv) When executed it returns the error [Errno 8] Exec format error. I searched for further documentation on os.ex...
There are multiple ways to achieve the same thing. Start by modifying the program to exit whenever the flag turns True. Then there are various options, each one with its advantages and disadvantages. Wrap it using a bash script. The script should handle exits and restart your program. A really basic version could be: #...
4
7
72,644,693
2022-6-16
https://stackoverflow.com/questions/72644693/new-union-shorthand-giving-unsupported-operand-types-for-str-and-type
Before 3.10, I was using Union to create union parameter annotations: from typing import Union class Vector: def __mul__(self, other: Union["Vector", float]): pass Now, when I use the new union shorthand syntax: class Vector: def __mul__(self, other: "Vector" | float): pass I get the error: TypeError: unsupported op...
The fact that it's being used as a type hint doesn't really matter; fundamentally the expression "Vector" | float is a type error because strings don't support the | operator, they don't implement __or__. To get this passing, you have three options: Defer evaluation (see PEP 563): from __future__ import annotations cl...
36
41
72,633,453
2022-6-15
https://stackoverflow.com/questions/72633453/how-can-i-style-a-django-form-with-css
I tried looking for the answer earlier but couldn't seem to figure out a few things. I'm creating my form in a form.py file so its a python file. Here is my forms.py file : class UploadForm(ModelForm): name = forms.TextInput(attrs={'class': 'myfieldclass'}) details = forms.TextInput() littype = forms.TextInput() image ...
Within your template you have to just import the css file in the head tag, but do ensure you load static first. html file: {% load static %} <!doctype html> <html lang="en"> <head> # import the css file here <link rel="stylesheet" href="{% static 'path to css file' %}"> </head> ... </html> Within the css file: # Styli...
3
5
72,633,461
2022-6-15
https://stackoverflow.com/questions/72633461/sample-from-each-group-in-polars-dataframe
I'm looking for a function along the lines of df.group_by('column').agg(sample(10)) so that I can take ten or so randomly-selected elements from each group. This is specifically so I can read in a LazyFrame and work with a small sample of each group as opposed to the entire dataframe. Update: One approximate solution ...
Let start with some dummy data: n = 100 seed = 0 df = pl.DataFrame({ "groups": (pl.int_range(n, eager=True) % 5).shuffle(seed=seed), "values": pl.int_range(n, eager=True).shuffle(seed=seed) }) shape: (100, 2) ┌────────┬────────┐ │ groups ┆ values │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞════════╪════════╡ │ 0 ┆ 55 │ │ 0 ┆ 40 │ ...
14
13
72,707,357
2022-6-21
https://stackoverflow.com/questions/72707357/buildx-failed-with-error-cache-export-feature-is-currently-not-supported-for-d
I have been trying to setup a CI pipeline through Github Actions to docker-hub. I have written the following .yml file part of .github\workflow and getting the error as indicated below in Build and Push step of the job. I have tried to find it on Internet but I could not able to find it. name: Build and Deploy Code on:...
You'll need something like this in your yml workflow file: - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 You can see a complete example at Configuring your GitHub Action builder
10
21
72,636,788
2022-6-15
https://stackoverflow.com/questions/72636788/in-python-how-can-i-add-a-patch-decorator-that-does-not-add-a-mock-input-argume
In python, how can I add a patch that does not add a mock input argument? I want to add a patch on all methods in a class like so: @patch('django.utils.timezone.now', return_value=datetime.datetime(2022, 4, 22, tzinfo=timezone.utc)) class TestmanyMethods(unittest.TestCase): # my test methods here But when I do that, a...
One can do this by using the new keyword arg in the patch like so: @patch('django.utils.timezone.now', new=Mock(return_value=datetime.datetime(2022, 4, 22, tzinfo=timezone.utc))) class TestmanyMethods(unittest.TestCase): # my test methods here With that, the mock input is not added to the class's test methods
7
7
72,668,275
2022-6-18
https://stackoverflow.com/questions/72668275/how-to-upload-an-image-file-to-github-using-pygithub
I want to upload an image file to my Github Repository using Pygithub. from github import Github g=Github("My Git Token") repo=g.get_repo("My Repo") content=repo.get_contents("") f=open("1.png") img=f.read() repo.create_file("1.png","commit",img) But I am getting the following error: File "c:\Users\mjjha\Documents\Che...
Just Tested my solution and it's working Explanation: The AssertionError assert isinstance(content, (str, bytes)) Tells us that it only takes string and bytes. So we just have to convert our image to bytes. #1 Converting image to bytearray file_path = "1.png" with open(file_path, "rb") as image: f = image.read() image_...
4
8
72,660,874
2022-6-17
https://stackoverflow.com/questions/72660874/how-to-print-one-log-line-per-every-10-epochs-when-training-models-with-tensorfl
When I fit the model with: model.fit(X, y, epochs=40, batch_size=32, validation_split=0.2, verbose=2) it prints one log line for each epoch as: Epoch 1/100 0s - loss: 0.2506 - acc: 0.5750 - val_loss: 0.2501 - val_acc: 0.3750 Epoch 2/100 0s - loss: 0.2487 - acc: 0.6250 - val_loss: 0.2498 - val_acc: 0.6250 Epoch 3/100 0s...
This callback will create and write on a log text file what you want: log_path = "text_file_name.txt" # it will be created automatically class print_training_on_text_every_10_epochs_Callback(Callback): def __init__(self, logpath): self.logpath = logpath def on_epoch_end(self, epoch, logs=None): with open(self.logpath, ...
4
2
72,642,843
2022-6-16
https://stackoverflow.com/questions/72642843/using-the-in-operator-in-python-3-10-match-case
Is there a "in" operator in python 3.10 Match Case like with if else statements if "\n" in message: the in operator doesn't work in match case match message: case "\n" in message: This doesn't work. How to have something like the "in" operator in Match-Case.
For completeness, it can be done indirectly using guards (as used in the other answer). match message: case message if "\n" in message: ... some code... case message if "foo" in message: ... some other code... Note using the name message in each case statement is not required (this does have the side effect of binding...
5
8
72,651,555
2022-6-16
https://stackoverflow.com/questions/72651555/attributeerror-module-jinja2-ext-has-no-attribute-autoescape-while-trying-t
I am new to Flask and Babel and I have just started a project which will contain several languages. After I have generated the babel.cfg file, when I attempt to extract it with the command pybabel extract -F babel.cfg -o messages.pot ., I get the AttributeError: module 'jinja2.ext' has no attribute 'autoescape' error....
With Jinja2 3.1, WithExtension and AutoEscapeExtension are built-in now. So you don't need these extensions anymore. Delete these extension from babel.cfg file [python: **.py] [jinja2: **/templates/**.html] ;extensions=jinja2.ext.auto escape,jinja2.ext.with_ https://jinja.palletsprojects.com/en/3.1.x/changes/#version-...
13
24
72,646,458
2022-6-16
https://stackoverflow.com/questions/72646458/how-to-authenticate-google-services-in-google-colaboratory-without-user-interact
I use the following to access bouth Google Drive and Google Sheets in my Google Colab Notebook: # Mount Google Drive from google.colab import drive drive.mount('/content/drive') # Google Sheets from google.colab import auth auth.authenticate_user() import gspread from google.auth import default creds, _ = default() gc ...
As a possible solution, I may suggest using Service Account. Go to GCP Console Select your current project (or create a new one): Once the project is selected, go to IAM and Admin -> Service accounts -> + Create service account: Next, you'll see a create service account prompt, which consists of 3 form steps. Fil...
4
4
72,686,010
2022-6-20
https://stackoverflow.com/questions/72686010/is-preexec-fn-ever-safe-in-multi-threaded-programs-under-what-circumstances
I understand that using subprocess.Popen(..., preexec_fn=func) makes Popen thread-unsafe, and might deadlock the child process if used within multi-threaded programs: Warning: The preexec_fn parameter is not safe to use in the presence of threads in your application. The child process could deadlock before exec is cal...
The following explanation is for POSIX only. This issue of executing code after forking and before execing in a multi-threaded process is not Python specific. In the child, do not call any library functions after calling fork() and before calling exec(). One of the library functions might use a lock that was held in t...
4
2
72,656,861
2022-6-17
https://stackoverflow.com/questions/72656861/how-to-add-hatches-to-boxplots-with-sns-boxplot-or-sns-catplot
I need to add hatches to a categorical box plot. What I have is this: What I need is something like this (with the median lines): And what I have tried is this code: exercise = sns.load_dataset("exercise") g = sns.catplot(x="time", y="pulse", hue="kind", data=exercise, kind="box") bars = g.axes[0][0].patches hatches=...
Iterate through each subplot / FacetGrid with for ax in g.axes.flat:. ax.patches contains matplotlib.patches.Rectangle and matplotlib.patches.PathPatch, so the correct ones must be used. Caveat: all hues must appear for each group in each Facet, otherwise the patches and hatches will not match. In this case, manual...
5
7
72,694,757
2022-6-21
https://stackoverflow.com/questions/72694757/cryptographydeprecationwarning-python-3-6-is-no-longer-supported-by-the-python
I upgraded my system from python 2 to python 3, and now when I run my code: from cryptography.hazmat.backends import default_backend I am getting this error /usr/local/lib/python3.6/site-packages/paramiko/transport.py:33: CryptographyDeprecationWarning: Python 3.6 is no longer supported by the Python core team. Theref...
I ran into this issue today and did some digging. Since the os is not provided I think you could consider one of the options below: Upgrade your python version. This might be the best option since python 3.6 reached its EOL. You might be using SSH in your code. Consider installing an older version of paramiko. You c...
9
5
72,663,716
2022-6-17
https://stackoverflow.com/questions/72663716/how-to-efficiently-convert-npy-to-xarray-zarr
I have a 37 GB .npy file that I would like to convert to Zarr store so that I can include coordinate labels. I have code that does this in theory, but I keep running out of memory. I want to use Dask in-between to facilitate doing this in chunks, but I still keep running out of memory. The data is "thickness maps" for ...
using threads If the dask workers can share threads, your code should just work. If you don't initialize a dask Cluster explicitly, dask.Array will create one with default args, which use processes. This results in the behavior you're seeing. To solve this, explicitly create a cluster using threads: # use threads, not ...
4
4
72,707,064
2022-6-21
https://stackoverflow.com/questions/72707064/vs-code-does-not-find-own-python-module-in-workspace
I am working on a python package with VS Code with the following layout of the opened workspace folder in VS Code workspace | + tests | | - test1.py | | + other_tests | | | - test2.py | + mymodule | | ... What I want is to call in test1.py and test2.py the package mymodule with import mymodule When I do this, I alway...
When the python interpreter is importing a package, it looks for the package in the following locations: the directory containing the input script (or the current directory). PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH). the installation-dependent default. So if your package...
7
3
72,688,032
2022-6-20
https://stackoverflow.com/questions/72688032/hash-of-integers-in-python
I understand that hash of an immutable object is an integer representation of that object which is unique within the process's lifetime. Hash of an integer object is the same as the value held by the integer. For example, >>> int(1000).__hash__() 1000 But when the integer grows big enough, above principle breaks after...
While this is machine and implementation dependent, for CPython on 64-bit machines, the hash() for a non-negative integer n is computed as n % k with k = (2 ** 61 - 1) (= 2305843009213693951) hence values between 0 and k - 1 are left as is. This is empirically evidenced here: k = 2 ** 61 - 1 for i in range(k - 2, k + 2...
4
2
72,697,369
2022-6-21
https://stackoverflow.com/questions/72697369/real-time-data-plotting-from-a-high-throughput-source
I want to plot Real time in a way that updates fast. The data I have: arrives via serial port at 62.5 Hz data corresponds to 32 sensors (so plot 32 lines vs time). 32points *62.5Hz = 2000 points/sec The problem with my current plotting loop is that it runs slower than 62.5[Hz], meaning I miss some data coming in from...
You could try to have two separate processes: one for acquiring and storing the data one for plotting the data Below there are two basic scripts to get the idea. You first run gen.py which starts to generate numbers and save them in a file. Then, in the same directory, you can run plot.py which will read the last pa...
4
4
72,691,325
2022-6-20
https://stackoverflow.com/questions/72691325/how-to-add-n-to-a-variable-value-to-submit-it-as-an-input-of-remote-process-v
I am working with Paramiko on Linux, I would like to know if I can send a variable to shell. I want to enter to "enable mode" of a Cisco router. But I don't want to hard-code the password in the script. I am using getpass, but when I run the script it fails in the enable command. I get "bad secrets". I know that happen...
Use + operator. shell.send(passwordE + '\n') Or you can simply call send twice: shell.send(passwordE) shell.send('\n') Obligatory warning: Do not use AutoAddPolicy this way – You are losing a protection against MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".
4
2
72,703,563
2022-6-21
https://stackoverflow.com/questions/72703563/read-a-pandas-dataframe-into-r
I have used reticulate package to source python code in R. source_python("data_loading.py") df = my_data() str(df) 'data.frame': 268 obs. of 13 variables: $ DKF: num 1.352 1.283 1.246 0.73 0.784 ... $ GDT: num NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... $ GSB: num 1.427 1.366 1.162 0.785 0.742 ... $ HKZ: num 1.355 1.49...
if you have data already in R you can run: library(reticulate) d <- py_to_r(py_eval('my_data().reset_index()')) d which should give you: year month DKF GDT GSB HKZ SLG SRL UAB UKE 1 2000 1 1.3517226 NaN 1.4273286 1.3554525 1.5487504 2.0594033 1.5548904 1.2689103 2 2000 2 1.2830497 NaN 1.3664731 1.4951631 1.5415838 1....
3
2
72,702,555
2022-6-21
https://stackoverflow.com/questions/72702555/how-do-i-fill-between-two-lineplots-in-seaborn
I have a graph that plots Bayesian mean point data in a line with credible intervals around the mean value. I'm trying to fill between to two credibility lines with a translucent color so the mean line really pops through. I've tried the following: plt.fill_between(b.get_data(), c.data_get(), color='blue', alpha = .5)...
If you get the last line graph, you will get data for three line graphs, which you can set to fill the first of the x-axis and y-axis and the second of the y-axis to fill to get the intended result. fig = plt.figure(figsize=(15,4)) a=sns.lineplot(x=date, y=mean, label = 'Posterior Predictive') b=sns.lineplot(x=date, y=...
3
8
72,687,875
2022-6-20
https://stackoverflow.com/questions/72687875/how-to-detect-which-key-was-pressed-on-keyboard-mouse-using-tkinter-python
I'm using tkinter to make a python app and I need to let the user choose which key they will use to do some specific action. Then I want to make a button which when the user clicks it, the next key they press as well in keyboard as in mouse will be detected and then it will be bound it to that specific action. How can ...
To expand on @darthmorf's answer in order to also detect mouse button events, you'll need to add a separate event binding for mouse buttons with either the '<Button>' event which will fire on any mouse button press, or '<Button-1>', (or 2 or 3) which will fire when that specific button is pressed (where '1' is the left...
3
3
72,699,442
2022-6-21
https://stackoverflow.com/questions/72699442/hangman-game-that-doesnt-show-any-errors-however-terminal-shows-nothing
import random from Words import words import string def get_valid_word(words): word = random.choice(words) while '-' or ' ' in word: word = random.choice(words) return word.upper() def hangman() -> object: word = get_valid_word(words) word_letter = set(word) alphabet = set(string.ascii_uppercase) used_letter = set() wh...
The issue appears to be with the line while '-' or ' ' in word: your syntax is slightly off meaning that this will always evaluate to True and thus the code enters an infinite loop at this point python interprets the above as while ('-') or (' ' in word): an thus the string - is one half of the or statement and any n...
3
2
72,699,262
2022-6-21
https://stackoverflow.com/questions/72699262/getting-cell-value-by-row-name-and-column-name-from-dataframe
Let's say I have the following data frame name age favorite_color grade 0 Willard Morris 20 blue 88 1 Al Jennings 19 blue 92 2 Omar Mullins 22 yellow 95 3 Spencer McDaniel 21 green 70 And I'm trying to get the grade for Omar which is "95" it can be easily obtained using ddf = df.loc[[2], ['grade']] print(ddf) Howeve...
Try this: ddf = df[df['name'] == 'Omar Mullins']['grade'] to output the grade values. Instead: ddf = df[df['name'] == 'Omar Mullins'] will output the full row.
3
6
72,692,790
2022-6-20
https://stackoverflow.com/questions/72692790/numpy-determine-the-corresponding-float-datatype-from-a-complex-datatype
I'm using two numpy arrays of floating point numbers Rs = np.linspace(*realBounds, realResolution, dtype=fdtype) Is = np.linspace(*imagBounds, imagResolution, dtype=fdtype) to make a grid Zs of complex numbers with shape (realResolution, imagResolution). I'd like to only specify the datatype of Zs and use this to dete...
I don't think there is such a function in numpy but you can easily roll your own using num, which uniquely identifies each of the built-in types: def get_corresonding_dtype(dt): return {11: np.csingle, 12: np.cdouble, 13: np.clongdouble, 14: np.single, 15: np.double, 16: np.longdouble}[np.dtype(dt).num] The dict was o...
4
2
72,693,302
2022-6-20
https://stackoverflow.com/questions/72693302/merge-dataframes-and-extract-only-the-rows-of-the-dataframe-that-does-not-exist
I am trying to merge two dataframes and create a new dataframe containing only the rows from the first dataframe that does not exist in the second one. For example: The dataframes that I have as input: The dataframe that I want to have as output: Do you know if there is a way to do that? If you could help me, I would...
Creating some data, we have two dataframes: import pandas as pd import numpy as np rng = np.random.default_rng(seed=5) df1 = pd.DataFrame(data=rng.integers(0, 5, size=(5, 2))) df2 = pd.DataFrame(data=rng.integers(0, 5, size=(5, 2))) # df1 a b 0 3 4 1 0 4 2 2 2 3 3 1 4 4 0 # df2 a b 0 1 1 1 2 2 2 0 0 3 0 0 4 0 4 We ca...
4
3
72,677,648
2022-6-19
https://stackoverflow.com/questions/72677648/how-to-iterate-through-list-infinitely-with-1-offset-each-loop
I want to infinitely iterate through the list from 0 to the end, but in the next loop I want to start at 1 to the end plus 0, and the next loop would start at 2 to the end plus 0, 1, up to the last item where it would start again at 0 and go to the end. Here is my code: a = [ 0, 1, 2 ] offset = 0 rotate = 0 while True:...
You can use a deque which has a built-in and efficient rotate function (~O(1)): >>> d = deque([0,1,2]) >>> for _ in range(10): ... print(*d) ... d.rotate(-1) # negative -> rotate to the left ... 0 1 2 1 2 0 2 0 1 0 1 2 1 2 0 2 0 1 0 1 2 1 2 0 2 0 1 0 1 2
28
49
72,686,762
2022-6-20
https://stackoverflow.com/questions/72686762/how-to-apply-filter-on-django-manytomanyfield-so-that-multiple-value-of-the-fiel
class Publication(models.Model): title = models.CharField(max_length=30) class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) p1 = Publication.objects.create(title='The Python Journal') p2 = Publication.objects.create(title='Science News') p3 = Publ...
If you chain mutliple calls to filter() they should behave like being connected with an AND: articles = Article.objects.filter(publications=p1).filter(publications=p3).distinct()
5
4
72,683,540
2022-6-20
https://stackoverflow.com/questions/72683540/count-unique-words-with-collections-and-dataframe
I have a problem, I want to count the unique words from a dataframe, but unfortunately it only counts the first sentences. text 0 hello is a unique sentences 1 hello this is a test 2 does this works import pandas as pd d = { "text": ["hello is a unique sentences", "hello this is a test", "does this works"], } df = pd...
I think simplier is join values by space, then split for words and count: counter = Counter((' '.join(df['text'])).split()) print (counter) Counter({'hello': 2, 'is': 2, 'a': 2, 'this': 2, 'unique': 1, 'sentences': 1, 'test': 1, 'does': 1, 'works': 1})
3
2
72,680,516
2022-6-19
https://stackoverflow.com/questions/72680516/having-problem-with-drawing-lines-thickness-in-pygame
Here is the board I drew using pygame: https://i.sstatic.net/Hne6A.png I'm facing a bug with the thickness of the last two lines as I marked them on the image. I believe there is something wrong with the if statement in my code but I can't quite figure it out, it just won't take effect. here is the code that has drawn ...
To draw a thick line, half the thickness is applied to both sides of the line. The simplest solution is to make the target surface a little larger and add a small offset to the coordinates of the lines. For performance reasons, I also recommend creating the surface before the application loop and continuously blit it i...
4
2
72,636,013
2022-6-15
https://stackoverflow.com/questions/72636013/efficiently-find-the-indices-of-shared-values-with-repeats-between-two-large-a
Problem description Let's take this simple array set # 0,1,2,3,4,5 a = np.array([1,1,3,4,6]) b = np.array([6,6,1,3]) From these two arrays I want to get the indices of all possible matches. So for number 1 we get 0,2 and 1,2, with the complete output looking like: 0,2 # 1 1,2 # 1 2,3 # 3 4,0 # 6 4,1 # 6 Note that t...
NOTE: this post is now superseded by the faster alternative sort-based solution. The dict based approach is an algorithmically efficient solution compared to others (I guess Polars should use a similar approach). However, the overhead of CPython make it a bit slow. You can speed it up a bit using Numba. Here is an impl...
4
3
72,676,882
2022-6-19
https://stackoverflow.com/questions/72676882/force-an-abstract-class-attribute-to-be-implemented-by-concrete-class
Considering this abstract class and a class implementing it: from abc import ABC class FooBase(ABC): foo: str bar: str baz: int def __init__(self): self.bar = "bar" self.baz = "baz" class Foo(FooBase): foo: str = "hello" The idea here is that a Foo class that implements FooBase would be required to specify the value o...
This is a partial answer. You can use class FooBase(ABC): @property @classmethod @abstractmethod def foo(cls) -> str: ... class Foo(FooBase): foo = "hi" def go(f: FooBase) -> str: return f.foo It's only partial because you'll only get a mypy error if you try to instantiate Foo without an initialized foo, like class Fo...
6
2
72,675,162
2022-6-19
https://stackoverflow.com/questions/72675162/pydantic-model-copied-when-passing-it-to-another-model
Pydantic copies a model when passing it to the constructor of another model. This fails: from pydantic import BaseModel class Child(BaseModel): pass class Parent(BaseModel): child: Child child = Child() parent = Parent(child=child) assert parent.child is child # Fails It seems child is copied when passing it to the pa...
I found the answer myself. Seems this was an issue but it was fixed in a PR by creating a config option copy_on_model_validation. If this option is set to False for the child, then the child is not copied in the construction. This does not copy the child: from pydantic import BaseModel class Child(BaseModel): class Con...
5
8
72,668,076
2022-6-18
https://stackoverflow.com/questions/72668076/why-does-splitlines-not-give-the-expected-result-for-triple-dots-in-jupyter
I believe the following code s = ''' ... .o. ... ''' print(s.splitlines()) should print ['', '...', '.o.', '...'] Indeed, this is the case when Python is executed normally (example run on Wandbox is here). But the reality is ruthless (as usual); Google Colaboratory prints a result without "triple dots": I also tried...
Google collab interprets ... as part of the prompt. You can change the prompt to some other string and the result will be as you expected : import sys sys.ps2 = '<<<' # default value is ... s = ''' ... .o. ... ''' print(s.splitlines()) ['', '...', '.o.', '...'] EDIT: As @user2357112 pointed out in the comments and in ...
16
11
72,668,970
2022-6-18
https://stackoverflow.com/questions/72668970/drf-yasg-swagger-auto-schema-not-showing-the-required-parameters-for-post-reque
I am using django-yasg to create an api documentation. But no parameters are showing in the documentation to create post request. Following are my codes: After that in swagger api, no parameters are showing for post request to create the event model.py class Events(models.Model): user = models.ForeignKey(User, on_dele...
I got it running with following changes in views.py @swagger_auto_schema( methods=['post'], request_body=openapi.Schema( type=openapi.TYPE_OBJECT, required=['category','name', 'location', 'start_date', 'end_date', 'description', 'completed', 'banner'], properties={ 'category':openapi.Schema(type=openapi.TYPE_STRING), '...
3
4
72,670,733
2022-6-18
https://stackoverflow.com/questions/72670733/insert-empty-row-after-every-nth-row-in-pandas-dataframe
I have a dataframe: pd.DataFrame(columns=['a','b'],data=[[3,4], [5,5],[9,3],[1,2],[9,9],[6,5],[6,5],[6,5],[6,5], [6,5],[6,5],[6,5],[6,5],[6,5],[6,5],[6,5],[6,5]]) I want to insert two empty rows after every third row so the resulting output looks like that: a b 0 3.0 4.0 1 5.0 5.0 2 9.0 3.0 3 NaN NaN 4 NaN NaN 5 1.0 ...
The following should scale well with the size of the DataFrame since it doesn't iterate over the rows and doesn't create intermediate DataFrames. import pandas as pd df = pd.DataFrame(columns=['a','b'],data=[[3,4], [5,5],[9,3],[1,2],[9,9],[6,5],[6,5],[6,5],[6,5], [6,5],[6,5],[6,5],[6,5],[6,5],[6,5],[6,5],[6,5]]) def ad...
4
6
72,671,820
2022-6-18
https://stackoverflow.com/questions/72671820/copied-list-passed-to-generator-reflects-changes-made-to-original
In answering this question, I stumbled across some unexpected behavior: from typing import List, Iterable class Name: def __init__(self, name: str): self.name = name def generator(lst: List[Name]) -> Iterable[str]: lst_copy = lst.copy() for obj in lst_copy: yield obj.name When modifying the list that is passed to the ...
I think the behavior is best understood with the addition of some extra print statements: def generator(lst: List[Name]) -> Iterable[str]: print("Creating list copy...") lst_copy = lst.copy() print("Created list copy!") for obj in lst_copy: yield obj.name lst = [Name("Tom"), Name("Tommy")] print("Starting assignment......
4
2
72,671,197
2022-6-18
https://stackoverflow.com/questions/72671197/how-to-make-a-select-field-using-django-model-forms-using-set-values
I recently switched from using simple forms in Django to model forms. I am now trying to use a select field in my form that has set field names (eg:Europe,North America,South America...) I thought I would just add a select input type to the for fields but it shows up as just a regular text input. The select field is su...
Here you can use ModelChoiceField provided by django forms. Define a Country model containing all the countries, and use that as a QuerySet here. It will be also be dynamic that can be changed later. from django import forms from .models import Trip, Country class TripForm(forms.ModelForm): class Meta: model = Trip fie...
4
6
72,669,730
2022-6-18
https://stackoverflow.com/questions/72669730/how-to-easily-and-cheaply-run-a-simply-python-script-every-5-mins-for-a-whole-we
I want to run a very simple python script (or any language) which collects data from an api at regular 5 minute intervals and saves the data. I need this process to run for a whole week - day and night. I can't keep my laptop on all week so I guess I will need this to run on some kind of server. What is the cheapest an...
You're going to need a cloud server as it's the cheapest option if u can't setup a system at home. I'll 2nd what furas said about pythonanywhere.com. I use their $5 a month plan to run simple tasks like this. You can cancel anytime so if it's just 1 week then you pay $5 for your account, that's it. There is no messing ...
3
4
72,631,305
2022-6-15
https://stackoverflow.com/questions/72631305/advance-a-interpolation
Note; No special knowledge of Pykrige is needed to answer the question, as I already mention examples in the question! Hi I would like to use Universal Kriging in my code. For this I have data that is structured as follows: Latitude Longitude Altitude H2 O18 Date Year month dates a_diffO O18a 0 45.320000 -75.670000 1...
From the documentation of pykrige.uk.UniversalKriging (https://geostat-framework.readthedocs.io/projects/pykrige/en/stable/generated/pykrige.uk.UniversalKriging.html#pykrige.uk.UniversalKriging): drift_terms (list of strings, optional) – List of drift terms to include in universal kriging. Supported drift terms are cu...
4
1
72,663,092
2022-6-17
https://stackoverflow.com/questions/72663092/getting-numpy-linalg-svd-and-numpy-matrix-multiplication-to-use-multithreadng
I have a script that uses a lot of numpy and numpy.linalg functions and after some reaserch it tourned out that supposedly they automaticaly use multithreading. Altought that, my htop display always shows just one thread being used to run my script. I am new to multithreading and I don´t quite now how to set up it corr...
The main issue is that the size of the matrices is too small for threads to be really worth it on all platforms. Indeed, OpenBLAS uses OpenMP to create threads regarding the size of the matrix. Threads are generally created once but the creation can take from dozens of microseconds to dozens of milliseconds regarding t...
6
5
72,649,475
2022-6-16
https://stackoverflow.com/questions/72649475/specify-python-version-on-cloud-run-buildpack
I am deploying a web app on Cloud Run using the automated Cloud Build "Buildpack" option (as explained here); hence not having to create a Docker File. I would like to deploy the app using python-3.8.12 and buildpacks. How can I specify that?
There’s no need to specify it. The builder attempts to autodetect the language of your source code and Python 3.7+ is one of the supported languages. You may try this Python buildpacks sample. You can also find out deeper information about buildpacks in this presentation. Update As an alternative, you can also manually...
3
0
72,660,954
2022-6-17
https://stackoverflow.com/questions/72660954/coverage-no-source-for-code-with-pytest
I am trying to measure code coverage by my pytest tests. I tried following the quick start guide of coverage (https://coverage.readthedocs.io/en/6.4.1/) When I run my test with the following command, everything seems fine coverage run -m pytest tests/ ===================================== test session starts =========...
It is possible to ignore errors using the command coverage html -i which solved my issue
6
3
72,657,415
2022-6-17
https://stackoverflow.com/questions/72657415/fix-futurewarning-related-to-the-pandas-append-function
I am getting the following FutureWarning in my Python code: FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead. Right now I was using the append function, in various parts of my code, to add rows to an existing DataFrame. Example 1: init_h...
Use pd.concat instead of append. Preferably on a bunch of rows at the same time. Also, use date_range and timedelta_range whenever possible. Example 1: # First transformation init_hour = pd.to_datetime('00:00:00') orig_hour = init_hour+timedelta(days=1) rows = [] while init_hour < orig_hour: rows.append({'Hours': init_...
4
4
72,657,327
2022-6-17
https://stackoverflow.com/questions/72657327/stdin-is-not-a-tty-when-populating-postgres-database
I get the message stdin is not a tty when I run the command below in my terminal. psql -U postgres kdc < kdc.psql kdc is the database and kdc.psql is the psql file with commands to populate the database. I am in the directory that holds the psql file.
I am not sure what causes that message (it does not happen here), but you should be able to avoid it using the -f option: psql -U postgres -d kdc -f kdc.psql
3
5
72,654,704
2022-6-17
https://stackoverflow.com/questions/72654704/filenotfounderror-op-type-not-registered-regexsplitwithoffsets-while-loading
I am trying to load a Keras model on aws server with the following command import tensorflow_hub as hub from keras.models import load_model model = load_model(model_path, custom_objects={'KerasLayer': hub.KerasLayer}) but its giving an error FileNotFoundError: Op type not registered 'RegexSplitWithOffsets' in binary r...
importing tensorflow_text resolve this issue
4
8
72,648,685
2022-6-16
https://stackoverflow.com/questions/72648685/how-to-test-if-one-graph-is-a-subgraph-of-another-in-networkx
I am new to building directed graphs with networkx and I'm trying to work out how to compare two graphs. More specifically, how to tell if a smaller graph is a subgraph (unsure of the exact terminology) of a larger graph As an example, assume I have the following directed graph: I would like to be able to check whethe...
You are looking for a subgraph isomorphisms. nx.isomorphism.DiGraphMatcher(A, B).subgraph_is_isomorphic() # True nx.isomorphism.DiGraphMatcher(A, C).subgraph_is_isomorphic() # False Note that the operation can be slow for large graphs, as the problem is NP-complete.
4
4
72,648,520
2022-6-16
https://stackoverflow.com/questions/72648520/how-to-remove-duplicate-values-from-list-of-dicts-and-keep-original-order
I have a list of dictionaries like this : time_array_final = [{'day': 15, 'month': 5},{'day': 29, 'month': 5}, {'day': 10, 'month': 6}, {'day': 10, 'month': 6}, {'day': 10, 'month': 6}, {'day': 10, 'month': 6}, {'day': 12, 'month': 6}, {'day': 12, 'month': 6}, {'day': 12, 'month': 6}, {'day': 12, 'month': 6}, {'day': 1...
You can create a dictionary where the key is the string representation of the items in your list, and the value is the actual item. time_array_final = [{'day': 15, 'month': 5},{'day': 29, 'month': 5}, {'day': 10, 'month': 6}, {'day': 10, 'month': 6}, {'day': 10, 'month': 6}, {'day': 10, 'month': 6}, {'day': 12, 'month'...
3
3
72,645,862
2022-6-16
https://stackoverflow.com/questions/72645862/numpy-array-slicing-to-return-sliced-array-and-corresponding-array-indices
I'm trying to generate two numpy arrays from one. One which is a slice slice of an original array, and another which represents the indexes which can be used to look up the values produced. The best way I can explain this is by example: import numpy as np original = np.array([ [5, 3, 7, 3, 2], [8, 4, 22, 6, 4], ]) slic...
You can use numpy's slice np.s_[] with a tiny bit of gymnastics to get the indices you are looking for: slc = np.s_[:, ::3] shape = original.shape ix = np.unravel_index(np.arange(np.prod(shape)).reshape(shape)[slc], shape) >>> ix (array([[0, 0], [1, 1]]), array([[0, 3], [0, 3]])) >>> original[ix] array([[5, 3], [8, 6]...
3
2
72,649,220
2022-6-16
https://stackoverflow.com/questions/72649220/precise-type-annotating-array-numpy-ndarray-of-matplotlib-axes-from-plt-subplo
I wanted to have no errors while using VSCode Pylance type checker. How to type the axs correctly in the following code: import matplotlib.pyplot as plt fig, axs = plt.subplots(2, 2) In the image below, you can see that Pylance on VSCode is detecting an error.
It turns out that strongly typing the axs variable is not straightforward at all and requires to understant well how to type np.ndarray. See this question and this question for more details. The simplest and most powerful solution is to wrap numpy.ndarray with ' characters, in order to avoid the infamous TypeError: 'nu...
4
1
72,646,846
2022-6-16
https://stackoverflow.com/questions/72646846/remove-duplicates-from-a-list-and-remove-elements-at-same-index-in-another-list
I have two lists, one with word and another one with word type like this ['fish', 'Robert', 'dog', 'ball', 'cat', 'dog', 'Robert'] ['animal', 'person', 'animal', 'object', 'animal', 'animal', 'person'] I need to remove duplicates in the first list and to remove the type at the same index of the word removed. In the en...
just do a loop and use the zip function Script # Input Vars a = ['fish', 'Robert', 'dog', 'ball', 'cat', 'dog', 'Robert'] b = ['animal', 'person', 'animal', 'object', 'animal', 'animal', 'person'] # Output Vars c = [] d = [] # Process for e, f in zip(a, b): if(e not in c): c.append(e) d.append(f) # Print Output print(c...
3
1
72,630,488
2022-6-15
https://stackoverflow.com/questions/72630488/valueerror-mutable-default-class-dict-for-field-headers-is-not-allowed-use
I am trying to get used with new python's features (dataclasses). I am trying to initialize variables and I get error: raise ValueError(f'mutable default {type(f.default)} for field ' ValueError: mutable default <class 'dict'> for field headers is not allowed: use default_factory My code: @dataclass class Application(...
Dataclasses have a few useful things for defining complex fields. The one that you need is called field. This one has the argument default_factory that needs to receive callable, and there is where lambda comes to the rescue. So using this above, code that will work looks like (just part with dict): from dataclasses im...
5
10
72,629,578
2022-6-15
https://stackoverflow.com/questions/72629578/python-how-to-make-poetry-include-a-package-module-thats-not-on-a-subpath
I have, in a single repo, two Python projects that both depend on a shared utility package. My goal is to package each of the two projects in a software distribution package (i.e. a .tzr.gz file) I am currently getting this done using setuptools and setup.py files and having a hard time of it. I would much rather use P...
This seems to be a issue with poetry. Check this out https://github.com/python-poetry/poetry/issues/5621.
7
5
72,637,057
2022-6-15
https://stackoverflow.com/questions/72637057/typeerror-get-takes-1-positional-argument-but-2-were-given
I am building and Inventory Web App and I am facing this error. I am trying to get Username from token to show a custom hello message and show that the user is logged in as someone. Here is my Views.py that gets Token from localStorage as logged in user: class UserDetails(APIView): def post(self, request): serializer =...
The .get(…) method [Django-doc] takes a request parameter as well, even if you do not use it, so: class UserDetails(APIView): # … def get(self, request): # … pass I would strongly advise, not to make token a global variable. The same webserver can be used for another user that thus has not authenticated (properly). Tak...
4
4
72,633,449
2022-6-15
https://stackoverflow.com/questions/72633449/add-checkbox-in-dataframe
I would like to add a column in a dataframe in the streamlit and this column be a checkbox, so that later I could list the lines that the checkboxes were marked, is this possible?
You can use the package streamlit-aggrid. Code """ pip install streamlit-aggrid """ import streamlit as st import pandas as pd from st_aggrid import AgGrid, GridUpdateMode from st_aggrid.grid_options_builder import GridOptionsBuilder data = { 'country': ['Japan', 'China', 'Thailand', 'France', 'Belgium', 'South Korea']...
3
7
72,631,150
2022-6-15
https://stackoverflow.com/questions/72631150/joblib-load-error-no-module-named-scipy-sparse-csr
Python version: 3.7 (I have to use this version) OS: Linux Cloud Platform: Azure Resource: Azure function with python Goal: Load a model created with skit-learn version 1.0.2 with the following dependencies installed: numpy: 1.17.3 joblib: 1.1.0 scipy: 1.7.3 I am using joblib to load a skit-learn model that I train...
To resolve this ModuleNotFoundError: No module named 'scipy.sparse._csr' error, try the following way: This error occurred because you have created a model in Python 3.9 but running it on Python 3.7. You can try creating a model in Python 3.7 or upgrade the Azure Python function app to a specific version of Python 3.9....
3
6
72,628,845
2022-6-15
https://stackoverflow.com/questions/72628845/pycharm-terminal-use-git-bash
Goal: use Git Bash as Terminal in PyCharm. How can I have a normal Bash with Git integrated Terminal in PyCharm? File path for Git Bash: C:\Users\me\AppData\Local\Programs\Git\git-bash.exe --cd-to-home. I apply Git Bash in PyCharm Settings: However, when I click New Session (new Terminal +), it launches as a Window:
You are pointing at git-bash.exe, which is wrong. You should point at bash.exe which is located inside the bin folder. So your Shell path should be: "C:\Users\<username>\AppData\Local\Programs\Git\bin\bash.exe" --login using "C:\Users\<username>\AppData\Local\Programs\Git\bin\sh.exe" --login would also work. Also wor...
3
6
72,624,883
2022-6-15
https://stackoverflow.com/questions/72624883/how-do-i-dump-pythons-logging-configuration
How do I dump the current configuration of the Python logging module? For example, if I use a module that configures logging for me, how can I see what it has done?
There does not appear to be a documented way to do so, but we can get hints by looking at how the logging module is implemented. All Loggers belong to a tree, with the root Logger instance at logging.root. The Logger instances do not track their own children but instead have a shared Manager that can be used to get a l...
4
3
72,607,940
2022-6-13
https://stackoverflow.com/questions/72607940/how-to-use-unboundedpreceding-unboundedfollowing-and-currentrow-in-rowsbetween
I am a little confused about the method pyspark.sql.Window.rowsBetween that accepts Window.unboundedPreceding, Window.unboundedFollowing, and Window.currentRow objects as start and end arguments. Could you please explain how the function works and how to use Window objects correctly, with some examples? Thank you!
Rows between/Range between as the name suggests help with limiting the number of rows considered inside a window. Let us take a simple example. Starting with data: dfw = ( spark .createDataFrame( [ ("abc", 1, 100), ("abc", 2, 200), ("abc", 3, 300), ("abc", 4, 200), ("abc", 5, 100), ], "name string,id int,price int", ) ...
8
22
72,604,922
2022-6-13
https://stackoverflow.com/questions/72604922/how-to-convert-python-dataclass-to-dictionary-of-string-literal
Given a dataclass like below: class MessageHeader(BaseModel): message_id: uuid.UUID def dict(self, **kwargs): return json.loads(self.json()) I would like to get a dictionary of string literal when I call dict on MessageHeader The desired outcome of dictionary is like below: {'message_id': '383b0bfc-743e-4738-8361-27e6...
You can use dataclasses.asdict: from dataclasses import dataclass, asdict class MessageHeader(BaseModel): message_id: uuid.UUID def dict(self): return {k: str(v) for k, v in asdict(self).items()} If you're sure that your class only has string values, you can skip the dictionary comprehension entirely: class MessageHea...
77
120
72,564,558
2022-6-9
https://stackoverflow.com/questions/72564558/django-celery-error-while-adding-tasks-to-rabbitmq-message-queue-attributeerro
I have setup celery, rabbitmq and django web server on digitalocean. RabbitMQ runs on another server where my Django app is not running. When I am trying to add the tasks to the queue using delay I am getting an error AttributeError: 'ChannelPromise' object has no attribute 'value' From django shell I am adding the t...
To ensure the app is loaded when Django starts, we need to import the Celery app we defined in myproject/__init__.py: sudo nano myproject/__init__.py # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ['celery_app...
6
9
72,551,035
2022-6-8
https://stackoverflow.com/questions/72551035/why-i-cant-access-my-environment-variable-from-env-file-in-vscode-python
What I am trying to do? I am trying to access my environment variable from the .env file and print its value in the terminal. What is the issue? When I run the script in the terminal I keep getting the error none Some more info: I am using Windows 10 The version of dotenv is 0.20.0 I downloaded it using python -m pip ...
I solved my issue but it wasn't after removing the "export" in the .env file (I tried with and without it both gave the same results in the terminal), I had to specify the full path of the .env file in the load_dotenv(), apparently I had to specify it but many code samples I saw in forums didn't need to do it I wonder ...
10
8
72,610,552
2022-6-14
https://stackoverflow.com/questions/72610552/most-replayed-data-of-youtube-video-via-api
Is there any way to extract the "Most Replayed" (aka Video Activity Graph) Data from a YouTube video via API? What I'm referring to:
One more time YouTube Data API v3 doesn't provide a basic feature. I recommend you to try out my open-source YouTube operational API. Indeed by fetching https://yt.lemnoslife.com/videos?part=mostReplayed&id=VIDEO_ID, you will get the most replayed graph values you are looking for in item["mostReplayed"]. With the video...
16
21
72,560,837
2022-6-9
https://stackoverflow.com/questions/72560837/custom-fastapi-query-parameter-validation
Is there any way to have custom validation logic in a FastAPI query parameter? example I have a FastAPI app with a bunch of request handlers taking Path components as query parameters. For example: def _raise_if_non_relative_path(path: Path): if path.is_absolute(): raise HTTPException( status_code=409, detail=f"Absolut...
This is the kind of validation that the Depends dependency management function is well-suited for. It allows you to define dependencies for given view functions, and add logic to validate (and lazily create) those dependencies. This gives a set of composable dependencies that can be re-used in those views where they ar...
7
8
72,587,334
2022-6-11
https://stackoverflow.com/questions/72587334/how-to-await-a-list-of-tasks-in-python
In .Net C#, there is a function Task.WhenAll that can take a list of tasks to await them. What should I use in python? I am trying to do the same with this: tasks = ... # list of coroutines for task in tasks: await task
After adding tasks to a list, you should use asyncio.gather that gives coroutines as an argument list and executes them asynchronously. Also, you could use asyncio.create_task that takes a coroutine and calls concurrent tasks in the event loop. import asyncio async def coro(i): await asyncio.sleep(i//2) async def main(...
4
8
72,620,996
2022-6-14
https://stackoverflow.com/questions/72620996/apple-m1-symbol-not-found-cfrelease-while-running-python-app
I wanna run my app without any problem, but I got this attached error. Could someone help or point me in the right direction regarding why this is happening? Traceback (most recent call last): File "/Users/enchant3dmango/Documents/GitHub/nexus/automation-api/app/main.py", line 4, in <module> from configurations import ...
I was able to get around the problem by rebuilding grpcio from source like this: pip uninstall grpcio export GRPC_PYTHON_LDFLAGS=" -framework CoreFoundation" pip install grpcio --no-binary :all:
17
14
72,583,781
2022-6-11
https://stackoverflow.com/questions/72583781/im-getting-an-import-error-does-anyone-know-the-solution
hi I'm getting an import error, does anyone know the solution? ImportError: Bindings generation error. Submodule name should always start with a parent module name. Parent name: cv2.cv2. Submodule name: cv2
If you are using opencv-python version 4.6.0.66, try to downgrade to 4.5.5.64 version, on Pycharm you can do that by go to File->Setting->Python Interpreter-> Double-click on opencv-python version->check the specify version box, then choose older version. Downgrade opencv also makes the auto-completion works again.
3
15
72,605,385
2022-6-13
https://stackoverflow.com/questions/72605385/how-to-install-local-pip-package-from-mounted-volume-in-docker-compose
I am working on a project which has dependency on another project. In live environment, the dependency is published and installed simply using pip install. On my local environment, I'd like to be able to install the local dependency instead, using the pip install -e command. The structure is as follow: - Home --- Proje...
For simpler packages, it may be enough to just mount it directly into the site-packages. In your example, you might want to try: putting relaton-py (just the package in its source form, e.g. the Git repository) one directory above your Compose file, and adding this line to docker-compose.yml under volumes: - ../relat...
4
2
72,584,282
2022-6-11
https://stackoverflow.com/questions/72584282/django-caddy-csrf-protection-issues
I deployed a Django 4 app with Daphne (ASGI) in a docker container. I use Caddy as a reverse proxy in front. It works, except I can't fill in any form because the CSRF protection kicks in. So no admin login, for example. I can currently access the admin interface in two ways: Directly through docker, via a SSH tunelle...
Finally found out what was happening. I first wanted to know the exact HTTP request that was sent from caddy to django: sudo tcpdump -i lo -A -n port 8088 This confirmed that: the Origin and Referer headers were set properly the csrftoken cookie was sent properly Once that was known, I could dig in the code from dja...
5
11
72,550,211
2022-6-8
https://stackoverflow.com/questions/72550211/valueerror-at-least-one-stride-in-the-given-numpy-array-is-negative-and-tensor
I am writing the code for Autonomous Driving using RL. I am using a stable baseline3 and an open ai gym environment. I was running the following code in the jupyter notebook and it is giving me the following error: # Testing our model episodes = 5 # test the environment 5 times for episodes in range(1,episodes+1): # lo...
Using .copy() for numpy arrays should help (because PyTorch tensors can't handle negative strides): action, _ = model.predict(obs.copy()) I haven't managed to run your notebook quickly because of dependencies problems, but I had the same error with AI2THOR simulator, and adding .copy() has helped. Maybe someone with m...
4
12
72,544,983
2022-6-8
https://stackoverflow.com/questions/72544983/how-can-i-bulk-upload-json-records-to-aws-opensearch-index-using-a-python-client
I have a sufficiently large dataset that I would like to bulk index the JSON objects in AWS OpenSearch. I cannot see how to achieve this using any of: boto3, awswrangler, opensearch-py, elasticsearch, elasticsearch-py. Is there a way to do this without using a python request (PUT/POST) directly? Note that this is not f...
I finally found a way to do it using opensearch-py, as follows. First establish the client, # First fetch credentials from environment defaults # If you can get this far you probably know how to tailor them # For your particular situation. Otherwise SO is a safe bet :) import boto3 credentials = boto3.Session().get_cre...
7
17
72,621,731
2022-6-14
https://stackoverflow.com/questions/72621731/is-there-any-graceful-way-to-interrupt-a-python-concurrent-future-result-call
The only mechanism I can find for handling a keyboard interrupt is to poll. Without the while loop below, the signal processing never happens and the process hangs forever. Is there any graceful mechanism for allowing a keyboard interrupt to function when given a concurrent future object? Putting polling loops all over...
OK, I wrote a solution to this based on digging in cypython source and some bug reports - but it's not pretty. If you want to be able to interrupt a future, especially on Windows, the following seems to work: @contextlib.contextmanager def interrupt_futures(futures): # pragma: no cover """Allows a list of futures to be...
5
2
72,593,814
2022-6-12
https://stackoverflow.com/questions/72593814/cannot-import-name-soft-unicode-from-markupsafe-in-google-colab
I'm trying to install pycaret==3.0.0 in google colab, But I'm having a problem, the library requires Jinja2 to be installed which I did, but then It finally throws off another error. ImportError Traceback (most recent call last) <ipython-input-26-4f8843d24b3a> in <module>() ----> 1 import jinja2 2 from pycaret.regressi...
This is caused by upgrade in MarkupSafe:2.1.0 where they have removed soft_unicode, try using: pip install markupsafe==2.0.1
12
22
72,581,774
2022-6-11
https://stackoverflow.com/questions/72581774/how-to-use-python-3-6-in-google-colab
I want to work with python 3.6 due to some file compatibility issue, can anyone help me out, where I can use python 3.6 in google Colab, apart from that I want to use tensorflow 2.0 and opencv 4.0.0.21, which I have already install in Colab am only stuck with python 3.6. any help would be appreciated
You can use the command below and then select the alternative version to change the python version. !sudo update-alternatives --config python3 Output: There are 2 choices for the alternative python3 (providing /usr/bin/python3). Selection Path Priority Status -----------------------------------------------------------...
4
2
72,541,971
2022-6-8
https://stackoverflow.com/questions/72541971/what-is-the-best-solution-for-cron-schedule-environmental-variables-in-a-docker
I have a Python script that will run on certain intervals as the cron schedule will invoke the Python script inside a Docker container. I want the cron schedule expression to be set through an environment variable, like this: CRON_SCHEDULE="*/5 * * * *" So the user can freely choose how often the script will run. On t...
You should use the solution described in this answer https://stackoverflow.com/a/70897876/3669093 Whenever the environment variable is changed the container is restarted and the schedule is updated. If you need more guidance, shoot your questions.
5
2
72,593,019
2022-6-12
https://stackoverflow.com/questions/72593019/how-can-i-fire-and-forget-a-task-without-blocking-main-thread
What I have in mind is a very generic BackgroundTask class that can be used within webservers or standalone scripts, to schedule away tasks that don't need to be blocking. I don't want to use any task queues (celery, rabbitmq, etc.) here because the tasks I'm thinking of are too small and fast to run. Just want to get ...
Your questions are so abstract that I'll try to give common answers to all of them. How can I "fire and forget" a task without blocking main thread? It depends on what you mean by saying forget. If you are not planning to access that task after running, you can run it in a parallel process. If the main application s...
4
7
72,567,630
2022-6-9
https://stackoverflow.com/questions/72567630/different-approaches-for-applying-svm-in-keras
I want to build a multi-class classification model using Keras. My data is containing 7 features and 4 labels. If I am using Keras I have seen two ways to apply the Support vector Machine (SVM) algorithm. First: A Quasi-SVM in Keras By using the (RandomFourierFeatures layer) presented here I have built the following mo...
You can check two models on your data like below: I check on mnist dataset and get the below result: Less overfitting with the second approach Fast training time with the first approach Less trainable params with the first approach Accuracy for two approaches same as each other from keras.utils.layer_utils import cou...
4
1
72,596,436
2022-6-12
https://stackoverflow.com/questions/72596436/how-to-perform-approximate-structural-pattern-matching-for-floats-and-complex
I've read about and understand floating point round-off issues such as: >>> sum([0.1] * 10) == 1.0 False >>> 1.1 + 2.2 == 3.3 False >>> sin(radians(45)) == sqrt(2) / 2 False I also know how to work around these issues with math.isclose() and cmath.isclose(). The question is how to apply those work arounds to Python's ...
The key to the solution is to build a wrapper that overrides the __eq__ method and replaces it with an approximate match: import cmath class Approximately(complex): def __new__(cls, x, /, **kwargs): result = complex.__new__(cls, x) result.kwargs = kwargs return result def __eq__(self, other): try: return isclose(self, ...
55
59
72,610,665
2022-6-14
https://stackoverflow.com/questions/72610665/in-the-latest-version-of-pytorch-what-is-best-practice-to-get-all-tensors-to-us
In pytorch, if I do something like import torch x = torch.randn(3) y = x + 5 all tensors correspond to the "cpu" device by default. Is there some way to make to make it so, by default, all tensors are on another device (e.g. "cuda:0")? I know I can always be careful to add .cuda() or specify cuda whenever creating a t...
Pytorch has an optional function to change the default type of tensor set_default_tensor_type. Applying the default type on the main script: >>> import torch >>> >>> if __name__ == '__main__': ... cuda = torch.cuda.is_available() ... if cuda: ... torch.set_default_tensor_type('torch.cuda.FloatTensor') ... a = torch.ran...
4
2
72,614,335
2022-6-14
https://stackoverflow.com/questions/72614335/how-to-share-initialize-and-close-aiohttp-clientsession-between-django-async-v
Django supports async views since version 3.1, so it's great for non-blocking calls to e.g. external HTTP APIs (using, for example, aiohttp). I often see the following code sample, which I think is conceptually wrong (although it works perfectly fine): import aiohttp from django.http import HttpRequest, HttpResponse as...
Django doesn't implement the ASGI Lifespan protocol. Ref: https://github.com/django/django/pull/13636 Starlette does. FastAPI directly uses Starlette's implementation of event handlers. Here's how you can achieve that with Django: Implement the ASGI Lifespan protocol in a subclass of Django's ASGIHandler. import djan...
4
6
72,561,628
2022-6-9
https://stackoverflow.com/questions/72561628/why-such-a-big-pickle-of-a-sklearn-decision-tree-30k-times-bigger
Why pickling a sklearn decision tree can generate a pickle thousands times bigger (in terms of memory) than the original estimator? I ran into this issue at work where a random forest estimator (with 100 decision trees) over a dataset with around 1_000_000 samples and 7 features generated a pickle bigger than 2GB. I wa...
As pointed out by @pygeek's answer and subsequent comments, the wrong assumption of the question is that the pickle is increasing the size of the object substantially. Instead the issue lies with pympler.asizeof which is not giving the correct estimate of the tree object. Indeed the DecisionTreeRegressor object has a t...
7
1
72,598,852
2022-6-13
https://stackoverflow.com/questions/72598852/getcacheentry-failed-cache-service-responded-with-503
I am trying to check the lint on the gitubaction. my github action steps are as below lint: name: Lint runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3 - name: Set up Python uses: actions/setup-python@v4 with: python-version-file: '.python-version' cache: 'pip' cache-dependency-path: 'requireme...
lint: name: Lint runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3 - name: Set up Python uses: actions/setup-python@v4 with: python-version-file: '.python-version' - name: Cache dependencies uses: actions/cache@v3 with: path: ~/.cache/pip key: ${{ runner.os }}-pip-${{ hashFiles('requirements.txt'...
26
2
72,618,062
2022-6-14
https://stackoverflow.com/questions/72618062/pypdf-does-not-read-the-pdf-text-line-by-line
I was using PyPdf to read text from a pdf file. However pyPDF does not read the text in pdf line by line, Its reading in some haphazard manner. Putting new line somewhere when its not even present in the pdf. import PyPDF2 pdf_path = r'C:\Users\PDFExample\Desktop\Temp\sample.pdf' pdfFileObj = open(pdf_path, 'rb') pdfRe...
I tried a different package called as pdfplumber. It was able to read the pdf line by line in exact way in which I wanted. 1. Install the package pdfplumber pip install pdfplumber 2. Get the text and store it in some container import pdfplumber pdf_text = None with pdfplumber.open(pdf_path) as pdf: first_page = pdf.pa...
4
5
72,622,309
2022-6-14
https://stackoverflow.com/questions/72622309/calculating-the-averages-of-elements-in-one-array-based-on-data-in-another-array
I need to average the Y values corresponding to the values in the X array... X=np.array([ 1, 1, 2, 2, 2, 2, 3, 3 ... ]) Y=np.array([ 10, 30, 15, 10, 16, 10, 15, 20 ... ]) In other words, the equivalents of the 1 values in the X array are 10 and 30 in the Y array, and the average of this is 20, the equivalents of the 2...
import numpy as np X = np.array([ 1, 1, 2, 2, 2, 2, 3, 3]) Y = np.array([ 10, 30, 15, 10, 16, 10, 15, 20]) # Only unique values unique_vals = np.unique(X); # Loop for every value for val in unique_vals: # Search for proper indexes in Y idx = np.where(X == val) # Mean for finded indexes aver = np.mean(Y[idx]) print(f"Av...
3
2