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,689,342
2020-11-4
https://stackoverflow.com/questions/64689342/plotly-how-to-add-volume-to-a-candlestick-chart
code: from plotly.offline import init_notebook_mode, iplot, iplot_mpl def plot_train_test(train, test, date_split): data = [Candlestick(x=train.index, open=train['open'], high=train['high'], low=train['low'], close=train['close'],name='train'), Candlestick(x=test.index, open=test['open'], high=test['high'], low=test['l...
You haven't provided a complete code snippet with a data sample, so I'm going to have to suggest a solution that builds on an example here. In any case, you're getting that error message simply because go.Candlestick does not have a Volume attribute. And it might not seem so at first, but you can easily set up go.Candl...
17
28
64,694,102
2020-11-5
https://stackoverflow.com/questions/64694102/matplotlib-does-not-print-any-plot-on-databricks
%matplotlib inline corr = df.corr() f, ax = plt.subplots(figsize=(11, 9)) ax = sns.heatmap( corr, vmin=-1, vmax=1, center=0, cmap=sns.diverging_palette(20, 220, n=500), linewidths=.50, cbar_kws={"shrink": .7}, square=True ) ax.set_xticklabels( ax.get_xticklabels(), rotation=45, horizontalalignment='right' ); plt.show()...
It looks like an issue with the matplotlib modules above 3.3.0. To know the exact reason, I would suggest you to report here: https://github.com/matplotlib/matplotlib/issues As per the test from our end, you will experience the following error message with the matplotlib modules above 3.3.0. If you have installed ma...
6
8
64,687,375
2020-11-4
https://stackoverflow.com/questions/64687375/get-labels-from-dataset-when-using-tensorflow-image-dataset-from-directory
I wrote a simple CNN using tensorflow (v2.4) + keras in python (v3.8.3). I am trying to optimize the network, and I want more info on what it is failing to predict. I am trying to add a confusion matrix, and I need to feed tensorflow.math.confusion_matrix() the test labels. My problem is that I cannot figure out how to...
If I were you, I'll iterate over the entire testData, I'll save the predictions and labels along the way and I'll build the confusion matrix at the end. testData = tf.keras.preprocessing.image_dataset_from_directory( dataDirectory, labels='inferred', label_mode='categorical', seed=324893, image_size=(height,width), bat...
18
16
64,703,065
2020-11-5
https://stackoverflow.com/questions/64703065/how-to-check-if-a-column-contains-list
import pandas as pd df = pd.DataFrame({"col1": ["a", "b", "c", ["a", "b"]]}) I have a dataframe like this, and I want to find the rows that contains list in that column. I tried value_counts() but it tooks so long and throws error at the end. Here is the error: TypeError Traceback (most recent call last) pandas/_libs/...
Lists are mutable, they cannot be compared, so you can neither count the values nor set them as index. You would need to convert to tuple or set (thanks @CameronRiddell) to be able to count: df['col1'].apply(lambda x: tuple(x) if isinstance(x, list) else x).value_counts() Output: c 1 b 1 a 1 (a, b) 1 Name: col1, dtype...
6
2
64,700,652
2020-11-5
https://stackoverflow.com/questions/64700652/how-to-assign-pandas-column-to-other-column-or-default-value-if-nan
I have df= a 1 nan 3 I want some syntax for df["b"] = df["a"] or 5 to create a b 1 1 nan 5 3 3 Does pandas support something like this? BONUS: what about different default values per index/group/anything?
import pandas as pd import numpy as np df = pd.DataFrame({"a": [1, np.nan, 3]}) df["b"] = df["a"].fillna(5) print(df) a b 0 1.0 1.0 1 NaN 5.0 2 3.0 3.0 digging through the doc gave the standard pandas solution. No need to go through numpy.
6
6
64,696,711
2020-11-5
https://stackoverflow.com/questions/64696711/longest-path-finding-with-condition
I'm trying to solve a problem in Python/Pandas which I think is closely related to the longest path algorithm. The DataFrame I'm working with has the following structure: import numpy as np import pandas as pd data = { "cusID": ["001", "001", "001", "001", "001", "001", "002", "002", "002"], "start": ["A", "B", "C", "D...
First step is to normalize the sequences. seqs = pd.concat([ df.drop(columns="end").rename(columns={"start":"node"}), df.groupby("cusID").tail(1).drop(columns="start").rename(columns={"end":"node"}) ]) seqs = seqs.sort_values("cusID", kind="mergesort").reset_index(drop=True) >>> seqs cusID node 0 001 A 1 001 B 2 001 C ...
7
5
64,695,324
2020-11-5
https://stackoverflow.com/questions/64695324/upload-via-the-youtube-via-api-set-to-private-locked
I have been using the youtube API to upload remotely. But after a while of messing around with the code all the videos that get uploaded gets "Private (locked)" due to Terms and policies. I cant appeal it either due to "Appealing this violation is not available". Just to clarify I have been able to upload before and on...
If you check the documentation for Video.insert you will find the following at the top of the page. This is a new policy that is recently beginning to be enforced. Until your application has been verified all videos you upload will be set to private. You need to go though the audit first then you will be able to uploa...
8
10
64,689,483
2020-11-5
https://stackoverflow.com/questions/64689483/how-to-do-multiclass-classification-with-keras
I want to make simple classifier with Keras that will classify my data. Features are numeric data and results are string/categorical data. I'm predicting 15 different categories/classes. This is how my code looks: model = Sequential() model.add(Dense(16, input_dim = x_train.shape[1], activation = 'relu')) # input layer...
You need to convert your string categories to integers, there is a method for that: y_train = tf.keras.utils.to_categorical(y_train, num_classes=num_classes) Also, the last layer for multi-class classification should be something like: model.add(Dense(NUM_CLASSES, activation='softmax')) And finally, for multi-class c...
8
13
64,673,038
2020-11-4
https://stackoverflow.com/questions/64673038/how-to-split-cell-in-vscode-jupyter-notebook
How can a Jupyter notebook cell be split in VSCode? I.e., how to split a single cell with multiple lines into two cells with the top lines (above the cursor) in one cell and the bottom lines (below the cursor) in another cell? I've tried Cntrl Shift - using the Daily Insiders Python Extension, but it doesn't seem to do...
The Ctrl Shift - is for zooming out the display by default in VS Code. This feature has been put for a long time in Github, and the following is the request: Jupyter Split Cell and Select Multiple Cells command This issue is still open, although there's Notebooks are getting revamped! existed, it's for VS Code Inside...
19
8
64,686,950
2020-11-4
https://stackoverflow.com/questions/64686950/whats-the-python-equivalent-of-julias-edit-macro
In Julia, calling a function with the @edit macro from the REPL will open the editor and put the cursor at the line where the method is defined. So, doing this: julia> @edit 1 + 1 jumps to julia/base/int.jl and puts the cursor on the line: (+)(x::T, y::T) where {T<:BitInteger} = add_int(x, y) As does the function for...
Disclaimer: In the Python ecosystem, this is not the job of the core language/runtime but rather tools such as IDEs. For example, the ipython shell has the ?? special syntax to get improved help including source code. Python 3.8.5 (default, Jul 21 2020, 10:42:08) Type 'copyright', 'credits' or 'license' for more inform...
8
5
64,692,669
2020-11-5
https://stackoverflow.com/questions/64692669/discord-bot-not-responding-to-commands-python
I've just gotten into writing discord bots. While trying to follow online instructions and tutorials, my bot would not respond to commands. It responded perfectly fine to on_message(), but no matter what I try it won't respond to commands. I'm sure it's something simple, but I would appreciate the help. import discord ...
Ok. First of all, the only import statement that you need at the top is from discord.ext import commands. The other two are not necessary. Second of all, I tried messing around with your code myself and found that the on_message() function seems to interfere with the commands so taking that out should help. Third of al...
5
0
64,677,450
2020-11-4
https://stackoverflow.com/questions/64677450/plotly-how-to-put-two-3d-graphs-on-the-same-plot-with-plotly-graph-objects
In below code, I draw 2 3D graphs with plotly.graph_objects. I'm unable to put them together. import plotly.graph_objects as go import numpy as np pts = np.loadtxt(np.DataSource().open('https://raw.githubusercontent.com/plotly/datasets/master/mesh_dataset.txt')) x, y, z = pts.T ### First graph fig = go.Figure(data=[go....
If you'd like to build on your first fig definition, just include the following after your first call to go.Figure() data = fig._data data is now a list which will have new elements appended to it in the rest of your already exising code under: for i,c in enumerate(coords): X1, Y1, Z1 = zip(c[0]) X2, Y2, Z2 = zip(c[1]...
6
5
64,686,981
2020-11-4
https://stackoverflow.com/questions/64686981/make-helix-from-two-objects
I have a plane and a sine curve in it. How to rotate these two objects, please? I mean to slowly incline the plane on the interval -0.1 to 0.4 in order to be, for instance, perpendicular to z at point 0.4? After longer rotation, the maximal and minimal value of the plane and sine would construct "the surface of a cylin...
To answer the title question, to create a helix, you are looking for a simple 3D function: amp, f = 1, 1 low, high = 0, math.pi*20 n = 1000 y = np.linspace(low, high, n) x = amp*np.cos(f*y) z = amp*np.sin(f*y) ax.plot(x,y,z) This gives: One way to find this yourself is to think about: what does it look like from each...
6
2
64,689,560
2020-11-5
https://stackoverflow.com/questions/64689560/measuring-the-distance-of-a-point-to-a-mask-in-opencv-python
Suppose that I have a mask of an object and a point. I want to find the closest point of the object mask to the point. For example, in my drawing, there is an object, the blue shape in the image (assume inside is also the part of the object mask). And the red point is the point from which I want to find the closest dis...
You could do a sort of binary search: let's call P your point and consider circles centred on P pick any point M on the mask, the circle through M will intersect the mask now repeat until convergence, if circle intersects mask, reduce radius otherwise increase it (by binary search type amounts) This will not work if ...
6
1
64,679,865
2020-11-4
https://stackoverflow.com/questions/64679865/error-while-installing-pytorch-using-pip-cannot-build-wheel
I get the following output when I try to run pip3 install pytorch or pip install pytorch Collecting pytorch Using cached pytorch-1.0.2.tar.gz (689 bytes) Building wheels for collected packages: pytorch Building wheel for pytorch (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/chaitany...
From your error: Exception: You tried to install "pytorch". The package named for PyTorch is "torch" which tells you what you need to know, instead of pip install pytorch it should be pip install torch I downloaded the matching wheel from here, but am couldn't figure out what to do with it Installing .whl files i...
14
38
64,676,672
2020-11-4
https://stackoverflow.com/questions/64676672/how-can-i-make-a-distance-matrix-with-own-metric-using-no-loop
I have a np.arrray like this: [[ 1.3 , 2.7 , 0.5 , NaN , NaN], [ 2.0 , 8.9 , 2.5 , 5.6 , 3.5], [ 0.6 , 3.4 , 9.5 , 7.4 , NaN]] And a function to compute the distance between two rows: def nan_manhattan(X, Y): nan_diff = np.absolute(X - Y) length = nan_diff.size return np.nansum(nan_diff) * length / (length - np.isnan(...
Leveraging broadcasting - def manhattan_nan(a): s = np.nansum(np.abs(a[:,None,:] - a), axis=-1) m = ~np.isnan(a) k = m.sum(1) r = a.shape[1]/np.minimum.outer(k,k) out = s*r return out Benchmarking From OP's comments, the use-case seems to be a tall array. Let's reproduce one for benchmarking re-using given sample data...
6
4
64,672,497
2020-11-4
https://stackoverflow.com/questions/64672497/unit-testing-mock-gcs
I have a hard time to find a way to make a unit test for the read and write methods present in this class. I am trying to create a mock with the mock patch library in order to avoid calling Google Storage but I have a hard time figure out how to do it. from google.cloud import storage class GCSObject(str): def __init__...
I am using google-cloud-storage==1.32.0 and python 3.7.5. Here is the unit test solution: gcs.py: from google.cloud import storage class GCSObject(str): def __init__(self, uri=""): self.base, self.bucket, self.path = self.parse_uri(uri) def parse_uri(self, uri): uri = uri.lstrip("gs://").replace("//", "/").split("/", 1...
6
8
64,613,706
2020-10-30
https://stackoverflow.com/questions/64613706/animate-update-a-matplotlib-plot-in-vs-code-notebook
Using Jupyter Notebook, I can create an animated plot (based on this sample code): %matplotlib notebook import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation fig, ax = plt.subplots() x = np.arange(0, 2*np.pi, 0.01) line, = ax.plot(x, np.sin(x)) def init(): line.set_ydata([np.nan] *...
Looks as though vscode supports ipywidgets (https://github.com/microsoft/vscode-python/issues/3429). So you can use the ipympl backend to matplotlib. install with pip install ipympl (also available on conda-forge) To use it you can use the %matplotlib ipympl magic. %matplotlib notebook does some javascript injection t...
22
34
64,610,269
2020-10-30
https://stackoverflow.com/questions/64610269/sqlalchemy-hangs-during-insert-while-querying-information-schema-tables
I have a Python process that uses SQLAlchemy to insert some data into a MS SQL Server DB. When the Python process runs it hangs during the insert. I turned on SQLAlchemy logging to get some more information. I found that it hangs at this point where SQLAlchemy seems to be requesting table schema info about the entire D...
As of pandas v.2.2.0 you can override the pandas method that runs the check which causes the block/deadlock. Add this before calling to_sql: from pandas.io.sql import SQLDatabase def pass_check_case_sensitive(*args, **kwargs): pass SQLDatabase.check_case_sensitive = pass_check_case_sensitive
8
2
64,631,086
2020-11-1
https://stackoverflow.com/questions/64631086/how-can-i-add-new-layers-on-pre-trained-model-with-pytorch-keras-example-given
I am working with Keras and trying to analyze the effects on accuracy that models which are built with some layers with meaningful weights, and some layers with random initializations. Keras: I load VGG19 pre-trained model with include_top = False parameter on load method. model = keras.applications.VGG19(include_top=F...
If all you want to do is to replace the classifier section, you can simply do so. That is : model = torch.hub.load('pytorch/vision:v0.6.0', 'vgg19', pretrained=True) model.classifier = nn.Linear(model.classifier[0].in_features, 4096) print(model) will give you: Before: VGG( (features): Sequential( (0): Conv2d(3, 64, k...
8
9
64,624,092
2020-10-31
https://stackoverflow.com/questions/64624092/how-to-solve-bug-on-snake-wall-teleportation
I'm doing a snake game and I got a bug I can't figure out how to solve, I want to make my snake teleport trough walls, when the snake colllides with a wall it teleports to another with the opposite speed and position, like the classic game, but with my code when the snake gets near the wall it duplicates to the opposit...
You want to implement a teleporter. Therefore, once the snake is over the edge of the window, you will have to teleport to the other side. The size of your window is 1020x585. The snake is out of the window if x == -15, y == -15, x == 1020 or y == 585 Hence you have to do the following teleportations: if x = 1020 tele...
6
4
64,630,130
2020-11-1
https://stackoverflow.com/questions/64630130/pipreqs-requirements-txt-is-not-correct
Hello I am having troubles with the pipreqs librairy in Python. It doesn't generate the correct requirements.txt file. I am using a Python Virtual Environment and the only packages I have installed are pipreqs and selenium with pip install pipreqs pip install selenium Structure of the project: MyProject |- test.py An...
So the issue I had was that my actual workspace was: MyProject |- .venv // <- My Python Virtual Environment |- test.py My Python Virtual Environment was in my Project folder so when I run the command pipreqs ./ it is looking at all the dependencies of all the files in the folder (including my virtual environment) and...
11
22
64,611,388
2020-10-30
https://stackoverflow.com/questions/64611388/exclude-a-function-from-coverage
I am using coverage.py to get the test coverage of the code. Suppose I have two functions with the same name in two different modules # foo/foo.py def get_something(): # fetch something # 10 line of branch code return "something foo/foo.py" # bar/foo.py def get_something(): # fetch something # 20 line of branch code re...
We can use pragma comment on the function definition level which tells the coveragepy to exclude the function completely. # bar/foo.py def get_something(): # pragma: no cover # fetch something # 20 line of branch code return "something bar/foo.py" Note If we have the coveragepy config file with an exclude_lines setting...
28
40
64,664,094
2020-11-3
https://stackoverflow.com/questions/64664094/i-cannot-use-opencv2-and-received-importerror-libgl-so-1-cannot-open-shared-obj
**env:**ubuntu16.04 anaconda3 python3.7.8 cuda10.0 gcc5.5 command: conda activate myenv python import cv2 error: Traceback (most recent call last): File "", line 1, in File "/home/.conda/envs/myenv/lib/python3.7/site-packages/cv2/__init__.py", line 5, in from .cv2 import * ImportError: libGL.so.1: cannot open shared o...
I have solved this problem! Firstly, find the file: find /usr -name libGL.so.1 I found /usr/lib/x86_64-linux-gnu/mesa/libGL.so.1. Then, I created a soft link: ln -s /usr/lib/x86_64-linux-gnu/mesa/libGL.so.1 /usr/lib/libGL.so.1 Finally, I verified that it is valid: # python import cv2
6
4
64,619,387
2020-10-31
https://stackoverflow.com/questions/64619387/how-to-call-the-linkedin-api-using-python
I tried so many methods, but none seem to work. Help me make a connection with LinkedIn using python. Issue in generating Access Token I received CODE but it doesn't work. I have python 3.9 Please post a sample of basic code that establishes a connection and gets a access Token. And which redirectUri I have to use. Can...
First solution valid for any (including free) applications, it useses so-called 3-Legged OAuth 2.0 Authentication: Login to your account in the browser. Create new application by this link. If you already have application you may use it by selecting it here and changing its options if needed. In application credential...
5
14
64,565,901
2020-10-28
https://stackoverflow.com/questions/64565901/how-to-retrieve-attributes-from-selected-datum-in-altair
I have a Streamlit dashboard which lets me interactively explore a t-SNE embedding using an Altair plot. I am trying to figure out how to access the metadata of the selected datum so that I can visualize the corresponding image. In other words, given: selector = alt.selection_single() chart = ( alt.Chart(df) .mark_circ...
I hate to disagree with the creator of Altair, but I was able to achieve this using streamlit-vega-lite package. This works by wrapping the call to the chart creation function with altair_component(): from streamlit_vega_lite import altair_component ... event_dict = altair_component(altair_chart=create_tsne_chart(tsne...
7
4
64,622,210
2020-10-31
https://stackoverflow.com/questions/64622210/how-to-extract-classes-from-prefetched-dataset-in-tensorflow-for-confusion-matri
I was trying to plot a confusion matrix for my image classifier with the following code but I got an error message: 'PrefetchDataset' object has no attribute 'classes' Y_pred = model.predict(validation_dataset) y_pred = np.argmax(Y_pred, axis=1) print('Confusion Matrix') print(confusion_matrix(validation_dataset.classe...
Disclaimer: this won't work for shuffled datasets. You can use tf.stack to concatenate all the dataset values. Like so: true_categories = tf.concat([y for x, y in test_dataset], axis=0) For reproducibility, let's say you have a dataset, a neural network, and a training loop: import tensorflow_datasets as tfds import t...
10
12
64,580,500
2020-10-28
https://stackoverflow.com/questions/64580500/sort-sounds-by-similarity-based-on-timbretone
Explanation I want to be able to sort a collection of sounds in a list based on the timbre(tone) of the sound. Here is a toy example where I manually sorted the spectrograms for 12 sound files that I created and uploaded to this repo. I know that these are sorted correctly because the sound produced for each file, is e...
I came up with a method, not sure if it does exactly what you are hoping but for your first dataset it is very close. Basically I'm looking at the power spectral density of the power spectral density of your .wav files and sorting by the normalized integral of that. (I have no good signal processing reason for doing th...
10
4
64,648,253
2020-11-2
https://stackoverflow.com/questions/64648253/error-img-empty-in-function-imwrite
I want to create frames from the video named project.avi and save them to frameIn folder. But some type of errors are not let me done. How can I solve this problem. Here is the code: cap = cv2.VideoCapture('project.avi') currentFrame = 0 while(True): ret, frame = cap.read() name = 'frameIn/frame' + str(currentFrame) + ...
The cause may be that image is empty, so, You should check weather video is opened correctly before read frames by: cap.isOpened(). Then, after execute ret, frame = cap.read() check ret variable value if true to ensure that frame is grabbed correctly. The code to be Clear : cap = cv2.VideoCapture('project.avi') if cap....
7
11
64,635,913
2020-11-1
https://stackoverflow.com/questions/64635913/why-im-getting-this-error-while-building-docker-image
I got the following error while building a docker image by "docker-compose build". ERROR: Couldn't connect to Docker daemon at http://127.0.0.1:2375 - is it running? If it's at a non-standard location, specify the URL with the DOCKER_HOST environment variable. Even if I try with "sudo", I got this: Building web Step 1...
Alpine Linux does not support the binary wheels Python packages ship under the manylinux tag, so you have to compile things like cffi and cryptography yourself. To do so you'll need a compiler and the correct set of headers. This is documented in the cryptography installation documentation for Alpine. Update September ...
7
14
64,663,862
2020-11-3
https://stackoverflow.com/questions/64663862/cant-install-h5py
I am trying to h5py on Windows10 64bit, Python 3.8.5, Pip 20.2.4. Used this command pip install h5py But this throws an error ERROR: Could not build wheels for h5py which use PEP 517 and cannot be installed directly Looks like it's quite known issue for pep 517 and other packages, so i try to check all of the solutio...
Found a solution - I was trying to install on Python3.8.5 32bit. Switching to 64bit just solved the issue. I saw that the latest version doesn't support win 32, check this: github.com/h5py/h5py/issues/1753
8
3
64,645,343
2020-11-2
https://stackoverflow.com/questions/64645343/plotly-update-subplot-titles-after-traces-where-created
I have a plotly plot composed of subplots - fig = make_subplots( rows=3, cols=1) fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]), row=1, col=1) fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]), row=2, col=1) fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]), row=3, col=1) I want to add a title for every one the ...
When make_subplots is used it's creating (correctly placed) annotations. So this can be mostly duplicated using annotation methods. In general, for the first: fig.add_annotation(xref="x domain",yref="y domain",x=0.5, y=1.2, showarrow=False, text="a", row=1, col=1) The downside is you may need to adjust x and y to your...
14
10
64,611,050
2020-10-30
https://stackoverflow.com/questions/64611050/python-change-exception-printable-output-eg-overload-builtins
I am searching for a way to change the printable output of an Exception to a silly message in order to learn more about python internals (and mess with a friend ;), so far without success. Consider the following code try: x # is not defined except NameError as exc: print(exc) The code shall output name 'x' is not defi...
I'll just explain the behaviour you described: exc.__repr__() This will just call your lambda function and return the expected string. Btw you should return the string, not print it in your lambda functions. print(repr(exc)) Now, this is going a different route in CPython and you can see this in a GDB session, it's...
8
1
64,611,957
2020-10-30
https://stackoverflow.com/questions/64611957/assertionerror-would-build-wheel-with-unsupported-tag-cp310-cp310-linux
I've got this message when I try to install numpy using Python 3.10. How to fix this? Copying numpy.egg-info to build/bdist.linux-x86_64/wheel/numpy-1.19.3-py3.10.egg-info running install_scripts Traceback (most recent call last): File "/home/walenty/.local/lib/python3.10/site-packages/pip/_vendor/pep517/_in_process.p...
It's a bug in python 3.10, a workaround is installing numpy with the --no-use-pep517 flag. E.g.: pip3.10 install numpy --no-use-pep517 There's a fix for this on the way though, so just waiting is an option as well.
7
8
64,654,838
2020-11-2
https://stackoverflow.com/questions/64654838/pytorch-tutorial-freeze-support-issue
I tried following the tutorial from PyTorch here: https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#sphx-glr-beginner-blitz-cifar10-tutorial-py. Full code is here: import torch import torchvision import torchvision.transforms as transforms import matplotlib.pyplot as plt import numpy as np import torch...
To anyone else with this issue, I believe you need to define a main function and run the training there. Then add: if __name__ == '__main__': main() at the end of the python file. This fixed the freeze_support() issue for me on a different PyTorch training program.
7
12
64,596,394
2020-10-29
https://stackoverflow.com/questions/64596394/importerror-cannot-import-name-docevents-from-botocore-docs-bcdoc-in-aws-co
ImportError: cannot import name 'docevents' from 'botocore.docs.bcdoc' (/python3.7/site-packages/botocore/docs/bcdoc/init.py) Traceback (most recent call last): File "/root/.pyenv/versions/3.7.6/bin/aws", line 19, in <module> import awscli.clidriver File "/root/.pyenv/versions/3.7.6/lib/python3.7/site-packages/awscli/c...
Reading this GitHub issue #2596. i fixed my error. Just before the PRE_BUILD section, I added this line to my buildspec-cd.yml file: pip3 install --upgrade awscli install: commands: - pip3 install awsebcli --upgrade - eb --version - pip3 install --upgrade awscli pre_build: commands: - AWS_REGION=${AWS_DEFAULT_REGION} -...
85
176
64,654,805
2020-11-2
https://stackoverflow.com/questions/64654805/how-do-you-fix-runtimeerror-package-fails-to-pass-a-sanity-check-for-numpy-an
This is the error I am getting and, as far as I can tell, there is nothing useful on the error link to fix this. RuntimeError: The current Numpy installation ('...\\venv\\lib\\site-packages\\numpy\\__init__.py') fails to pass a sanity check due to a bug in the windows runtime. See this issue for more information: htt...
This error occurs when using python3.9 and numpy1.19.4 So uninstalling numpy1.19.4 and installing 1.19.3 will work. Edit As of January 5th 2021 numpy version 1.19.5 is out and appears to solve the problem.
140
193
64,588,486
2020-10-29
https://stackoverflow.com/questions/64588486/address-already-in-use-fastapi
I keep getting [Errno 98] Address already in use But the address is not in use. I tried to change the ip and port but It isn't budging. from fastapi import FastAPI app = FastAPI() @app.get("/") async def main(): return {"message": "Helloworld,FastAPI"} if __name__ == '__main__': import uvicorn uvicorn.run(app, host="1...
Basically, you can do this. This will kill the process that listens TCP connections on port 8000 sudo lsof -t -i tcp:8000 | xargs kill -9
21
52
64,638,010
2020-11-1
https://stackoverflow.com/questions/64638010/compare-csv-files-content-with-filecmp-and-ignore-metadata
import filecmp comparison = filecmp.dircmp(dir_local, dir_server) comparison.report_full_closure() I want to compare all CSV files kept on my local machine to files kept on a server. The folder structure is the same for both of them. I only want to do a data comparison and not metadata (like time of creation, etc). I ...
There are multiple ways to compare the .csv files between the 2 repositories (server file system and local file system). Method 1: using hashlib This method uses the Python module hashlib. I used the hashing algorithm sha256 to compute the hash digest for the files. I compare the hashes for files with the exact file n...
8
6
64,639,526
2020-11-2
https://stackoverflow.com/questions/64639526/numba-data-type-error-cannot-unify-array
I am using Numba to speed up a series of functions as shown below. if I set the step_size variable in function PosMomentSingle to a float (e.g. step_size = 0.5), instead of an integer (e.g step_size = 1.0), I get the following error: Cannot unify array(float32, 1d, C) and array(float64, 1d, C) for 'axle_coords.2', defi...
After removing all type conversions in your code, the following error was returned TypingError: Cannot unify array(int64, 1d, C) and array(float64, 1d, C) for 'axle_coords.2' This helped me to trace back the error to the dtype of spacings. In your code this initialized as a C compatible single, which seems to be diffe...
9
9
64,665,978
2020-11-3
https://stackoverflow.com/questions/64665978/any-workaround-to-do-forward-forecasting-for-estimating-time-series-in-python
I want to make forward forecasting for monthly times series of air pollution data such as what would be 3~6 months ahead of estimation on air pollution index. I tried scikit-learn models for forecasting and fitting data to the model works fine. But what I wanted to do is making a forward period estimate such as what wo...
In order to obtain your desired output, I think you need to use a model that can return the standard deviation in the predicted value. Therefore, I adopt Gaussian process regression. From the code you provided in your post, I don't see how this is a time series forecasting task, so in my solution below, I also treat th...
6
3
64,648,186
2020-11-2
https://stackoverflow.com/questions/64648186/using-a-data-converter-to-display-3d-volume-as-images
I would like to write a data converter tool. I need analyze the bitstream in a file to display the 2D cross-sections of a 3D volume. The dataset I am trying to view can be found here: https://figshare.com/articles/SSOCT_test_dataset_for_OCTproZ/12356705. It's the file titled: burned_wood_with_tape_1664x512x256_12bit.ra...
Down below I implemented next visualization. Example RAW file burned_wood_with_tape_1664x512x256_12bit.raw consists of 1664 samples per A-scan, 512 A-scans per B-scan, 16 B-scans per buffer, 16 buffers per volume, and 2 volumes in this file, each sample is encoded as 2-bytes unsigned integer in little endian order, onl...
6
1
64,658,304
2020-11-3
https://stackoverflow.com/questions/64658304/determining-lunar-eclipse-in-skyfield
I am given a list of dates in UTC, all hours cast to 00:00. I'd like to determine if a (lunar) eclipse occurred in a given day (ie past 24 hours) Considering the python snippet from sykfield.api import load eph = load('de421.bsp') def eclipticangle(t): moon, earth = eph['moon'], eph['earth'] e = earth.at(t) x, y, _ = e...
I just went through section 11.2.3 of the Explanatory Supplement to the Astronomical Almanac and tried turning it into Skyfield Python code. Here is what I came up with: import numpy as np from skyfield.api import load from skyfield.constants import ERAD from skyfield.functions import angle_between, length_of from skyf...
7
9
64,622,708
2020-10-31
https://stackoverflow.com/questions/64622708/typing-how-to-bind-owner-class-to-generic-descriptor
Can I implement a generic descriptor in Python in a way it will support/respect/understand inheritance hierarchy of his owners? It should be more clear in the code: from typing import ( Generic, Optional, TYPE_CHECKING, Type, TypeVar, Union, overload, ) T = TypeVar("T", bound="A") # noqa class Descr(Generic[T]): @overl...
I am not sure if you need to have the descriptor class as generic; it will probably just suffice to have __get__ on an instance of Type[T] to return T: T = TypeVar("T") # noqa class Descr: @overload def __get__(self, instance: None, owner: Type[T]) -> "Descr": ... @overload def __get__(self, instance: T, owner: Type[T]...
8
8
64,664,813
2020-11-3
https://stackoverflow.com/questions/64664813/get-the-public-ipv4-address-of-a-newly-created-amazon-ec2-instance-with-boto3
I am creating a ec2 instance with boto3 and I want print the ip address of that new instance. ec2 = boto3.resource('ec2') # create the instance new_instance = ec2.create_instances( ImageId='###', MinCount = 1, MaxCount = 1, InstanceType = 't2.nano', KeyName = "key", SecurityGroupIds = ["###"] ) ... wait until running ....
ec2.create_instances returns a list of ec2.Instance objects. ec2.Instance objects have an attribute named private_ip_address. You can use that to get the private IP address. A side note (based on the comments in your code example) you can also use the wait_until_running waiter to have your code halt until the instance ...
5
11
64,613,552
2020-10-30
https://stackoverflow.com/questions/64613552/gcloud-sdk-install-for-mac
I have an issue to install the gcloud sdk on my mac. I have the following error when I do the ./install.sh. Source: https://cloud.google.com/sdk/docs/quickstart Welcome to the Google Cloud SDK! Traceback (most recent call last): File "/Users/kevin/Downloads/google-cloud-sdk/bin/bootstrapping/install.py", line 12, in <m...
This is a known issue across Mac, Windows and Linux: https://issuetracker.google.com/170125513. I'd suggest to use the recommended Python versions mentioned here (3.5 to 3.8). Also this does not affect only to Cloud SDK but others as well (for example as mentioned here).
5
5
64,644,449
2020-11-2
https://stackoverflow.com/questions/64644449/recover-from-segfault-in-python
I have a few functions in my code that are randomly causing SegmentationFault error. I've identified them by enabling the faulthandler. I'm a bit stuck and have no idea how to reliably eliminate this problem. I'm thinking about some workaround. Since the functions are crashing randomly, I could potentially retry them a...
I had some unreliable C extensions throw segfaults every once in a while and, since there was no way I was going to be able to fix that, what I did was create a decorator that would run the wrapped function in a separate process. That way you can stop segfaults from killing the main process. Something like this: https:...
6
16
64,660,458
2020-11-3
https://stackoverflow.com/questions/64660458/how-to-properly-deprecate-a-custom-exception-in-python
I have custom inheriting exceptions in my Python project and I want to deprecate one of them. What is the proper way of doing it? Exceptions I have: class SDKException(Exception): pass class ChildException(SDKException): pass class ChildChildException(ChildException): # this one is to be deprecated pass I want to depr...
You could use a decorator which shows a warning DeprecationWarning category on each instantiation of exception class: import warnings warnings.filterwarnings("default", category=DeprecationWarning) def deprecated(cls): original_init = cls.__init__ def __init__(self, *args, **kwargs): warnings.warn(f"{cls.__name__} is d...
8
4
64,670,318
2020-11-3
https://stackoverflow.com/questions/64670318/how-to-create-a-new-conda-env-based-on-a-yml-file-but-with-different-python-vers
I have a conda environment with python=3.6.0 and all it's dependencies. Now I would like to use this yaml file to create another environment with the same dependencies but with python=3.7.0 without the need for installing the packages with right version one by one.
# Activate old environment conda activate so # Save the list of package to a file: conda list > log # Extract the package name but not the version or hash cat log | awk '{print $1}' > log2 # make the list of packages tr '\n' ' ' < log2 > log3 # print the list of packages cat log3 Use notepad to replace python by pytho...
6
1
64,669,355
2020-11-3
https://stackoverflow.com/questions/64669355/how-to-copy-download-file-created-in-pyodide-in-browser
I managed to run Pyodide in browser. I created hello.txt file. But how can I access it. Pyodide https://github.com/iodide-project/pyodide/blob/master/docs/using_pyodide_from_javascript.md pyodide.runPython('open("hello.txt", "w")') What I tried in chrome devtools? pyodide.runPython('os.chdir("../")') pyodide.runPytho...
Indeed pyodide operates in an in-memory (MEMFS) filesystem created by Emscripten. You can't directly write files to disk from pyodide since it's executed in the browser sandbox. You can however, pass your file to JavaScript, create a Blob out of it and then download it. For instance, using, let txt = pyodide.runPython(...
8
7
64,666,718
2020-11-3
https://stackoverflow.com/questions/64666718/dataframe-removes-duplicate-when-certain-values-are-reached
I have a data frame that contains duplicates. and I would like to remove these duplicates. I also found this function from pandas df.drop_duplicates(subset=['Action', 'Name']). Unfortunately, this function removes too much, because only if the time is less than or equal to 5 minutes should it be removed. How can I do t...
IIUC you can create a group number by getting the time difference, and then groupby and first: print (df.assign(group=pd.to_datetime(df["Time"]).diff().dt.seconds.gt(300).cumsum()) .groupby(["group", "Action", "Name"]).first()) Time Action Name group 0 01.10.2019, 9:56:52 Opened Max 1 02.10.2019 12:56:12 Closed Susan 2...
6
2
64,664,437
2020-11-3
https://stackoverflow.com/questions/64664437/how-do-you-open-multiple-pages-asynchronously-with-playwright-python
I want to open multiple urls at once using Playwright for Python. But I am struggling to figure out how. This is from the async documentation: async def main(): async with async_playwright() as p: for browser_type in [p.chromium, p.firefox, p.webkit]: browser = await browser_type.launch() page = await browser.newPage()...
I believe you need to call your go_to_url function using the same recipe: asyncio.get_event_loop().run_until_complete(go_to_url())
8
1
64,662,085
2020-11-3
https://stackoverflow.com/questions/64662085/fix-not-load-dynamic-library-for-tensorflow-gpu
I want to use my GPU for Tensorflow. I tried this Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Unfortunately, I keep getting an error Could not load dynamic library 'cudart64_110.dll'; dlerror: cudart64_110.dll not found. How can I fix this? Python-version: 3.8.3, CUDA 10.1 2020...
Well, you can see that your Tensorflow installation is looking for Cuda libraries of version 11, 10, while you have 10.1. So in order to fix this, install the proper Cuda version. Why is it looking for 3 different versions, I have no idea. But you can find valid combinations of Cuda, Tensorflow, and CUDNN here. EDIT: R...
9
3
64,636,104
2020-11-1
https://stackoverflow.com/questions/64636104/websocket-handshaking-error-in-python-django
I am getting issue with websocket connection as it is getting closed due to handshake error. The error message is as below: WebSocket HANDSHAKING /ws/polData/ [127.0.0.1:59304] Exception inside application: object.__init__() takes exactly one argument (the instance to initialize) Traceback (most recent call last): File...
Check your routing.py in app, under websocket_urlpatterns, on repath you may have missed .as_asgi() eg:- websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), ]
5
17
64,597,425
2020-10-29
https://stackoverflow.com/questions/64597425/how-to-set-a-repr-for-a-function-itself
__repr__ is used to return a string representation of an object, but in Python a function is also an object itself, and can have attributes. How do I set the __repr__ of a function? I see here that an attribute can be set for a function outside the function, but typically one sets a __repr__ within the object definitio...
I think a custom decorator could help: import functools class reprable: """Decorates a function with a repr method. Example: >>> @reprable ... def foo(): ... '''Does something cool.''' ... return 4 ... >>> foo() 4 >>> foo.__name__ 'foo' >>> foo.__doc__ 'Does something cool.' >>> repr(foo) 'foo: Does something cool.' >>...
5
4
64,650,877
2020-11-2
https://stackoverflow.com/questions/64650877/install-of-opencv-python-headless-takes-a-long-time
When I install opencv-python-headless in Google Colab, it takes 15 minutes to complete. My code: ! pip install --upgrade pip ! pip install opencv-python-headless Here's a notebook with this code which recreates the problem: https://colab.research.google.com/gist/mherzog01/38b6cf71942a443da072f09bc097387f/slow-install-...
Might be related to changes in OpenCV >=4.3 wheels https://github.com/skvark/opencv-python#backward-compatibility Starting from 4.3.0 and 3.4.10 builds the Linux build environment was updated from manylinux1 to manylinux2014. This dropped support for old Linux distributions. My workaround: pip install "opencv-python-...
8
12
64,590,535
2020-10-29
https://stackoverflow.com/questions/64590535/how-to-make-pipenv-install-package-use-ssl-certificate-of-firewall
Sitting behind a very strict firewall with SSL decryption, I usually install python packages (on macOS 10.15.) with these options pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org <packagename>. But pipenv install --trusted-host pypi.org --trusted-host files.pythonhosted.org <packagename> doesn'...
As already stated in the comments, setting the environment variable would solve the problem. It should look like this: export REQUESTS_CA_BUNDLE=/path/to/certificates.pem Complete Chain In certificates.pem you must have a complete chain that includes the root certificate. Therefore certificates.pem should look like th...
10
18
64,646,867
2020-11-2
https://stackoverflow.com/questions/64646867/downloading-huggingface-pre-trained-models
Once I have downloaded a pre-trained model on a Colab Notebook, it disappears after I reset the notebook variables. Is there a way I can download the model to use it for a second occasion? tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
Mount your google drive: from google.colab import drive drive.mount('/content/drive') Do your stuff and save your models: from transformers import BertTokenizer tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') tokenizer.save_pretrained('/content/drive/My Drive/tokenizer/') Reload it in a new session: to...
5
12
64,643,427
2020-11-2
https://stackoverflow.com/questions/64643427/python-regular-expressions-in-xpaths-using-selenium
I try to get the id of certain HTML tags using Python and Selenium. There is html code: <tr id="10"> <td colspan="5"> <div class="card-view"> <span class="value">PROVIDER_628_54678931</span> </div> </td> </tr> <tr id="11"> <td colspan="5"> <div class="card-view"> <span class="value">PROVIDER_629_54678932</span> </div> ...
I found solution here : link def findTrunksByRegExp(): pattern = re.compile(r"PROVIDER_6\d{2}") elements = browser.find_elements_by_xpath("//span[contains(@class, 'value')]") for element in elements: match = pattern.match(element.text) if match: parent = element.find_element_by_xpath('../../..') print(parent.get_attrib...
6
4
64,603,280
2020-10-30
https://stackoverflow.com/questions/64603280/finding-a-pattern-in-a-grid-python
I have randomly generated grid containing 0 and 1: 1 1 0 0 0 1 0 1 1 1 1 0 1 1 1 1 1 0 0 0 1 0 1 1 0 0 1 0 1 0 1 1 1 1 1 1 0 0 1 1 0 0 1 1 1 1 1 0 0 1 0 0 1 0 1 1 How can I iterate through the grid to find the largest cluster of 1s, that is equal or larger than 4 items (across row and column)? I assume I need to keep a...
I've implemented three algorithms. First algorithm is Simple, using easiest approach of nested loops, it has O(N^5) time complexity (where N is one side of input grid, 10 for our case), for our inputs of size 10x10 time of O(10^5) is quite alright. Algo id in code is algo = 0. If you just want to see this algorithm jum...
9
2
64,635,630
2020-11-1
https://stackoverflow.com/questions/64635630/pytorch-runtimeerror-expected-scalar-type-float-but-found-byte
I am working on the classic example with digits. I want to create a my first neural network that predict the labels of digit images {0,1,2,3,4,5,6,7,8,9}. So the first column of train.txt has the labels and all the other columns are the features of each label. I have defined a class to import my data: class DigitDatase...
This line is the cause of your error: images = self.data.iloc[idx, 1:-1].values.astype(np.uint8).reshape((1, 16, 16)) images are uint8 (byte) while the neural network needs inputs as floating point in order to calculate gradients (you can't calculate gradients for backprop using integers as those are not continuous an...
15
20
64,633,018
2020-11-1
https://stackoverflow.com/questions/64633018/removing-white-or-light-colors-from-matplotlib-color-palette
The matplotlib color palettes often feature white or very light colors which do not show up well on scatter or line plots. I am making a plot in which I use norm = mpl.colors.Normalize(vmin=0, vmax=1) cmap = mpl.cm.ScalarMappable(norm=norm, cmap=mpl.cm.Blues) plt.plot(x, y, c=cmap.to_rgba(z)) cbar = plt.colorbar(cmap) ...
You can easily create a custom colormap using LinearSegmentedColormap and choosing the colors that you want (in this case, a subset of the original colormap) min_val, max_val = 0.3,1.0 n = 10 orig_cmap = plt.cm.Blues colors = orig_cmap(np.linspace(min_val, max_val, n)) cmap = matplotlib.colors.LinearSegmentedColormap.f...
6
10
64,631,371
2020-11-1
https://stackoverflow.com/questions/64631371/unpivot-multiindex-dataframe-with-pd-melt
I would like to unpivot a DataFrame with MultiIndex columns, but I struggle to get the exact output I want. I played with all the parameters of the pd.melt() function but couldn't make it... Here is the kind of input I have : import pandas as pd indexes = [['TC1', 'TC2'], ['x', 'z', 'Temp']] data = pd.DataFrame(columns...
Give this a try data_out = data.stack(level=0).rename_axis(['Time','TC']).reset_index() Out[87]: Time TC Temp x z 0 0 TC1 250 10 100 1 0 TC2 255 20 200
5
7
64,617,670
2020-10-31
https://stackoverflow.com/questions/64617670/best-way-for-installing-non-conda-dependencies-in-snakemake-conda-environments
I would like to be able to install R packages from GitHub in a R conda environment created by Snakemake, as well as python libraries via pip in a python environment. I'll use these environments in a whole set of rules thereafter. My initial thought was to create a rule running a script to install the specified packages...
I think there are quite a few wrong things: remotes::install_github("ramiromagno/gwasrapidd", upgrade = "never"): In your r.yaml you should include the remotes package. !pip install gseapy is not valid python code. If anything, it is code to be executed by shell but I'm not sure that leading ! is correct. Also, gseap...
6
2
64,629,702
2020-11-1
https://stackoverflow.com/questions/64629702/pytorch-transform-totensor-changes-image
I want to convert images to tensor using torchvision.transforms.ToTensor(). After processing, I printed the image but the image was not right. Here is my code: trans = transforms.Compose([ transforms.ToTensor()]) demo = Image.open(img) demo_img = trans(demo) demo_array = demo_img.numpy()*255 print(Image.fromarray(demo_...
It seems that the problem is with the channel axis. If you look at torchvision.transforms docs, especially on ToTensor() Converts a PIL Image or numpy.ndarray (H x W x C) in the range [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0] So once you perform the transformation and return to nump...
10
20
64,626,073
2020-10-31
https://stackoverflow.com/questions/64626073/solve-equation-with-sum-and-index-using-sympy
After having tried many things, I thought it would be good to ask on SO. My problem is fairly simple: how can I solve the following equation using Sympy? Equation I want to solve this for lambda_0 and q is an array of size J containing elments between 0 and 1 that sum op to 1 (discrete probability distribution). I trie...
List p needs to be converted into symbolic array before it can be indexed with symbolic value j. from sympy.solvers import solve from sympy import symbols, summation, Array p = Array([0.2, 0.3, 0.3, 0.1, 0.1]) l, j = symbols('l j') eq = summation(j * (1 - p[j]) / (l - j), (j, 0, 4)) s = solve(eq - 1, l) # [1.1317576214...
6
2
64,627,112
2020-10-31
https://stackoverflow.com/questions/64627112/adding-multiple-columns-in-pyspark-dataframe-using-a-loop
I need to add a number of columns (4000) into the data frame in pyspark. I am using the withColumn function, but getting assertion error. df3 = df2.withColumn("['ftr' + str(i) for i in range(0, 4000)]", [expr('ftr[' + str(x) + ']') for x in range(0, 4000)]) Not sure what is wrong.
Try to do something like this: df2 = df3 for i in range(0, 4000): df2 = df2.withColumn(f"ftr{i}", lit(f"frt{i}"))
6
2
64,621,585
2020-10-31
https://stackoverflow.com/questions/64621585/pytorch-optimizer-adamw-and-adam-with-weight-decay
Is there any difference between torch.optim.Adam(weight_decay=0.01) and torch.optim.AdamW(weight_decay=0.01)? Link to the docs: torch.optim.
Yes, Adam and AdamW weight decay are different. Hutter pointed out in their paper (Decoupled Weight Decay Regularization) that the way weight decay is implemented in Adam in every library seems to be wrong, and proposed a simple way (which they call AdamW) to fix it. In Adam, the weight decay is usually implemented b...
65
66
64,618,631
2020-10-31
https://stackoverflow.com/questions/64618631/how-to-filter-and-paginate-in-listview-django
I have a problem when I want to paginate the filter that I create with django_filter, in my template it shows me the query set and filter but paginate does not work, I would like to know why this happens and if you could help me. I'll insert snippets of my code so you can see. This is my views.py PD: i have all the nec...
You should override get_queryset.This means you have to put your filter in get_queryset like this: @method_decorator(staff_member_required, name='dispatch') class EmployeeListView(ListView): model = Employee paginate_by = 4 def dispatch(self, request, *args, **kwargs): if not request.user.has_perm('employee.view_employ...
7
8
64,617,770
2020-10-31
https://stackoverflow.com/questions/64617770/why-pytest-deselect-all-the-tests-when-run-with-python-m-test
I can run my tests by executing (on Windows) pytest .\tests\test_x.py Result: ================================= test session starts ================================== platform win32 -- Python 3.8.3, pytest-5.4.3, py-1.9.0, pluggy-0.13.1 rootdir: C:\Users\...... collected 9 items tests\test_x.py ......... [100%] ======...
You're using -m which filters which tests to run according to how you mark your tests. You're telling pytest to only run tests tagged @pytest.mark.test. Presumably, you don't have any tests marked as such. https://docs.pytest.org/en/stable/example/markers.html#mark-run
6
5
64,616,582
2020-10-30
https://stackoverflow.com/questions/64616582/unordered-list-as-dict-key
I want to be able to do something like: foo = Counter(['bar', 'shoo', 'bar']) tmp = {} tmp[foo] = 5 In other words, is there a hashable equivalent for Counter? Note that I can't use frozenset since I have repeated elements that I want to keep in the key. Edit: In my actual application, the objects in foo may not be co...
What you seem to require is a way to use unordered pairs of key-amount as keys. A frozenset is probably the way to go, although you will have to create it out of the items of the Counter and not its keys. foo = Counter(['bar', 'shoo', 'bar']) tmp = {} tmp[frozenset(foo.items())] = 5 # tmp: {frozenset({('bar', 2), ('sho...
8
4
64,616,462
2020-10-30
https://stackoverflow.com/questions/64616462/python-how-to-decode-jwt-header
I have a token that includes the following header eyJraWQiOiI4NkQ4OEtmIiwiYWxnIjoiUlMyNTYifQ. How can I obtain the following JSON decoding of it as jwt.io provides? { "kid": "86D88Kf", "alg": "RS256" } jwt.decode() doesn't give this header. Thanks!
This is an unencrpyted header. Its a URL-safe base64 encoding of a JSON encoding of the data you want. You need to add padding characters to the end of the encoded string to make sure its on a 4 character boundary, then decode. >>> import json >>> import base64 >>> token = "eyJraWQiOiI4NkQ4OEtmIiwiYWxnIjoiUlMyNTYifQ" >...
5
14
64,616,163
2020-10-30
https://stackoverflow.com/questions/64616163/pandas-read-csv-ignore-ending-semicolon-of-last-column
My data file looks like this: data.txt user,activity,timestamp,x-axis,y-axis,z-axis 0,33,Jogging,49105962326000,-0.6946376999999999,12.680544,0.50395286; 1,33,Jogging,49106062271000,5.012288,11.264028,0.95342433; 2,33,Jogging,49106112167000,4.903325,10.882658000000001,-0.08172209; 3,33,Jogging,49106222305000,-0.6129156...
The problem with your txt is that it has mixed content. As I can see the header doesn't have the semicolon as termination character If you change the first line adding the semicolon it's quite simple pd.read_csv("data.txt", lineterminator=";")
14
14
64,615,988
2020-10-30
https://stackoverflow.com/questions/64615988/what-does-vertical-bar-pipe-in-function-arguments-type-annotations-mean
I came across function with signature like this: def get_quantile(numbers: List[float], q: float | int ) -> float | int | None : What does it mean? It's a syntax error on my python 3.8. Do I need to import something from future to make it work?
According to PEP 604, | will be used to designate union types from Python 3.10. So float | int will mean Union[float, int], i.e. a float or an int.
19
31
64,567,464
2020-10-28
https://stackoverflow.com/questions/64567464/mask-0-values-during-normalization
I am doing normalization for datasets but the data contains a lot of 0 because of padding. I can mask them during model training but apparently, these zero will be affected when I applied normalization. from sklearn.preprocessing import StandardScaler,MinMaxScaler I am currently using the Sklearn library to do the norm...
The task of just MinMaxScaler() masking can be solved by next code. Each other operation needs separate way of handling, if you'll mention all operations that need masking then we can solve them one-by-one basis and I'll extend my answer. E.g. keras layers can be masked by tf.keras.layers.Masking() layer as you mention...
8
3
64,594,493
2020-10-29
https://stackoverflow.com/questions/64594493/filter-out-nan-values-from-a-pytorch-n-dimensional-tensor
This question is very similar to filtering np.nan values from pytorch in a -Dimensional tensor. The difference is that I want to apply the same concept to tensors of 2 or higher dimensions. I have a tensor that looks like this: import torch tensor = torch.Tensor( [[1, 1, 1, 1, 1], [float('nan'), float('nan'), float('na...
Use PyTorch's isnan() together with any() to slice tensor's rows using the obtained boolean mask as follows: filtered_tensor = tensor[~torch.any(tensor.isnan(),dim=1)] Note that this will drop any row that has a nan value in it. If you want to drop only rows where all values are nan replace torch.any with torch.all. F...
7
11
64,594,693
2020-10-29
https://stackoverflow.com/questions/64594693/how-to-delete-multiple-defined-and-undefined-variables-safely-in-python
I am currently using jupyter notebook, and I want to delete variables that are used only within the cell, so that I won't accidentally misuse these variables in other cells. For example, I want to remove the variable myvar and loop variable i in the following codes: start = 1 stop = 2 for i in range(start, stop): pass ...
A one-liner to do del x safely: globals().pop('x', None); There are many ways to do that, but they need more than 1 line of code, which I guess is not what you look for. Note ; at the end, which prevents the variable from being printed by Jupiter.
9
3
64,591,665
2020-10-29
https://stackoverflow.com/questions/64591665/unpacking-x-y-x-y-x-y-what-is-the-difference
What is the difference in Python between unpacking a function call with [], with () or with nothing? def f(): return 0, 1 a, b = f() # 1 [a, b] = f() # 2 (a, b) = f() # 3
There is no difference. Regardless of what kind of syntactic sequence you use, the same byte code is generated. >>> def f(): ... return 0, 1 ... >>> import dis >>> dis.dis('[a,b] = f()') 1 0 LOAD_NAME 0 (f) 2 CALL_FUNCTION 0 4 UNPACK_SEQUENCE 2 6 STORE_NAME 1 (a) 8 STORE_NAME 2 (b) 10 LOAD_CONST 0 (None) 12 RETURN_VALU...
30
36
64,590,557
2020-10-29
https://stackoverflow.com/questions/64590557/how-to-get-the-predict-proba-for-the-class-predicted-by-predict-in-random-fo
from sklearn import ensemble model = ensemble.RandomForestClassifier(n_estimators=10) model.fit(x,y) predictions = model.predict(new) I know predict() uses predict_proba() to get the predictions, by computing the mean of the predicted class probabilities of the trees in the forest. I want to get the result of predict_...
The predict_proba() method returns a two-dimensional array, containing the estimated probabilities for each instance and each class: import numpy as np from sklearn.ensemble import RandomForestClassifier X = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) y = np.array([0, 0, 1, 1]) model = RandomForestClassif...
7
12
64,579,258
2020-10-28
https://stackoverflow.com/questions/64579258/sentence-embedding-using-t5
I would like to use state-of-the-art LM T5 to get sentence embedding vector. I found this repository https://github.com/UKPLab/sentence-transformers As I know, in BERT I should take the first token as [CLS] token, and it will be the sentence embedding. In this repository I see the same behaviour on T5 model: cls_tokens...
In order to obtain the sentence embedding from the T5, you need to take the take the last_hidden_state from the T5 encoder output: model.encoder(input_ids=s, attention_mask=attn, return_dict=True) pooled_sentence = output.last_hidden_state # shape is [batch_size, seq_len, hidden_size] # pooled_sentence will represent t...
6
7
64,579,002
2020-10-28
https://stackoverflow.com/questions/64579002/error-when-installing-pywin32-on-ubuntu
I'm trying to install the pywin32 module on Ubuntu for python 3.6, I've tried pip3 install pywin32 and got the following output: Collecting pywin32 Could not find a version that satisfies the requirement pywin32 (from versions: ) No matching distribution found for pywin32 Then I tried pip3 install pypiwin32 and got th...
The pywin32 and pypiwin32 is "Python extensions for Microsoft Windows Provides access to much of the Win32 API, the ability to create and use COM objects, and the Pythonwin environment." One supported OS is Microsoft Windows, because you can access the Win32 API only from Windows. Source: https://pypi.org/project/pywi...
8
7
64,569,062
2020-10-28
https://stackoverflow.com/questions/64569062/how-to-handle-custom-exceptions-with-grpc-in-python
I need to implement custom exceptions for handling gRPC request errors with Python. For HTTP requests it's straightforward - requests library catches it well when there's an error code etc. I am looking for analogous ways for gRPC to do something like: try: # send gRPC request except SomeGRPCException as e: # custom ha...
For simple RPC error handling, you can use try-catch: try: response = stub.SayHello(...) except grpc.RpcError as rpc_error: if rpc_error.code() == grpc.StatusCode.CANCELLED: pass elif rpc_error.code() == grpc.StatusCode.UNAVAILABLE: pass else: print(f"Received unknown RPC error: code={rpc_error.code()} message={rpc_err...
9
16
64,577,138
2020-10-28
https://stackoverflow.com/questions/64577138/implement-iter-and-next-in-different
I'm reading a book on Python which illustrates how to implement the iterator protocol. class Fibbs: def __init__(self): self.a = 0 self.b = 1 def __next__(self): self.a, self.b = self.b, self.a + self.b return self.a def __iter__(self): return self Here, self itself is the iterable and iterator, I believe? However, th...
How you make iterators and iterables There are two ways to do this: Implement __iter__ to return self and nothing else, implement __next__ on the same class. You've written an iterator. Implement __iter__ to return some other object that follows the rules of #1 (a cheap way to do this is to write it as a generator fun...
7
20
64,568,775
2020-10-28
https://stackoverflow.com/questions/64568775/tf-idf-vectorizer-to-extract-ngrams
How can I use TF-IDF vectorizer from the scikit-learn library to extract unigrams and bigrams of tweets? I want to train a classifier with the output. This is the code from scikit-learn: from sklearn.feature_extraction.text import TfidfVectorizer corpus = [ 'This is the first document.', 'This document is the second do...
TfidfVectorizer has an ngram_range parameter to determin the range of n-grams you want in the final matrix as new features. In your case, you want (1,2) to go from unigrams to bigrams: vectorizer = TfidfVectorizer(ngram_range=(1,2)) X = vectorizer.fit_transform(corpus).todense() pd.DataFrame(X, columns=vectorizer.get_f...
7
4
64,522,040
2020-10-25
https://stackoverflow.com/questions/64522040/dynamically-create-literal-alias-from-list-of-valid-values
I have a function which validates its argument to accept only values from a given list of valid options. Typing-wise, I reflect this behavior using a Literal type alias, like so: from typing import Literal VALID_ARGUMENTS = ['foo', 'bar'] Argument = Literal['foo', 'bar'] def func(argument: 'Argument') -> None: if argum...
Go the other way around, and build VALID_ARGUMENTS from Argument: Argument = typing.Literal['foo', 'bar'] VALID_ARGUMENTS: typing.Tuple[Argument, ...] = typing.get_args(Argument) I've used a tuple for VALID_ARGUMENTS here, but if for some reason you really prefer a list, you can get one: VALID_ARGUMENTS: typing.List[A...
98
109
64,535,462
2020-10-26
https://stackoverflow.com/questions/64535462/plotly-how-to-change-line-style-using-px-line
I have dataframe tha tlooks similar to this: >>>Hour Level value 0 7 H 1.435 1 7 M 3.124 2 7 L 5.578 3 8 H 0.435 4 8 M 2.124 5 8 L 4.578 I want to create line chart in plotly that will have different line style based in the column "level". Right now I have the line chart with the deafult line style: import plotly.grap...
One way you can set different styles through variables in your dataframe is: line_dash='Level' Plot Complete code import plotly.graph_objects as go import pandas as pd import numpy as np import plotly.io as pio import plotly.express as px group = pd.DataFrame({'Hour': {0: 7, 1: 7, 2: 7, 3: 8, 4: 8, 5: 8}, 'Level': {0...
9
12
64,530,101
2020-10-26
https://stackoverflow.com/questions/64530101/the-black-formatter-python
I just started using the 'Black' formatter module with Visual Studio Code. Everything was going well till I just noticed that it uses double quotes over single quotes which I already was using in my code... And it overrode that... So, is there an Black argument that I could add to Visual Studio Code which solves this p...
You can use the --skip-string-normalization option at the command line, or in your Visual Studio Code options. See The Black code style, Strings. For example: { ... "python.formatting.provider": "black", "python.formatting.blackArgs": [ "--skip-string-normalization", "--line-length", "100" ] ... }
12
28
64,517,048
2020-10-24
https://stackoverflow.com/questions/64517048/pandas-loc-and-pep8
I've tried to search this a number of times but I don't see it answered so here goes... I often use pandas to clean up a dataframe and conform it to my needs. With this comes a lot of .loc accessing to query it and return values. Depending on what I am doing (and column lengths), this can get pretty lengthy. Given PEP8...
I'd advise two things Ignore PEP 8's 80 char advice, but try to keep to 120 or 150 lines Keeping some line length requirement makes sense to aid readability, but if you're trying to keep to 80 chars in (for example) a class method, it will lead to worse and less-readable code PEP 8 actually has a section on this, A Fo...
6
7
64,506,283
2020-10-23
https://stackoverflow.com/questions/64506283/create-a-pandas-table
In using pandas, how can I display a table similar to this one. I think I have to use a dataframe similar to df = pandas.DataFrame(results) and display it with display.display(df) but from there I don't know what to do?
You can pass in a dictionary as data when you use pd.DataFrame: >>> import pandas as pd >>> d = { ... 'Algothime': ['KNN', 'SVM', 'MLP'], ... 'Param. 1': ['-', '-', '-'], ... 'Param. 2': ['-', '-', '-'], ... 'Plage param. 1': ['-', '-', '-'], ... 'Plage param. 2': ['-', '-', '-'], ... } >>> df = pd.DataFrame(data=d) >>...
6
7
64,467,644
2020-10-21
https://stackoverflow.com/questions/64467644/add-density-curve-on-the-histogram
I am able to make histogram in python but I am unable to add density curve , I see many code which are using different ways to add density curve on histogram but I am not sure how to get on my code I have added density = true but not able to get density curve on histogram df = pd.DataFrame(np.random.randn(100, 4), colu...
distplot has been removed: removed in a future version of seaborn. Therefore, alternatives are to use histplot and displot. sns.histplot import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD')) X = df['A'] sns.histplot(...
7
6
64,462,578
2020-10-21
https://stackoverflow.com/questions/64462578/laplace-transform-using-numerical-integration-in-python-has-very-poor-precision
I have written a function to compute the Laplace transform of a function using scipy.integrate.quad. It is not a very sophisticated function and currently performs poorly on the probability density function of an Erlang distribution. I have included all my work below. I first compute the Laplace transform and then the ...
Good day. I am repeating the Updates section from the original questions as this is the solution to the questions. This way, the questions can be marked as resolved. UPDATE After two cups of VERY strong coffee, I managed to see the obvious mistake and make the code work. It quite embarrassing actually. Have a look at t...
8
1
64,495,333
2020-10-23
https://stackoverflow.com/questions/64495333/pydantic-dynamically-create-a-model-with-multiple-base-classes
From the pydantic docs I understand this: import pydantic class User(pydantic.BaseModel): id: int name: str class Student(pydantic.BaseModel): semester: int # this works as expected class Student_User(User, Student): building: str print(Student_User.__fields__.keys()) #> dict_keys(['semester', 'id', 'name', 'building']...
As of pydantic==1.9.2, Student_User2 = pydantic.create_model("Student_User2", __base__=(User, Student), building=(str, ...)) runs successfully and print(Student_User2.__fields__.keys()) returns dict_keys(['semester', 'id', 'name', 'building'])
8
5
64,558,200
2020-10-27
https://stackoverflow.com/questions/64558200/python-requests-in-docker-compose-containers
Problem I have a 2-container docker-compose.yml file. One of the containers is a small FastAPI app. The other is just trying to hit the API using Python's requests package. I can access the app container from outside with the exact same code as is in the Python package trying to hit it, and it works, but it will not ...
Within the Docker network, applications must be accessed with the service names defined in the docker-compose.yml. If you're trying to access the toy-api service, use get_from_api(session, path="http://toy-api/test") You can access the application via http://localhost/test on your host machine because Docker exposes t...
12
2
64,499,294
2020-10-23
https://stackoverflow.com/questions/64499294/validate-on-entire-validation-set-when-using-ddp-backend-with-pytorch-lightning
I'm training an image classification model with PyTorch Lightning and running on a machine with more than one GPU, so I use the recommended distributed backend for best performance ddp (DataDistributedParallel). This naturally splits up the dataset, so each GPU will only ever see one part of the data. However, for vali...
training_epoch_end() and validation_epoch_end() receive data that is aggregated from all training / validation batches of the particular process. They simply receive a list of what you returned in each training or validation step. When using the DDP backend, there's a separate process running for every GPU. There's no ...
7
6
64,517,793
2020-10-24
https://stackoverflow.com/questions/64517793/why-is-this-function-slower-in-jax-vs-numpy
I have the following numpy function as seen below that I'm trying to optimize by using JAX but for whatever reason, it's slower. Could someone point out what I can do to improve the performance here? I suspect it has to do with the list comprehension taking place for Cg_new but breaking that apart doesn't yield any fur...
For general considerations on benchmark comparisons between JAX and NumPy, see https://jax.readthedocs.io/en/latest/faq.html#is-jax-faster-than-numpy As for your particular code: when JAX jit compilation encounters Python control flow, including list comprehensions, it effectively flattens the loop and stages the full ...
5
11
64,559,768
2020-10-27
https://stackoverflow.com/questions/64559768/flask-socketio-import-wont-work-error-no-module-named-flask-socketio
Im trying to create connection between flask socketio and react native socketio, I have already prepared client side with react native socketio BUT I have run into problem with importing flask_socketio in rpi. Im trying to use simplest implementation possible, this is my code: from flask import Flask from flask_socke...
Problem was that I was installing it with sudo python pip install flask_socketio, BUT I had to use python3, so right installation is python3 -m pip install flask_socketio
5
8
64,514,398
2020-10-24
https://stackoverflow.com/questions/64514398/python-multiprocessing-within-flask-request-with-gunicorn-nginx
I want to build a service that will be able to handle: a low volume of requests a high compute cost for each request but where the high compute cost can be parallelized. My understanding of a pre-fork server is that something like the following happens: server starts Gunicorn creates multiple OS processes, also call...
Great question! With Python multiprocessing, there are 3 "start methods" that can be used, and they all have implications for your questions. As the docs explain, they are: 'spawn': The parent process starts a fresh python interpreter process. The child process will only inherit those resources necessary to run the p...
29
32
64,457,733
2020-10-21
https://stackoverflow.com/questions/64457733/django-dumpdata-fails-on-special-characters
I'm trying to dump my entire DB to a json. When I run python manage.py dumpdata > data.json I get an error: (env) PS C:\dev\watch_something> python manage.py dumpdata > data.json CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefined> Exce...
One solution is to use ./manage.py dumpdata -o data.json instead of ./manage.py dumpdata > data.json. Another solution is to use Python's UTF-8 mode, run: python -Xutf8 ./manage.py dumpdata > data.json
24
92
64,555,101
2020-10-27
https://stackoverflow.com/questions/64555101/receive-an-error-from-lingnutls-hogweed-when-importing-cv2
I've never seen an error like this and don't know where to start. I installed opencv with conda install opencv and am running Ubuntu Linux 18.04 using a conda environment named fpn. How should I even approach debugging this? Traceback (most recent call last): File "test.py", line 5, in <module> import cv2 ImportError:...
There seems to be a problem with the recent releases of opencv packages for Conda. I have tested all the 4.x releases and found that the problem occurs starting from 4.3. Unless you really depend on >=4.3, forcing a version prior to 4.3 solves the problem, name: test channels: - anaconda - conda-forge dependencies: - p...
7
2
64,517,366
2020-10-24
https://stackoverflow.com/questions/64517366/python-error-while-installing-matplotlib
OS: Windows 10 Python ver: 3.9.0 Error code: ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. I tried: python -m pip install -U pip python -m pip install -U matplotlib didn't work. and then I tried: pip install --upgrade setuptools didn't solve the probl...
edit: matplotlib has now released wheels for python 3.9 so pip install --upgrade matplotlib should work. original answer matplotlib hasn't made a wheel yet for version 3.9 so your python attempted to build it from source. You should downgrade to python 3.8 and then everything should work
7
8