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
64,520,995
2020-10-25
https://stackoverflow.com/questions/64520995/odoo-14-add-a-section-functionality-in-tree-view
I need add a section functionality like sales > quotation view has, in one of my tree views. . Code of my view is something like this: <record id="view_qualification_form_inh" model="ir.ui.view"> <field name="name">hr.applicant.form</field> <field name="model">hr.applicant</field> <field name="inherit_id" ref="hr_recru...
You need to set the qualification_lines widget attribute to section_and_note_one2many and define the display_type in the applicant qualification model instead of the applicant model, it will be used to check if you need to add a section (help: Technical field for UX purpose). In the following example the section text w...
5
7
64,519,479
2020-10-25
https://stackoverflow.com/questions/64519479/modulenotfounderror-no-module-named-sksurv-in-python
I am trying to run survival analysis in python (pycharm) in linux, here is a part of the code import numpy as np import matplotlib.pyplot as plt #matplotlib inline import pandas as pd from sklearn.impute import SimpleImputer from sklearn.pipeline import make_pipeline from sklearn.model_selection import train_test_split...
The required dependencies for scikit-survival, cvxpy cvxopt joblib numexpr numpy 1.12 or later osqp pandas 0.21 or later scikit-learn 0.22 scipy 1.0 or later ...will be automatically installed by pip when you run: pip install scikit-survival However, one module in particular, osqp, has CMake as one of its d...
6
3
64,484,905
2020-10-22
https://stackoverflow.com/questions/64484905/getting-celery-task-results-using-rpc-backend
I'm struggling with getting results from the Celery task. My app entry point looks like this: from app import create_app,celery celery.conf.task_default_queue = 'order_master' order_app = create_app('../config.order_master.py') Now, before I start the application I start the RabbitMQ and ensure it has no queues: root@...
According to Celery documentation: RPC Result Backend (RabbitMQ/QPid) The RPC result backend (rpc://) is special as it doesn’t actually store the states, but rather sends them as messages. This is an important difference as it means that a result can only be retrieved once, and only by the client that initiated the ta...
7
15
64,550,426
2020-10-27
https://stackoverflow.com/questions/64550426/using-progress-bars-of-pip
I want use progress bars in my python code. I know there are many libraries for that but I want to use the progress bars used by pip [the package manager]. Please tell if there is a way to do this.
The progress package available on pypi is used by pip. It can be imported by including the following line in your python file: from pip._vendor import progress Usage is available on https://pypi.org/project/progress/
13
11
64,534,844
2020-10-26
https://stackoverflow.com/questions/64534844/python-asyncio-aiohttp-timeout
Word of notice: This is my first approach with asyncio, so I might have done something really stupid. Scenario is as follows: I need to "http-ping" a humongous list of urls to check if they respond 200 or any other value. I get timeouts for each and every request, though tools like gobuster report 200,403, etc. My code...
Actually, I ended up finding an open issue in aio-libs/aiohttp: https://github.com/aio-libs/aiohttp/issues/3203 This way, they suggest a workaround that achieves my needs: session_timeout = aiohttp.ClientTimeout(total=None,sock_connect=timeout_seconds,sock_read=timeout_seconds) async with aiohttp.ClientSession(timeout=...
12
25
64,563,105
2020-10-27
https://stackoverflow.com/questions/64563105/aws-lambda-read-csv-and-convert-to-pandas-dataframe
I have got a simple Lambda code to read the csv file from S3 Bucket. All is working fine however I tried to get the csv data to pandas data frame and the error comes up string indices must be integers My code is bog-standard but I just need to use the csv as a data frame for further manipulation. The hashed line is the...
I believe that your problem is likely tied to this line - df=pd.DataFrame( list(reader(data))) in your function. The answer below should allow you to read the csv file into the pandas dataframe for processes. import boto3 import pandas as pd from io import BytesIO s3_client = boto3.client('s3') def lambda_handler(event...
8
11
64,497,615
2020-10-23
https://stackoverflow.com/questions/64497615/how-to-add-a-custom-decorator-to-a-fastapi-route
I want to add an auth_required decorator to my endpoints. (Please consider that this question is about decorators, not middleware) So a simple decorator looks like this: def auth_required(func): def wrapper(*args, **kwargs): if user_ctx.get() is None: raise HTTPException(...) return func(*args, **kwargs) return wrapper...
How can I add any decorators to FastAPI endpoints? As you said, you need to use @functools.wraps(...)--(PyDoc) decorator as, from functools import wraps from fastapi import FastAPI from pydantic import BaseModel class SampleModel(BaseModel): name: str age: int app = FastAPI() def auth_required(func): @wraps(func) asy...
67
102
64,502,578
2020-10-23
https://stackoverflow.com/questions/64502578/mutlithreading-with-raw-pymysql-for-celery
In the project I am currently working on, I am not allowed to use an ORM so I made my own It works great but I am having problems with Celery and it's concurrency. For a while, I had it set to 1 (using --concurrency=1) but I'm adding new tasks which take more time to process than they need to be run with celery beat, w...
PyMSQL does not allow threads to share the same connection (the module can be shared, but threads cannot share a connection). Your Model class is reusing the same connection everywhere. So, when different workers call on the models to do queries, they are using the same connection object, causing conflicts. Make sure y...
6
1
64,497,080
2020-10-23
https://stackoverflow.com/questions/64497080/how-to-speed-up-the-performance-of-array-masking-from-the-results-of-numpy-searc
I want to generate a mask from the results of numpy.searchsorted(): import numpy as np # generate test examples x = np.random.rand(1000000) y = np.random.rand(200) # sort x idx = np.argsort(x) sorted_x = np.take_along_axis(x, idx, axis=-1) # searchsort y in x pt = np.searchsorted(sorted_x, y) pt is an array. Then I wa...
Approach #1 Going by the new-found information picked up off OP's comments that states only y is changing in real-time, we can pre-process lots of stuffs around x and hence do much better. We will create a hashing array that will store stepped masks. For the part that involves y, we will simply index into the hashing a...
7
3
64,561,637
2020-10-27
https://stackoverflow.com/questions/64561637/cant-import-module-situated-in-parent-folder-from-jupyter-lab-notebook-and-path
Here's my situation. I have some jupyter notebooks inside some folder and I would like to share some code between those notebooks trough a library I made. The folder structure is the following: 1.FirstFolder/ notebookA.ipynb 2.SecondFolder/ notebookB.ipynb mylib/ __init__.py otherfiles.py I tried putting the following...
You have added the contents of os.path.join(Path.cwd().parent,'mylib') to your path, this means python will look inside this dir for the module you are importing. mylib is not located in this dir, but rather the parent dir. Also Path.cwd().parent returns a pathlib.PosixPath object. Convert this to a string to use it wi...
7
5
64,464,111
2020-10-21
https://stackoverflow.com/questions/64464111/sendgrid-authenticate-with-api-keys
I got the following mail from SentGrid, We are emailing to inform you of an upcoming requirement to update your authentication method with Twilio SendGrid to API keys exclusively by December 9th, 2020 in order to ensure uninterrupted service and improve the security of your account. Our records show that you have used...
Yes, once they force two factor authentication (2FA), your application will not be able to do basic authentication by just using username/email & password. So, you need to start using API keys. Migration is simple: Login to sendgrid account Goto https://app.sendgrid.com/settings/api_keys "Generate API Key" - generate ...
7
12
64,483,856
2020-10-22
https://stackoverflow.com/questions/64483856/use-pre-trained-nodes-from-past-runs-pytorch-biggraph
After struggling with this amazing facebookresearch / PyTorch-BigGraph project, and its impossible API, I managed to get a grip on how to run it (thanks to stand alone simple example) My system restrictions do not allow me to train the dense (embedding) representation of all edges, and I need from time to time to uploa...
Since torchbiggraph is file based, you can modify the saved files to load pre-trained embeddings and add new nodes. I wrote a function to achieve this import json def pretrained_and_new_nodes(pretrained_nodes,new_nodes,entity_name,data_dir,embeddings_path): """ pretrained_nodes: A dictionary of nodes and their embeddin...
8
4
64,468,858
2020-10-21
https://stackoverflow.com/questions/64468858/trouble-updating-to-anaconda-navigator-1-10-0-macos
My Anaconda Navigator (v1.9.12) has been prompting me to upgrade to 1.10.0. Only problem is, when I click "yes" on the update prompt (which should close the navigator and update it), nothing happens. No problem, I thought. I ran conda update anaconda-navigator in the terminal. To no avail (and yes, I read the doc onl...
I am having completely the same issue (same Navigator version on macOS). I think I have spent several hours of all possible solution and nothing helped. The only solution that worked was to uninstall and install again. The environment setup remains the same so there is nothing to lose (but still it is strange thought) ...
26
3
64,484,166
2020-10-22
https://stackoverflow.com/questions/64484166/exclude-folder-from-pycharms-duplicate-check
Q: How do I exclude a folder from pycharm's duplicate check? Minimal Example: Say my pycharm project folder structure looks like this: project/main.py project/.backup/main_copy.py How do I tell pycharm not to warn me that main.py and main_copy.py contain duplicate code?
Try to mark .backup as excluded via right-click on it -> Mark Directory as.
13
21
64,492,922
2020-10-23
https://stackoverflow.com/questions/64492922/pytube-only-works-periodically-keyerror-assets
Five out of ten times Pytube will send me this error when attempting to run my small testing script. Here's the script: import pytube import urllib.request from pytube import YouTube yt = YouTube('https://www.youtube.com/watch?v=3NCyD3XoJgM') print('Youtube video title is: ' + yt.title + '! Downloading now!') Here's w...
For now fixed 100% with this: https://github.com/nficano/pytube/pull/767#issuecomment-716184994 With anyone else getting this error or issue, run this command in a terminal or cmd: python -m pip install git+https://github.com/nficano/pytube An update to pytubeX that hasn't been released with the pip installation yet. T...
5
11
64,530,316
2020-10-26
https://stackoverflow.com/questions/64530316/euclidean-distance-of-delaney-triangulation-scipy
The spatial package imported from Scipy can measure the Euclidean distance between specified points. Is it possible to return the same measurement by using the Delaunay package? Using the df below, the average distance between all points is measured grouped by Time. However, I'm hoping to use Delaunay triangulation to ...
You can try this function from itertools import combinations import numpy as np def edges_with_no_replacement(points): # get the unique coordinates points = np.unique(points.loc[:,['A_X','A_Y']].values,return_index=False,axis=0) if len(points) <= 1: return 0 # for two points, no triangle # I think return the distance b...
5
6
64,503,039
2020-10-23
https://stackoverflow.com/questions/64503039/how-do-i-call-pyspark-code-with-whl-file
I have used poetry to create a wheel file. I am running following spark-submit command , but it is not working. I think I am missing something spark-submit --py-files /path/to/wheel Please note that I have referred to below as well, but did not get much details as I am new to Python. how to pass python package to spar...
Wheel file can be executed as a part of below spark-submit command spark-submit --deploy-mode cluster --py-files /path/to/wheel main_file.py
7
3
64,464,861
2020-10-21
https://stackoverflow.com/questions/64464861/how-can-i-convert-a-two-column-array-to-a-matrix-with-counts-of-occurences
I have the following numpy array: import numpy as np pair_array = np.array([(205, 254), (205, 382), (254, 382), (18, 69), (205, 382), (31, 183), (31, 267), (31, 382), (183, 267), (183, 382)]) print(pair_array) #[[205 254] # [205 382] # [254 382] # [ 18 69] # [205 382] # [ 31 183] # [ 31 267] # [ 31 382] # [183 267] # [...
One way could be to build a graph using NetworkX and obtain the adjacency matrix directly as a dataframe with nx.to_pandas_adjacency. To account for the co-occurrences of the edges in the graph, we can create a nx.MultiGraph, which allows for multiple edges connecting the same pair of nodes: import networkx as nx G = n...
31
19
64,556,120
2020-10-27
https://stackoverflow.com/questions/64556120/early-stopping-with-multiple-conditions
I am doing multi-class classification for a recommender system (item recommendations), and I'm currently training my network using sparse_categorical_crossentropy loss. Therefore, it is reasonable to perform EarlyStopping by monitoring my validation loss, val_loss as such: tf.keras.callbacks.EarlyStopping(monitor='val_...
With guidance from Gerry P above I managed to create my own custom EarlyStopping callback, and thought I post it here in case anyone else are looking to implement something similar. If both the validation loss and the mean average precision at 10 does not improve for patience number of epochs, early stopping is perform...
13
10
64,556,874
2020-10-27
https://stackoverflow.com/questions/64556874/how-can-i-debug-python-console-script-command-line-apps-with-the-vscode-debugger
I've a Python package package_name which provides a command line application command-line-app-name as console_script: setup.py: setup( ... entry_points={"console_scripts": ["command-line-app-name=package_name.cli:main"]}, ... ) The virtualenv is located in <project>/.venv and managed with pipenv. pipenv managed venvs ...
console_scripts cannot be debugged out-of-the-box. The solution is to call the entry point function directly instead ("program": "${workspaceRoot}/package_name/cli.py",). This requires to add the if __name__ == '__main__': idiom in the corresponding module (here: cli.py). In my case the command line argument parser use...
7
8
64,554,908
2020-10-27
https://stackoverflow.com/questions/64554908/how-to-count-number-of-elements-in-a-row-greater-than-zero
I need to count the number of values in each row that are greater than zero and store them in a new column The df bellow: team goals goals_against games_in_domestic_league 0 juventus 1 0 0 1 barcelona 0 1 1 2 santos 2 1 2 Should become: team goals goals_against games_in_domestic_league total 0 juventus 1 0 0 1 1 bar...
First idea is select numeric columns, test if greater like 0 and count Trues by sum: df['total'] = df.select_dtypes(np.number).gt(0).sum(axis=1) If want specify columns by list: cols = ['goals','goals_against','games_in_domestic_league'] df['total'] = df[cols].gt(0).sum(axis=1)
5
5
64,543,449
2020-10-26
https://stackoverflow.com/questions/64543449/update-during-resize-in-pygame
I'm developing a grid based game in pygame, and want the window to be resizable. I accomplish this with the following init code: pygame.display.set_mode((740, 440), pygame.RESIZABLE) As well as the following in my event handler: elif event.type == pygame.VIDEORESIZE: game.screen = pygame.display.set_mode((event.w, eve...
If you run into this kind of problem, it's always worth to google it using SDL instead of pygame, since pygame is a pretty low-level SDL wrapper. So that's not a problem of pygame itself, but rather how sdl and your window manager interact, e.g. see this SDL bug report. Nonetheless, if you really need to update the win...
8
7
64,504,406
2020-10-23
https://stackoverflow.com/questions/64504406/how-to-hot-reload-grpc-server-in-python
I'm developing some python microservices with grpc and i'm using docker for the cassandra database and the microservices. Is there a way to setup reload on change within docker-compose? I'm guessing that first I need the code mounted as a volume but I don't see a way to reload on GRPC server like for example flask does...
We use watchdog[watchmedo] with our grpc services and Docker. Install watchdog or add to your requirements.txt file python -m pip install watchdog[watchmedo] Then in your docker-compose.yml add watchmedo auto-restart --recursive --pattern="*.py" --directory="/usr/src/app/" python -- -m app to your container where --dir...
8
8
64,533,731
2020-10-26
https://stackoverflow.com/questions/64533731/how-is-floor-division-not-giving-result-according-to-the-documented-rule
>>> print (12//0.2) 59.0 >>> print(floor(12/0.2)) 60 Why floor division is not working according to the rule in this case? p.s. Here Python is treating 0.2 as 0.20000000001 in the floor division case So (12/0.2000000001) is resulting in 59.999999... And floor(59.999999999) outputting 59 But don't know why python is tr...
The reason why 12 / 0.2 results in 60.0, is not because 0.2 is treated differently, but because the error in the floating point division cancels the error in the representation of 0.2. The float always has the same value (greater than decimal 0.2), but depending on the operations those errors will either accumulate or ...
9
9
64,546,583
2020-10-26
https://stackoverflow.com/questions/64546583/plot-multiple-arrows-between-scatter-points
I'm trying to plot multiple arrows between two sets of scatter points. Plotting a line is easy enough with ax.plot. But I'm trying to implement an arrow instead of a line. The arrows don't appear to be aligning between the points. So if the line plot is initialised below, it works fine. But the quiver plot does not plo...
According to the documentation, see scale_units option, you need: angles='xy', scale_units='xy', scale=1 in quiver: AB = ax.scatter(x1, y1, c = 'blue', marker = 'o', s = 10, zorder = 3) CD = ax.scatter(x2, y2, c = 'red', marker = 'o', s = 10, zorder = 2) ax.quiver(x1, y1, (x2-x1), (y2-y1), angles='xy', scale_units='xy'...
5
6
64,545,132
2020-10-26
https://stackoverflow.com/questions/64545132/will-run-in-executor-ever-block
suppose if I have a web server like this: from fastapi import FastAPI import uvicorn import asyncio app = FastAPI() def blocking_function(): import time time.sleep(5) return 42 @app.get("/") async def root(): loop = asyncio.get_running_loop() result = await loop.run_in_executor(None, blocking_function) return result @a...
Both time.sleep (as explained in this question) and the win32com library (according to this mailing list post) release the GIL when they are called, so they will not prevent other threads from making progress while they are blocking. To answer the "high-level" question - "can run_in_executor ever (directly or indirectl...
6
6
64,540,868
2020-10-26
https://stackoverflow.com/questions/64540868/faster-for-loops-with-arrays-in-python
N, M = 1000, 4000000 a = np.random.uniform(0, 1, (N, M)) k = np.random.randint(0, N, (N, M)) out = np.zeros((N, M)) for i in range(N): for j in range(M): out[k[i, j], j] += a[i, j] I work with very long for-loops; %%timeit on above with pass replacing the operation yields 1min 19s ± 663 ms per loop (mean ± std. dev. o...
This is basically the idea behind Numba. Not as fast as C, but it can get close... It uses a jit compiler to compile python code to machine and it's compatible with most Numpy functions. (In the docs you find all the details) import numpy as np from numba import njit @njit def f(N, M): a = np.random.uniform(0, 1, (N, M...
7
5
64,527,464
2020-10-25
https://stackoverflow.com/questions/64527464/clickable-link-inside-message-discord-py
I would like my bot to send message into chat like this: await ctx.send("This country is not supported, you can ask me to add it here") But to make "here" into clickable link, In HTML I would do it like this, right? <a href="https://www.youtube.com/" > This country is not supported, you can ask me to add it here </a> ...
As the other answer explained, you can't add hyperlinks in normal messages, but you can in Embeds. I don't see why you wouldn't want to use an Embed for an error message, especially considering it adds more functionality, so you should consider using that. embed = discord.Embed() embed.description = "This country is no...
6
11
64,523,533
2020-10-25
https://stackoverflow.com/questions/64523533/environment-properties-are-not-passed-to-application-in-elastic-beanstalk
When deploying my Django project, database settings are not configured because 'RDS_HOSTNAME' in os.environ returns false. In fact no environment properties are available at the time of deployment. All these properties are available after the deployment. Running /opt/elasticbeanstalk/bin/get-config environment returns ...
Seems like this is a serious bug and AWS doesn't care about it. There are few ways I came up with to make this work but all of them require logging into the EB environment and do some manual work. Solution 1 As suggested in comment by hephalump Create an AWS secret manager Check IAM instance profile in EB's environme...
6
8
64,524,963
2020-10-25
https://stackoverflow.com/questions/64524963/efficient-elementwise-argmin-of-matrix-vector-difference
Suppose an array a.shape == (N, M) and a vector v.shape == (N,). The goal is to compute argmin of abs of v subtracted from every element of a - that is, out = np.zeros(N, M) for i in range(N): for j in range(M): out[i, j] = np.argmin(np.abs(a[i, j] - v)) I have a vectorized implementation via np.matlib.repmat, and it'...
Inspired by this post, we can leverage np.searchsorted - def find_closest(a, v): sidx = v.argsort() v_s = v[sidx] idx = np.searchsorted(v_s, a) idx[idx==len(v)] = len(v)-1 idx0 = (idx-1).clip(min=0) m = np.abs(a-v_s[idx]) >= np.abs(v_s[idx0]-a) m[idx==0] = 0 idx[m] -= 1 out = sidx[idx] return out Some more perf. boost...
9
4
64,525,237
2020-10-25
https://stackoverflow.com/questions/64525237/how-to-calculate-the-size-of-blocks-of-values-in-a-list
I have a list like this: list_1 = [0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1] How can I calculate the size of blocks of values of 1 and 0 in this list? The resulting list will look like : list_2 = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 1, 1]
Try with cumsum with diff then transform count s = pd.Series(list_1) s.groupby(s.diff().ne(0).cumsum()).transform('count') Out[91]: 0 1 1 2 2 2 3 3 4 3 5 3 6 4 7 4 8 4 9 4 10 1 11 1 dtype: int64
7
6
64,455,605
2020-10-21
https://stackoverflow.com/questions/64455605/show-all-colums-of-a-pandas-dataframe-in-describe
I am stuck here, but I it's a two part question. Looking at the output of .describe(include = 'all'), not all columns are showing; how do I get all columns to show? This is a common problem that I have all of the time with Spyder, how to have all columns to show in Console. Any help is appreciated. import matplotlib.py...
Solution You could use either of the following methods: Method-1: source pd.options.display.max_columns = None Method-2: source pd.set_option('display.max_columns', None) # to reset this pd.reset_option('display.max_columns') Method-3: source # assuming df is your dataframe pd.set_option('display.max_columns', df.col...
7
14
64,480,047
2020-10-22
https://stackoverflow.com/questions/64480047/how-to-use-intrinsic-functions-sub-method-in-aws-cdk
I want to use this resource below for my cdk app, I using Python for CDK: 'arn:aws:s3:::${LoggingBucket}/AWSLogs/${AWSAccoutID}/*' Therefore I need to substitute the value of LoggingBucket and AWSAccountID. Here is what I tried: bucket = s3.Bucket(self, "my-bucket", bucket_name = 'my-bucket') core.Fn.sub('arn:aws:s3::...
Since you are using Python (or other programming language) there is no need to use the instrinsic functions that Cloudformation provides. I suggest a more elegant and easy way to format the arn: arn= f'arn:aws:s3:::{bucket.bucket_name}/AWSLogs/{core.Environment.account}/*'
5
3
64,501,193
2020-10-23
https://stackoverflow.com/questions/64501193/fastapi-how-to-use-httpexception-in-responses
The documentation suggests raising an HTTPException with client errors, which is great. But how can I show those specific errors in the documentation following HTTPException's model? Meaning a dict with the "detail" key. The following does not work because HTTPException is not a Pydantic model. @app.get( '/test', respo...
Yes it is not a valid Pydantic type however since you can create your own models, it is easy to create a Model for it. from fastapi import FastAPI from fastapi.exceptions import HTTPException from pydantic import BaseModel class Dummy(BaseModel): name: str class HTTPError(BaseModel): detail: str class Config: schema_ex...
22
30
64,497,319
2020-10-23
https://stackoverflow.com/questions/64497319/python-discord-py-error-could-not-build-wheels-for-multidict-yarl-which-use
trying to download discord.py using pip install, gave me the error message in the title. I installed using cmd and the commands py -m pip install -U discord, the cmd was also run in admin. tried using pip, pip3, and pip3.9, all of which didnt work. I tried uninstalling/reinstalling/upgrading (in that order) the said li...
I also had the exact same issue today, since i downloaded node.js and it updated my python 8 to python 9 and i had to reinstall all of my moduels including dpy. The solution is to follow what it says error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.m...
23
6
64,503,929
2020-10-23
https://stackoverflow.com/questions/64503929/convert-x-and-y-arrays-into-a-frequencies-grid
I would like to convert two arrays (x and y) into a frequency n x n matrix (n = 5), indicating each cell the number of point that contains. It consists on resampling both variables into five intervals and count the existing number of points per cell. I have tried using pandas pivot_table but don't know the way of refer...
If you do not explicitly need to use pandas (which you don't, if it's just about a frequency matrix), consider using numpy.histogram2d: # Sample data x = 100*np.random.random(15) y = 100*np.random.random(15) Construct your bins (since your x and y bins are the same, one set is enough) bins = np.linspace(0, 100, 5+1) #...
19
7
64,483,136
2020-10-22
https://stackoverflow.com/questions/64483136/how-can-you-identify-what-versions-of-vs-code-an-extensions-will-work-with
I'm trying to install the MS Python extension (ms-python.python-2020.7.96456.vsix) on a VS Code (1.40.2) install and I'm receiving the following error. "Unable to install extension 'ms-python-python' as it is not compatible with VS Code '1.40.2'". How do I go about finding out what version would be compatible? I'm in a...
Thanks rioV8! After looking into the package.json I've found that the "engines" field is what details the minimum version of VS Code required. Per code.visualstudio.com (https://code.visualstudio.com/api/working-with-extensions/publishing-extension) Visual Studio Code compatibility When authoring an extension, you wil...
7
4
64,500,342
2020-10-23
https://stackoverflow.com/questions/64500342/creating-requirements-txt-in-pip-compatible-format-in-a-conda-virtual-environmen
I have created a conda virtual environment on a Windows 10 PC to work on a project. To install the required packages and dependencies, I am using conda install <package> instead of pip install <package> as per the best practices mentioned in https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environ...
The best solution I've found for the above is the combination I will describe below. For conda, I would first export the environment list as environment.yml and omit the package build numbers, which is often what makes it hard to reproduce the environment on another OS: conda env export > environment.yml --no-builds O...
20
45
64,499,551
2020-10-23
https://stackoverflow.com/questions/64499551/formatting-of-df-to-latex
I want to export a Pandas DataFrame to LaTeX with . as a thousand seperator and , as a decimal seperator and two decimal digits. E.g. 4.511,34 import numpy as np import pandas as pd df = pd.DataFrame( np.array([[4511.34242, 4842.47565]]), columns=['col_1', 'col_2'] ) df.to_latex('table.tex', float_format="{:0.2f}".form...
I would format with _ as the thousands seperator and . as the decimal seperator and then replace those with str.replace. df.applymap(lambda x: str.format("{:0_.2f}", x).replace('.', ',').replace('_', '.')).to_latex('table.tex') Gives the following latex: \begin{tabular}{lll} \toprule {} & col\_1 & col\_2 \\ \midrule 0...
8
1
64,498,561
2020-10-23
https://stackoverflow.com/questions/64498561/activate-conda-environment-using-subprocess
I am trying to find version of pandas: def check_library_version(): print("Checking library version") subprocess.run(f'bash -c "conda activate {ENV_NAME};"', shell=True) import pandas pandas.__version__ Desired output: 1.1.3 Output: Checking library version CommandNotFoundError: Your shell has not been properly confi...
This doesn't make any sense at all; the Conda environment you activated is terminated when the subprocess terminates. You should (conda init and) conda activate your virtual environment before you run any Python code. If you just want to activate, run a simple Python script as a subprocess of your current Python, and t...
6
3
64,499,180
2020-10-23
https://stackoverflow.com/questions/64499180/pandas-find-the-nearest-value-for-in-a-column
I have the following table: year pop1 pop2 0 0 100000 100000 1 1 999000 850000 2 2 860000 700000 3 3 770000 650000 I want to find for each pop (pop1 ,pop2) the year the pop was closest to a given number, for example, the year the pop was the closest to 830000. Is there any way to find the nearest value inside column ...
Convert column year to index, then subtract value, get absolute values and last index (here year) by nearest value - here minimal by DataFrame.idxmin: val = 830000 s = df.set_index('year').sub(val).abs().idxmin() print (s) pop1 2 pop2 1 dtype: int64
6
7
64,496,437
2020-10-23
https://stackoverflow.com/questions/64496437/python-list-type-declaration
I tried to set variable types in my functions. There is no problem when I tried to use normal variable type. For example, def myString(name:str) -> str: return "hello " + name However, I got problem in list. Many examples in internet said use List, but it got error. Now I use list, and there is no error. Is it ok to u...
TypeError: 'type' object is not subscriptable Python 3.9 allows for list[str]. Earlier you had to import List from typing and do -> List[str]. NameError: name 'Point' is not defined If you want to declare the type of "self" you can either put that in a string def isSamePoint(self, p: "Point") -> bool: or create an ...
6
12
64,496,264
2020-10-23
https://stackoverflow.com/questions/64496264/python-class-self-value-error-expected-type-str-got-tuplestr-instead-azure
I've created a class and trying to assign one of its values to something that expects a string, however it is saying it is getting a Tuple[str] instead, and I don't see how? from azure.identity import ClientSecretCredential class ServicePrincipal: """ Service Principal class is used to authorise the service """ def __i...
You should remove the commas here: def __init__(self): self.tenant_id = "123-xyz", # remove the comma self.client_id = "123-abc", # remove the comma self.client_secret = "123-lmn", # remove the comma Comma make the variable be a Tuple
9
16
64,493,332
2020-10-23
https://stackoverflow.com/questions/64493332/jinja-templating-in-airflow-along-with-formatted-text
I'm trying to run a SQL statement to be rendered by Airflow, but I'm also trying to include a variable inside the statement which is passed in from Python. The SQL statement is just a where clause, and after the WHERE, I'm trying to add a datetime, minus a few seconds: f" ' {{ ts - macros.timedelta(seconds={lower_delay...
Jinja templating requires two curly braces, when you use f-strings or str.format it will replace two braces with one while rendering: Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. ...
9
19
64,489,249
2020-10-22
https://stackoverflow.com/questions/64489249/generating-better-help-from-argparse-when-nargs
Like many command line tools, mine accepts optional filenames. Argparse seems to support this via nargs='*', which is working for me as expected: import argparse parser = argparse.ArgumentParser() parser.add_argument( 'files', help='file(s) to parse instead of stdin', nargs='*') parser.parse_args() However, the help o...
This was fixed in Python 3.9, see https://bugs.python.org/issue38438 and commit a0ed99bc that fixed it. Your code produces the usage message you expect if run on 3.9: Python 3.9.0 (default, Oct 12 2020, 02:44:01) [GCC 9.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import argp...
5
6
64,470,052
2020-10-21
https://stackoverflow.com/questions/64470052/how-to-set-default-branch-for-gitpython
With GitPython, I can create a new repo with the following: from git.repo.base import Repo Repo.init('/tmp/some-repo/') The repo is created with the default branch master. How can I modify this default branch? Update: As suggested in the answers below, I have tried using Repo.init('/tmp/some-repo', initial_branch="mai...
According to the docs, init takes the same arguments as git init as keyword arguments. You do have to turn - into _. from git import Repo Repo.init('/tmp/some-repo/', initial_branch='main') UPDATE initial-branch was added very recently in v2.28.0. You'll need to upgrade Git to use it. If you can't, manually change th...
5
8
64,482,562
2020-10-22
https://stackoverflow.com/questions/64482562/specify-per-file-ignores-with-pyproject-toml-and-flake8
I am using flake8 (with flakehell but that should not interfere) and keep its configuration in a pyproject.toml file. I want to add a per-file-ignores config but nothing works and there is no documentation on how it is supposed to be formatted in a toml file. Flake8 docs show only the 'native' config file format: per-f...
flake8 does not have support for pyproject.toml, only .flake8, setup.cfg, and tox.ini disclaimer: I am the flake8 maintainer
27
50
64,483,854
2020-10-22
https://stackoverflow.com/questions/64483854/efficient-way-of-filtering-by-datetime-in-groupby
Given the DataFrame generated by: import numpy as np import pandas as pd from datetime import timedelta np.random.seed(0) rng = pd.date_range('2015-02-24', periods=14, freq='9H') ids = [1]*5 + [2]*2 + [3]*7 df = pd.DataFrame({'id': ids, 'time_entered': rng, 'val': np.random.randn(len(rng))}) df: id time_entered val 0...
Generally, avoid groupby().apply() since it's not vectorized across groups, not to mention the overhead for memory allocation if you are returning new dataframes as in your case. How about finding the time threshold with groupby().transform then use boolean indexing on the whole data: time_max_by_id = df.groupby('id')[...
7
4
64,481,847
2020-10-22
https://stackoverflow.com/questions/64481847/partial-disallow-overriding-given-keyword-arguments
Is there a way to disallow overriding given keyword arguments in a partial? Say I want to create function bar which always has a set to 1. In the following code: from functools import partial def foo(a, b): print(a) print(b) bar = partial(foo, a=1) bar(b=3) # This is fine and prints 1, 3 bar(a=3, b=3) # This prints 3, ...
This is by design. The documentation for partial says (emphasize mine): functools.partial(func, /, *args, **keywords) Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords. If more arguments are supplied to the call, they are appen...
6
3
64,465,836
2020-10-21
https://stackoverflow.com/questions/64465836/python17874-0x111e92dc0-malloc-cant-allocate-region
I am building a Python web scraping script and i have to use cv2 (OpenCV). So I install using pip install opencv-python as the website directs. And it also installs numpy as a dependency. However, right after installing that, I'm unable to run my python script. It crashes with the error below: I think the issue is fro...
I had the same issue when I tried to run a project I made on Windows on Mac OS. The solution I found was to install an older version of numpy (e.g. numpy 1.18). Here is the command I ran to do so : sudo python -m pip install numpy==1.18 --force I don't think it is a good solution but it is ok for a temporary fix.
7
8
64,464,513
2020-10-21
https://stackoverflow.com/questions/64464513/how-to-resize-sg-window-in-pysimplegui
I am using PYsimpleGUI in my python code, and while using the window element to create the main window, this is my code. My code: import PySimpleGUI as sg layout = [ [sg.Button('Close')] ] window = sg.Window('This is a long heading.', layout) while True: event, values = window.read() if event == sg.WIN_CLOSED or event ...
You can add size argument in the sg.Window. Try this : import PySimpleGUI as sg layout = [ [sg.Button('Close')] ] window = sg.Window('This is a long heading.', layout,size=(290, 50)) while True: event, values = window.read() if event == sg.WIN_CLOSED or event == 'Close': break break window.close()
7
9
64,470,110
2020-10-21
https://stackoverflow.com/questions/64470110/how-to-delete-multiple-files-in-gcs-except-1-using-gsutil
I currently have this: gsutil ls gs://basty/*_TZ001.* gs://basty/20201007_TZ001.csv gs://basty/20201008_TZ001.csv gs://basty/20201009_TZ001.csv My problem is that I have bcuket with many files I want to delete all except 1 (20201009_TZ001.csv) I thought using bash or python I don't know.
You can filter results with grep (using -v flag to invert results) and the pipe with xargs gsutil ls gs://basty/*_TZ001.* |\ grep -v 20201009_TZ001.csv |\ xargs -i{} gsutil rm {} To be sure that is precisely what you want, you could first execute a dry-run command: gsutil ls gs://basty/*_TZ001.* |\ grep -v 20201009_TZ...
5
9
64,466,231
2020-10-21
https://stackoverflow.com/questions/64466231/pythonic-way-to-operate-comma-separated-list-of-ranges-1-5-10-25-27-30
I'm currently working on an api where they send me a str range in this format: "1-5,10-25,27-30" and i need add or remove number conserving the format. if they send me "1-5,10-25,27-30" and I remove "15" the result must be "1-5,10-14,16-25,27-30" and if they send me "1-5,10-25,27-30" and i add "26" the result must be "...
intspan deals with ranges of integers and operations on them >>> from intspan import intspan >>> s = "1-5,10-25,27-30" >>> span = intspan(s) >>> str(span) '1-5,10-25,27-30' >>> span.add(26) >>> str(span) '1-5,10-30' >>> span.discard(15) >>> str(span) '1-5,10-14,16-30'
5
7
64,459,175
2020-10-21
https://stackoverflow.com/questions/64459175/how-to-replace-multiple-forward-slashes-in-a-directory-by-a-single-slash
My path: '/home//user////document/test.jpg' I want this to be converted into: '/home/user/document/test.jpg' How to do this?
Use os.path.abspath or normpath to canonicalise the path: >>> import os.path >>> os.path.abspath('/home//user////document/test.jpg') '/home/user/document/test.jpg'
9
9
64,371,174
2020-10-15
https://stackoverflow.com/questions/64371174/how-to-change-variable-label-names-for-the-legend-in-a-plotly-express-line-chart
I want to change the variable/label names in plotly express in python. I first create a plot: import pandas as pd import plotly.express as px d = {'col1': [1, 2, 3], 'col2': [3, 4, 5]} df = pd.DataFrame(data=d) fig = px.line(df, x=df.index, y=['col1', 'col2']) fig.show() Which yields: I want to change the label names...
The answer: Without changing the data source, a complete replacement of names both in the legend, legendgroup and hovertemplate will require: newnames = {'col1':'hello', 'col2': 'hi'} fig.for_each_trace(lambda t: t.update(name = newnames[t.name], legendgroup = newnames[t.name], hovertemplate = t.hovertemplate.replace(t...
55
58
64,368,565
2020-10-15
https://stackoverflow.com/questions/64368565/delete-and-release-memory-of-a-single-pandas-dataframe
I am running a long ETL pipeline in pandas. I have to create different pandas dataframes and I want to release memory for some of the dataframes. I have been reading how to release memory and I saw that runing this command doesn't release the memory: del dataframe Following this link: How to delete multiple pandas (py...
From the original link that you included, you have to include variable in the list, delete the variable and then delete the list. If you just add to the list, it won't delete the original dataframe, when you delete the list. import pandas import psutil import gc psutil.virtual_memory().available * 100 / psutil.virtual_...
9
13
64,413,061
2020-10-18
https://stackoverflow.com/questions/64413061/python-pip-install-ends-with-command-errored-out-with-exit-status-1
I'm new to python, and I'm trying to run some basic codes that require some libraries. And when I'm trying to install a library (e.g. pip install matplotlib-venn) I get this long error: ERROR: Command errored out with exit status 1: command: 'c:\users\scurt\appdata\local\programs\python\python39\python.exe' -c 'import...
I had a similar problem while trying to run "pip install seaborn". The problem is that the new Python 3.9 does not provide binary wheels scipy and numpy do not as discussed here. What I did was uninstall Python 3.9 and reinstall Python 3.8 and everything worked perfectly.
9
1
64,430,805
2020-10-19
https://stackoverflow.com/questions/64430805/how-to-compress-video-to-target-size-by-python
I am uploading text and videos to a site by Python program. This site says they only receive video files of up to 50 MB in size. Otherwise, they will reject the video and other associated information. To ensure I can send video continuously, I want to compress it to target size (e.g. 50 MB) before sending. Because no l...
Compress video files by Python and FFmpeg Tools FFmpeg is a powerful tool for video editing. And there is a great Python binding named ffmpeg-python (API Reference) for this. Firstly, pip install ffmpeg-python and install FFmpeg. Steps Probe the configuration of video by function ffmpeg.probe() to get duration, audio &...
12
21
64,445,167
2020-10-20
https://stackoverflow.com/questions/64445167/how-to-convert-positive-numbers-to-negative-in-python
I know that abs() can be used to convert numbers to positive, but is there somthing that does the opposite? I have an array full of numbers which I need to convert to negative: array1 = [] arrayLength = 25 for i in range(arrayLength): array1.append(random.randint(0, arrayLength) I thought perhaps I could convert the n...
If you want to force a number to negative, regardless of whether it's initially positive or negative, you can use: -abs(n) Note that integer 0 will remain 0.
24
47
64,435,497
2020-10-19
https://stackoverflow.com/questions/64435497/how-to-properly-insert-pandas-nat-datetime-values-to-my-postgresql-table
I am tying to bulk insert a dataframe to my postgres dB. Some columns in my dataframe are date types with NaT as a null value. Which is not supported by PostgreSQL, I've tried to replace NaT (using pandas) with other NULL type identifies but that did not work during my inserts. I used df = df.where(pd.notnull(df), 'Non...
You're re-inventing the wheel. Just use pandas' to_sql method and it will match up the column names, and take care of the NaT values. Use method="multi" to give you the same effect as psycopg2's execute_values. from pprint import pprint import pandas as pd import sqlalchemy as sa table_name = "so64435497" engine = sa...
12
4
64,381,297
2020-10-16
https://stackoverflow.com/questions/64381297/cant-fully-disable-python-linting-pylance-vscode
I've been searching online for quite a while now and can't seem to find a solution for my problem. I installed Pylance (the newest Microsoft interpreter for Python) and can't seem to disable linting at all. I've tried a lot of options but none worked. Here's a screenshot of how annoying linting is in my code now. Here'...
You can disable the language server with: "python.languageServer": "None"
33
35
64,382,706
2020-10-16
https://stackoverflow.com/questions/64382706/dask-distributed-scheduler-error-couldnt-gather-keys
import joblib from sklearn.externals.joblib import parallel_backend with joblib.parallel_backend('dask'): from dask_ml.model_selection import GridSearchCV import xgboost from xgboost import XGBRegressor grid_search = GridSearchCV(estimator= XGBRegressor(), param_grid = param_grid, cv = 3, n_jobs = -1) grid_search.fit(d...
I also meet the same issue, and I find it's likely to be caused by firewall. Suppose we have two machines, 191.168.1.1 for scheduler and 191.168.1.2 for worker. When we start scheduler, we may get following info: distributed.scheduler - INFO - ----------------------------------------------- distributed.http.proxy - INF...
8
1
64,429,113
2020-10-19
https://stackoverflow.com/questions/64429113/how-should-a-namedtemporaryfile-be-annotated
I tried typing.IO as suggested in Type hint for a file or file-like object?, but it doesn't work: from __future__ import annotations from tempfile import NamedTemporaryFile from typing import IO def example(tmp: IO) -> str: print(tmp.file) return tmp.name print(example(NamedTemporaryFile())) for this, mypy tells me: t...
I don't think this can be easily type hinted. If you check the definition of NamedTemporaryFile, you'll see that it's a function that ends in: return _TemporaryFileWrapper(file, name, delete) And _TemporaryFileWrapper is defined as: class _TemporaryFileWrapper: Which means there isn't a super-class that can be indica...
15
12
64,420,348
2020-10-19
https://stackoverflow.com/questions/64420348/ignore-userwarning-from-openpyxl-using-pandas
I have tons of .xlsm files that I have to load. Each Excel file has 6 sheets. Because of that, I'm opening each Excel file like this, using pandas: for excel_file in files_list: with pd.ExcelFile(excel_file, engine = "openpyxl") as f: df1 = pd.read_excel(f, "Sheet1") df2 = pd.read_excel(f, "Sheet2") df3 = pd.read_excel...
You can do this using warnings core module: import warnings warnings.filterwarnings('ignore', category=UserWarning, module='openpyxl') You can also specify the particular module you'd like to silence warnings for by adding an argument module="openpyxl".
9
25
64,348,889
2020-10-14
https://stackoverflow.com/questions/64348889/how-to-get-local-ip-address-python
There's a code I found in internet that says it gives my machines local network IP address: hostname = socket.gethostname() local_ip = socket.gethostbyname(hostname) but the IP it returns is 192.168.94.2 but my IP address in WIFI network is actually 192.168.1.107 How can I only get wifi network local IP address with o...
You can use this code: import socket hostname = socket.getfqdn() print("IP Address:",socket.gethostbyname_ex(hostname)[2][1]) or this to get public ip: import requests import json print(json.loads(requests.get("https://ip.seeip.org/jsonip?").text)["ip"])
5
10
64,414,009
2020-10-18
https://stackoverflow.com/questions/64414009/why-is-user-is-authenticated-asserting-true-after-logout
I am trying to write a test for logging out a user in Django. Here is the code: urls.py from django.conf.urls import url from django.contrib import admin from accounts.views import LoginView, LogoutView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/', LoginView.as_view(), name='login'), url(r'^logout/'...
It seems like the user would not be authenticated after calling logout(). Am I missing something? .is_authenticated [Django-doc] does not check if a user is logged in. Every real User returns always True for is_authenticated. An AnonymousUser [Django-doc] will return False for example. If you thus log out, then reque...
6
6
64,390,904
2020-10-16
https://stackoverflow.com/questions/64390904/how-can-i-extract-the-weight-and-bias-of-linear-layers-in-pytorch
In model.state_dict(), model.parameters() and model.named_parameters() weights and biases of nn.Linear() modules are contained separately, e.q. fc1.weight and fc1.bias. Is there a simple pythonic way to get both of them? Expected example looks similar to this: layer = model['fc1'] print(layer.weight) print(layer.bias)
You can recover the named parameters for each linear layer in your model like so: from torch import nn for layer in model.children(): if isinstance(layer, nn.Linear): print(layer.state_dict()['weight']) print(layer.state_dict()['bias'])
6
7
64,436,317
2020-10-19
https://stackoverflow.com/questions/64436317/how-to-check-ocsp-client-certificate-revocation-using-python-requests-library
How do I make a simple request for certificate revocation status to an EJBCA OSCP Responder using the Python requests library? Example: # Determine if certificate has been revoked ocsp_url = req_cert.extensions[2].value[0].access_location.value ocsp_headers = {"whatGoes: here?"} ocsp_body = {"What goes here?"} ocsp_res...
Basically it involves the following steps: retrieve the corresponding cert for a hostname if a corresponding entry is contained in the certificate, you can query the extensions via AuthorityInformationAccessOID.CA_ISSUERS, which will provide you with a link to the issuer certificate if successful retrieve the issuer c...
7
15
64,362,772
2020-10-14
https://stackoverflow.com/questions/64362772/switching-python-version-installed-by-homebrew
I have Python 3.8 and 3.9 installed via Homebrew: ~ brew list | grep python python@3.8 python@3.9 I want to use Python 3.9 as my default one with python3 command. I tried the following: ~ brew switch python 3.9 Error: python does not have a version "3.9" in the Cellar. python's installed versions: 3.8.6 I tried to un...
There is an Homebrew known issue related to side by side install of Python 3.8 / 3.9. To workaround, following commands should work for you: brew unlink python@3.9 brew unlink python@3.8 brew link --force python@3.9 Re-opening your terminal or execute command rehash can be required to take account the change.
68
107
64,448,567
2020-10-20
https://stackoverflow.com/questions/64448567/python3-8-no-such-file-or-directory-when-trying-to-git-commit-to-bitbucket-on-ma
I am currently on a new mac with python 3.8.2 installed. I have a bitbucket repo I cloned down. When I modify a file and git add that works fine. But when I make a git commit I get this error message env: python3.8: No such file or directory My path env variable looks like this PATH=/Users/rach/bin:/Users/rach/bin:/us...
Since you're using pre-commit, you can uninstall hooks by: pre-commit uninstall To install them again, run: pre-commit install
25
40
64,381,222
2020-10-16
https://stackoverflow.com/questions/64381222/python-click-access-option-values-globally
Say I have an flag --debug/--no-debug defined for the base command. This flag will affect the behavior of many operations in my program. Right now I find myself passing this flag as function parameters all over the place, which doesn't seem elegant. Especially when I need to access this flag in a deep call stack, I'll ...
There are two ways to do so, depending on your needs. Both of them end up using the click Context. Personally, I'm a fan of Option 2 because then I don't have to modify function signatures (and I rarely write multi-threaded programs). It also sounds more like what you're looking for. Option 1: Pass the Context to the f...
6
7
64,406,727
2020-10-17
https://stackoverflow.com/questions/64406727/is-there-any-solution-to-packaging-a-python-app-that-uses-cppyy
I'm no novice when creating cross-platform runtimes of my python desktop apps. I create various tools for my undergraduates using mostly pyinstaller, cxfreeze, sometimes fbs, and sometimes briefcase. Anyone who does this one a regular basis knows that there are lots of quirks and adjustments needed to target Linux, win...
EDIT: figured out the pyinstaller hooks; this should all be fully automatic once released With the caveat that I have no experience whatsoever with packaging run-times, so I may be missing something obvious, but I've just tried pyinstaller, and the following appears to work. First, saving your script above as example.p...
7
4
64,428,208
2020-10-19
https://stackoverflow.com/questions/64428208/why-is-listx-for-x-in-a-faster-for-a-0-than-for-a
I tested list(x for x in a) with three different CPython versions. On a = [0] it's significantly faster than on a = []: 3.9.0 64-bit 3.9.0 32-bit 3.7.8 64-bit a = [] a = [0] a = [] a = [0] a = [] a = [0] 465 ns 412 ns 543 ns 515 ns 513 ns 457 ns 450 ns 406 ns 544 ns 515 ns 506 ns 491 ns 456 ns 408 ns 551 ns 513 ns 515...
What you observe, is that pymalloc (Python memory manager) is faster than the memory manager provided by your C-runtime. It is easy to see in the profiler, that the main difference between both versions is that list_resize and _PyObjectRealloc need more time for the a=[]-case. But why? When a new list is created from a...
37
40
64,445,333
2020-10-20
https://stackoverflow.com/questions/64445333/opencv-probabilistic-hough-line-transform-giving-different-results-with-c-and
I was working on a project using OpenCV, Python that uses Probabilistic Hough Line Transform function "HoughLinesP" in some part of the project. My code worked just fine and there was no problem. Then I thought of converting the same code to C++. After converting the code to C++, the output is not the same as that of t...
Explanation & Fix The problem arises because in the Python version you are not setting the arguments that you think you are setting. In contrast to some other functions for which the argument lists are adapted in the Python interface, HoughLinesP does not only return the lines but also still takes a parameter lines for...
7
17
64,401,570
2020-10-17
https://stackoverflow.com/questions/64401570/error-using-shap-with-simplernn-sequential-model
In the code below, I import a saved sparse numpy matrix, created with python, densify it, add a masking, batchnorm and dense ouptput layer to a many to one SimpleRNN. The keras sequential model works fine, however, I am unable to use shap. This is run in Jupyter lab from Winpython 3830 on a Windows 10 desktop. The X ma...
The owner of the shap repo said: The fundamental issue here is that DeepExplainer does not yet support TF 2.0. That was on 11 Dec 2019. Is this still the case? Try it with Tensorflow 1.15 and see if that works. Another issue on the shap repo about this (2 Jun 2020) says: Alright, thank you. I did not see the post by...
6
4
64,434,461
2020-10-19
https://stackoverflow.com/questions/64434461/how-to-abort-cancel-http-request-in-python-thread
I'm looking to abort/cancel an HTTP request in a Python thread. I have to stick with threads. I can't use asyncio or anything outside the standard library. This code works fine with sockets: """Demo for Canceling IO by Closing the Socket Works! """ import socket import time from concurrent import futures start_time = t...
What you describe is the intended well documented behavior: Note close() releases the resource associated with a connection but does not necessarily close the connection immediately. If you want to close the connection in a timely fashion, call shutdown() before close(). Some further details regarding this behavior c...
11
5
64,448,442
2020-10-20
https://stackoverflow.com/questions/64448442/replace-data-of-an-array-by-two-values-of-a-second-array
I have two numpy arrays "Elements" and "nodes". My aim is to gather some data of these arrays. I need to replace "Elements" data of the two last columns by the two coordinates contains in "nodes" array. The two arrays are very huge, I have to automate it. This posts refers to an old one: Replace data of an array by 2 v...
Most of the game would be to figure out the corresponding matching indices from Elements in nodes. Approach #1 Since it seems you are open to conversion to integer, let's assume we could take them as integers. With that, we could use an array-assignment + mapping based method, as shown below : ar = Elements.astype(int)...
8
2
64,449,971
2020-10-20
https://stackoverflow.com/questions/64449971/pip-install-pyodbc-failed-error-failed-building-wheel-for-pyodbc
I'am trying to import pyodbc library into google colab, but i'am getting this error. Just in case, I have Anaconda installed in my notebook, and I never had problem with pyodbc in there. Can you help me please? Tks! Collecting pyodbc Using cached https://files.pythonhosted.org/packages/81/0d/bb08bb16c97765244791c73e49d...
You can try the following: !apt install unixodbc-dev !pip install pyodbc
19
59
64,437,677
2020-10-20
https://stackoverflow.com/questions/64437677/aws-throws-the-following-error-bad-interpreter-no-such-file-or-directory
I'm not aware of anything on my system having changed, but the aws CLI tool has stopped working. $ aws-bash: /Users/user_name/Library/Python/3.7/bin/aws:/usr/local/opt/python/bin/ python3.7: bad interpreter: No such file or directory I've tried brew reinstall awscli which is suggested elsewhere, but with no luck.
Option 1 Type brew uninstall awscli Then brew install awscli update python to 3.9. look in the following post. If this approach does not work for you, then try : Option 2 Go to https://www.python.org/ and use the GUI installer for your OS pip3 install awscli
16
27
64,452,984
2020-10-20
https://stackoverflow.com/questions/64452984/how-to-share-mmap-between-python-and-node-processes
I'm trying to share memory between a python process and a nodejs process started from the python process using an anonymous mmap. Essentially, the python process begins, initializes the mmap and starts a subprocess using either call or Popen to launch a child that runs some node code. This nodejs code uses mmap to try ...
Fortunately this doesn't work: imagine how confusing if all of the system's MAP_ANONYMOUS mappings were against the same area and kept overwriting each other. Instead, use shm_open to create a new handle you can mmap in both processes. This is a portable wrapper around the equally valid but less portable strategy of cr...
6
3
64,451,966
2020-10-20
https://stackoverflow.com/questions/64451966/how-to-embed-code-examples-into-a-docstring
How can I embed code into a docstring to tell Sphinx to format the code similar as it will be done in Markdown (different background colour, monospaced sans-serif font)? For example to document a code usage example. """ This is a module documentation Use this module like this: res = aFunction(something, goes, in) print...
There are a few ways to do it. I think the most sensible in your case would be .. code-block:: """ This is a module documentation Use this module like this: .. code-block:: python res = aFunction(something, goes, in) print(res.avalue) """ Notice the blank line between the directive and the code block - it must be ther...
11
16
64,436,858
2020-10-20
https://stackoverflow.com/questions/64436858/fastest-algorithm-to-find-the-minimum-sum-of-absolute-differences-through-list-r
By rotating 2 lists either from left to right, Find the smallest possible sum of the absolute value of the differences between each corresponding item in the two lists given they're the same length. Rotation Sample: List [0, 1, 2, 3, 4, 5] rotated to the left = [1, 2, 3, 4, 5, 0] List [0, 1, 2, 3, 4, 5] rotated to the ...
I haven't cracked the full problem, but in the special case where the input values are all 0 or 1 (or any two different values, or any of O(1) different values, but we'll need another idea to get much further than that), we can get an O(n log n)-time algorithm by applying fast convolution. The idea is to compute all of...
9
2
64,448,221
2020-10-20
https://stackoverflow.com/questions/64448221/python-mean-doesnt-work-when-groupby-aggregates-dataframe-to-one-line
I have dataframe: time_to_rent = {'rentId': {0: 43.0, 1: 87.0, 2: 140.0, 3: 454.0, 4: 1458.0}, 'creditCardId': {0: 40, 1: 40, 2: 40, 3: 40, 4: 40}, 'createdAt': {0: Timestamp('2020-08-24 16:13:11.850216'), 1: Timestamp('2020-09-10 10:47:31.748628'), 2: Timestamp('2020-09-13 15:29:06.077622'), 3: Timestamp('2020-09-24 0...
It's not your mistake, possibly a bug in Pandas since Timedelta can be averaged. A work-around is apply: time_to_rent.groupby('creditCardId')['rent_time'].apply(lambda x: x.mean()) Output: creditCardId 40 0 days 05:08:10.562342200 Name: rent_time, dtype: timedelta64[ns]
6
1
64,447,085
2020-10-20
https://stackoverflow.com/questions/64447085/how-to-delete-char-after-without-using-a-regular-expression
Given a string s representing characters typed into an editor, with "->" representing a delete, return the current state of the editor. For every one "->" it should delete one char. If there are two "->" i.e "->->" it should delete 2 char post the symbol. Example 1 Input s = "a->bcz" Output "acz" Explanation The "b" g...
Here's a simple recursive solution- # Constant storing the length of the arrow ARROW_LEN = len('->') def delete_forward(s: str): try: first_occurence = s.index('->') except ValueError: # No more arrows in string return s if s[first_occurence + ARROW_LEN:first_occurence + ARROW_LEN + ARROW_LEN] == '->': # Don't delete p...
7
4
64,423,083
2020-10-19
https://stackoverflow.com/questions/64423083/why-cant-both-args-and-keyword-only-arguments-be-mixed-with-args-and-kwargs
The usage of *args and **kwargs in python is clear to me and there are many questions out there in SO (eg Use of *args and **kwargs and What does ** (double star/asterisk) and * (star/asterisk) do for parameters?). But one thing I would like to understand is: why is it not possible to simultaneously define mandatory po...
The correct syntax is def cant_do_that(a, *args, b, **kwargs):. Note that * is used only once, both to mark the end of positional arguments and to set the name for variadic positional arguments. The * in a function definition is syntactically unique at the separation between positional-or-keyword and keyword-only argu...
11
14
64,440,753
2020-10-20
https://stackoverflow.com/questions/64440753/bigqueryoperator-changes-the-table-schema-and-column-modes-when-write-dispositio
I am using Airflow's BigQueryOperator to populate the BQ table with write_disposition='WRITE_TRUNCATE'. The problem is that every time the task runs, it alters the table schema and also the column mode from Required to Nullable. The create_disposition I am using is 'CREATE_NEVER'. Since my tables are pre-created, I don...
I had a similar issue, not with the required/nullable shcema value, but on policy tags, and the behavior is the same: the policy tags are overriden (and lost). Here the answer of the Google support team: If you overwrite to a destination table, any existing policy tags are removed from the table, unless you use the --...
7
10
64,401,503
2020-10-17
https://stackoverflow.com/questions/64401503/is-there-a-way-to-further-improve-sparse-solution-times-using-python
I have been trying different sparse solvers available in Python 3 and comparing the performance between them and also against Octave and Matlab. I have chosen both direct and iterative approaches, I will explain this more in detail below. To generate a proper sparse matrix, with a banded structure, a Poisson's problem ...
I will try to answer to myself. To provide an answer, I tried an even more demanding example, with a matrix of size of (N,N) of about half a million by half a million and the corresponding vector (N,1). This, however, is much less sparse (more dense) than the one provided in the question. This matrix stored in ascii is...
10
6
64,434,655
2020-10-19
https://stackoverflow.com/questions/64434655/stop-tensorflow-from-printing-to-the-console
I've been using tensorflow without issue, until I added the following lines of code: log_dir = os.path.join("logs", "fit", datetime.datetime.now().strftime("%Y%m%d-%H%M%S")) tensorboard_callback = TensorBoard(log_dir) After running this I get an large amount of information printed to the console. I've tried looking at...
You can disable debugging logs with os.environ. import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import tensorflow as tf Possible values are as follows: 0 = all messages are logged (default behavior) 1 = INFO messages are not printed 2 = INFO and WARNING messages are not printed 3 = INFO, WARNING, and ERROR messages...
8
10
64,433,923
2020-10-19
https://stackoverflow.com/questions/64433923/how-can-i-get-all-the-subplots-to-zoom-and-pan-the-same-way-on-the-x-axis-with
I have a plotly graph with subplots drawn this way: fig = make_subplots( rows=4, cols=1, subplot_titles=("Price, orders and positions", "Margin use", "PnL and fees", "Volume traded"), row_heights=[0.5, 0.2, 0.2, 0.1], vertical_spacing=0.1 ) # price, orders, etc fig.add_traces( [ # draw price, average price and min / ma...
Have a look at the Shared X-Axes section of the Plotly docs. I believe this is what you're looking for. Essentially, add shared_xaxes=True to the make_subplots() function.
11
17
64,431,313
2020-10-19
https://stackoverflow.com/questions/64431313/split-multiple-columns-in-pandas-dataframe-by-delimiter
I have survey data which annoying has returned multiple choice questions in the following way. It's in an excel sheet There is about 60 columns with responses from single to multiple that are split by /. This is what I have so far, is there any way to do this quicker without having to do this for each individual column...
We can use list comprehension with add_prefix, then we use pd.concat to concatenate everything to your final df: splits = [df[col].str.split(pat='/', expand=True).add_prefix(col) for col in df.columns] clean_df = pd.concat(splits, axis=1) q10 q20 q21 q22 q30 q31 q32 0 one one two three a b c 1 two a b c d e f 2 three...
10
6
64,428,794
2020-10-19
https://stackoverflow.com/questions/64428794/flake8-disable-linter-only-for-a-block-of-code
I have a file in python like: def test_constructor_for_legacy_json(): """Test if constructor works for a legacy JSON in an old database""" a = A(**{ 'field1': 'BIG TEXT WITH MORE THAN 500 CHARACTERS....(...)', 'field2': 'BIG TEXT WITH MORE THAN 500 CHARACTERS....(...)', 'field3': 'BIG TEXT WITH MORE THAN 500 CHARACTERS...
There isn't a way in flake8 to ignore a block of code Your options are: ignore each line that produces an error by putting # noqa: E501 on it ignore the entire file (but this turns off all other errors as well) with a # flake8: noqa on a line by itself ignore E501 in the entire file by using per-file-ignores: [flake...
49
53
64,425,864
2020-10-19
https://stackoverflow.com/questions/64425864/zeep-client-throws-service-has-no-operation-error
I am using zeep to call a SOAP webservice. It is throwing an error even if the method exists in the WSDL client = Client(self.const.soap_url) client.service.getPlansDetails(id) I get this error AttributeError: Service has no operation 'getPlansDetails' Here is the information from the python -m zeep <wsd_url> Prefixe...
The reason why it's giving that error is because by default, zeep binds to 1st service and 1st port. But in your case you are trying to call method from 2nd port. So this should work: client = Client(self.const.soap_url) plan_client = client.bind('RoutingService', 'BasicHttpBinding_LFCPaymentPlanDetailsServices') plan_...
6
5
64,427,593
2020-10-19
https://stackoverflow.com/questions/64427593/how-to-check-if-default-value-for-python-function-argument-is-set-using-inspect
I'm trying to identify the parameters of a function for which default values are not set. I'm using inspect.signature(func).parameters.value() function which gives a list of function parameters. Since I'm using PyCharm, I can see that the parameters for which the default value is not set have their Parameter.default at...
You can do it like this: import inspect def foo(a, b=1): pass for param in inspect.signature(foo).parameters.values(): if param.default is param.empty: print(param.name) Output: a param.empty holds the same object inspect._empty. I suppose that this way of using it is recommended because of the example in the officia...
8
12
64,422,367
2020-10-19
https://stackoverflow.com/questions/64422367/how-to-overwrite-python-dataclass-asdict-method
I have a dataclass, which looks like this: @dataclass class myClass: id: str mode: str value: float This results in: dataclasses.asdict(myClass) {"id": id, "mode": mode, "value": value} But what I want is {id:{"mode": mode, "value": value}} I thought I could achive this by adding a to_dict method to my dataclass, wh...
from dataclasses import dataclass, asdict @dataclass class myClass: id: str mode: str value: float def my_dict(data): return { data[0][1]: { field: value for field, value in data[1:] } } instance = myClass("123", "read", 1.23) data = {"123": {"mode": "read", "value": 1.23}} assert asdict(instance, dict_factory=my_dict)...
15
7
64,422,974
2020-10-19
https://stackoverflow.com/questions/64422974/pandas-select-rows-that-contain-any-substring-from-a-list
I would like to select those rows in a column that contains any of the substrings in a list. This is what I have for now. product = ['LID', 'TABLEWARE', 'CUP', 'COVER', 'CONTAINER', 'PACKAGING'] df_plastic_prod = df_plastic[df_plastic['Goods Shipped'].str.contains(product)] df_plastic_prod.info() Sample df_plastic Nam...
For match values by subtrings join all values of list by | for regex or - so get values LID or TABLEWARE ...: Solution working well also with 2 or more words in list. pat = '|'.join(r"\b{}\b".format(x) for x in product) df_plastic_prod = df_plastic[df_plastic['Product'].str.contains(pat)] print (df_plastic_prod) Name P...
6
6
64,421,671
2020-10-19
https://stackoverflow.com/questions/64421671/error-getting-for-src-type-cv-8uc3-to-cv-8uc1-in-opencv-python
import cv2 as cv import numpy as np from matplotlib import pyplot as plt img = cv.imread('t2.jpg', cv.COLOR_BGR2GRAY) blur = cv.GaussianBlur(img, (5, 5), 0) ret3, th3 = cv.threshold(blur, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU) I get the error: Traceback (most recent call last): File "F:/l4 project docs/project/l4p...
img = cv.imread('t2.jpg', cv.IMREAD_GRAYSCALE) or img = cv.imread('t2.jpg', cv.IMREAD_COLOR) img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
10
15
64,414,486
2020-10-18
https://stackoverflow.com/questions/64414486/how-to-check-if-a-user-is-subscribed-to-a-specific-telegram-channel-python-py
I am writing a Telegram bot using the PyTelegramBotApi library, I would like to implement the function of checking the user's subscription to a certain telegram channel, and if there is none, offer to subscribe. Thanks in advance for your answers!
use getChatMember method to check if a user is member in a channel or not. getChatMember Use this method to get information about a member of a chat. Returns a ChatMember object on success. import telebot bot = telebot.TeleBot("TOKEN") CHAT_ID = -1001... USER_ID = 700... result = bot.get_chat_member(CHAT_ID, USER_ID)...
8
11
64,408,338
2020-10-17
https://stackoverflow.com/questions/64408338/include-raw-tab-literal-character-in-doctest
I can't figure out how to avoid this doctest error: Failed example: print(test()) Expected: output <BLANKLINE> Got: output <BLANKLINE> For this code def test(): r'''Produce string according to specification. >>> print(test()) output <BLANKLINE> ''' return '\toutput\n' I have put a tab literal into the source code, li...
The tabs in the docstring get expanded to 8 spaces, but the tabs in the output are not expanded. From the doctest documentation (emphasis added): All hard tab characters are expanded to spaces, using 8-column tab stops. Tabs in output generated by the tested code are not modified. Because any hard tabs in the sample o...
8
8
64,412,233
2020-10-18
https://stackoverflow.com/questions/64412233/how-to-format-pandas-matplotlib-graph-so-the-x-axis-ticks-are-only-hours-and-m
I am trying to plot temperature with respect to time data from a csv file. My goal is to have a graph which shows the temperature data per day. My problem is the x-axis: I would like to show the time for uniformly and only be in hours and minutes with 15 minute intervals, for example: 00:00, 00:15, 00:30. The csv is lo...
Answer First of all, you have to convert "New Time" (your x axis) from str to datetime type with: ndf["New_Time"] = pd.to_datetime(ndf["New_Time"], format = "%H:%M:%S") Then you can simply add this line of code before showing the plot (and import the proper matplotlib library, matplotlib.dates as md) to tell matplotli...
6
4
64,409,191
2020-10-18
https://stackoverflow.com/questions/64409191/angle-between-two-vectors-in-the-interval-0-360
I'm trying to find the angle between two vectors. Following is the code that I use to evaluate the angle between vectors ba and bc import numpy as np import scipy.linalg as la a = np.array([6,0]) b = np.array([0,0]) c = np.array([1,1]) ba = a - b bc = c - b cosine_angle = np.dot(ba, bc) / (la.norm(ba) * la.norm(bc)) an...
Conceptually, obtaining the angle between two vectors using the dot product is perfectly alright. However, since the angle between two vectors is invariant upon translation/rotation of the coordinate system, we can find the angle subtended by each vector to the positive direction of the x-axis and subtract one value fr...
6
5