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
65,539,129
2021-1-2
https://stackoverflow.com/questions/65539129/how-does-inheritance-work-in-python-metaclass
Suppose, I have a custom metaclass and a class linked to it: class Meta(type): pass class A(metaclass=Meta): pass From my understanding that at the end of the class A statement, the following steps are executed: Call Meta('A', (), {}). Because step 1 is a built-in call, it means that type.__call__(...) will be invoke...
So --- a somewhat confusing question that can be answered,and somethat simplified by simply running some examples in the interactive mode. But to start, when you state: type.__call__(...) in turn run two other methods (a __new__ and a __init__). It is a simplification of what takes place. When we create new class, li...
5
6
65,539,313
2021-1-2
https://stackoverflow.com/questions/65539313/combine-two-dictionaries-with-preference-to-one-of-them
I have two dictionaries One: default = {"val1": 10, "val2": 20, "val3": 30, "val4": 40} Two: parsed = {"val1": 60, "val2": 50} Now, I want to combine these two dictionaries in such a way that values for the keys present in both the dictionaries are taken from the parsed dictionary and for rest of the keys in default ...
You can create a new dict with {**dict1,**dict2} where dict2 is the one that should have priority in terms of values >>> updated = {**default, **parsed} >>> updated {'val1': 60, 'val2': 50, 'val3': 30, 'val4': 40}
19
21
65,533,684
2021-1-1
https://stackoverflow.com/questions/65533684/python-3-9-and-pycharm-htmlparser-attributeerror
When trying to create new python 3.9 Virtualenv Environment in Pycharm I got such error AttributeError: 'HTMLParser' object has no attribute 'unescape' Traceback (most recent call last): File "/var/folders/6g/vnvmvlf51gv49m22rzj9zdtw0000gn/T/tmpifdsjw6lpycharm-management/setuptools-40.8.0/setup.py", line 11, in <module...
Based on Matthias comment To fix this error I have to update both pycharm (>=2020) and setuptools (>=41). Hope this will help somebody
8
8
65,529,808
2021-1-1
https://stackoverflow.com/questions/65529808/undetected-chromedriver-not-loading-correctly
I'm attempting to use a headless chrome browser with selenium that also bypasses the bot detection test and currently using the the following project https://github.com/ultrafunkamsterdam/undetected-chromedriver Every time I try to implement the code it doesn't recognise the driver. Here is the link for you to understa...
ChromeOptions() is defined within selenium.webdriver.chrome.options but not within undetected_chromedriver. Solution You can use the following solution: Code Block: import undetected_chromedriver as uc from selenium import webdriver options = webdriver.ChromeOptions() options.headless = True driver = uc.Chrome(option...
7
14
65,534,384
2021-1-1
https://stackoverflow.com/questions/65534384/django-jsonfield-doesnt-accept-value
I add a JSONField for one of my models. I want to create an instance of that model in admin panel but that JSONField returns a validation error (Enter a valid JSON.) how I can fix this?? model: class Product(models.Model): category = models.ManyToManyField(Category, related_name='products') name = models.CharField(max_...
This is not valid JSON. The strings in JSON are wrapped with double quotes. Indeed, you can verify this for example with JSONLint.com. It is a valid Python dictionary, but not valid JSON. You thus should enter: { "key": "value" } For more information, see the JSON specifications. I add products in admin panel. I want ...
5
9
65,532,002
2021-1-1
https://stackoverflow.com/questions/65532002/how-to-enable-code-folding-in-jupyter-lab
Running JupyterLab version 3.0.0 and would like to enable code folding (collapse classes, functions etc in Python). I have followed the instructions in this Jupyter Lab github post: Under Settings / Text Editor, I have these User preferences (right pane): { "editorConfig": { "lineNumbers": true, "codeFolding": true } }...
Those instructions are specifically for the text editor, not the notebook interface. Try this instead, in Settings / Notebook: { "codeCellConfig": { "codeFolding": true } } If you want to enable code folding for Markdown or raw cells, see markdownCellConfig and rawCellConfig respectively.
22
27
65,531,537
2021-1-1
https://stackoverflow.com/questions/65531537/returning-true-if-a-value-is-present-in-an-enum-returning-false-if-not
I apologise if I'm missing anything obvious; is there a way to see if a value is in an enum which returns True if it is, False if not? For example, if I take the following enum from the python documentation, from enum import Enum class Colour(Enum): RED = 1 GREEN = 2 BLUE = 3 is there any way to do the following actio...
Enums have a __members__ dict that you can check: if colour_test in Colour.__members__: print("In enum") else: print("Not in enum") You can alternatively use a generalized approach with hasattr, but this returns wrong results for some non-members like "__new__": if hasattr(Colour, colour_test): print("In enum") else: ...
5
8
65,527,272
2021-1-1
https://stackoverflow.com/questions/65527272/how-does-the-following-expression-work-in-python
How does the following expression work in python? >>> 1 ++++++++++++++++++++ 1 2 >>> 1 ++++++++++++++++++++-+ 1 0 I thought this would raise a SyntaxError but that was not the case.
You have to use the logic of brackets and arithmetic operations for this kind of calculation. 1--2 becomes, 1-(-(2)) = 1-(-2) = 1+2 = 3 1+++1 becomes, 1+(+(+1)) = 2 1++-1 becomes, 1+(+(-1)) = 0
17
12
65,516,999
2020-12-31
https://stackoverflow.com/questions/65516999/how-to-programmatically-open-an-application-by-name-on-macos
I'm writing a cross-platform Python application that acts as a frontend for DOSBox. It needs to call the DOSBox executable with a number of command line arguments. I don't want to hardcode a specific path to DOSBox because it might depend on where the user has installed it. On Linux, I can simply do: import subprocess ...
I don't know DOSBox or want it on my Mac, but in general, when you install an application on macOS it has a "property list" file, or plist or "info.plist" in it. In there, the developer is supposed to put a "bundle identifier" key called CFBundleIdentifier. This must be unique across all applications, so for DOSBox it ...
6
5
65,518,787
2020-12-31
https://stackoverflow.com/questions/65518787/how-to-retrieve-minimum-unique-values-from-list
I have a list of dictionary. I wish to have only one result for each unique api and the result need to show according to priority: 0, 1, 2. May I know how should I work on it? Data: [ {'api':'test1', 'result': 0}, {'api':'test2', 'result': 1}, {'api':'test3', 'result': 2}, {'api':'test3', 'result': 0}, {'api':'test3', ...
data = [ {'api': 'test1', 'result': 0}, {'api': 'test3', 'result': 2}, {'api': 'test2', 'result': 1}, {'api': 'test3', 'result': 1}, {'api': 'test3', 'result': 0} ] def find(data): step1 = sorted(data, key=lambda k: k['result']) print('step1', step1) step2 = {} for each in step1: if each['api'] not in step2: step2[each...
17
7
65,512,500
2020-12-30
https://stackoverflow.com/questions/65512500/how-to-get-current-logging-formatter
I'm using the logging module from the python standard library and would like to obtain the current Formatter. The reason is that I'm using multiprocessing module and for each process I'd like to assign its logger another file handler to log to its own log file. When I do this in the following way logger = logging.getLo...
Judging by the cpython source code on logging.basicConfig, it appears that the formatter object which contains your formatting string is eventually added to a handler that is passed to the root logger (see: here ). So you can obtain the handler (and therefore the formatter) from the root logger object by doing logging....
7
5
65,505,336
2020-12-30
https://stackoverflow.com/questions/65505336/plotly-add-trace-vs-append-trace
Is there any difference between add_trace and append_trace in Plotly? Is the latter a legacy of the former? In the Plotly.py GitHub, there are 88 markdown + 21 Python instances of add_trace and 9 markdowbn + 7 Python instances of append_trace. The latter are mainly coming from doc and packages/python/plotly/plotly/figu...
I don't have the technical background to explain it to you, but the official reference has the following explanation New traces can be added to a graph object figure using the add_trace() method. This method accepts a graph object trace (an instance of go.Scatter, go.Bar, etc.) and adds it to the figure. This allows y...
15
10
65,503,864
2020-12-30
https://stackoverflow.com/questions/65503864/django-makemigrations-is-creating-migrations-for-model-with-managed-false
While Django documentation https://docs.djangoproject.com/en/3.1/ref/models/options/#managed mentions the use of managed = False field in meta is used to not create migrations I am still getting migrations when I call makemigrations. This is the meta of the model: class FieldOpsBooking(models.Model): . . class Meta: ma...
I checked my own projetcs with models having managed=False: YES there is an entry in migrations file like: operations = [ migrations.CreateModel( name='xyz', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], options={ 'db_table': 'xyz_table', 'managed': Fals...
12
14
65,501,827
2020-12-30
https://stackoverflow.com/questions/65501827/python-avoid-ugly-nested-for-loop
I'm new to python programming. I have tried a lot to avoid these nested for loops, but no success. My data input like: [ { "province_id": "1", "name": "HCM", "districts": [ { "district_id": "1", "name": "Thu Duc", "wards": [ { "ward_id": "1", "name": "Linh Trung" }, { "ward_id": "2", "name": "Linh Chieu" } ] }, { "dist...
Your data structure is naturally nested, but one option you have for neatening your code is to write a generator function for iterating over it: def all_wards(data): for province in data: for district in province['districts']: for ward in district['wards']: yield province, district, ward This function has the same tri...
6
9
65,439,214
2020-12-24
https://stackoverflow.com/questions/65439214/what-are-the-differences-between-python-playwright-sync-vs-async-apis
I've started learning playwright-python and the package playwright has the two submodules async_api and sync_api. However I could not find any deeper description or discussion on their respective benefits and drawbacks. From their names I assume that the synchronous API calls are blocking and the asynchronous ones run ...
The sync_api is simply a wrapper around the async_api that abstracts asyncio usage away from you. As such, the capabilities are largely the same, but the async_api may afford some more flexibility in complex scenarios. I would suggest using async in case you need the flexibility in the future, or sync for ease of use.
10
12
65,421,561
2020-12-23
https://stackoverflow.com/questions/65421561/how-can-i-check-if-an-user-is-superuser-in-django
I'm listing registered users on a ListView page and I'm trying to show if user is superuser or not. My main user is created with python manage.py createsuperuser command and I'm sure it is a superuser beacuse I've checked from admin panel too. When I try to print if it is superuser or not my code always shows a False o...
I tried in my code and it's working maybe there's issue in your data this is how my code looks like views.py def user_detail(request): user_detail = CustomUser.objects.filter(id=id) return(request, 'user_datail.html', {'user_detail': user_detail}) user_datail.html {% for i in user_detail %} {% if i.is_superuser %} <td...
10
2
65,447,992
2020-12-25
https://stackoverflow.com/questions/65447992/pytorch-how-to-apply-the-same-random-transformation-to-multiple-image
I am writing a simple transformation for a dataset which contains many pairs of images. As a data augmentation, I want to apply some random transformation for each pair but the images in that pair should be transformed in the same way. For example, given a pair of two images A and B, if A is flipped horizontally, B mus...
Usually a workaround is to apply the transform on the first image, retrieve the parameters of that transform, then apply with a deterministic transform with those parameters on the remaining images. However, here RandomChoice does not provide an API to get the parameters of the applied transform since it involves a var...
15
11
65,424,771
2020-12-23
https://stackoverflow.com/questions/65424771/how-to-convert-one-hot-vector-to-label-index-and-back-in-pytorch
How to transform vectors of labels to one-hot encoding and back in Pytorch? The solution to the question was copied to here after having to go through the entire forum discussion, instead of just finding an easy one from googling.
From the Pytorch forums import torch import numpy as np labels = torch.randint(0, 10, (10,)) # labels --> one-hot one_hot = torch.nn.functional.one_hot(labels) # one-hot --> labels labels_again = torch.argmax(one_hot, dim=1) np.testing.assert_equals(labels.numpy(), labels_again.numpy())
17
24
65,464,463
2020-12-27
https://stackoverflow.com/questions/65464463/importerror-cannot-import-name-keras-tensor-from-tensorflow-python-keras-eng
I'm getting this error while loading the tensorflow addons library import tensorflow_addons as tfa ImportError: cannot import name 'keras_tensor' from 'tensorflow.python.keras.engine'
This error is because you have incompatibility issues between your TensorFlow, Python and tensorflow-addons. Uninstall the tensorflow-addons and install the version based on the table below. Refer the Github repo for more information.
10
41
65,446,464
2020-12-25
https://stackoverflow.com/questions/65446464/how-to-convert-a-video-in-numpy-array
Program to convert a video file into a NumPy array and vice-versa. I had searched for many search engines but was unable to find the answer.
There are multiple libraries people use for this (i.e. PyAV, decord, opencv); I personally use Python OpenCV for this a lot (mostly with PyTorch, but it's a similar principle), so I'll speak about my experience there. You can use cv2.VideoCapture to load a video file into a numpy array; in theory, you can also use cv2....
6
8
65,498,782
2020-12-29
https://stackoverflow.com/questions/65498782/how-to-dump-confusion-matrix-using-tensorboard-logger-in-pytorch-lightning
The official doc only states >>> from pytorch_lightning.metrics import ConfusionMatrix >>> target = torch.tensor([1, 1, 0, 0]) >>> preds = torch.tensor([0, 1, 0, 0]) >>> confmat = ConfusionMatrix(num_classes=2) >>> confmat(preds, target) This doesn't show how to use the metric with the framework. My attempt (methods a...
Updated answer, August 2022 class IntHandler: def legend_artist(self, legend, orig_handle, fontsize, handlebox): x0, y0 = handlebox.xdescent, handlebox.ydescent text = plt.matplotlib.text.Text(x0, y0, str(orig_handle)) handlebox.add_artist(text) return text class LightningClassifier(LightningModule): ... def _common_s...
9
5
65,468,026
2020-12-27
https://stackoverflow.com/questions/65468026/norm-ppf-vs-norm-cdf-in-pythons-scipy-stats
so i have pasted my complete code for your reference, i want to know what's the use of ppf and cdf here? can you explain it? i did some research and found out that ppf(percent point function) is an inverse of CDF(comulative distribution function) if they really are, shouldn't this code work if i replaced ppf and cdf as...
The .cdf() function calculates the probability for a given normal distribution value, while the .ppf() function calculates the normal distribution value for which a given probability is the required value. These are inverse of each other in this particular sense. To illustrate this calculation, check the below sample c...
8
23
65,445,174
2020-12-25
https://stackoverflow.com/questions/65445174/what-is-the-difference-between-an-embedding-layer-with-a-bias-immediately-afterw
I am reading the "Deep Learning for Coders with fastai & PyTorch" book. I'm still a bit confused as to what the Embedding module does. It seems like a short and simple network, except I can't seem to wrap my head around what Embedding does differently than Linear without a bias. I know it does some faster computational...
Embedding [...] what Embedding does differently than Linear without a bias. Essentially everything. torch.nn.Embedding is a lookup table; it works the same as torch.Tensor but with a few twists (like possibility to use sparse embedding or default value at specified index). For example: import torch embedding = torch....
16
23
65,492,317
2020-12-29
https://stackoverflow.com/questions/65492317/copy-file-in-python-with-copy-on-write-cow
My filesystem (FS) (ZFS specifically) supports copy-on-write (COW), i.e. a copy (if done right) is a very cheap constant operation, and does not actually copy the underlying content. The content is copied only once I write/modify the new file. Actually, I just found out, ZFS-on-Linux actually has not implemented that f...
While searching further, I actually found the answer, and a related issue report. Issue 37157 (shutil: add reflink=False to file copy functions to control clone/CoW copies (use copy_file_range)) is exactly about that, which would use FICLONE/FICLONERANGE on Linux. So I assume that shutil would support this in upcoming ...
5
3
65,461,962
2020-12-27
https://stackoverflow.com/questions/65461962/tkinter-ttk-see-custom-theme-settings
After using ttk.Style().theme_create('name', settings={}) is it possible to see the settings of that theme? The reason I'm asking is that when I'm creating a new theme and I add ttk.Notebook(root) to my code, the tabs have rounded corners, which I do not want. Here is an example: import tkinter as tk import tkinter.ttk...
Offical list of all options by ttk finally found a list that includes all coloration options to style with ttk. https://wiki.tcl-lang.org/page/Changing+Widget+Colors ttk.Button ttk::style configure TButton -background color ttk::style configure TButton -foreground color ttk::style configure TButton -font namedfont ttk...
6
8
65,491,184
2020-12-29
https://stackoverflow.com/questions/65491184/ratelimit-in-fastapi
How to ratelimit API endpoint request in Fastapi application ? I need to ratelimit API call 5 request per second per user and exceeding that limit blocks that particular user for 60 seconds. In main.py def get_application() -> FastAPI: application = FastAPI(title=PROJECT_NAME, debug=DEBUG, version=VERSION) application....
Best option is using a library since FastAPI does not provide this functionality out-of-box. slowapi is great, and easy to use. You can use ut like this. from fastapi import FastAPI from slowapi.errors import RateLimitExceeded from slowapi import Limiter, _rate_limit_exceeded_handler from slowapi.util import get_remote...
23
47
65,451,457
2020-12-25
https://stackoverflow.com/questions/65451457/how-can-i-update-class-members-in-processes
I have looked for other questions, and this un-accepted-answered question is the only one I could find that somehow covers this issue and is not really helpful. Also, I need this to work with processes, and not threads. So from the ground up I wrote a sample program to show my issue, you should be able to paste it and ...
You can derive a specialized version of a Proxy class used by multiprocessing.BaseManager from the (undocumented) multiprocessing.managers.NamespaceProxy class that, unlike the base class, exposes all of its methods and attributes. This is similar to @shtse8's answer to the linked duplicate question, but I'm posting a ...
6
6
65,470,807
2020-12-27
https://stackoverflow.com/questions/65470807/how-to-add-a-new-dimension-to-a-pytorch-tensor
In NumPy, I would do a = np.zeros((4, 5, 6)) a = a[:, :, np.newaxis, :] assert a.shape == (4, 5, 1, 6) How to do the same in PyTorch?
a = torch.zeros(4, 5, 6) a = a[:, :, None, :] assert a.shape == (4, 5, 1, 6)
51
68
65,426,515
2020-12-23
https://stackoverflow.com/questions/65426515/how-to-resolve-attempted-relative-import-with-no-known-parent-package
I have a bare bones project structure with mostly empty python files for the sake of testing a concept from an online tutorial: project |--package1 | |--__init__.py | |--module1.py | |--package2 | |--__init__.py | |--module2.py | |--__init__.py module1.py: from .package2.module2 import function2 module2.py: def funct...
The relative imports failed to work because module1.py could not look into it's parent folder for more packages when executed directly. The correct call required the -m parameter to signify that module1 was a module within a package. My terminal also needed to go up one directory: PS C:\...\"parent of project folder"> ...
8
4
65,452,383
2020-12-25
https://stackoverflow.com/questions/65452383/macos-11-or-later-required-error-on-pycharm
I am learning how to use python by watching some online videos. When I run the code below using PyCharm, I get the following: macOS 11 or later required! Process finished with exit code 134 (interrupted by signal 6: SIGABRT) I have an M1 Mac mini with macOS Big Sur 11.1. This was happening when I had Python 3.8.2. Then...
If you used Homebrew to do your Python installation, there have been some reported issues with Python3 installs via brew (Source 1, Source 2). Updates are always in the works though, so you could try remedying your problem first with a brew update. If the issue persists, the current recommendation is to actually instal...
6
5
65,473,454
2020-12-28
https://stackoverflow.com/questions/65473454/what-is-difference-between-python-pylance-vs-code-extensions
I just shifted from my old bud Sublime to VSCode. I really liked the way it works and the features it has. I'm a newbie python developer. I found two popular python extensions for VSCode: Python, and PyLance. My question is, What is the difference between Python and Pylance extension? I searched a lot but didn't find a...
As an editor, VSCode cannot recognize all languages and many functions cannot be implemented independently. Therefore, when we use Python code in VSCode, we need to install the 'Python' extension, which provides us with functions such as code completion, support for Jupyter notebooks, debugging Python code, etc. Theref...
30
40
65,439,154
2020-12-24
https://stackoverflow.com/questions/65439154/pytorch-doesnt-work-with-cuda-in-pycharm-intellij
I have just downloaded PyTorch with CUDA via Anaconda and when I type into the Anaconda terminal: import torch if torch.cuda.is_available(): print('it works') then he outputs that; that means that it worked and it works with PyTorch. But when I go to my IDE (PyCharm and IntelliJ) and write the same code, it doesn't ou...
It was driving me mad as well... What finally helped me was the first link that says to use PyCharm "Terminal" to run the pip install command (from the PyTorch website). That fixed all my problems. (I had installed pytorch 3 times by that time and tried different interpreters...) https://www.datasciencelearner.com/how-...
4
9
65,498,975
2020-12-29
https://stackoverflow.com/questions/65498975/forward-method-error-in-dnn-module-of-opencv-ptyhon-using-onnx-model
I wanted to test a pretrained model downloaded from here to perform an ocr task. Link to download, its name is CRNN_VGG_BiLSTM_CTC.onnx. This model is extracted from here. The sample-image.png can be download from here (see the code bellow). When I do the forward of the neural network to predict (ocr) in the blob I get...
Your problem is actually that the input data you feed to your model doesn't match the shape of the data the model was trained on. I used this answer to inspect your onnx model and it appears that it expects an input of shape (1, 1, 32, 100). I modified your code to reshape the image to 1 x 32 x 100 pixels and the infer...
5
4
65,429,877
2020-12-23
https://stackoverflow.com/questions/65429877/aws-lambda-container-running-selenium-with-headless-chrome-works-locally-but-not
I am currently developing a Python program which has a segment which uses a headless version of Chrome and Selenium to perform a repetitive process. I am aiming to run the program on Lambda. The overall program has around 1GB of dependencies so the option to use the standard method of using a .zip archive, containing a...
Python v3.6 works great. I have a bin directory with chromedriver v2.41 (https://chromedriver.storage.googleapis.com/2.41/chromedriver_linux64.zip) and headless-chrome v68.0.3440.84 (https://github.com/adieuadieu/serverless-chrome/releases/download/v1.0.0-53/stable-headless-chromium-amazonlinux-2017-03.zip). Below is m...
16
7
65,491,229
2020-12-29
https://stackoverflow.com/questions/65491229/python-http-module-cannot-parse-response-if-the-server-answers-before-the-put
I'm using the requests (which uses urllib3 and the Python http module under the hood) library to upload a file from a Python script. My backend starts by inspecting the headers of the request and if it doesn't comply with the needed prerequisites, it stops the request right away and respond with a valid 400 response. T...
This problem should be fixed in urllib3 v1.26.0. What version are you running? The problem is that the server closes the connection after it responds with 400, so the socket is closed when urllib3 tries to keep sending data to it. So it isn't really mistakenly thinking that the connection is closed, it just mishandles ...
9
2
65,451,045
2020-12-25
https://stackoverflow.com/questions/65451045/cnn-model-conditional-layer-in-keras
I am trying to build a conditional CNN model. The model is, At the first stage of my model, I feed my data to Model 1 then, based on the prediction of Model 1, I want to train the model to Conditional Cat model or Conditional Dog model and finally, give the output from Conditional Cat model or Conditional Dog model. H...
The problem with conditionals in neural networks The issue with a switch or conditionals (like if-then-else) as part of a neural network is that conditionals are not differentiable everywhere. Therefore the automatic differentiation methods would not work directly and solving this is super complex. Check this for more ...
15
15
65,487,601
2020-12-29
https://stackoverflow.com/questions/65487601/how-to-deal-with-lat-lon-arrays-with-multiple-dimensions
I'm working with Pygrib trying to get surface temperatures for particular lat/lon coordinates using the NBM grib data (available here if it helps). I've been stuck trying to get an index value to use with representative data for a particular latitude and longitude. I was able to derive an index, but the problem is the ...
You cannot evaluate "closeness" of latitudes independently of longitudes - you have to evaluate how close the pair of coordinates is to your input coordinates. Lat/Lon are really just spherical coordinates. Given two points (lat1,lon1) (lat2,lon2), closeness (in terms of great circles) is given by the angle between the...
5
5
65,453,234
2020-12-26
https://stackoverflow.com/questions/65453234/twint-criticalroottwint-feedfollowindexerror-for-any-call
import twint import os, requests, re, time c = twint.Config() c.Username = <anyusername> #Replace with an actual uname in quotes c.Store_object = True c.Limit = 10 try: twint.run.Followers(c) except: print("Unexpected error:", sys.exc_info()[0]) f = twint.output.follows_list print(f) Output CRITICAL:root:twint.feed:Fo...
Legacy mobile Twitter version will shut down on December 15th 2020. (M2 mobile web) That's the headline of a reddit thread talking about the recent shutdown of the M2 Mobile Web ("Legacy") Twitter version; from this date on Twitter will only support these browsers. If you take a look at the GitHub repository of Twint...
5
14
65,480,162
2020-12-28
https://stackoverflow.com/questions/65480162/how-to-remove-repititve-pattern-from-an-image-using-fft
I have image of skin colour with repetitive pattern (Horizontal White Lines) generated by a scanner that uses a line of sensors to perceive the photo. My Question is how to denoise the image effectively using FFT without affecting the quality of the image much, somebody told me that I have to suppress the lines tha...
Here is a simple and effective linear filtering strategy to remove the horizontal line artifact: Outline: Estimate the frequency of the distortion by looking for a peak in the image's power spectrum in the vertical dimension. The function scipy.signal.welch is useful for this. Design two filters: a highpass filter wi...
8
9
65,489,705
2020-12-29
https://stackoverflow.com/questions/65489705/transcribing-mp3-to-text-python-riff-id-error
I am trying to turn mp3 file to text, but my code returns the error outlined below. Any help is appreciated! This is a sample mp3 file. And below is what I have tried: import speech_recognition as sr print(sr.__version__) r = sr.Recognizer() file_audio = sr.AudioFile(r"C:\Users\Andrew\Podcast.mp3") with file_audio as s...
You need to first convert the mp3 to wav, and then you can transcribe it, below is the modified version of your code. import speech_recognition as sr from pydub import AudioSegment # convert mp3 file to wav src=(r"C:\Users\Andrew\Podcast.mp3") sound = AudioSegment.from_mp3(src) sound.export("C:\Users\Andrew\podcast.wav...
6
5
65,492,399
2020-12-29
https://stackoverflow.com/questions/65492399/gradient-descent-using-tensorflow-is-much-slower-than-a-basic-python-implementat
I'm following a machine learning course. I have a simple linear regression (LR) problem to help me get used to TensorFlow. The LR problem is to find parameters a and b such that Y = a*X + b approximates an (x, y) point cloud (which I generated myself for the sake of simplicity). I am solving this LR problem using a 'fi...
The actual answer to my question is hidden in the various comments. For future readers, I will summarize these findings in this answer. About the speed difference between TensorFlow and a raw Python/NumPy implementation This part of the answer is actually quite logically. Each iteration (= each call of Session.run()) T...
6
1
65,462,220
2020-12-27
https://stackoverflow.com/questions/65462220/how-to-create-custom-eval-metric-for-catboost
Similar SO questions: Python Catboost: Multiclass F1 score custom metric Catboost tutorials https://catboost.ai/docs/concepts/python-usages-examples.html#user-defined-loss-function Question In this question, I have a binary classification problem. After modelling we get the test model predictions y_pred and we alre...
The main difference from yours is: @staticmethod def get_profit(y_true, y_pred): y_pred = expit(y_pred).astype(int) y_true = y_true.astype(int) #print("ACCURACY:",(y_pred==y_true).mean()) tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel() loss = 400*tp - 200*fn - 100*fp return loss It's not obvious from the exa...
8
6
65,499,535
2020-12-29
https://stackoverflow.com/questions/65499535/how-to-create-an-asyncio-task-that-return-value
I'm figuring out how to return a list[] in asyncio I know asyncio.gather could help me but there are so many ways I'm now confused. How Do I return value from main() ? Thank async def wait_until(dt): # sleep until the specified datetime now = datetime.now() await asyncio.sleep((dt - now).total_seconds()) async def run_...
From the asyncio.gather documentation: If all awaitables are completed successfully, the result is an aggregate list of returned values. The order of result values corresponds to the order of awaitables in aws. From the asyncio.loop.run_until_complete documentation: Return the Future’s result or raise its exception....
6
7
65,437,506
2020-12-24
https://stackoverflow.com/questions/65437506/how-to-get-raw-html-with-absolute-links-paths-when-using-requests-html
When making a request using the requests library to https://stackoverflow.com page = requests.get(url='https://stackoverflow.com') print(page.content) I get the following: <!DOCTYPE html> <html class="html__responsive html__unpinned-leftnav"> <head> <title>Stack Overflow - Where Developers Learn, Share, &amp; Build Ca...
This should probably a feature request for the request-html developers. However for now we can achieve this with this hackish solution: from requests_html import HTMLSession from lxml import etree with HTMLSession() as session: html = session.get('https://stackoverflow.com').html html.render() # iterate over all links ...
5
2
65,420,550
2020-12-23
https://stackoverflow.com/questions/65420550/python-string-occurence-count-regex-performance
I was asked to find the total number of substring (case insensitive with/without punctuations) occurrences in a given string. Some examples: count_occurrences("Text with", "This is an example text with more than +100 lines") # Should return 1 count_occurrences("'example text'", "This is an 'example text' with more than...
OK, I was struggling to make it work without regexes, as we all know that regexes are slow. Here is what I came up with: def count_occurrences(word, text): spaces = [' ', '\n', '(', '«', '\u201d', '\u201c', ':', "''", "__"] endings = spaces + ['?', '.', '!', ',', ')', '"', '»'] s = text.lower().split(word.lower()) l = ...
7
3
65,487,163
2020-12-29
https://stackoverflow.com/questions/65487163/python-sphinx-autodoc-not-rendering-on-readthedocs
I have a Python package hosted on Github called spike2py. I have prepared my docs using Sphinx and .rst files. These files are hosted on GitHub here. I am able to successfully run make html locally and obtain the desired output. That is, the Reference Guide part of the documentation contains the API automatically gener...
Your project's dependencies are not specified on RTD, but you have installed the dependencies locally. You can verify this in the build log. Visit your project's Builds, click a build, and click "view raw". WARNING: autodoc: failed to import class 'trial.TrialInfo' from module 'spike2py'; the following exception was ra...
11
7
65,491,369
2020-12-29
https://stackoverflow.com/questions/65491369/how-to-specify-mypy-type-pytest-configure-fixtures
I am trying to specify mypy type hints for the pytest native fixtures I am using in my test project e.g.: import pytest def pytest_configure(config): # Do something useful here The config fixture returns a _pytest.config.Config object. If I try to model this naively: import pytest def pytest_configure(config: Config) ...
Importing from _pytest.config Since pytest doesn't currently export Config (as of 6.2), the only way for typing is to use from _pytest.config import Config. This is how I also type config, as can be seen e.g. in this question of mine: from _pytest.config import Config def pytest_configure(config: Config) -> None: ... ...
9
6
65,496,688
2020-12-29
https://stackoverflow.com/questions/65496688/how-can-i-get-the-line-of-the-text-where-an-xml-tag-is-found-in-python-using-bs4
I have an XML document and I want to get the line at which the tag extracted by BeautifulSoup or lxml is found. Is there a way to do that?
For BeautifulSoup this attribute is stored in the sourceline attribute of the Tag class, and is being populated in the parsers here and here. For lxml this is also possible through the sourceline attribute. Here is an example: #!/usr/bin/python3 from lxml import etree xml = ''' <a> <b> <c> </c> </b> <d> </d> </a> ''' r...
5
4
65,486,981
2020-12-29
https://stackoverflow.com/questions/65486981/what-is-peg-parser-in-python
I was using the keyword built-in module to get a list of all the keywords of the current Python version. And this is what I did: >>> import keyword >>> print(keyword.kwlist) ['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', '...
It was an easter egg related to the rollout of the new PEG parser. The easter egg, along with the old LL(1) parser, will be removed in 3.10.
62
39
65,483,030
2020-12-28
https://stackoverflow.com/questions/65483030/notch-reject-filtering-in-python
I'm trying to implement notch-reject filtering in python for an assignment. I have tried using the notch reject filter formula from Rafael Gonzales book and all I got was a edge detected image. Then I tried ideal notch rejecting and here are the results: Input image--Output of my program -- Expected output Here is my c...
all I got was a edge detected image because your implementation was High pass filter which is a black circle in the middle, and that works as Edge detector. Then I tried ideal notch rejecting This is correct if you applied that correctly. The main concept is to filter the undesired Noise in the frequency domain, the ...
6
9
65,480,707
2020-12-28
https://stackoverflow.com/questions/65480707/how-to-solve-symbolic-equations-on-numpy-arrays
I try to solve an equation with solve from Sympy. But my approach doesn't work as desired. My equation : 0.00622765954483725 = (x * 24.39 * 0.921107170819325) / 143860432.178345. My code : from sympy import symbols, solve import numpy as np x = symbols('x') sol = solve((np.array([[x],[x]]) * np.array([[24.39],[293.6]])...
Numpy doesn't understand about sympy's symbols, nor does sympy understand about numpy arrays. The only way to make them work together, is with sympy's lambdify which can convert a symbolic sympy expression to a numpy function. In your case, you first need to create a symbolic solution, lambdify it, and call it on your ...
5
4
65,479,238
2020-12-28
https://stackoverflow.com/questions/65479238/how-to-install-python-packages-in-a-virtual-environment-without-downloading-them
It's a great hassle when installing some packages in a VE and conda or pip downloads them again even when I already have it in my base environment. Since I have limited internet bandwidth and I'm assuming I'll work with many different VE's, it will take a lot of time to download basic packages such as OpenCV/Tensorflow...
By default, pip caches anything it downloads, and will used the cached version whenever possible. This cache is shared between your base environment and all virtual environments. So unless you pass the --no-cache-dir option, pip downloading a package means it has not previously downloaded a compatible version of that p...
6
4
65,481,308
2020-12-28
https://stackoverflow.com/questions/65481308/argsort-dataframe-according-to-columns
I have the following DataFrame: userId column_1 column_2 column_3 A 4.959 3.231 1.2356 B 0.632 0.963 2.4556 C 3.234 7.445 5.3435 D 1.454 0.343 2.2343 I would like to argsort w.r.t columns from the previous one: userId first second third A column_3 column_2 column_1 B column_1 column_2 column...
You can use np.argsort over axis 1. Then convert df.columns to numpy array using pd.Index.to_numpy and use numpy indexing. df = df.set_index('userId') # If userId is not index already. idx = df.values.argsort(axis=1) out = pd.DataFrame(df.columns.to_numpy()[idx], index=df.index) 0 1 2 userId A column_3 column_2 column_...
5
9
65,481,013
2020-12-28
https://stackoverflow.com/questions/65481013/how-to-import-analysisexception-in-pyspark
I can't find how to import AnalysisException in PySpark so I can catch it. For example: df = spark.createDataFrame([[1, 2], [1, 2]], ['A', 'A']) try: df.select('A') except AnalysisException as e: print(e) Error message: NameError: name 'AnalysisException' is not defined
You can import it here: from pyspark.sql.utils import AnalysisException This is shown in the error traceback like Traceback (most recent call last): ... File "<string>", line 3, in raise_from pyspark.sql.utils.AnalysisException: cannot resolve ...
12
17
65,469,173
2020-12-27
https://stackoverflow.com/questions/65469173/matplotlib-add-border-around-group-of-bins-with-most-frequent-values-in-hexbin
I am making a hexbin plot with the following Python script: pitch = Pitch( line_color="#747474", pitch_color="#222222", orientation="vertical", half=True, plot_arrow=False ) fig, ax = pitch.create_pitch() ## color-map cmap = [ "#222222", "#3A2527", "#52282B", "#6A2B30", "#762C32", "#822D34", "#8E2F37", "#9A3039", "#B23...
I worked out two versions for plotting a contour line for the hexagons. (header) import numpy as np, matplotlib.pyplot as plt, matplotlib.colors # color-map cmap = [ "#222222", "#3A2527", "#52282B", "#6A2B30", "#762C32", "#822D34", "#8E2F37", "#9A3039", "#B2323D", "#BE3440", "#CA3542", "#E13746"] cmap = matplotlib.colo...
5
2
65,473,257
2020-12-28
https://stackoverflow.com/questions/65473257/ftpshook-airflow-522-ssl-tls-required-on-the-data-channel
I'm trying to use FTPSHook to send file through FTP TLS/SSL Explicit Encryption. Here's my code remote_filepath=pathfile local_filepath=pathfile2 hook = FTPSHook(ftp_conn_id='ftp_test') hook.store_file(remote_filepath, local_filepath) and I'm getting this error when I run the DAG: 522 SSL/TLS required on the data cha...
The ftplib (the underlying implementation of FTP(S) for the FTPSHook) does not encrypt the FTP data connection by default. To enable it, you have to call FTP_TLS.prot_p(). With FTPSHook API, you do it like this: hook = FTPSHook(ftp_conn_id='ftp_test') hook.get_conn().prot_p()
5
4
65,459,632
2020-12-26
https://stackoverflow.com/questions/65459632/cannot-import-pywinauto-on-windows-10
I installed pywinauto using pip install pywinauto. OS: Windows 10 Python: 3.6.2 When I run python and try to import pywinauto, I get the error: Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from pywinau...
I have the same issue today and fixed it by pip install comtypes==1.1.7. It caused by comtypes library which release a new version 1.1.8 at Dec.26. Downgrade to previous version, it works well now.
12
24
65,471,540
2020-12-27
https://stackoverflow.com/questions/65471540/get-monthly-average-in-pandas
I have the following time series: Date Value 0 2006-01-03 18 1 2006-01-04 12 2 2006-01-05 11 3 2006-01-06 10 4 2006-01-09 22 ... ... ... 3510 2019-12-23 47 3511 2019-12-24 46 3512 2019-12-26 35 3513 2019-12-27 35 3514 2019-12-30 28 I want to calculate the average values per month. So the pseudocode for each month is ...
We can convert your datetime column into a PeriodIndex on monthly frequency, then take the mean using GroupBy.mean: df.groupby(pd.PeriodIndex(df['Date'], freq="M"))['Value'].mean() Date 2006-01 14.6 2019-12 38.2 Freq: M, Name: Value, dtype: float64 df.groupby(pd.PeriodIndex(df['Date'], freq="M"))['Value'].mean().rese...
9
14
65,467,349
2020-12-27
https://stackoverflow.com/questions/65467349/pandas-data-frame-filtering-multiple-conditions
I have the following data frame df = pd.DataFrame([[1990,7,1000],[1990,8,2500],[1990,9,2500],[1990,9,1500],[1991,1,250],[1991,2,350],[1991,3,350],[1991,7,450]], columns = ['year','month','data1']) year month data1 1990 7 1000 1990 8 2500 1990 9 2500 1990 9 1500 1991 1 250 1991 2 350 1991 3 350 1991 7 450 I would like ...
You could do: mask = ~df[['year', 'month']].apply(tuple, 1).isin([(1990, 7), (1990, 8), (1991, 1)]) print(df[mask]) Output year month data1 2 1990 9 2500 3 1990 9 1500 5 1991 2 350 6 1991 3 350 7 1991 7 450
11
11
65,463,794
2020-12-27
https://stackoverflow.com/questions/65463794/valueerror-unknown-label-type-continuous-in-decisiontreeclassifier
I am trying to create a model which predicts results column below: Date Open High Close Result 1/22/2010 25.95 31.29 30.89 0.176104 2/19/2010 23.98 24.22 23.60 -0.343760 3/19/2010 21.46 23.16 22.50 0.124994 4/23/2010 21.32 21.77 21.06 -0.765601 5/21/2010 55.41 55.85 49.06 0.302556 The code I am using is: import panda...
In ML, it's important as a first step to consider the nature of your problem. Is it a regression or classification problem? Do you have target data (supervised learning) or is this a problem where you don't have a target and want to learn more about your data's inherent structure (such as unsupervised learning). Then, ...
5
12
65,463,877
2020-12-27
https://stackoverflow.com/questions/65463877/pyspark-illegal-reflective-access-operation-when-executed-in-terminal
I've installed Spark and components locally and I'm able to execute PySpark code in Jupyter, iPython and via spark-submit - however receiving the following WARNING's: WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by org.apache.spark.unsafe.Platform (file:/Users/ayubk/sp...
Install Java 8 instead of Java 11, which is known to give this sort of warnings with Spark.
14
8
65,463,062
2020-12-27
https://stackoverflow.com/questions/65463062/azure-functions-parameters-are-declared-in-python-but-not-in-function-json
I cannot understand what is going on. I literally follow all Microsoft docs and in fact don't even use any of my own scripts/codes. Firstly, I followed their docs to create Python function. It worked. https://learn.microsoft.com/en-us/azure/azure-functions/create-first-function-cli-python?tabs=azure-cli%2Ccmd%2Cbrowser...
Try below and it will works fine: host.json { "version": "2.0", "logging": { "applicationInsights": { "samplingSettings": { "isEnabled": true, "excludedTypes": "Request" } } }, "extensionBundle": { "id": "Microsoft.Azure.Functions.ExtensionBundle", "version": "[1.*, 2.0.0)" } } __init__.py import logging import azure....
10
4
65,462,266
2020-12-27
https://stackoverflow.com/questions/65462266/find-out-skipped-values-in-a-series-of-integers
I have a column in my dataframe being the customer ids which contains no repetitions. The id series starts at integer 1, and ends at 4003. As the following output shows, there are 4 id numbers being skipped. I would like some help in finding out what they are. Thanks in advance! df['customer_id'].describe() Out[150]: c...
Assuming the dtype is int (which appears to be the case), it looks like we can use setdiff1d here from numpy: c_id = df['customer_id'] missing_ids = np.setdiff1d(np.arange(c_id.min(), c_id.max()+1), c_id)
5
4
65,461,959
2020-12-27
https://stackoverflow.com/questions/65461959/calling-a-static-method-with-self-vs-class-name
Calling Python static methods using the class name is more common, but can be a real eye sore for long class names. Sometimes I use self within the same class to call the static methods, because I find it looks cleaner. class ASomewhatLongButDescriptiveClassName: def __init__(self): # This works, but it's an eyesore AS...
You make a few statements that aren't entirely correct: Calling Python static methods using the class name is more common It's not more common, it's the only way to do so from outside the class. i.e.: class MyClass: @staticmethod def a_method(): pass MyClass.a_method() In this example, self.a_method() would not work...
15
32
65,456,517
2020-12-26
https://stackoverflow.com/questions/65456517/join-two-dataframes-on-common-columns-only-if-the-difference-in-a-separate-colum
I have two data frames df1 and df2 as shown below: df1 Date BillNo. Amount 10/08/2020 ABBCSQ1ZA 878 10/09/2020 AADC9C1Z5 11 10/12/2020 AC928Q1ZS 3998 10/14/2020 AC9268RE3 198 10/16/2020 AA171E1Z0 5490 10/19/2020 BU073C1ZW 3432 df2 Date BillNo. Amount 10/08/2020 ABBCSQ1ZA 876 10/11/2020 ATRC95REW 115 10/14/2020 AC9268RE...
We can merge, then perform a query to drop rows not within the range: (df1.merge(df2, on=['Date', 'BillNo.']) .query('abs(Amount_x - Amount_y) <= 5') .drop('Amount_x', axis=1)) Date BillNo. Amount_y 0 10/08/2020 ABBCSQ1ZA 876 1 10/16/2020 AA171E1Z0 5491 This works well as long as there is only one row that corresponds...
7
8
65,451,000
2020-12-25
https://stackoverflow.com/questions/65451000/python-command-not-found-on-linux
I have a problem while running python on linux, I have python3 already installed. When type python3 on the terminal i got: python 3.9.0 When I run any program I made with for example python I got this error bash: python: command not found And this happen to every python program I try to install on my machine.
Place the below line in ~/.bashrc file: alias python=python3 After inserting run the below command: source ~/.bashrc .bashrc is the configuration file for bash, a linux shell/command interpreter. An alias is a substitute for a (complete) command. It can be thought of as a shortcut. By adding the above line, an alias ...
9
8
65,453,576
2020-12-26
https://stackoverflow.com/questions/65453576/diference-between-os-getcwd-and-os-path-dirname-file
In a previous project, I used the first version of the following two lines. Now that I found getcwd() I thought this would be the shorter alternative. print(os.path.dirname(__file__)) # D:/Personal_Software/my_project print(os.getcwd()) # D:\Personal_Software\my_project I already read this post, but the thing I'm curi...
There is a difference, though you wouldn't be able to tell from a single script. __file__ is the full filename of a loaded module or script, so getting the parent directory of it with os.path.dirname(__file__) gets you the directory that script is in. Note: on Linux (and similar OSes), such a filename can be a symbolic...
11
3
65,444,396
2020-12-25
https://stackoverflow.com/questions/65444396/how-can-i-combine-two-dataframes-based-on-a-column-of-lists-in-pandas
import pandas as pd Reproducible setup I have two dataframes: df=\ pd.DataFrame.from_dict({'A':['xy','yx','zy','zz'], 'B':[[1, 3],[4, 3, 5],[3],[2, 6]]}) df2=\ pd.DataFrame.from_dict({'B':[1,3,4,5,6], 'C':['pq','rs','pr','qs','sp']}) df looks like: A B 0 xy [1, 3] 1 yx [4, 3, 5] 2 zy [3] 3 zz [2, 6] df2 looks like...
You can explode "B" into separate rows, then merge on "B" and drop duplicates. Big thanks to Asish M. in the comments for pointing out a potential bug with the ordering. (df.explode('B') .merge(df2, on='B', how='left') .dropna(subset=['C']) .drop_duplicates('A')) A B C 0 xy 1 pq 2 yx 4 pr 5 zy 3 rs 7 zz 6 sp Ideally,...
5
8
65,438,156
2020-12-24
https://stackoverflow.com/questions/65438156/tensorflow-keras-error-unknown-image-file-format-one-of-jpeg-png-gif-bmp-re
i'm training a classifier and i made sure all the pictures are jpg but still, this error occurs: InvalidArgumentError: Unknown image file format. One of JPEG, PNG, GIF, BMP required. [[{{node decode_image/DecodeImage}}]] [[IteratorGetNext]] [Op:__inference_train_function_1481] i tried training on a smaller dataset and ...
When you say you made sure they were jpg's how did you verify that? Just because the extension is .jpg does not mean the file is a true jpg image. I suggest you run the code below to see which image may be defective. import os import cv2 def check_images( s_dir, ext_list): bad_images=[] bad_ext=[] s_list= os.listdir(s_...
8
9
65,443,086
2020-12-24
https://stackoverflow.com/questions/65443086/django-psycopg2-errors-stringdatarighttruncation-value-too-long-for-type-charac
Facing the above error when running the django app. What exactly needs to be changed though? The comment_body = models.TextField() aspect most probably is the culprit since it stores reddit comments which can be of varying lengths. When i do a git clone and run it on my local, strangely it works. Models.py from django...
Given the error: value too long for type character varying(200) you should look for model fields that have a max_length of 200. Since you have multiple fields with a max_length set to 200, you need to determine which model and field are throwing the error. Check the stacktrace, run a debugger and/or insert some debuggi...
7
2
65,436,017
2020-12-24
https://stackoverflow.com/questions/65436017/minimizing-this-error-function-using-numpy
Background I've been working for some time on attempting to solve the (notoriously painful) Time Difference of Arrival (TDoA) multi-lateration problem, in 3-dimensions and using 4 nodes. If you're unfamiliar with the problem, it is to determine the coordinates of some signal source (X,Y,Z), given the coordinates of n n...
It seems like the Bancroft method applies to this problem? Here's a pure NumPy implementation. # Implementation of the Bancroft method, following # https://gssc.esa.int/navipedia/index.php/Bancroft_Method M = np.diag([1, 1, 1, -1]) def lorentz_inner(v, w): return np.sum(v * (w @ M), axis=-1) B = np.array( [ [x_1, y_1, ...
6
2
65,439,688
2020-12-24
https://stackoverflow.com/questions/65439688/pandas-rows-multiple-rows-as-one-adding-specific-column
import pandas as pd training_data = pd.DataFrame() training_data['a'] = [401,401.2,410,420,425,426, 426.1] training_data['b'] = [1,1,2,2,2,3,3] training_data['condition'] = [True, False, True, True, True,False, False] My training data: a b condition 401 1 True 401.2 1 False 410 2 True 420 2 True 425 2 True 426 3 False...
Here we go with cumsum out = training_data.groupby(training_data['condition'].cumsum()).agg({'a':'first','b':'sum','condition':'first'}) Out[271]: a b condition condition 1 401.0 2 True 2 410.0 2 True 3 420.0 2 True 4 425.0 8 True
6
7
65,438,868
2020-12-24
https://stackoverflow.com/questions/65438868/difference-between-re-split-string-and-re-split-s-string
I'm currently studying regular expressions and have come across an inquiry. So the title of the question is what I'm trying to find out. I thought since \s represents a white space, re.split(" ", string) and re.split("\s+", string) would give out same values, as shown next: >>> import re >>> a = re.split(" ", "Why is t...
This only look similar based on your example. A split on ' ' (a single space) does exactly that - it splits on a single space. Consecutive spaces will lead to empty "matches" when you split. A split on '\s+' will also split on multiple occurences of those characters and it includes other whitespaces then "pure spaces":...
4
13
65,428,255
2020-12-23
https://stackoverflow.com/questions/65428255/how-is-pythons-iterator-unpacking-star-unpacking-implemented-or-what-magic
I am writing a class that defines __iter__ and __len__, where the value of __len__ depends on the iterator returned by __iter__. I am getting an interesting RecursionError. Language versions: Python 3.8.6, 3.7.6. Examples are for illustrating the error only. In the following example, Iter.__len__() attempts to unpack s...
It has little to do with unpacking as such, but with the implementations of different collection types, their constructors in particular. [*iterable] # list (*iterable,) # tuple {*iterable} # set all trigger calls to their classes' respective constructors. From the current C implementation for list(iterable): list___i...
7
7
65,432,087
2020-12-23
https://stackoverflow.com/questions/65432087/is-there-a-way-to-use-the-secrets-python-module-with-a-seed
Random.seed() Is less secure than secrets, but I can't find any documentation on using a seed with secrets? or is random.seed just as fine?
No, there isn't. secrets uses random's SystemRandom class, which reads from the operating system's random device, such as /dev/urandom on Linux. This OS randomness is based off hardware entropy, which is what gives it its security, and there is no way to seed it.
8
11
65,431,837
2020-12-23
https://stackoverflow.com/questions/65431837/transformers-v4-x-convert-slow-tokenizer-to-fast-tokenizer
I'm following the transformer's pretrained model xlm-roberta-large-xnli example from transformers import pipeline classifier = pipeline("zero-shot-classification", model="joeddav/xlm-roberta-large-xnli") and I get the following error ValueError: Couldn't instantiate the backend tokenizer from one of: (1) a `tokenizers...
According to Transformers v4.0.0 release, sentencepiece was removed as a required dependency. This means that "The tokenizers that depend on the SentencePiece library will not be available with a standard transformers installation" including the XLMRobertaTokenizer. However, sentencepiece can be installed as an extra...
37
62
65,428,535
2020-12-23
https://stackoverflow.com/questions/65428535/why-does-this-solution-work-in-javascript-but-not-in-python-dynamic-programmin
I'm following this tutorial about dynamic programming and I'm struggling to implement memoization in the following problem: *Write a function called canSum(targetSum, numbers) that returns True only if the numbers in the array can sum to the target sum. All the numbers in the array are positive integers and you can use...
Thanks to the article shared by @Jared Smith I was able to figure it out. The problem is caused by how python handles default arguments. From the article: In Python, when passing a mutable value as a default argument in a function, the default argument is mutated anytime that value is mutated. My memo dictionary was ...
7
4
65,426,069
2020-12-23
https://stackoverflow.com/questions/65426069/use-of-mathbb-in-matplotlib
I have recently (i.e., yesterday) discovered matplotlib as a much better alternative to Matlab for plots. Unfortunately, my knowledge of python is close to zero. I would like to use \mathbb{} in the legend and/or axes (for example, to denote expected value or variance) and it seems that this requires the additional STI...
\mathbb is provided by the LaTeX package amsfonts, so you have to load this package for the figure to compile properly. You can load packages using the text.latex.preamble setting, as follows: import numpy as np import scipy.io from matplotlib import pyplot as plt plt.figure(figsize=[3.3, 3.3]) plt.rcParams.update({ 'f...
6
7
65,424,114
2020-12-23
https://stackoverflow.com/questions/65424114/in-playwright-for-python-how-do-i-retrieve-a-handle-for-elements-from-within-an
I have successfully used Playwright in python to get elements from a page. I now ran into to challenge of getting elements from a document embedded within an iframe. As an example, I used the w3schools page explaining the <option> element, which displays the result in an iframe. I am trying to retrieve a handle for thi...
Turns out I was close, but to get the iframe correctly, I needed to call the contentFrame() method. Returns the content frame for element handles referencing iframe nodes, or null otherwise Then, querySelector() will return the respective elementHandle just fine: with sync_playwright() as p: for browser_type in [p.ch...
6
4
65,422,225
2020-12-23
https://stackoverflow.com/questions/65422225/how-to-solve-keyerrorfnone-of-key-are-in-the-axis-name-in-this-case
I have a CSV file for example like this : id name email physics chemistry maths 1 Sta sta@example.com 67 78 90 2 Danny dany@example.com 77 98 89 3 Elle elle@example.com 77 67 90 Now I want to output a new CSV file using pandas which has new columns too for example like this : id name grade address p...
If you want to add new columns you should try reindex with axis=1: import pandas as pd df = pd.read_csv("sample.csv") final_df = df.reindex(['id','name','grade','address','physics','chemistry','attendance','maths','total'], axis=1)
8
1
65,420,853
2020-12-23
https://stackoverflow.com/questions/65420853/pandas-appending-a-row-of-boolean-values-to-df-using-loc-changes-to-int
Consider df: In [2098]: df = pd.DataFrame({'a': [1,2], 'b':[3,4]}) In [2099]: df Out[2099]: a b 0 1 3 1 2 4 Now, I try to append a list of values to df: In [2102]: df.loc[2] = [3, 4] In [2103]: df Out[2103]: a b 0 1 3 1 2 4 2 3 4 All's good so far. But now when I try to append a row with list of boolean values, it co...
Why is it not automatically changing the dtypes of columns to object when I append boolean to it? Because the type are being upcasted (see upcasting), from the documentation: Types can potentially be upcasted when combined with other types, meaning they are promoted from the current type (e.g. int to float). Upcastin...
6
3
65,420,399
2020-12-23
https://stackoverflow.com/questions/65420399/unable-to-read-mp4-and-avi-files-in-opencv-python
I want to just read and display an MP4 video using OpenCV, I wrote the following basic code for it: import cv2 input_video_path = './Input Video/Input_video1.mp4' cap = cv2.VideoCapture(input_video_path) while(cap.isOpened()): ret, frame = cap.read() print(frame, ret) cv2.imshow("frame", frame) cap.release() cv2.destro...
If you recieved ret as False it means that video reach end frame. If video isn't finished but you recieved False, it probably broken. Try this code: import cv2 input_video_path = './Input Video/Input_video1.mp4' cap = cv2.VideoCapture(input_video_path) while(cap.isOpened()): ret, frame = cap.read() print(frame, ret) if...
6
7
65,418,722
2020-12-23
https://stackoverflow.com/questions/65418722/what-is-in-julia-and-its-equivalent-in-python
I'm new to julia and I'm working on to rewrite julia code to python code. And I saw the some codes using .== expression. I couldn't understand what this means. So I searched it on web but couldn't find an answer. Can someone tell me what is .== in julia and its equivalent in python? fyi, it was written like below. x = ...
That's a Vectorized dot operation and is used to apply the operator to an array. You can do this for one dimensional lists in python via list comprehensions, but here it seems like you are just counting all zeroes, so >>> y = [0,1,1,1,0] >>> sum(not bool(v) for v in y) 2 Other packages like numpy or pandas will vector...
15
13
65,417,166
2020-12-22
https://stackoverflow.com/questions/65417166/how-to-make-discord-py-bot-delete-its-own-message-after-some-time
I have this code in Python: import discord client = commands.Bot(command_prefix='!') @client.event async def on_voice_state_update(member): channel = client.get_channel(channels_id_where_i_want_to_send_message)) response = f'Hello {member}!' await channel.send(response) client.run('bots_token') And I want the bot to d...
There is a better way than what Dean Ambros and Dom suggested, you can simply add the key-word argument delete_after in .send await ctx.send('whatever', delete_after=60.0) reference
6
15
65,327,247
2020-12-16
https://stackoverflow.com/questions/65327247/load-pytorch-dataloader-into-gpu
Is there a way to load a pytorch DataLoader (torch.utils.data.Dataloader) entirely into my GPU? Now, I load every batch separately into my GPU. CTX = torch.device('cuda') train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=BATCH_SIZE, shuffle=True, num_workers=0, ) net = Net().to(CTX) criterion = nn.C...
you can put your data of dataset in advance train_dataset.train_data.to(CTX) #train_dataset.train_data is a Tensor(input data) train_dataset.train_labels.to(CTX) for example of minst import torch from torch.utils.data import DataLoader from torchvision import datasets from torchvision import transforms batch_size = 64...
16
14
65,319,009
2020-12-16
https://stackoverflow.com/questions/65319009/how-to-add-a-timezone-to-a-datetime-object
I have a variable which is grabbing a date object from a file. My aim is to add a timezone to this object so that it automatically changes the time based on the date its it then. So I expected it to add +1hour to it for dates in summertime (between march and october) and add +0hour in wintertime (between october and ma...
Regarding pytz, note that there is zoneinfo in the standard lib. No need for a third party library for time zone handling with Python >= 3.9. Example usage. Then, if your input represents wall time in some time zone, you can just localize. If the input represents UTC, you can set the tzinfo to UTC a bit more easily an...
10
17
65,407,999
2020-12-22
https://stackoverflow.com/questions/65407999/how-to-make-setup-py-for-standalone-python-application-in-a-right-way
I have read several similar topics but haven't succeeded yet. I feel I miss or misunderstand some fundamental thing and this is the reason of my failure. I have an 'application' written in a python which I want to deploy with help of standard setup.py. Due to complex functionality it consists of different python module...
With that directory (package) structure, in your app.py you should import as one of the following: from app.aaa.module_a import method1 from .aaa.module_a import method1 Then make sure to call you application like one of the following: app (this should work thanks to the console entry point) python -m app.app (this...
7
4
65,318,382
2020-12-16
https://stackoverflow.com/questions/65318382/expected-browser-binary-location-but-unable-to-find-binary-in-default-location
from selenium import webdriver; browser= webdriver.Firefox(); browser.get('http://www.seleniumhq.org'); When I try to run this code, it gives me an error message: Expected browser binary location, but unable to find binary in default location, no 'moz:firefoxOptions.binary' capability provided, and no binary flag set ...
This error message... Expected browser binary location, but unable to find binary in default location, no 'moz:firefoxOptions.binary' capability provided, and no binary flag set on the command line. ...implies that the GeckoDriver was unable to find the Firefox binary at the default location. Additionally you haven't ...
45
78
65,371,837
2020-12-19
https://stackoverflow.com/questions/65371837/my-on-member-join-event-is-not-working-i-tried-intents-but-it-gives-this-error
Consider: st recent call last): File "randomgg.py", line 1271, in \u003cmodule\u003e client.run(token) File "/usr/local/lib/python3.8/site-packages/discord/client.py", line 708, in run return future.result() File "/usr/local/lib/python3.8/site-packages/discord/client.py", line 687, in runner await self.start(*ar...
The error tells you exactly what to do. Go to https://discord.com/developers/applications Navigate to your application Go to the Bot section Scroll down and enable SERVER MEMBERS INTENT
10
24
65,326,080
2020-12-16
https://stackoverflow.com/questions/65326080/python-setup-config-install-requires-good-practices
My question here may seem really naive but I never found any clue about it on web resources. The question is, concerning install_requires argument for setup() function or setup.cfg file, is it a good practice to mention every package used, even python built-in ones such as os for example ? One can assume that any pytho...
install_requires should include non-standard library requirements, and constraints on their versions (as needed). For example, this would declare minimal versions for numpy and scipy, but allow any version of scikit-learn: setup( # ... install_requires=["numpy>=1.13.3", "scipy>=0.19.1", "scikit-learn"] ) Packages such...
9
10
65,381,244
2020-12-20
https://stackoverflow.com/questions/65381244/how-to-check-if-a-tensor-is-on-cuda-or-send-it-to-cuda-in-pytorch
I have a tensor t = torch.zeros((4, 5, 6)) How to check if it is on gpu or not, and send it to gpu and back?
From the pytorch forum use t.is_cuda, t.cuda(), t.cpu() t = torch.randn(2,2) t.is_cuda # returns False t = torch.randn(2,2).cuda() t.is_cuda # returns True t = t.cpu() t.is_cuda # returns False When passing to and from gpu and cpu, new arrays are allocated on the relevant device.
24
43
65,400,809
2020-12-21
https://stackoverflow.com/questions/65400809/in-playwright-for-python-how-do-i-get-elements-relative-to-elementhandle-child
In playwright-python I know I can get an elementHandle using querySelector(). Example (sync): from playwright import sync_playwright with sync_playwright() as p: for browser_type in [p.chromium, p.firefox, p.webkit]: browser = browser_type.launch() page = browser.newPage() page.goto('https://duckduckgo.com/') element =...
Original answer: Using querySelector() / querySelectorAll with XPath (XML Path Language) lets you retrieve the elementHandle (respectively a collection of handles). Generally speaking, XPath can be used to navigate through elements and attributes in an XML document. from playwright import sync_playwright with sync_play...
7
10
65,361,686
2020-12-18
https://stackoverflow.com/questions/65361686/websockets-bridge-for-audio-stream-in-fastapi
Objective My objective is to consume an audio stream. Logically, this is my objective: Audio stream comes through WebSocket A (FastAPI endpoint) Audio stream is bridged to a different WebSocket, B, which will return a JSON (Rev-ai's WebSocket) Json results are sent back through WebSocket A, in real-time. Thus, while t...
Bridge for websocket <-> websocket Below is a simple example of websocket proxy, where websocket A and websocket B are both endpoints in the FastAPI app, but websocket B can be located in something else, just change its address ws_b_uri. For websocket client, websockets library is used. To perform data forwarding, the ...
9
16
65,324,352
2020-12-16
https://stackoverflow.com/questions/65324352/pandas-df-equals-returning-false-on-identical-dataframes
Let df_1 and df_2 be: In [1]: import pandas as pd ...: df_1 = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]}) ...: df_2 = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]}) In [2]: df_1 Out[2]: a b 0 1 4 1 2 5 2 3 6 We add a row r to df_1: In [3]: r = pd.DataFrame({'a': ['x'], 'b': ['y']}) ...: df_1 = df_1.append(r, ignore...
Use pandas.testing.assert_frame_equal(df_1, df_2, check_dtype=True), which will also check if the dtypes are the same. (It will pick up in this case that your dtypes changed from int to 'object' (string) when you appended, then deleted, a string row; pandas did not automatically coerce the dtype back down to less expan...
6
7
65,318,931
2020-12-16
https://stackoverflow.com/questions/65318931/stratifiedkfold-vs-kfold-in-scikit-learn
I use this code to test KFold and StratifiedKFold. import numpy as np from sklearn.model_selection import KFold,StratifiedKFold X = np.array([ [1,2,3,4], [11,12,13,14], [21,22,23,24], [31,32,33,34], [41,42,43,44], [51,52,53,54], [61,62,63,64], [71,72,73,74] ]) y = np.array([0,0,0,0,1,1,1,1]) sfolder = StratifiedKFold(n...
I think you should ask "When to use StratifiedKFold instead of KFold?". You need to know what "KFold" and "Stratified" are first. KFold is a cross-validator that divides the dataset into k folds. Stratified is to ensure that each fold of dataset has the same proportion of observations with a given label. So, it mea...
28
52
65,411,519
2020-12-22
https://stackoverflow.com/questions/65411519/typeerror-object-of-type-natype-is-not-json-serializable
Thank you in advance for your help. My python code reads json input file and loads the data into a data frame, masks or changes on the data frame column specified by configuration and in the last stage, creates json output file. read json into data frame --> mask/change the df column ---> generate json Input json: [ {...
Indeed, Pandas NA and NaT are not JSON serialisable by the built-in Python json library. But the Pandas DataFrame to_json() method will handle those values for you and convert them to JSON null. from pandas import DataFrame, Series, NA, NaT df = DataFrame({"ServerId" : Series([8920, NA, 9148, 2434, NA], dtype="Int64") ...
10
4
65,324,466
2020-12-16
https://stackoverflow.com/questions/65324466/typeerror-invalid-shape-3-32-32-for-image-data-showing-a-colored-image-in
I have an array of images where each image is stored as the following dimension (3, 32, 32) if I wanted to show an image using plt.imshow(img) then I am getting the following error: TypeError: Invalid shape (3, 32, 32) for image data I understand why I am getting this error, because according to imshow documentati...
Try transposing: img.T This will reverse the order of the dimensions, making it (M,N,3).
14
15
65,390,129
2020-12-21
https://stackoverflow.com/questions/65390129/venv-activate-doesnt-not-change-my-python-path
I create a virtual environment (test_venv) and I activate it. So far, successful. HOWEVER, the path of the Python Interpreter doesn't change. I have illustrated the situation below. For clarification, the python path SHOULD BE ~/Desktop/test_venv/bin/python. >>> python3 -m venv Desktop/test_venv >>> source Desktop/test...
It is not an answer specifically to your question, but it corresponds the title of the question. I faced similar problem and couldn't find solution on Internet. Maybe someone use my experience. I created virtual environment for my python project. Some time later my python interpreter also stopped changing after virtual...
18
22
65,348,890
2020-12-17
https://stackoverflow.com/questions/65348890/python-was-not-found-run-without-arguments-to-install-from-the-microsoft-store
I was trying to download a GUI, but the terminal kept giving me this error: Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases. I'm trying to install it using this command: python -m pip install --upgrade pip setuptool...
You need to download Python from https://python.org. When in the installation, be sure to check the option that adds Python to PATH.
246
32
65,383,338
2020-12-20
https://stackoverflow.com/questions/65383338/zsh-illegal-hardware-instruction-python-when-installing-tensorflow-on-macbook
I'm trying to get tensorflow working on my MacBook pro M1. However, I keep getting the following error when trying to import: zsh: illegal hardware instruction python I have downloaded and installed tensorflow via this link. These were my installation steps: install a venv: python3 -m venv venv. drag the install_venv....
This worked for me after trying a bunch of solutions to no avail. Step 1 Using pyenv install python version 3.8.5 and set it as your default python version. This tutorial(https://realpython.com/intro-to-pyenv/) is helpful for getting pyenv configured properly. Step 1.1 Use this post(https://github.com/pyenv/pyenv/issue...
47
41