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
60,899,445
2020-3-28
https://stackoverflow.com/questions/60899445/how-to-connect-kafka-topic-with-web-endpoint-using-faust-python-package
I have a simple app, with two functions, one for listening to topic and other for web endpoint. I want to create server side event streaming (SSE) i.e text/event-stream, so that on client end I could listen to it using EventSource. I have the following code for now, where each function is doing its particular job: imp...
The Faust worker will also expose a web server on every instance, that by default runs on port 6066. The server will use the aiohttp HTTP server library and you can take advantage of this thing and create a server-side event streaming (SSE) like in your example code. You can create an agent that will read from Kafka to...
12
14
60,858,424
2020-3-25
https://stackoverflow.com/questions/60858424/authentication-with-hashing
I need to make a connection to an API using a complicated authentication process that I don't understand. I know it involves multiple steps and I have tried to mimic it, but I find the documentation to be very confusing... The idea is that I make a request to an endpoint which will return a token to me that I need to u...
The main task here is to reverse the API-Sign SHA-512 HMAC calculation. Use DateTimeOffset.Now.ToUnixTimeMilliseconds to get the API nonce, it will return a Unix timestamp milliseconds value. Then it all boils down concating byte arrays and generating the hashes. I'm using a hardcoded api_nonce time just to demonstrate...
7
8
60,960,889
2020-3-31
https://stackoverflow.com/questions/60960889/django-formset-creates-multiple-inputs-for-multiple-image-upload
I am trying to create a simple post sharing form like this one. I'm using formset for image upload. But this gives me multiple input as you can see. Also each input can choose single image. But I'm trying to upload multiple image with single input. views.py def share(request): ImageFormSet = modelformset_factory(Image...
If you need one filed for multiple image upload, try this: views.py from .forms import PostForm from .models import Post, Images def share(request): form = PostForm() if request.method == 'POST': post = Post() post.title = request.POST['title'] post.content = request.POST['content'] post.author = request.user post.save...
7
8
60,928,718
2020-3-30
https://stackoverflow.com/questions/60928718/python-how-to-replace-tqdm-progress-bar-by-next-one-in-nested-loop
I use tqdm module in Jupyter Notebook. And let's say I have the following piece of code with a nested for loop. import time from tqdm.notebook import tqdm for i in tqdm(range(3)): for j in tqdm(range(5)): time.sleep(1) The output looks like this: 100%|██████████| 3/3 [00:15<00:00, 5.07s/it] 100%|██████████| 5/5 [00:10...
You can use leave param when create progress bar. Something like this: import time from tqdm import tqdm for i in tqdm(range(3)): for j in tqdm(range(5), leave=bool(i == 2)): time.sleep(1)
10
12
60,951,814
2020-3-31
https://stackoverflow.com/questions/60951814/how-to-avoid-conda-activate-base-from-automatically-executing-in-my-vs-code-edit
PS E:\Python and Data Science\PythonDatabase> conda activate base conda : The term 'conda' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + conda activate ba...
You can set "python.terminal.activateEnvironment": false in your settings to deactivate activation of your environment. Alternatively, you can set "python.condaPath" to where conda exists so the extension can use conda appropriately.
16
26
60,928,734
2020-3-30
https://stackoverflow.com/questions/60928734/robust-way-to-ensure-other-people-can-run-my-python-program
I wish to place a python program on GitHub and have other people download and run it on their computers with assorted operating systems. I am relatively new to python but have used it enough to have noticed that getting the assorted versions of all the included modules to work together can be problematic. I just discov...
Have you considered setting up a setup.py file? It's a handy way of bundling all of your... well setup into a single location. So all your user has to do is A) clone your repo and B) run pip install . to run the setup.py There's a great stack discussion about this. As well as a handle example written by the requests gu...
17
16
60,949,451
2020-3-31
https://stackoverflow.com/questions/60949451/how-to-send-a-cvmat-to-python-over-shared-memory
I have a c++ application that sends data through to a python function over shared memory. This works great using ctypes in Python such as doubles and floats. Now, I need to add a cv::Mat to the function. My code currently is: //h #include <iostream> #include <opencv2\core.hpp> #include <opencv2\highgui.hpp> struct Tran...
The general idea (as used in the OpenCV Python bindings) is to create a numpy ndarray that shares its data buffer with the Mat object, and pass that to the Python function. Note: At this point, I'll limit the example to continuous matrices only. We can take advantage of the pybind11::array class. We need to determine ...
9
15
60,954,146
2020-3-31
https://stackoverflow.com/questions/60954146/how-to-create-date-from-year-month-and-day-in-pyspark
I have three columns about year, month and day. How can I use these to create date in PySpark?
You can use concat_ws() to concat columns with - and cast to date. #sampledata df.show() #+----+-----+---+ #|year|month|day| #+----+-----+---+ #|2020| 12| 12| #+----+-----+---+ from pyspark.sql.functions import * df.withColumn("date",concat_ws("-",col("year"),col("month"),col("day")).cast("date")).show() +----+-----+--...
13
19
60,945,542
2020-3-31
https://stackoverflow.com/questions/60945542/string-formatting-using-many-pandas-columns-to-create-a-new-one
I would like to create a new columns in a pandas DataFrame just like I would do using a python f-Strings or format function. Here is an example: df = pd.DataFrame({"str": ["a", "b", "c", "d", "e"], "int": [1, 2, 3, 4, 5]}) print(df) str int 0 a 1 1 b 2 2 c 3 3 d 4 4 e 5 I would like to obtain: str int concat 0 a 1 a...
Use lsit comprehension with f-strings: df['concat'] = [f"{a}-{b:02d}" for a, b in zip(df['str'], df['int'])] Or is possible use apply: df['concat'] = df.apply(lambda x: f"{x['str']}-{x['int']:02d}", axis=1) Or solution from comments with Series.str.zfill: df["concat"] = df["str"] + "-" + df["int"].astype(str).str.zfi...
12
15
60,919,782
2020-3-29
https://stackoverflow.com/questions/60919782/how-to-get-count-on-mongodbs-motor-driver
I want to get count with Motor's diver but I got this error. AttributeError: 'AsyncIOMotorCursor' object has no attribute 'count' This is my code: await MOTOR_CURSOR.users.find().count()
MotorCollection.find() returns AsyncIOMotorCursor and it does not have count method. Instead, you should call MotorCollection.count_documents() instead. await db.users.count_documents({'x': 1}) Also worth noting that what you're referring to as MOTOR_CURSOR is MotorDatabase instance, it would preferable to call it a ...
7
10
60,879,235
2020-3-27
https://stackoverflow.com/questions/60879235/python-windows-10-launching-an-application-on-a-specific-virtual-desktop-envir
I have 3 different Windows 10 virtual desktops. When the computer starts up, I want python to load all of my applications in the different virtual desktops. Right now I can only start things in Desktop 1. How do I tell python to launch an app but in Desktop 2 and 3? I'm using python 3.6.
How do I tell python to launch an app but in Desktop 2 and 3? This can be achieved by launching your applications with subprocess.Popen(), then changing virtual desktop by calling GoToDesktopNumber() from VirtualDesktopAccessor.dll with the help of ctypes, and launching your applications again. Tested with 64-bit Win...
10
14
60,905,976
2020-3-28
https://stackoverflow.com/questions/60905976/cloudfront-give-access-denied-response-created-through-aws-cdk-python-for-s3-buc
Created Cloud Front web distribution with AWS CDK for S3 bucket without public access. Able to create Origin access identity, and deploy but on successful deploy i get access denied response on browser. Grant Read Permissions on Bucket from Origin settings will be set to No, setting this to Yes manually everything will...
I tried to mimic this and was able to integrate Cloudfront distribution to a private S3 bucket successfully. However, I used TS for my stack. I am sure it will be easy to correlate below code to Python version. Assume there is an index.html file in dist aws-cdk v1.31.0 (latest as of March 29th, 2020) import { App, Stac...
14
47
60,914,361
2020-3-29
https://stackoverflow.com/questions/60914361/python-import-error-module-factory-has-no-attribute-fuzzy
I'm a new to factory_boy module. In my code, I import factory and then used this import to access the fuzzy attribute with factory.fuzzy then it throws error module 'factory' has no attribute 'fuzzy'. I solved this problem by again importing like this import factory from factory import fuzzy by doing so there were no ...
Why this happens? When you import a Python module (your import factory), you can then access directly what is declared in that module (e.g factory.Factory): all symbols declared in the module are automatically exported. However, if a nested module is not imported in its parent, you have to import it directly. Here, fac...
8
6
60,932,036
2020-3-30
https://stackoverflow.com/questions/60932036/check-if-pandas-column-contains-all-elements-from-a-list
I have a df like this: frame = pd.DataFrame({'a' : ['a,b,c', 'a,c,f', 'b,d,f','a,z,c']}) And a list of items: letters = ['a','c'] My goal is to get all the rows from frame that contain at least the 2 elements in letters I came up with this solution: for i in letters: subframe = frame[frame['a'].str.contains(i)] This...
I would build a list of Series, and then apply a vectorized np.all: contains = [frame['a'].str.contains(i) for i in letters] resul = frame[np.all(contains, axis=0)] It gives as expected: a 0 a,b,c 1 a,c,f 3 a,z,c
25
21
60,895,196
2020-3-27
https://stackoverflow.com/questions/60895196/pandas-dataframe-droping-certain-hours-of-the-day-from-20-years-of-historical
I have stock market data for a single security going back 20 years. The data is currently in an Pandas DataFrame, in the following format: The problem is, I do not want any "after hours" trading data in my DataFrame. The market in question is open from 9:30AM to 4PM (09:30 to 16:00 on each trading day). I would like t...
Problem here is how you are importing data. There is no indicator whether 04:00 is am or pm? but based on your comments we need to assume it is PM. However input is showing it as AM. To solve this we need to include two conditions with OR clause. 9:30-11:59 0:00-4:00 Input: df = pd.DataFrame({'date': {880551: '2015-...
9
9
60,909,380
2020-3-29
https://stackoverflow.com/questions/60909380/django-serializers-vs-rest-framework-serializers
What is the difference between Django serializers vs rest_framework serializers? I making a webapp, where I want the API to be part of the primary app created by the project. Not creating a separate App for the API functionality. Which serializer do I need to use for Django views and models, and at the same time will w...
tl;dr If you want to create just a few very small API endpoints and don't want to use DRF, you're better off manually building the dictionaries. Django core serializers are not meant for external consumers. You can use the same primary app in your project and make it work with DRF in parallel. Just add a serializers.p...
7
12
60,920,851
2020-3-29
https://stackoverflow.com/questions/60920851/django-models-how-can-i-create-abstract-methods
In django abstract classes seem to be posibble by using: class Meta: abstract = True However I do not see how to declare abstract methods/functions within these classes that do not contain any logic like e.g. class AbstractClass(models.Model): def abstractFunction(): class Meta: abstract = True The library abc repect...
From what I understand, you're correct. Meta: abstract=True in Django models is there to make sure Django doesn't create database tables for the model. It predates Pythons ABC, which might explain the naming/functional confusion. Inheriting from both ABC and django.db.models.Model raises metaclass exception However, a ...
7
8
60,887,648
2020-3-27
https://stackoverflow.com/questions/60887648/colorize-the-background-of-a-seaborn-plot-using-a-column-in-dataframe
Question How to shade or colorize the background of a seaborn plot using a column of a dataframe? Code snippet import numpy as np import seaborn as sns; sns.set() import matplotlib.pyplot as plt fmri = sns.load_dataset("fmri") fmri.sort_values('timepoint',inplace=True) ax = sns.lineplot(x="timepoint", y="signal", data=...
ax.axvspan() could work for you, assuming backgrounds don't overlap over timepoints. import numpy as np import seaborn as sns; sns.set() import matplotlib.pyplot as plt fmri = sns.load_dataset("fmri") fmri.sort_values('timepoint',inplace=True) arr = np.ones(len(fmri)) arr[:300] = 0 arr[600:] = 2 fmri['background'] = ar...
10
13
60,908,298
2020-3-28
https://stackoverflow.com/questions/60908298/cannot-use-assignment-expressions-with-subscript
if session['dp'] := current_user.avatar : ^ SyntaxError: cannot use assignment expressions with subscript Why Python forbids this use of walrus operator?
Because, as the alternative name (named expressions) suggests, the left hand side of the walrus operator is to be a NAME. Therefore, by definition such expressions as noted in your question as well as, for instance, function calls are not allowed to be assigned in this form. The documentation also specifies: Single as...
20
13
60,910,345
2020-3-29
https://stackoverflow.com/questions/60910345/django-how-to-annotate-multiple-fields-from-a-subquery
I'm working on a Django project on which i have a queryset of a 'A' objects ( A.objects.all() ), and i need to annotate multiple fields from a 'B' objects' Subquery. The problem is that the annotate method can only deal with one field type per parameter (DecimalField, CharField, etc.), so, in order to annotate multiple...
What I do in such situations is to use prefetch-related a_qs = A.objects.all().prefetch_related( models.Prefetch('b_set', # NOTE: no need to filter with OuterRef (it wont work anyway) # Django automatically filter and matches B objects to A queryset=B_queryset, to_attr='b_records' ) ) Now a.b_records will be a list c...
23
19
60,909,455
2020-3-29
https://stackoverflow.com/questions/60909455/what-will-happen-if-you-dont-await-a-async-function
If I don't use await to call the async function, I will get back a coroutine. In that case, what will happen for the coroutine? Do I have to manually execute the coroutine? Or this coroutine will continue to run itself in the background? Using await async def work(): result = await stuff() Without await async def wor...
From the official docs: Note that simply calling a coroutine will not schedule it to be executed: That means you did not call your function actually so there no one waiting for anything and nothing to be waiting for if you did not place await before your function call. You could instead schedule a task for it or many...
10
8
60,904,532
2020-3-28
https://stackoverflow.com/questions/60904532/first-row-to-header-with-pandas
I have the following pandas dataframe df : import pandas as pd from io import StringIO s = '''\ "Unnamed: 0","Unnamed: 1" Objet,"Unités vendues" Chaise,3 Table,2 Tabouret,1 ''' df = pd.read_csv(StringIO(s)) which looks as: Unnamed: 0 Unnamed: 1 0 Objet Unités vendues 1 Chaise 3 2 Table 2 3 Tabouret 1 My target is to...
what about defining that when you load your table in the first place? pd.read_csv('filename', header = 1) otherwise I guess you can just do this: df.drop('0', axis = 1)
7
3
60,903,145
2020-3-28
https://stackoverflow.com/questions/60903145/typeerror-cannot-instantiate-typing-optional
I have such a method: def select_unassigned_variable(self, variables: List[V]) -> Optional(V): I want this to return something of type V or None in some cases. But I get such error: TypeError: Cannot instantiate typing.Optional What should I change?
You need to use it with brackets instead of parentheses: def select_unassigned_variable(self, variables: List[V]) -> Optional[V]: like you did with List.
7
22
60,894,798
2020-3-27
https://stackoverflow.com/questions/60894798/importerror-cannot-import-name-bigquery
This must be a super trivial issue, but i've updated my windows virtual machine with; pip install --upgrade google-cloud-storage However, when I run the script I still receive the following error; Traceback (most recent call last): File "file.py", line 6, in <module> from google.cloud import bigquery, storage ImportEr...
From a fresh setup of the VM; Failed - pip3 install --upgrade google-cloud Worked - pip3 install --upgrade google-cloud-bigquery Worked - pip3 install --upgrade google-cloud-storage It appears that individual product solutions should be installed instead of the generic google-cloud. If you're still stuck, this helped!
25
17
60,882,638
2020-3-27
https://stackoverflow.com/questions/60882638/install-a-particular-version-of-python-package-in-a-virtualenv-created-with-reti
When using reticulate package in order to use Python inside R, we can create a virtualenv thanks to the command reticulate::virtualenv_create specifying env name and the path to the python bin. We can also add packages to the previously created environment like this: reticulate::virtualenv_create(envname = 'venv_shiny...
You can request a specific version of a package with, for example: reticulate::virtualenv_install(packages = c("numpy==1.8.0"))
7
10
60,892,714
2020-3-27
https://stackoverflow.com/questions/60892714/how-to-get-the-weight-of-evidence-woe-and-information-value-iv-in-python-pan
I was wondering how to calculate the WOE and IV in python. Are there any dedication function in numpy/scipy/pandas/sklearn? Here is my example dataframe: import numpy as np import pandas as pd np.random.seed(100) df = pd.DataFrame({'grade': np.random.choice(list('ABCD'),size=(20)), 'pass': np.random.choice([0,1],size=(...
Formulas for woe and iv: Code to achieve this: import numpy as np import pandas as pd np.random.seed(100) df = pd.DataFrame({'grade': np.random.choice(list('ABCD'),size=(20)), 'pass': np.random.choice([0,1],size=(20)) }) feature,target = 'grade','pass' df_woe_iv = (pd.crosstab(df[feature],df[target], normalize='column...
7
16
60,841,650
2020-3-25
https://stackoverflow.com/questions/60841650/how-to-test-one-single-image-in-pytorch
I created my model in pytorch and is working really good, but when i want to test just one image batch_size=1 always return the second class (in this case a dog). I tried to test with batch > 1 and in all cases this works! The architecture: model = models.densenet121(pretrained=True) for param in model.parameters(): pa...
I realized that my model wasn't in eval mode. So i just added model.eval() and now that's all, works for any size batch
7
11
60,883,397
2020-3-27
https://stackoverflow.com/questions/60883397/using-pymongo-upsert-to-update-or-create-a-document-in-mongodb-using-python
I have a dataframe that contains data I want to upload into MongoDB. Below is the data: MongoRow = pd.DataFrame.from_dict({'school': {1: schoolID}, 'student': {1: student}, 'date': {1: dateToday}, 'Probability': {1: probabilityOfLowerThanThreshold}}) school student date Probability 1 5beee5678d62101c9c4e7dbb 5bf3e06f9...
To upsert you cannot use insert() (deprecated) insert_one() or insert_many(). You must use one of the collection level operators that supports upserting. To get started I would point you towards reading the dataframe line by line and using replace_one() on each line. There are more advanced ways of doing this but this ...
13
10
60,879,982
2020-3-27
https://stackoverflow.com/questions/60879982/attributeerror-timedelta-object-has-no-attribute-dt
I have a df: id timestamp data group Date 27001 27242 2020-01-01 09:07:21.277 19.5 1 2020-01-01 27002 27243 2020-01-01 09:07:21.377 19.0 1 2020-01-01 27581 27822 2020-01-02 07:53:05.173 19.5 1 2020-01-02 27582 27823 2020-01-02 07:53:05.273 20.0 1 2020-01-02 27647 27888 2020-01-02 10:01:46.380 20.5 1 2020-01-02 ... an...
As @hpaulj said in the comments, dt is only associated with dataframe like object. So to obtain total seconds you have to use difference = (df.loc[0, 'timestamp'] - df.loc[1, 'timestamp']).total_seconds()
7
3
60,878,196
2020-3-27
https://stackoverflow.com/questions/60878196/seaborn-rc-parameters-for-set-context-and-set-style
In the tutorial for setting up the aesthetics of your plots, there are a few different methods: set_style set_context axes_style Each one of these accepts an rc keyword parameter dictionary. In each individual API page for the above three functions, it says: rcdict, optional: Parameter mappings to override the value...
It would appear that the answer is 'none of the above'. The valid keys for set_style and set_context are listed here: _style_keys = [ "axes.facecolor", "axes.edgecolor", "axes.grid", "axes.axisbelow", "axes.labelcolor", "figure.facecolor", "grid.color", "grid.linestyle", "text.color", "xtick.color", "ytick.color", "xti...
7
11
60,878,959
2020-3-27
https://stackoverflow.com/questions/60878959/attributeerror-numpy-ndarray-object-has-no-attribute-save
i have short code for crop image all image in folder that i labeled and save as csv using opencv like this: import os, sys from PIL import Image import cv2 import pandas as pd # The annotation file consists of image names, text label, # bounding box information like xmin, ymin, xmax and ymax. ANNOTATION_FILE = 'data/an...
try using cv2.imwrite(path,img_to_save) in the last line.
7
15
60,842,487
2020-3-25
https://stackoverflow.com/questions/60842487/python-was-not-found-but-can-be-installed-from-the-microsoft-store-march-2020
I started watching a Python course on YouTube in which the guy giving the lesson teaches using VSCode. He started with software installation (Python & Pycharm). Then, in VSCode he downloaded the Python extension (the one made by Microsoft) and the extension called "Code Runner" to run the Python code on VSCode. When I ...
You don't have the command python installed into your PATH on Windows which is the default if you didn't get your copy of Python from the Windows Store. If you selected your Python interpreter in VS Code (look in the status bar), then I would disable Code Runner. That way the Python extension is what provides the abili...
42
35
60,872,434
2020-3-26
https://stackoverflow.com/questions/60872434/django-onetoonefield-relatedobjectdoesnotexist
I have this two following classes in my model: class Answer(models.Model): answer = models.CharField(max_length=300) question = models.ForeignKey('Question', on_delete=models.CASCADE) def __str__(self): return "{0}, view: {1}".format(self.answer, self.answer_number) class Vote(models.Model): answer = models.OneToOneFie...
Your related_name IS recognized, but it is only assigned to the instance if the related object exists. In your case, there is no Vote instance in your database where its answer field points to your Answer instance Just catch the exception and return None if you want to proceed: answer = Answer.objects.all().first() tr...
7
14
60,868,060
2020-3-26
https://stackoverflow.com/questions/60868060/module-on-test-pypi-cant-install-dependencies-even-though-they-exist
I have done this small package that I want to distribute in my community. It is now on test.pypi and when I want to try to install it, it gives an error that dependencies couldn't be found. setup.py ... install_requires=[ 'defcon>=0.6.0', 'fonttools>=3.31.0' ] ... throws this error ERROR: Could not find a version tha...
-i URL, or --index-url URL means "use URL for installing packages from exclusively". By passing -i https://test.pypi.org/simple/, you thus prohibit searching and downloading packages from PyPI (https://pypi.org/simple). To use both indexes, use --extra-index-url: $ python -m pip install --extra-index-url https://test.p...
7
22
60,870,128
2020-3-26
https://stackoverflow.com/questions/60870128/cant-install-geopandas-in-anaconda-environment
I am trying to install the geopandas package with Anaconda Prompt, but after I use conda install geopandas an unexpected thing happened: Collecting package metadata (current_repodata.json): done Solving environment: failed with initial frozen solve. Retrying with flexible solve. Solving environment: failed with repodat...
You can install geopandas with pip, however, geopandas requires other dependencies (such as pandas, fiona, shapely, pyproj, rtree). You need to make sure that they are properly installed. After that you should be able to use them in jupyter with a simple import geopandas.
15
-3
60,869,306
2020-3-26
https://stackoverflow.com/questions/60869306/how-to-simple-crop-the-bounding-box-in-python-opencv
I am trying to learn opencv and implementing a research project by testing some used cases. I am trying to crop the bounding box of the inside the image using python opencv . I have successfully created the bounding box but failed in crop this is the image import cv2 import matplotlib.pyplot as plt img = cv2.imread("...
I figured it out the formula for cropping the bounding box from the original image cropped_image = img[Y:Y+H, X:X+W] print([X,Y,W,H]) plt.imshow(cropped_image) cv2.imwrite('contour1.png', cropped_image)
15
33
60,869,243
2020-3-26
https://stackoverflow.com/questions/60869243/how-can-i-filter-dataframe-based-on-null-not-null-using-a-column-name-as-a-varia
I want to list a dataframe where a specific column is either null or not null, I have it working using - df[df.Survive.notnull()] # contains no missing values df[df.Survive.isnull()] #---> contains missing values This works perfectly but I want to make my code more dynamic and pass the column "Survive" as a variable b...
So idea is always is necessary Series or list or 1d array for mask for filtering. If want test only one column use scalar: variableToPredict = 'Survive' df[df[variableToPredict].notnull()] But if add [] output is one column DataFrame, so is necessaty change function for test by any (test if at least one NaN per row, s...
17
27
60,868,629
2020-3-26
https://stackoverflow.com/questions/60868629/valueerror-solver-lbfgs-supports-only-l2-or-none-penalties-got-l1-penalty
I'm running the process of feature selection on classification problem, using the embedded method (L1 - Lasso) With LogisticRegression. I'm running the following code: from sklearn.linear_model import Lasso, LogisticRegression from sklearn.feature_selection import SelectFromModel # using logistic regression with penalt...
This is cleared up in the documentation. solver : {‘newton-cg’, ‘lbfgs’, ‘liblinear’, ‘sag’, ‘saga’}, default=’lbfgs’ ... ‘newton-cg’, ‘lbfgs’, ‘sag’ and ‘saga’ handle L2 or no penalty ‘liblinear’ and ‘saga’ also handle L1 penalty Call it like this: LogisticRegression(C=1, penalty='l1', solver='liblinear')
26
45
60,867,546
2020-3-26
https://stackoverflow.com/questions/60867546/save-failed-in-google-colab
I opened a number of tabs at the same time. I think that's why Google Colab was not able to support the heavy load. The message stated: Save failed This file could not be saved. Please use the File menu to download the .ipynb and upload the notebook to make a copy that includes your recent changes. Is downloading the...
This can happen if you open the same notebook in multiple tabs and make incompatible edits to the notebook. At this point, the only way to save your work is to follow the advice in the dialog. To prevent this in the future, avoid simultaneously editing the same notebook in multiple browser windows.
8
-1
60,862,145
2020-3-26
https://stackoverflow.com/questions/60862145/what-is-the-point-of-norm-fit-in-scipy
Im generating a random sample of data and plotting its pdf using scipy.stats.norm.fit to generate my loc and scale parameters. I wanted to see how different my pdf would look like if I just calculated the mean and std using numpy without any actual fitting. To my surprise when I plot both pdfs and print both sets of mu...
The point is that there are several other distributions out there besides the normal distribution. Scipy provides a consistent API for learning the parameters of these distributions from data. (Want an exponential distribution instead of a normal distribution? It’s scipy.stats.expon.fit.) So sure, your way also works b...
8
8
60,858,862
2020-3-25
https://stackoverflow.com/questions/60858862/write-a-functon-to-modify-a-certain-string-in-a-certain-way-by-adding-character
I have to write a function that takes a string, and will return the string with added "asteriks" or "*" symbols to signal multiplication. As we know 4(3) is another way to show multiplication, as well as 4*3 or (4)(3) or 4*(3) etc. Anyway, my code needs to fix that problem by adding an asterik between the 4 and the 3 f...
I'll share mine. def insertAsteriks(string): lstring = list(string) c = False for i in range(1, len(lstring)): if c: c = False pass elif lstring[i] == '(' and (lstring[i - 1] == ')' or lstring[i - 1].isdigit() or lstring[i - 1].isalpha() or (lstring[i - 1] == ' ' and not lstring[i - 2] in "*^-+/")): lstring.insert(i, '...
7
2
60,865,887
2020-3-26
https://stackoverflow.com/questions/60865887/exclude-env-directory-from-flake8-tests
Problem I'm getting thousands of flake8 errors stemming from my local .env. An example of some of the error messages: ./env/lib/python3.7/site-packages/pip/_vendor/pyparsing.py:3848:80: E501 line too long (85 > 79 characters) ./env/lib/python3.7/site-packages/pip/_vendor/pyparsing.py:3848:84: E202 whitespace before ')'...
I notice your .flake8 file is inside app folder. I presume you are starting flake8 from outside the app folder, in other words from the project root. Move .flake8 to the project root, and everything's gonna work: mv app/.flake8 .
37
13
60,844,846
2020-3-25
https://stackoverflow.com/questions/60844846/read-a-body-json-list-with-fastapi
The body of an HTTP PUT request is a JSON list - like this: [item1, item2, item3, ...] I can't change this. (If the root was a JSON object rather than a list there would be no problem.) Using FastAPI I seem to be unable to access this content in the normal way: @router.put('/data') def set_data(data: DataModel): # Thi...
Descending from the model perspective to primitives In FastAPI, you derive from BaseModel to describe the data models you send and receive (i.e. FastAPI also parses for you from a body and translates to Python objects). Also, it relies on the modeling and processing from pydantic. from typing import List from pydantic ...
15
36
60,852,962
2020-3-25
https://stackoverflow.com/questions/60852962/training-time-of-gensim-word2vec
I'm training word2vec from scratch on 34 GB pre-processed MS_MARCO corpus(of 22 GB). (Preprocessed corpus is sentnecepiece tokenized and so its size is more) I'm training my word2vec model using following code : from gensim.test.utils import common_texts, get_tmpfile from gensim.models import Word2Vec class Corpus(): ...
Completing a model requires one pass over all the data to discover the vocabulary, then multiple passes, with a default of 5, to perform vector training. So, you should expect to see about 6x your data size in disk-reads, just from the model training. (If your machine winds up needing to use virtual-memory swapping dur...
7
14
60,851,784
2020-3-25
https://stackoverflow.com/questions/60851784/remove-pandas-columns-based-on-list
I have a list: my_list = ['a', 'b'] and a pandas dataframe: d = {'a': [1, 2], 'b': [3, 4], 'c': [1, 2], 'd': [3, 4]} df = pd.DataFrame(data=d) What can I do to remove the columns in df based on list my_list, in this case remove columns a and b
This is very simple: df = df.drop(columns=my_list) drop removes columns by specifying a list of column names
9
15
60,850,596
2020-3-25
https://stackoverflow.com/questions/60850596/calculate-average-of-every-n-rows-from-a-csv-file
I have a csv file that has 25000 rows. I want to put the average of every 30 rows in another csv file. I've given an example with 9 rows as below and the new csv file has 3 rows (3, 1, 2): | H | ======== | 1 |---\ | 3 | |--->| 3 | | 5 |---/ | -1 |---\ | 3 | |--->| 1 | | 1 |---/ | 0 |---\ | 5 | |--->| 2 | | 1 |---/ Wha...
You can use integer division by step for consecutive groups and pass to groupby for aggregate mean: step = 30 m_df = pd.read_csv(m_path, usecols=['Col-01']) df = m_df.groupby(m_df.index // step).mean() Or: df = m_df.groupby(np.arange(len(dfm_df// step).mean() Sample data: step = 3 df = m_df.groupby(m_df.index // step...
9
9
60,842,775
2020-3-25
https://stackoverflow.com/questions/60842775/how-to-package-a-python-module-with-extras-as-default
My Python package has optional features (extras_require) and I would prefer them to be selected by default. More specifically, I'd like that pip install mypackage behaves like pip install mypackage[extra] and that I can install a minimal version with something like pip install mypackage[core]. setup( name="mypackage", ...
Unfortunately this is not possible with the current state of Python packaging metadata & tooling. See a long discussion here as to why.
11
7
60,775,172
2020-3-20
https://stackoverflow.com/questions/60775172/pyenvs-python-is-missing-bzip2-module
I used pyenv to install python 3.8.2 and to create a virtualenv. In the virtualenv, I used pipenv to install pandas. However, when importing pandas, I'm getting the following: [...] File "/home/luislhl/.pyenv/versions/poc-prefect/lib/python3.8/site-packages/pandas/io/common.py", line 3, in <module> import bz2 File "/h...
On Ubuntu 22 LTS Missing Library Problem in Python Installation with Pyenv Before the fix: $> pyenv install 3.11.0 command result: pyenv: /home/user/.pyenv/versions/3.11.0 already exists continue with installation? (y/N) y Downloading Python-3.11.0.tar.xz... -> https://www.python.org/ftp/python/3.11.0/Python-3.11.0.ta...
59
118
60,736,556
2020-3-18
https://stackoverflow.com/questions/60736556/pandas-rolling-apply-using-multiple-columns
I am trying to use a pandas.DataFrame.rolling.apply() rolling function on multiple columns. Python version is 3.7, pandas is 1.0.2. import pandas as pd #function to calculate def masscenter(x): print(x); # for debug purposes return 0; #simple DF creation routine df = pd.DataFrame( [['02:59:47.000282', 87.60, 739], ['03...
How about this: import pandas as pd def masscenter(ser: pd.Series, df: pd.DataFrame): df_roll = df.loc[ser.index] return your_actual_masscenter(df_roll) masscenter_output = df['price'].rolling(window=3).apply(masscenter, args=(df,)) It uses the rolling logic to get subsets via an arbitrary column. The arbitrary column...
40
46
60,827,896
2020-3-24
https://stackoverflow.com/questions/60827896/how-to-configure-an-equivalent-of-ssh-stricthostkeychecking-no-in-python-paramik
I am using Paramiko for sshing from Python script. My ssh command is listed below: ssh -A -o strictHostKeyChecking=no <hostname> I need same Paramiko code for Python.
In Paramiko, an equivalent of OpenSSH StrictHostKeyChecking=no is the default behaviour of MissingHostKeyPolicy, which implements missing_host_key to simply do nothing. client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy()) client.connect(hostname, ...) Though you should not...
8
13
60,768,676
2020-3-20
https://stackoverflow.com/questions/60768676/what-is-the-default-install-path-for-poetry
I installed poetry, however I'm getting the following error when attempting to call poetry zsh: command not found: poetry I know I have it installed because I get the following output when trying to run the following install script $ curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py...
The default install location is ~/.poetry/bin/poetry I added the following to my .zshrc export PATH="$HOME/.local/bin:$PATH"
22
56
60,814,982
2020-3-23
https://stackoverflow.com/questions/60814982/how-to-setup-pip-to-download-from-mirror-repository-by-default
I am forced to download python packages from local mirror PyPi repository. I do this by using the -i and --trusted-host options. Whole installation command looks like this: pip install -i https://sampleurl.com/pypi-remote/simple --trusted-host sample.host.com package_name Having to type in that options each time is ki...
using pip config, on user or global level. I have /etc/pip.conf configured like this: [global] index=https://my-company/nexus/repository/pypi-group/pypi index-url=https://my-company/nexus/repository/pypi-group/simple trusted-host=my-company but you can configure this using pip config on user or global level, something...
76
127
60,839,470
2020-3-24
https://stackoverflow.com/questions/60839470/pymongo-errors-serverselectiontimeouterrorlocalhost27017winerror-10061-no-c
I am following the Python tutorial from W3Schools. I just started the MongoDB chapter. I installed MongoDB and checked it with: import pymongo without getting an error. But as soon as I enter the following code: import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] m...
There is nothing wrong with your code. If you have disabled your firewall, the most likely reason is that the MongoDB service is not installed or running. On Windows, press the Windows key and type services to open the services application. Check the service MongoDB Server is listed and has a Running status. You can te...
9
11
60,832,201
2020-3-24
https://stackoverflow.com/questions/60832201/how-can-i-do-real-time-voice-activity-detection-in-python
I am performing a voice activity detection on the recorded audio file to detect speech vs non-speech portions in the waveform. The output of the classifier looks like (highlighted green regions indicate speech): The only issue I face here is making it work for a stream of audio input (for eg: from a microphone) and do...
You should try using Python bindings to webRTC VAD from Google. It's lightweight, fast and provides very reasonable results, based on GMM modelling. As the decision is provided per frame, the latency is minimal. # Run the VAD on 10 ms of silence. The result should be False. import webrtcvad vad = webrtcvad.Vad(2) sampl...
19
25
60,782,785
2020-3-20
https://stackoverflow.com/questions/60782785/python3-m-pip-install-vs-pip3-install
I always use pip install (which I think is equivalent to pip3 install since I only have python3 in my env) to install packages. But I recently heard python3 -m pip install is better. Why?
I would advise against ever calling any pip somecommand (or pip3) script directly. Instead it's much safer to call pip's executable module for a specific Python interpreter explicitly, something of the form path/to/pythonX.Y -m pip somecommand. There are many advantages to this, for example: It is explicit for which P...
12
10
60,830,938
2020-3-24
https://stackoverflow.com/questions/60830938/python-multiprocessing-logging-via-queuehandler
I have a Python multiprocessing application to which I would like to add some logging functionality. The Python logging cookbook recommends using a Queue. Every process will put log records into it via the QueueHandler and a Listener Process will handle the records via a predefined Handler. Here is the example provided...
In your case a few simple classes will do the trick. Have a look and let me know if you need some further explanations or want something different. import logging import logging.handlers import multiprocessing import multiprocessing.pool from random import choice, random import time class ProcessLogger(multiprocessing....
10
12
60,788,680
2020-3-21
https://stackoverflow.com/questions/60788680/what-is-the-time-complexity-of-type-casting-function-in-python
For example, int(x) float(x) str(x) What is time complexity of them?
There is no definite answer to this because it depends not just what type you're converting to, but also what type you're converting from. Let's consider just numbers and strings. To avoid writing "log" everywhere, we'll measure the size of an int by saying n is how many bits or digits it takes to represent it. (Asympt...
14
10
60,765,317
2020-3-19
https://stackoverflow.com/questions/60765317/how-to-create-an-openapi-schema-for-an-uploadfile-in-fastapi
FastAPI automatically generates a schema in the OpenAPI spec for UploadFile parameters. For example, this code: from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/uploadfile/") async def create_upload_file(file: UploadFile = File(..., description="The file")): return {"filename": file.filename} ...
You can edit the OpenAPI schema itself. I prefer to just move these schemas to the path (since they are unique to each path anyway): from fastapi import FastAPI, File, UploadFile from fastapi.openapi.utils import get_openapi app = FastAPI() @app.post("/uploadfile/") async def create_upload_file(file1: UploadFile = File...
13
4
60,762,378
2020-3-19
https://stackoverflow.com/questions/60762378/exec-python-executable-file-not-found-in-path
I am running Arduion IDE 1.8.12 on Ubuntu 18.04.4 LTS. I am trying to compile Example code for ESP32 Camera module (standard camera module with default example on Arduino IDE) and I got this error (which I think is not Arduino issue, but Python): "exec: "python": executable file not found in $PATH Error compiling for b...
To solve & Fixed the following upload error from Arduino To ESP32-CAM (And for ESP32 too): environment: ubuntu 20.04 64bit, Arduino 1.8.13 ESP32-CAM And yp-05 (for ESP's serial connection) exec: "python": executable file not found in $PATH Error compiling for board AI Thinker ESP32-CAM. The solution is: Installing t...
10
2
60,739,653
2020-3-18
https://stackoverflow.com/questions/60739653/gdown-is-giving-permission-error-for-particular-file-although-it-is-opening-up-f
I am not able to download file using gdown package.It is giving permission error. But when i am opening it manually.It is giving no such error and opening up fine. Here is the code i am using and link import gdown url='https://drive.google.com/uc?id=0B1lRQVLFjBRNR3Jqam1menVtZnc' output='letter.pdf' gdown.download(url, ...
If you're working with big files (in my case was a >1gb file), you can solve by copying the url from 'Download anyway' button in Google Drive.
32
10
60,819,376
2020-3-23
https://stackoverflow.com/questions/60819376/fastapi-throws-an-error-error-loading-asgi-app-could-not-import-module-api
I tried to run FastAPI using uvicorn webserver but it throws an error. I run this command, uvicorn api:app --reload --host 0.0.0.0 but there is an error in the terminal. Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) Started reloader process [23445] Error loading ASGI app. Could not import module "api"....
TL;DR Add the directory name in front of your filename uvicorn src.main:app or cd into that directory cd src uvicorn main:app Long Answer It happens because you are not in the same folder with your FastAPI app instance more specifically: Let's say i have an app-tree like this; my_fastapi_app/ ├── app.yaml ├── docker-...
171
316
60,816,403
2020-3-23
https://stackoverflow.com/questions/60816403/get-week-number-with-week-start-day-different-than-monday-python
I have a dataset with a date column. I want to get the week number associated with each date. I know I can use: x['date'].isocalendar()[1] But it gives me the week num with start day = monday. While I need the week to start on a friday. How do you suggest I go about doing that?
tl;dr The sections "ISO Standard" and "What you want" is to clarify your need. You could just copy paste the code in the section "Solution" and see if the result is what you want. ISO Standard Definition Weeks start with Monday. Each week's year is the Gregorian year in which the Thursday falls. Result of Python Sta...
12
10
60,783,222
2020-3-21
https://stackoverflow.com/questions/60783222/how-to-test-a-fastapi-api-endpoint-that-consumes-images
I am using pytest to test a FastAPI endpoint that gets in input an image in binary format as in @app.post("/analyse") async def analyse(file: bytes = File(...)): image = Image.open(io.BytesIO(file)).convert("RGB") stats = process_image(image) return stats After starting the server, I can manually test the endpoint suc...
You see a different behavior because requests and TestClient are not exactly same in every aspect as TestClient wraps requests. To dig deeper, refer to the source code: (FastAPI is using TestClient from starlette library, FYI) https://github.com/encode/starlette/blob/master/starlette/testclient.py To solve, you can get...
20
33
60,827,999
2020-3-24
https://stackoverflow.com/questions/60827999/use-dictionary-in-tf-function-input-signature-in-tensorflow-2-0
I am using Tensorflow 2.0 and facing the following situation: @tf.function def my_fn(items): .... #do stuff return If items is a dict of Tensors like for example: item1 = tf.zeros([1, 1]) item2 = tf.zeros(1) items = {"item1": item1, "item2": item2} Is there a way of using input_signature argument of tf.function so I ...
The input signature has to be a list, but elements in the list can be dictionaries or lists of Tensor Specs. In your case I would try: (the name attributes are optional) signature_dict = { "item1": tf.TensorSpec(shape=[2], dtype=tf.int32, name="item1"), "item2": tf.TensorSpec(shape=[], dtype=tf.int32, name="item2") } #...
14
15
60,789,886
2020-3-21
https://stackoverflow.com/questions/60789886/error-failed-to-create-temp-directory-c-users-user-appdata-local-temp-conda
When I try to Activate "conda activate tensorflow_cpu" conda activate tensorflow_cpu Error : Failed to create temp directory "C:\Users\user\AppData\Local\Temp\conda-\"
It is due to a bug from conda developers. The bug is the temp path is having names with spaces, so to overcome please reassign the Env Variables TEMP, TMP. (for windows) go to environment variables In "User Variables for " section look for TEMP, TMP double click on TMP and in "variable value", type "C:\conda_tmp" simi...
12
20
60,839,909
2020-3-24
https://stackoverflow.com/questions/60839909/errors-running-pandas-profile-report
I'm trying to run a Profile Report for EDA in conda Jupyter NB, but keep getting errors. Here is my code thus far: import pandas_profiling from pandas_profiling import ProfileReport profile = ProfileReport(data) and profile = pandas_profiling.ProfileReport(data) both of which produce: TypeError: concat() got an ...
Installed most recent version (March 2020) of pandas-profiling in conda. conda install -c conda-forge/label/cf202003 pandas-profiling Was then able to import pandas_profiling in jupyter notebook
12
4
60,835,421
2020-3-24
https://stackoverflow.com/questions/60835421/pyspark-topandas-function-is-changing-column-type
I have a pyspark dataframe with following schema: root |-- src_ip: integer (nullable = true) |-- dst_ip: integer (nullable = true) When converting this dataframe to pandas via toPandas(), the column type changes from integer in spark to float in pandas: <class 'pandas.core.frame.DataFrame'> RangeIndex: 9847 entries, 0...
SPARK-21766 (https://issues.apache.org/jira/browse/SPARK-21766) explains the behavior your observed. As a workaround, you can call fillna(0) before toPandas(): df1 = sc.createDataFrame([(0, None), (None, 8)], ["src_ip", "dest_ip"]) print(df1.dtypes) # Reproduce the issue pdf1 = df1.toPandas() print(pdf1.dtypes) # A wor...
8
3
60,828,641
2020-3-24
https://stackoverflow.com/questions/60828641/simplest-way-to-perform-logging-from-google-cloud-run
I followed this guide https://firebase.google.com/docs/hosting/cloud-run to setup cloud run docker. Then I tried to follow this guide https://cloud.google.com/run/docs/logging to perform a simple log. Trying to write a structured log to stdout This is my code: trace_header = request.headers.get('X-Cloud-Trace-Context'...
I am running into the exact same issue. I did find that flushing stdout causes the logging to appear when it otherwise would not. Looks like a bug in Cloud Run to me. print(json.dumps(entry)) import sys sys.stdout.flush() Output with flushing
14
14
60,778,279
2020-3-20
https://stackoverflow.com/questions/60778279/fastapi-middleware-peeking-into-responses
I try to write a simple middleware for FastAPI peeking into response bodies. In this example I just log the body content: app = FastAPI() @app.middleware("http") async def log_request(request, call_next): logger.info(f'{request.method} {request.url}') response = await call_next(request) logger.info(f'Status code: {resp...
I had a similar need in a FastAPI middleware and although not ideal here's what we ended up with: app = FastAPI() @app.middleware("http") async def log_request(request, call_next): logger.info(f'{request.method} {request.url}') response = await call_next(request) logger.info(f'Status code: {response.status_code}') body...
15
14
60,776,749
2020-3-20
https://stackoverflow.com/questions/60776749/plot-confusion-matrix-without-estimator
I'm trying to use plot_confusion_matrix, from sklearn.metrics import confusion_matrix y_true = [1, 1, 0, 1] y_pred = [1, 1, 0, 0] confusion_matrix(y_true, y_pred) Output: array([[1, 0], [1, 2]]) Now, while using the followings; using 'classes' or without 'classes' from sklearn.metrics import plot_confusion_matrix plo...
plot_confusion_matrix expects a trained classifier. If you look at the source code, what it does is perform the prediction to generate y_pred for you: y_pred = estimator.predict(X) cm = confusion_matrix(y_true, y_pred, sample_weight=sample_weight, labels=labels, normalize=normalize) So in order to plot the confusion m...
8
10
60,827,049
2020-3-24
https://stackoverflow.com/questions/60827049/how-to-document-small-changes-to-complex-api-functions
Let's say we have a complex API function, imported from some library. def complex_api_function( number, <lots of positional arguments>, <lots of keyword arguments>): '''really long docstring''' # lots of code I want to write a simple wrapper around that function to make a tiny change. For example, it should be possibl...
I'd recommend something like the following: def my_complex_api_function(number_or_str, *args, **kwargs): """This function is a light wrapper to `complex_api_function`. It allows you to pass a string or a number, whereas `complex_api_function` requires a number. See :ref:`complex_api_function` for more details. :param n...
8
3
60,747,047
2020-3-18
https://stackoverflow.com/questions/60747047/spyder-4-deactivate-automatic-highlighting-of-last-word-after-few-seconds
When I stop typing in Spyder 4, all occurrences of the last word are automatically highlighted after about two seconds. Is it a bug or can I disable it? I use Spyder on Ubuntu 18.04.
I found the setting: Tools > Preferences > Editor > Display > Highlight occurrences after
9
16
60,736,569
2020-3-18
https://stackoverflow.com/questions/60736569/timestamp-subtraction-must-have-the-same-timezones-or-no-timezones-but-they-are
There are questions that addresses the same error TypeError: Timestamp subtraction must have the same timezones or no timezones but none faces the same issue as this one. I have 2 UTC Timestamps that throw that error when substracted. print(date, type(date), date.tzinfo) >>> 2020-07-17 00:00:00+00:00 <class 'pandas._li...
After checking the timezone types: type(date.tzinfo) gives <class 'datetime.timezone'> and type(date2.tzinfo) gives <class 'pytz.UTC'> so acording of pandas source code they are not considered equal even even if they are both UTC. So the solution was to make them have the same tzinfo type (either pytz or datitme.timezo...
13
6
60,793,752
2020-3-21
https://stackoverflow.com/questions/60793752/extract-artwork-from-table-game-card-image-with-opencv
I wrote a small script in python where I'm trying to extract or crop the part of the playing card that represents the artwork only, removing all the rest. I've been trying various methods of thresholding but couldn't get there. Also note that I can't simply record manually the position of the artwork because it's not a...
I used Hough line transform to detect linear parts of the image. The crossings of all lines were used to construct all possible rectangles, which do not contain other crossing points. Since the part of the card you are looking for is always the biggest of those rectangles (at least in the samples you provided), i simpl...
12
5
60,838,082
2020-3-24
https://stackoverflow.com/questions/60838082/altair-line-chart-with-stroked-point-markers
I'm trying to create a line chart with point markers in Altair. I'm using the multi-series line chart example from Altair's documentation and trying to combine it with the line chart with stroked point markers example from Vega-Lite's documentation. Where I'm confused is how to handle the 'mark_line' argument. From th...
You can always pass a raw vega-lite dict to any property in Altair: source = data.stocks() alt.Chart(source).mark_line( point={ "filled": False, "fill": "white" } ).encode( x='date', y='price', color='symbol' ) or you can check the docstring of mark_line() and see that it expects point to be an OverlayMarkDef() and us...
7
9
60,832,569
2020-3-24
https://stackoverflow.com/questions/60832569/pandas-rolling-aggregate-boolean-values
Is there any rolling "any" function in a pandas.DataFrame? Or is there any other way to aggregate boolean values in a rolling function? Consider: import pandas as pd import numpy as np s = pd.Series([True, True, False, True, False, False, False, True]) # this works but I don't think it is clear enough - I am not # inte...
This method is not implemented, close, what you need is use Rolling.apply: s = s.rolling(2).apply(lambda x: x.any(), raw=False) print (s) 0 NaN 1 1.0 2 1.0 3 1.0 4 1.0 5 0.0 6 0.0 7 1.0 dtype: float64 s = s.rolling(2).apply(lambda x: x.any(), raw=False).fillna(0).astype(bool) print (s) 0 False 1 True 2 True 3 True 4 Tr...
6
3
60,820,508
2020-3-23
https://stackoverflow.com/questions/60820508/how-to-make-pytest-cases-runnable-in-intellij
I want to write my test using pytest and to be able to run them (individually) in IntelliJ. I have pytest installed, along with (obviously) Python plugin for the IDE. My test file (tests/test_main.py) looks like that: from app.main import sum_numbers def test_sum_numbers(): assert sum_numbers(1, 2) == 3 assert sum_numb...
Here what you need to do: 1) Remove all the existing run configurations for your test file. 2) Make sure that Preferences | Tools | Python Integrated Tools | Default rest runner is set to pytest. After that, you should see the run icon next to your test functions and right-clicking the test file should suggest running ...
13
27
60,741,970
2020-3-18
https://stackoverflow.com/questions/60741970/optional-cli-arguments-with-python-click-library-option
I'm having a conundrum with the Python Click library when parsing some CLI options. I would like an option to act as a flag by itself, but optionally accept string values. E.g.: $ myscript ⇒ option = False $ myscript -o ⇒ option = True $ myscript -o foobar ⇒ option = Foobar Additionally, I would like the option to be...
One way that I have managed to achieve this behaviour was by actually using arguments as below. I'll post this as a workaround, while I try to see if it could be done with an option, and I'll update my post accordingly @click.command(context_settings={"ignore_unknown_options": True}) @click.argument("options", nargs=-1...
10
5
60,814,081
2020-3-23
https://stackoverflow.com/questions/60814081/how-to-convert-a-rgb-image-into-a-cmyk
I want to convert a RGB image into CMYK. This is my code; the first problem is when I divide each pixel by 255, the value closes to zero, so the resulting image is approximately black! The second problem is that I don't know how to convert the one-channel resultant image to 4 channels. Of course, I'm not sure the made ...
You can let PIL/Pillow do it for you like this: from PIL import Image # Open image, convert to CMYK and save as TIF Image.open('drtrump.jpg').convert('CMYK').save('result.tif') If I use IPython, I can time loading, converting and saving that at 13ms in toto like this: %timeit Image.open('drtrump.jpg').convert('CMYK')....
9
13
60,805,253
2020-3-22
https://stackoverflow.com/questions/60805253/matplotlib-turning-axes-off-and-setting-facecolor-at-the-same-time-not-possible
can someone explain why this simple code wont execute the facecolor command while setting the axis off? fig = plt.figure(1) ax = fig.add_subplot(211, facecolor=(0,0,0), aspect='equal') ax.scatter(np.random.random(10000), np.random.random(10000), c="gray", s=0.25) ax.axes.set_axis_off() Thanks in advance!
The background patch is part of the axes. So if the axes is turned off, so will the background patch. Some options: Re-add the background patch ax = fig.add_subplot(211, facecolor=(0,0,0), aspect='equal') ax.set_axis_off() ax.add_artist(ax.patch) ax.patch.set_zorder(-1) Create new patch ax = fig.add_subplot(211, face...
7
11
60,811,307
2020-3-23
https://stackoverflow.com/questions/60811307/check-if-all-sides-of-a-multidimensional-numpy-array-are-arrays-of-zeros
An n-dimensional array has 2n sides (a 1-dimensional array has 2 endpoints; a 2-dimensional array has 4 sides or edges; a 3-dimensional array has 6 2-dimensional faces; a 4-dimensional array has 8 sides; etc.). This is analogous to what happens with abstract n-dimensional cubes. I want to check if all sides of an n-dim...
Here's how you can do it: assert(all(np.all(np.take(x, index, axis=axis) == 0) for axis in range(x.ndim) for index in (0, -1))) np.take does the same thing as "fancy" indexing.
15
10
60,810,463
2020-3-23
https://stackoverflow.com/questions/60810463/is-this-a-correct-way-to-create-a-read-only-view-of-a-numpy-array
I would like to create a read-only reference to a NumPy array. Is this a correct way to make b a read-only reference to a (a is any NumPy array)? def get_readonly_view(a): b = a.view() b.flags.writeable = False return b Specifically, I would like to ensure the above does not 'copy' the contents of a? (I tried testing ...
Your approach seems to be the suggested way of creating a read-only view. In particular, arr.view() (which can also be written as a slicing arr[:]) will create a reference to arr, while modifying the writeable flag is the suggested way of making a NumPy array read-only. The documentation also provides some additional i...
10
9
60,792,029
2020-3-21
https://stackoverflow.com/questions/60792029/modulenotfounderror-in-docker
I have imported my entire project into docker, and I am getting a ModuleNotFoundError from one of the modules I have created. FROM python:3.8 WORKDIR /workspace/ COPY . /workspace/ RUN pip install pipenv RUN pipenv install --deploy --ignore-pipfile #EXPOSE 8000 #CMD ["pipenv", "run", "python", "/workspace/bin/web.py...
So I finally fixed the issue. For those who may be wondering how was it that I fixed it. You need to define a PYTHONPATH environment variable either in the Dockerfile or docker-compose.yml.
8
21
60,792,121
2020-3-21
https://stackoverflow.com/questions/60792121/filling-area-under-the-curve-with-matplotlib
I have a pandas series, and this is the graph: I want to fill the area under the curve. The problem is that calling plt.fill(y) outputs: As seen in other answers, this is because we need to send a polygon to the function, so we have to add a (0,0) point. (And a (lastPoint, 0), but in this case it's not necessary). ...
There is such a function: matplotlib.pyplot.fill_between() import matplotlib.pyplot as plt plt.plot(y, c='red') plt.fill_between(y.index, y, color='blue', alpha=0.3)
7
11
60,779,234
2020-3-20
https://stackoverflow.com/questions/60779234/how-to-add-a-default-array-of-values-to-arrayfield
Is it possible to add a default value to ArrayField? I tried to do this for email field, but this did not work: constants.py: ORDER_STATUS_CHANGED = 'order_status_changed' NEW_SIGNAL = 'new_signal' NOTIFICATION_SOURCE = ( (ORDER_STATUS_CHANGED, 'Order Status Changed'), (NEW_SIGNAL, 'New Signal'), ) models.py: from not...
The default property on an ArrayField should be a callable. You can read more about that here: https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/. What you are getting by placing directly there list(dict(constants.NOTIFICATION_SOURCE).keys()) is just a warning so it should still add the defaults to the ...
13
21
60,761,175
2020-3-19
https://stackoverflow.com/questions/60761175/how-to-solve-importerror-dlopen-symbol-not-found-expected-in-flat-name
Can anyone help me solve this issue? ImportError: dlopen(/Users/......./venv/lib/python3.6/site-packages/recordclass/mutabletuple.cpython-36m-darwin.so, 2): Symbol not found: __PyEval_GetBuiltinId Referenced from: /Users/......./venv/lib/python3.6/site-packages/recordclass/mutabletuple.cpython-36m-darwin.so Expected in...
I couldn't quite figure out what the issue was but I'm assuming __PyEval_GetBuiltinId was broken/uninstalled. So all I did to fix this was pip uninstall recordclass and then pip install --no-cache-dir recordclass and it seemed to have worked
16
14
60,796,555
2020-3-22
https://stackoverflow.com/questions/60796555/certain-members-of-a-torch-module-arent-moved-to-gpu-even-if-model-todevice-i
An mwe is as follows: import torch import torch.nn as nn class model(nn.Module): def __init__(self): super(model,self).__init__() self.mat = torch.randn(2,2) def forward(self,x): print('self.mat.device is',self.mat.device) x = torch.mv(self.mat,x) return x device = torch.device('cuda' if torch.cuda.is_available() else ...
pytorch apply Module's methods such as .cpu(), .cuda() and .to() only to sub-modules, parameters and buffers, but NOT to regular class members. pytorch has no way of knowing that self.mat, in your case, is an actual tensor that should be moved around. Once you decide if your mat should be a parameter or a buffer, simpl...
7
8
60,785,825
2020-3-21
https://stackoverflow.com/questions/60785825/vscode-how-to-pass-pytest-command-line-arguments-running-in-debugger
I've written tests to be run by pytest in a vscode project. The configuration file .vscode/settings.json allow passing additional command line parameters to pytest using: "python.testing.pytestArgs": [ "test/", "--exitfirst", "--verbose" ], How can I also pass custom script arguments to the test script itself? like i...
After much experimentation I finally found how to do it. What I needed was to pass user name and password to my script in order to allow the code to log into a test server. My test looked like this: my_module_test.py import pytest import my_module def login_test(username, password): instance = my_module.Login(username,...
32
20
60,786,220
2020-3-21
https://stackoverflow.com/questions/60786220/attributeerror-gridsearchcv-object-has-no-attribute-best-params
Grid search is a way to find the best parameters for any model out of the combinations we specify. I have formed a grid search on my model in the below manner and wish to find best parameters identified using this gridsearch. from sklearn.model_selection import GridSearchCV # Create the parameter grid based on the resu...
You cannot get best parameters without fitting the data. Fit the data grid_search.fit(X_train, y_train) Now find the best parameters. grid_search.best_params_ grid_search.best_params_ will work after fitting on X_train and y_train.
24
38
60,780,831
2020-3-20
https://stackoverflow.com/questions/60780831/python-how-to-cut-out-an-area-with-specific-color-from-image-opencv-numpy
so I've been trying to code a Python script, which takes an image as input and then cuts out a rectangle with a specific background color. However, what causes a problem for my coding skills, is that the rectangle is not on a fixed position in every image (the position will be random). I do not really understand how t...
Updated Answer I have updated my answer to cope with specks of noisy outlier pixels of the same colour as the yellow box. This works by running a 3x3 median filter over the image first to remove the spots: #!/usr/bin/env python3 import numpy as np from PIL import Image, ImageFilter # Open image and make into Numpy arra...
12
9
60,763,529
2020-3-19
https://stackoverflow.com/questions/60763529/unable-to-import-pandas-pandas-libs-window-aggregations
I've lost a couple of hours trying to solve this so I guess it's time to ask someone/somehwere. I (think) I have uninstalled everything related to python and than installed again. I just installed python most recent version and used pip to install pandas. I also try to install it with anaconda but the error persists. I...
I finally ended up trying a slightly older version of pandas to resolve this exact error. The default install was 1.0.3, so I backed up a couple of release points: pip uninstall pandas pip install pandas==1.0.1 Then I could import pandas without error
10
14
60,783,788
2020-3-21
https://stackoverflow.com/questions/60783788/virtualenv-virtualenvwrapper-virtualenv-error-unrecognized-arguments-no-sit
I am trying to upgrade python from 3.6 to 3.8. I was successfully using virtualenv/wrapper successfully (although only one environment and no bells, whistles, or hooks), but the upgrade has not gone smoothly. I deleted everything and tried to start again. I am trying to make a new environment with mkvirtualenv test, an...
--no-site-packages is the default for virtualenv (and has been for like 5 years?) you can remove export VIRTUALENVWRAPPER_VIRTUALENV_ARGS='--no-site-packages' from your .bashrc it appears in virtualenv>=20 that this option was removed
23
36
60,780,433
2020-3-20
https://stackoverflow.com/questions/60780433/how-can-i-pass-a-list-of-columns-to-select-in-pyspark-dataframe
I have list column names. columns = ['home','house','office','work'] and I would like to pass that list values as columns name in "select" dataframe. I have tried it... df_tables_full = df_tables_full.select('time_event','kind','schema','table',columns) but I have received error below.. TypeError: Invalid argument, n...
Use * before columns to unnest columns list and use in .select. columns = ['home','house','office','work'] #select the list of columns df_tables_full.select('time_event','kind','schema','table',*columns).show() df_tables_full = df_tables_full.select('time_event','kind','schema','table',*columns)
16
36
60,766,714
2020-3-19
https://stackoverflow.com/questions/60766714/pyserial-flush-vs-reset-input-buffer-reset-output-buffer
I am trying to use pySerial==3.4, and find the documentation on serial.Serial.flush() rather lacking: Flush of file like objects. In this case, wait until all data is written. Source Questions What is a "file like object"? What is being flushed? When would one use flush as opposed to just individually resetting the...
It looks like this: What is a "file like object"? What is exactly a file-like object in Python? file-like objects are mainly StringIO objects, connected sockets and well.. actual file objects. If everything goes fine, urllib.urlopen() also returns a file-like objekt supporting the necessary methods. file-like object A...
7
5
60,761,243
2020-3-19
https://stackoverflow.com/questions/60761243/how-to-specify-several-marks-for-the-pytest-command
Reading http://doc.pytest.org/en/latest/example/markers.html I see the example of including or excluding certain python tests based on a mark. Including: pytest -v -m webtest Excluding: pytest -v -m "not webtest" What if I would like to specify several marks for both include and exclude?
Use and/or to combine multiple markers, same as for -k selector. Example test suite: import pytest @pytest.mark.foo def test_spam(): assert True @pytest.mark.foo def test_spam2(): assert True @pytest.mark.bar def test_eggs(): assert True @pytest.mark.foo @pytest.mark.bar def test_eggs2(): assert True def test_bacon(): ...
22
31
60,758,625
2020-3-19
https://stackoverflow.com/questions/60758625/sort-pandas-dataframe-by-sum-of-columns
I have a dataframe that looks like this Australia Austria United Kingdom Vietnam date 2020-01-30 9 0 1 2 2020-01-31 9 9 4 2 I would like to crate a new dataframe that inclues countries that have sum of their column > 4 and I do it df1 = df[[i for i in df.columns if int(df[i].sum()) > 4]] this gives me Australia Au...
IIUC, you can do: s = df.sum() df[s.sort_values(ascending=False).index[:2]] Output: Australia Austria date 2020-01-30 9 0 2020-01-31 9 9
21
21
60,751,868
2020-3-19
https://stackoverflow.com/questions/60751868/how-to-check-whether-a-bucket-exists-in-gcs-with-python
Code: from google.cloud import storage client = storage.Client() bucket = ['symbol_wise_nse', 'symbol_wise_final'] for i in bucket: if client.get_bucket(i).exists(): BUCKET = client.get_bucket(i) if the bucket exists i want to do client.get_bucket. How to check whether the bucket exists or not?
There is no method to check if the bucket exists or not, however you will get an error if you try to access a non existent bucket. I would recommend you to either list the buckets in the project with storage_client.list_buckets() and then use the response to confirm if the bucket exists in your code, or if you wish to ...
10
2
60,751,819
2020-3-19
https://stackoverflow.com/questions/60751819/valueerror-2-columns-passed-passed-data-had-1-columns
I have a list with name of organizations like this: name = ['ALPHABET INC', 'AMAZON COM INC', 'APPLE INC',....] and another list of cu values like this: cu = ['02079K305', '023135106', '037833100',....] When i'm trying to convert it to dataframe it's giving me error message saying, "ValueError: 2 columns passed, pa...
I think simpliest is create dictionaries: df = pd.DataFrame({'name of issuer': name, 'cusip':cu}) Your solution is possible with zip, in last version of pandas should be omit list: df = pd.DataFrame(list(zip(name, cu)), columns=['name of issuer', 'cusip']) print (df) name of issuer cusip 0 ALPHABET INC 02079K305 1 A...
7
12
60,749,032
2020-3-18
https://stackoverflow.com/questions/60749032/how-to-keep-a-docker-container-run-for-ever
I created a Dockerfile which sets up python environment so that when people run the image in their host, they can run my python file without installing multiple python packages themselves. The problem is after I build and run the image, the container stopped immediately (because it completed). How can I keep the cont...
From HOW TO KEEP DOCKER CONTAINERS RUNNING, we can know that docker containers, when run in detached mode (the most common -d option), are designed to shut down immediately after the initial entrypoint command (program that should be run when container is built from image) is no longer running in the foreground. So to ...
8
13
60,749,802
2020-3-19
https://stackoverflow.com/questions/60749802/python-with-pandas-file-size-44546-not-512-multiple-of-sector-size-512
After read excel file with pandas, gets the follow warning: key code: pd_obj = pd.read_excel("flie.xls", dtype=str, usecols=usecols, skiprows=3) for idx, row in pd_obj.iterrows(): json_tmpl = copy.deepcopy(self.details) json_tmpl["nameInBank"] = row["nameInBank"] json_tmpl["totalBala"] = row["totalBala"].replace(",", ...
This appears to be a normal warning from the underlying XLRD library, and it seems safe to ignore. A pandas issue (#16620) was opened and closed without a conclusive resolution. However, the discussion did provide an alternative that would allow you to suppress the warnings: from os import devnull import pandas as pd i...
7
14