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 |
|---|---|---|---|---|---|---|
62,541,192 | 2020-6-23 | https://stackoverflow.com/questions/62541192/display-pytorch-tensor-as-image-using-matplotlib | I am trying to display an image stored as a pytorch tensor. trainset = datasets.ImageFolder('data/Cat_Dog_data/train/', transform=transforms) trainload = torch.utils.data.DataLoader(trainset, batch_size=32, shuffle=True) images, labels = iter(trainload).next() image = images[0] image.shape >>> torch.Size([3, 224, 224])... | That's very odd. Try putting the channels last by permuting rather than reshaping: image.permute(1, 2, 0) | 8 | 16 |
62,537,703 | 2020-6-23 | https://stackoverflow.com/questions/62537703/how-to-find-inflection-point-in-python | I have a histogram of an image in RGB which represents the three curves of the three components R, G and B. I want to find the inflection points of each curve. I used the second derivative to find them but I can't, the second derivative does not cancel its returns null. So how can I find the inflection point? Is there ... | There are two issues of numerical nature with your code: the data does not seem to be continuous enough to rely on the second derivative computed from two subsequent np.diff() applications even if it were, the chances of it being exactly 0 are very slim To address the first point, you should smooth your histogram (e.... | 12 | 28 |
62,518,389 | 2020-6-22 | https://stackoverflow.com/questions/62518389/how-to-convert-a-dataframe-of-counts-to-a-probability-density-function | Suppose that I have the following observations of integers: df = pd.DataFrame({'observed_scores': [100, 100, 90, 85, 100, ...]}) I know that this can be used as an input to make a density plot: df['observed_scores'].plot.density() but suppose that what I have is a counts table: df = pd.DataFrame({'observed_scores': [... | IIUC, statsmodels lets you fit a weighted KDE: from statsmodels.nonparametric.kde import KDEUnivariate df = pd.DataFrame({'observed_scores': [100, 95, 90, 85], 'counts': [1534, 1399, 3421, 8764]}) kde1= KDEUnivariate(df.observed_scores) kde_noweight = KDEUnivariate(df.observed_scores) kde1.fit(weights=df.counts, fft=Fa... | 8 | 3 |
62,536,189 | 2020-6-23 | https://stackoverflow.com/questions/62536189/select-rows-where-value-of-column-a-starts-with-value-of-column-b | I have a pandas dataframe and want to select rows where values of a column starts with values of another column. I have tried the following: import pandas as pd df = pd.DataFrame({'A': ['apple', 'xyz', 'aa'], 'B': ['app', 'b', 'aa']}) df_subset = df[df['A'].str.startswith(df['B'])] But it errors out and this solutions... | For row wise comparison, we can use DataFrame.apply: m = df.apply(lambda x: x['A'].startswith(x['B']), axis=1) df[m] A B 0 apple app 2 aa aa The reason your code is not working is because Series.str.startswith accepts a character sequence (a string scalar), and you are using a pandas Series. Quoting the docs: pat : s... | 7 | 8 |
62,532,237 | 2020-6-23 | https://stackoverflow.com/questions/62532237/how-can-i-create-an-api-token-on-pypi-for-a-new-project | I am trying to upload a package to PyPI using API tokens. I would like to use a project specific API token instead of an account specific token, as this seems more secure. However, since the project is not created on PyPI yet, there is no project for me to select when I try to create a new API token on the PyPI website... | So the question is then, how can I create an API token for a not-yet-created PyPI project? You cannot, for sure! Create and use a token for the account; later you can replace it with a project token. | 8 | 4 |
62,525,771 | 2020-6-23 | https://stackoverflow.com/questions/62525771/python-range-with-uneven-gap | Today I had a python exam where following question was asked: Given the following code extract, Complete the code so the output is: 10 7 5. nums = list (range (?,?,?)) print(nums) How is it possible to get such output in python using range function? | not sure if this answer the question, provided we can fill in any syntax to the ? as long it produce the result. 1st ? = 10 2nd ? = 4 3rd ? = -3))+(([5] # nums = list(range( ? , ? , ? )) nums = list(range( 10 , 4 , -3))+(([5] )) print(nums) # nums = [10,7,5] | 23 | 28 |
62,525,295 | 2020-6-22 | https://stackoverflow.com/questions/62525295/how-to-use-python-to-schedule-tasks-in-a-django-application | I'm new to Django and web frameworks in general. I have an app that is all set up and works perfectly fine on my localhost. The program uses Twitter's API to gather a bunch of tweets and displays them to the user. The only problem is I need my python program that gets the tweets to be run in the background every-so-oft... | I've encountered a similar situation and have had a lot of success with django-apscheduler. It is all self-contained - it runs with the Django server and jobs are tracked in the Django database, so you don't have to configure any external cron jobs or anything to call a script. Below is a basic way to get up and runnin... | 10 | 30 |
62,519,791 | 2020-6-22 | https://stackoverflow.com/questions/62519791/finding-duplicates-in-two-dataframes-and-removing-the-duplicates-from-one-datafr | Working in Python / pandas / dataframes I have these two dataframes: Dataframe one: 1 2 3 1 Stockholm 100 250 2 Stockholm 150 376 3 Stockholm 105 235 4 Stockholm 109 104 5 Burnley 145 234 6 Burnley 100 250 Dataframe two: 1 2 3 1 Stockholm 100 250 2 Stockholm 117 128 3 Stockholm 105 235 4 Stockholm 100 250 5 Burnley ... | Use: df_merge = pd.merge(df1, df2, on=[1,2,3], how='inner') df1 = df1.append(df_merge) df1['Duplicated'] = df1.duplicated(keep=False) # keep=False marks the duplicated row with a True df_final = df1[~df1['Duplicated']] # selects only rows which are not duplicated. del df_final['Duplicated'] # delete the indicator colum... | 11 | 11 |
62,436,766 | 2020-6-17 | https://stackoverflow.com/questions/62436766/cant-login-to-instagram-using-requests | I'm trying to login to Instagram using requests library. I succeeded using following script, however it doesn't work anymore. The password field becomes encrypted (checked the dev tools while logging in manually). I've tried : import re import requests from bs4 import BeautifulSoup link = 'https://www.instagram.com/acc... | You can use authentication version 0 - plain password, no encryption: import re import requests from bs4 import BeautifulSoup from datetime import datetime link = 'https://www.instagram.com/accounts/login/' login_url = 'https://www.instagram.com/accounts/login/ajax/' time = int(datetime.now().timestamp()) payload = { '... | 8 | 24 |
62,521,777 | 2020-6-22 | https://stackoverflow.com/questions/62521777/how-to-declare-python-dataclass-member-field-same-as-the-dataclass-type | How can I have a member field of a dataclass same as the class name in python3.7+ ? I am trying to define a class like so (which can be done in Java or C++) -- which might be used as a class for LinkedList node @dataclass class Node: val:str next:Node prev:Node However, all I get is NameError: name 'Node' is not defin... | You need to add the following import to your file from __future__ import annotations This enables deferred annotations, which are proposed in PEP 563. Deferred annotations allow you to reference a class that is not yet defined, in your example the Node class is not defined when you are still in it's body | 9 | 15 |
62,522,117 | 2020-6-22 | https://stackoverflow.com/questions/62522117/how-to-calculate-execution-time-of-a-view-in-django | This is my view: def post_detail(request, year, month, day, slug): post = get_object_or_404(models.Post, slug=slug, status='published', publish__year=year, publish__month=month, publish__day=day) comment_form = forms.CommentForm() comments = post.comments.filter(active=True) context = { 'comments': comments, 'post': po... | You can write a timer decorator to output the results in your console from functools import wraps import time def timer(func): """helper function to estimate view execution time""" @wraps(func) # used for copying func metadata def wrapper(*args, **kwargs): # record start time start = time.time() # func execution result... | 7 | 12 |
62,513,005 | 2020-6-22 | https://stackoverflow.com/questions/62513005/how-does-poetry-work-regarding-binary-dependencies-esp-numpy | Until now I have been using conda as virtual environment and dependency management. However, some stuff does not work as expected when transfering my environment.yml file from my development machine to the production server. Now, I would like to look into alternatives. Poetry seems nice, especially because poetry also... | numpy provides several wheel files for different os, cpu architecture and python versions. wheel packages are precompiled, so the target system doesn't have to compile the package. poetry is able to choose the right wheel for you, depending on your system. Saying this, I would recommend using poetry, as long as you jus... | 15 | 9 |
62,505,041 | 2020-6-21 | https://stackoverflow.com/questions/62505041/add-autopep8-and-linting-to-jupyter-in-vs-code-python-notebook | Question Error highlighting and autoformatting can be great tools to help one create great notebooks. I am trying to change the settings on the VS code to allow me to autoformat to pep8 in my python notebooks. On this page for Jupiter notebooks have found that I have to put some lines in my .json files in the settings>... | Nbextensions are notebook extensions and only work within the notebook itself. VS Code does not support native notebooks so these extensions won't work at the time. They are planning to add it in future releases per link | 9 | 6 |
62,498,436 | 2020-6-21 | https://stackoverflow.com/questions/62498436/how-to-run-a-django-project-with-pyc-files-without-using-source-codes | I have a django project and i want to create the .pyc files and remove the source code. My project folder name is mysite and I ran the command python -m compileall mysite. The .pyc files are created. After that i tried to run my project with python __pycache__/manage.cpython-37.pyc runserver command but i've got an err... | First of all, I created a new folder in another directory such as a new django project and i created my app folders, static folder, templates folder etc. manually as the same as my django project architecture that I created before. Then, I moved the .pyc files that I created with the compileall command to my new projec... | 8 | 3 |
62,500,697 | 2020-6-21 | https://stackoverflow.com/questions/62500697/django-model-attribute-and-database-field-with-different-name-in-model | I have a database table called Person contains following columns: Id, first_name, last_name, So is there any way to assign different name to table fields in django model. like this class Person(models.Model): firstname = models.CharField(max_length = 30) lastname = models.CharField(max_length = 30) firstname instead... | You can pass db_column to the field to customise the column name for a field class Person(models.Model): firstname = models.CharField(max_length=30, db_column='first_name') lastname = models.CharField(max_length=30, db_column='last_name') | 7 | 12 |
62,495,381 | 2020-6-21 | https://stackoverflow.com/questions/62495381/how-to-compare-2-files-having-random-numbers-in-non-sequential-order | There are 2 files named compare 1.txt and compare2.txt having random numbers in non-sequential order cat compare1.txt 57 11 13 3 889 014 91 cat compare2.txt 003 889 13 14 57 12 90 Aim Output list of all the numbers which are present in compare1 but not in compare 2 and vice versa If any number has zero in its prefi... | Could you please try following, written and tested with shown samples in GNU awk. awk ' { $0=$0+0 } FNR==NR{ a[$0] next } ($0 in a){ b[$0] next } { print } END{ for(j in a){ if(!(j in b)){ print j } } } ' compare1.txt compare2.txt Explanation: Adding detailed explanation for above. awk ' ##Starting awk program from he... | 13 | 14 |
62,497,603 | 2020-6-21 | https://stackoverflow.com/questions/62497603/is-there-a-plugin-similar-to-gitlens-for-pycharm-or-other-products | My question is very simple , as you read the title I want plugin similar to GitLens that I found in vscode. As you know with GitLens you can easily see the difference between two or multiple commits. I searched it up and I found GitToolBox but I don't know how to install it as well and I don't think that's like GitLens... | You can use Git Toolbox link here. Features : Git status: number of ahead / behind commits for current branch as status bar widget ahead / behind, current branch, tags on HEAD as Project View decoration on modules status bar widget with detailed information and additional actions Git blame: inline blame - show blam... | 10 | 15 |
62,498,581 | 2020-6-21 | https://stackoverflow.com/questions/62498581/typeerror-when-merging-dictionaries-unsupported-operand-types-for-dict-a | I wanted to join two dictionaries using | operator and I got the following error: TypeError: unsupported operand type(s) for |: 'dict' and 'dict' The MWE code is the following: d1 = {'k': 1, 'l': 2, 'm':4} d2 = {'g': 3, 'm': 7} e = d1 | d2 | The merge (|) and update (|=) operators for dictionaries were introduced in Python 3.9 so they do not work in older versions. You have an option to either update your Python interpreter to Python 3.9 or use one of the alternatives: # option 1: e = d1.copy() e.update(d2) # option 2: e = {**d1, **d2} However, should you... | 9 | 8 |
62,446,077 | 2020-6-18 | https://stackoverflow.com/questions/62446077/0-accuracy-with-lstm | I trained LSTM classification model, but got weird results (0 accuracy). Here is my dataset with preprocessing steps: import pandas as pd from sklearn.model_selection import train_test_split import tensorflow as tf from tensorflow import keras import numpy as np url = 'https://raw.githubusercontent.com/MislavSag/tradem... | You're using sigmoid activation, which means your labels must be in range 0 and 1. But in your case, the labels are 1. and -1. Just replace -1 with 0. for i, y in enumerate(y_train_lstm): if y == -1.: y_train_lstm[i,:] = 0. for i, y in enumerate(y_val_lstm): if y == -1.: y_val_lstm[i,:] = 0. for i, y in enumerate(y_tes... | 8 | 7 |
62,493,590 | 2020-6-21 | https://stackoverflow.com/questions/62493590/creating-a-new-column-assigning-same-index-to-repeated-values-in-pandas-datafram | How can I generate a new column listing repeated values? For example, my dataframe is: id color 123 white 123 white 123 white 345 blue 345 blue 678 red This is the desired output: # id color 1 123 white 1 123 white 1 123 white 2 345 blue 2 345 blue 3 678 red | Check withfactorize df['#']=df.id.factorize()[0]+1 df id color # 0 123 white 1 1 123 white 1 2 123 white 1 3 345 blue 2 4 345 blue 2 5 678 red 3 Another method df.groupby('id').ngroup()+1 0 1 1 1 2 1 3 2 4 2 5 3 dtype: int64 To add it to the first positon: df.insert(loc=0, column='#', value=df.id.factorize()[0]+1) df... | 7 | 10 |
62,475,443 | 2020-6-19 | https://stackoverflow.com/questions/62475443/regex-to-find-a-pair-of-adjacent-digits-with-different-digits-around-them | I want to find if there are two of the same digits next to each other, and the digit behind and in front of the pair is different. For example, 123456678 should match as there is a double 6, 1234566678 should not match as there is no double with different surrounding numbers. 12334566 should match because there are two... | With regex, it is much more convenient to use a PyPi regex module with the (*SKIP)(*FAIL) based pattern: import regex rx = r'(\d)\1{2,}(*SKIP)(*F)|(\d)\2' l = ["123456678", "1234566678"] for s in l: print(s, bool(regex.search(rx, s)) ) See the Python demo. Output: 123456678 True 1234566678 False Regex details (\d)\1... | 58 | 33 |
62,487,112 | 2020-6-20 | https://stackoverflow.com/questions/62487112/python-issue-with-for-loop-and-append | I'm having trouble understanding the output of a piece of python code. mani=[] nima=[] for i in range(3) nima.append(i) mani.append(nima) print(mani) The output is [[0,1,2], [0,1,2], [0,1,2]] I can't for the life of me understand why it is not [[0], [0,1], [0,1,2]] Any help much appreciated. | It's because when you append nima into mani, it isn't a copy of nima, but a reference to nima. So as nima changes, the reference at each location in mani, just points to the changed nima. Since nima ends up as [0, 1, 2], then each reference appended into mani, just refers to the same object. | 9 | 6 |
62,484,597 | 2020-6-20 | https://stackoverflow.com/questions/62484597/understanding-width-shift-range-and-height-shift-range-arguments-in-kerass | The Keras documentation of ImageDataGenerator class says— width_shift_range: Float, 1-D array-like or int - float: fraction of total width, if < 1, or pixels if >= 1. - 1-D array-like: random elements from the array. - int: integer number of pixels from interval (-width_shift_range, +width_shift_range) - With width_sh... | These two argument used by ImageDataGenerator class Which use to preprocess image before feeding it into network. If you want to make your model more robust then small amount of data is not enough. That is where data augmentation come in handy. This are used to generate random data. width_shift_range: It actually shift... | 26 | 31 |
62,478,839 | 2020-6-19 | https://stackoverflow.com/questions/62478839/sklearn-set-config-is-erroring | I am facing an issue where the sklearn set_config is failing. I am using Google Colab and also it is failing on Jupyter Notebook as well. Even the code when copied from https://scikit-learn.org/stable/auto_examples/release_highlights/plot_release_highlights_0_23_0.html#sphx-glr-auto-examples-release-highlights-plot-rel... | You need to upgrade scikit-learn on colab, its version is 'v0.22.2.post1', while display parameter in set_config() function was introduced in v0.23. !pip install --upgrade scikit-learn Then, restart the runtime, display should work now. | 10 | 15 |
62,479,386 | 2020-6-19 | https://stackoverflow.com/questions/62479386/no-module-named-application-error-while-deploying-simple-web-app-to-elastic-be | I am deploying a web app to elastic beanstalk using this tutorial and the same 'application.py' file they have: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-flask.html#python-flask-setup-venv I get a 502 error when going to the site, and degraded/severe health on the environment. When I c... | A possible reason is the use of Amazon Linux 2 environment, instead of Amazon Linux 1. The list of python environments and their linux distributions is here. From the link you provided: In this tutorial we use Python 3.6 and the corresponding Elastic Beanstalk platform version. The Python 3.6 is supported in Amazon... | 13 | 6 |
62,479,608 | 2020-6-19 | https://stackoverflow.com/questions/62479608/lambdatype-vs-functiontype | What's the difference? docs show nothing on this, and their help() is identical. Is there an object for which isinstance will fail with one but not other? | Back in 1994 I wasn't sure that we would always be using the same implementation type for lambda and def. That's all there is to it. It would be a pain to remove it, so we're just leaving it (it's only one line). If you want to add a note to the docs, feel free to submit a PR. | 13 | 26 |
62,475,991 | 2020-6-19 | https://stackoverflow.com/questions/62475991/how-to-write-an-app-layout-in-dash-such-that-two-graphs-are-side-by-side | I want to plot two charts side by side (and not one above the other) in Dash by Plotly. The tutorials did not have an example where the graphs are plotted side by side. I am writing the app.layout in the following way app.layout = html.Div(className = 'row', children= [ html.H1("Tips database analysis (First dashboard)... | You can achieve this by wrapping the graphs in a div and adding display: inline-block css property to each of the graphs. app.layout = html.Div(className='row', children=[ html.H1("Tips database analysis (First dashboard)"), dcc.Dropdown(), html.Div(children=[ dcc.Graph(id="graph1", style={'display': 'inline-block'}),... | 13 | 22 |
62,470,743 | 2020-6-19 | https://stackoverflow.com/questions/62470743/change-line-width-of-specific-line-in-line-plot-pandas-matplotlib | I am plotting a dataframe that looks like this. Date 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 Date 01 Jan 12.896 13.353 12.959 13.011 13.073 12.721 12.643 12.484 12.876 13.102 02 Jan 12.915 13.421 12.961 13.103 13.125 12.806 12.644 12.600 12.956 13.075 03 Jan 12.926 13.379 13.012 13.116 13.112 12.790 12.713 12... | You can iterate over the lines in the plot, which can be retrieved with ax.get_lines, and increase the width using set_linewidth if its label matches the value of interest: fig, ax = plt.subplots() df.plot(figsize=(20,12), title='Arctic Sea Ice Extent', lw=3, fontsize=16, ax=ax, grid=True) for line in ax.get_lines(): i... | 12 | 21 |
62,470,439 | 2020-6-19 | https://stackoverflow.com/questions/62470439/vscode-python-jedienabled-false-showing-as-unknown-configuration-setting | this is the settings.json file code { "python.autoComplete.addBrackets": true, "python.linting.enabled": true, "python.pythonPath": "C:\\Program Files\\Python37\\python.exe", "python.jediEnabled": false, "python.languageServer": "Microsoft" } in this "python.jediEnabled": false, showing error that Unknown Configurati... | With vscode-python's release on June 16th 2020 they removed the python.jediEnabled setting in favor for the python.languageServer setting. From the changelog: Removed python.jediEnabled setting in favor of python.languageServer. Instead of "python.jediEnabled": true please use "python.languageServer": "Jedi". (#7010) | 8 | 17 |
62,455,693 | 2020-6-18 | https://stackoverflow.com/questions/62455693/access-all-column-values-of-joined-tables-with-sqlalchemy | Imagine one has two SQL tables objects_stock id | number and objects_prop id | obj_id | color | weight that should be joined on objects_stock.id=objects_prop.obj_id, hence the plain SQL-query reads select * from objects_prop join objects_stock on objects_stock.id = objects_prop.obj_id; How can this query be performe... | Just in case someone encounters a similar problem: the best way I have found so far is listing the columns to fetch explicitly, query = session.query(ObjectsStock.id, ObjectsStock.number, ObjectsProp.color, ObjectsProp.weight).\ select_from(ObjectsStock).join(ObjectsProp, ObjectsStock.id == ObjectsProp.obj_id) results... | 8 | 7 |
62,460,182 | 2020-6-18 | https://stackoverflow.com/questions/62460182/how-to-invoke-another-command-inside-another-one-in-discord-py | I want my bot to play a specific song when typing +playtest using already defined function (+play) but i got an error says "Discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'Command' object is not callable" an entire code work perfectly fine except for this command i wonder doe... | ctx.invoke does allow passing arguments, but they need to be handled in a different way to how you may be used to ( function(params) ) The parameters must be explicitly shown in the invoke (e.g. param = 'value') and the command must be a command object. This would be how you could invoke a command: @commands.command() ... | 8 | 12 |
62,429,677 | 2020-6-17 | https://stackoverflow.com/questions/62429677/how-to-use-str-replace-to-replace-multiple-pairs-at-once | Currently I am using the following code to make replacements which is a little cumbersome: df1['CompanyA'] = df1['CompanyA'].str.replace('.','') df1['CompanyA'] = df1['CompanyA'].str.replace('-','') df1['CompanyA'] = df1['CompanyA'].str.replace(',','') df1['CompanyA'] = df1['CompanyA'].str.replace('ltd','limited') df1[... | You can create a dictionary and pass it to the function replace() without needing to chain or name the function so many times. replacers = {',':'','.':'','-':'','ltd':'limited'} #etc.... df1['CompanyA'] = df1['CompanyA'].replace(replacers) | 11 | 29 |
62,459,704 | 2020-6-18 | https://stackoverflow.com/questions/62459704/np-reshape-with-padding-if-there-are-not-enough-elements | Is it possible to reshape a np.array() and, in case of inconsistency of the new shape, fill the empty spaces with NaN? Ex: arr = np.array([1,2,3,4,5,6]) Target, for instance a 2x4 Matrix: [1 2 3 4] [5 6 NaN NaN] I need this to bypass the error: ValueError: cannot reshape array of size 6 into shape (2,4) | We'll use np.pad first, then reshape: m, n = 2, 4 np.pad(arr.astype(float), (0, m*n - arr.size), mode='constant', constant_values=np.nan).reshape(m,n) array([[ 1., 2., 3., 4.], [ 5., 6., nan, nan]]) The assumption here is that arr is a 1D array. Add an assertion before this code to fail on unexpected cases. | 7 | 12 |
62,436,382 | 2020-6-17 | https://stackoverflow.com/questions/62436382/how-to-get-the-name-of-a-property-in-python | How do you get the name of a property in python? Any suggestions welcome. For functions and methods it is as simple as f.__name__. But properties do not have the __name__ attribute. | The property does not have a name, but you are probably really looking for the name of its fget attribute, which (ignoring any shuffling done after the fact) will be the name of the class attribute to which the property instance is bound. class A: @property def foo(self): return 3 assert A.foo.fget.__name__ == "foo" | 8 | 14 |
62,453,270 | 2020-6-18 | https://stackoverflow.com/questions/62453270/why-do-different-strings-have-the-same-id-in-python | It is stated that strings are immutable objects, and when we make changes in that variable it actually creates a new string object. So I wanted to test this phenomenon with this piece of code: result_str = "" print("string 1 (unedited):", id(result_str)) for a in range(1,11): result_str = result_str + str(a) print(f"st... | The string you associate with result_str create reaches end of lifetime at the next assignment. Hence the possibility of duplicate id. Here's the doc Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlappin... | 9 | 4 |
62,449,983 | 2020-6-18 | https://stackoverflow.com/questions/62449983/how-to-specify-return-value-of-mocked-function-with-pytest-mock | The below prints False. Is this not how mocking works? I tried changing the path to the function, but it errors out, so the path seems correct. What am I missing? import pytest from deals.services.services import is_user_valid class TestApi: def test_api(self, mocker): mocker.patch('deals.services.services.is_user_vali... | The issue here is that you're essentially doing the following: from deals.services.services import is_user_valid import deals.services.services deals.services.services.is_user_valid = Mock(return_value=True) # call local is_user_valid By importing the "terminal" symbol itself you've shorted any possibility of mocking,... | 20 | 20 |
62,449,644 | 2020-6-18 | https://stackoverflow.com/questions/62449644/multiple-insert-columns-if-not-exist-pandas | I have the following df list_columns = ['A', 'B', 'C'] list_data = [ [1, '2', 3], [4, '4', 5], [1, '2', 3], [4, '4', 6] ] df = pd.DataFrame(columns=list_columns, data=list_data) I want to check if multiple columns exist, and if not to create them. Example: If B,C,D do not exist, create them(For the above df it will ... | Here loop is not necessary - use DataFrame.reindex with Index.union: cols = ['B','C','D'] df = df.reindex(df.columns.union(cols, sort=False), axis=1, fill_value=0) print (df) A B C D 0 1 2 3 0 1 4 4 5 0 2 1 2 3 0 3 4 4 6 0 | 18 | 27 |
62,440,193 | 2020-6-17 | https://stackoverflow.com/questions/62440193/passing-multiple-parameters-in-threadpoolexecutor-map | The following code: import concurrent.futures def worker(item, truefalse): print(item, truefalse) return item processed = [] with concurrent.futures.ThreadPoolExecutor() as pool: for res in pool.map(worker, [1,2,3], False): processed.append(res) Yields an exception: TypeError: zip argument #2 must support iteration I ... | If you're trying to call the worker function with 1, False, then 2, False, then 3, False, you need to extend your single False to an iterable of Falses at least as long as the other iterable. Two approaches that work: Multiply a sequence: for res in pool.map(worker, [1,2,3], [False] * 3): Use itertools.repeat to make... | 12 | 25 |
62,436,786 | 2020-6-17 | https://stackoverflow.com/questions/62436786/attributeerror-module-time-has-no-attribute-clock-in-sqlalchemy-python-3-8 | Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\Anirudh\Documents\flask_app\connecting_to_database\application.py", line 2, in <module> from flask_sqlalchemy import SQLAlchemy File "C:\Users\Anirudh\AppData\Local\Programs\Python\Python38\lib\site-packages\flask_sqlalchemy\__init__.... | The error occurs because in python 2, there is time.clock(), but in python 3, it has been replaced with time.perf_counter(). Just replace all the time.clock to time.perf_counter, and it should be fine. For more info: https://www.webucator.com/blog/2015/08/python-clocks-explained/ | 10 | 4 |
62,433,286 | 2020-6-17 | https://stackoverflow.com/questions/62433286/truncate-f-string-float-without-rounding | I want to print a very very close-to-one float, truncating it to 2 decimal places without rounding, preferably with the least amount of code possible. a = 0.99999999999 print(f'{a:0.2f}') Expected: 0.99 Actual: 1.00 | I don't think you need f-strings or math functions, if I understand you correctly. Plain old string manipulation should get you there: a = 0.987654321 print(str(a)[:4]) output: 0.98 | 8 | 2 |
62,427,205 | 2020-6-17 | https://stackoverflow.com/questions/62427205/in-python-3-using-pytest-how-do-we-test-for-exit-code-exit1-and-exit0-fo | I am new to Pytest in python . I am facing a tricky scenario where I need to test for exit codes - exit(1) and exit(0) , using Pytest module. Below is the python program : def sample_script(): count_file = 0 if count_file == 0: print("The count of files is zero") exit(1) else: print("File are present") exit(0) Now I ... | Once you put the exit(1) inside the if block as suggested, you can test for SystemExit exception: from some_package import sample_script def test_exit(): with pytest.raises(SystemExit) as pytest_wrapped_e: sample_script() assert pytest_wrapped_e.type == SystemExit assert pytest_wrapped_e.value.code == 42 The example i... | 15 | 26 |
62,362,693 | 2020-6-13 | https://stackoverflow.com/questions/62362693/how-do-i-read-project-dependencies-from-pyproject-toml-from-my-setup-py-to-avoi | We're upgrading to use BeeWare's Briefcase 0.3.1 for packaging, which uses pyproject.toml instead of setup.py to specify how to package, including which dependencies to include in a package. Here's a minimal example of a pyproject.toml for briefcase: [tool.briefcase.app.exampleapp] formal_name = "exampleapp" descriptio... | This answer might be outdated. I do not have time to investigate right now. I recommend checking the briefcase resources for more up-to-date information. For example this section of the doc might be relevant: https://briefcase.readthedocs.io/en/latest/reference/configuration.html#pep621-compatibility As far as I can t... | 10 | 8 |
62,408,128 | 2020-6-16 | https://stackoverflow.com/questions/62408128/buffererror-local-queue-full-in-python | import logging from confluent_kafka import Producer import os logger = logging.getLogger("main") BOOTSTRAP_SERVERS = os.environ['BOOTSTRAP_SERVERS'] APPLICATION_ID = os.getenv('APPLICATION_ID', default = "nke-data-source") RECONNECT_BACKOFF_MS = os.getenv('RECONNECT_BACKOFF_MS', default = 1000) REQUEST_TIMEOUT_MS = os.... | This Queue is something implemented in the librdkafka library (which confluent_kafka is binding to) There is an inner Queue for the produce that takes the producer delivery report and waits for the produce to deal with them (mostly doing nothing), but you need to trigger this mechanism of going through the queue, which... | 11 | 21 |
62,410,871 | 2020-6-16 | https://stackoverflow.com/questions/62410871/how-do-i-test-if-point-is-in-polygon-multipolygon-with-geopandas-in-python | I have the Polygon data from the States from the USA from the website arcgis and I also have an excel file with coordinates of citys. I have converted the coordinates to geometry data (Points). Now I want to test if the Points are in the USA. Both are dtype: geometry. I thought with this I can easily compare, but when ... | contains in GeoPandas currently work on a pairwise basis 1-to-1, not 1-to-many. For this purpose, use sjoin. points_within = gp.sjoin(gdf, US, predicate='within') That will return only those points within the US. Alternatively, you can filter polygons which contain points. polygons_contains = gp.sjoin(US, gdf, predica... | 11 | 13 |
62,363,657 | 2020-6-13 | https://stackoverflow.com/questions/62363657/how-can-i-plot-validation-curves-using-the-results-from-gridsearchcv | I am training a model with GridSearchCV in order to find the best parameters Code: grid_params = { 'n_estimators': [100, 200, 300, 400], 'criterion': ['gini', 'entropy'], 'max_features': ['auto', 'sqrt', 'log2'] } gs = GridSearchCV( RandomForestClassifier(), grid_params, cv=2, verbose=1, n_jobs=-1 ) clf = gs.fit(X_trai... | You can use the cv_results_ attribute of GridSearchCV and get the results for each combination of hyperparameters. Validation Curve is meant to depict the impact of single parameter in training and cross validation scores. Since fine tuning is done for multiple parameters in GridSearchCV, multiple plots are required to... | 8 | 16 |
62,349,875 | 2020-6-12 | https://stackoverflow.com/questions/62349875/how-long-does-colabs-usage-limit-lasts | This message keeps popping out after I used two GPUs simultaneously for two notebooks from the same account for about half an hour (Colab wasn't running for 12 hours): Photo of pop-out message You cannot currently connect to a GPU due to usage limits in Colab. It has been about two hours since I last used colab, but ... | The usage limit is pretty dynamic and depends on how much/long you use colab. I was able to use the GPUs after 5 days; however, my account again reached usage limit right after 30mins of using the GPUs (google must have decreased it further for my account). The situation really became normal after months of not using c... | 22 | 8 |
62,411,746 | 2020-6-16 | https://stackoverflow.com/questions/62411746/flaskenv-or-env-file-not-being-read | I have a flask app that uses some enviroment variables, I don't now what has changed but now it doesn't read the variables in the .flaskenv file, already tried changing its name to .env, still not working. This is the .flaskenv file: FLASK_APP=app FLASK_ENV=development CONSUMER_KEY= CONSUMER_SECRET= ACCESS_KEY= ACCESS... | As written in the flask docs: If python-dotenv is installed, running the flask command will set environment variables defined in the files .env and .flaskenv. This can be used to avoid having to set FLASK_APP manually every time you open a new terminal, and to set configuration using environment variables similar to h... | 9 | 18 |
62,346,091 | 2020-6-12 | https://stackoverflow.com/questions/62346091/how-can-i-disable-hide-the-grouping-of-variables-in-vscode-python | Recently the ms-python extension (v2020.5.86806) for vscode implements grouping of variables in the debug console/variable explorer. They appear as: <object> > special variables > function variables Is there a way to disable this behavior? EDIT: Screenshot added: | There's no single flag to revert to old behavior, but you can fine-tune it on a per-group basis in your launch.json: { "version": "0.2.0", "configurations": [ { "name": ..., "module": ..., ... "variablePresentation": { "all": "inline", "class": "group", "function": "hide", "protected": ..., "special": ... } } ] } "all... | 12 | 10 |
62,331,439 | 2020-6-11 | https://stackoverflow.com/questions/62331439/how-to-terminate-current-colab-session-from-notebook-cell | I'm trying to be a good citizen and make sure my notebook session is terminated immediately after running even if I'm not sitting at my machine. Is there any code I can run in a notebook cell to achieve this? | We have a way to do this correctly now: from google.colab import runtime runtime.unassign() | 18 | 7 |
62,312,308 | 2020-6-10 | https://stackoverflow.com/questions/62312308/typeerror-file-must-have-read-and-readline-attributes | 1st approach: I am trying to make the below code work since morning. I have read many answers here in stackoverflow and tutorials on google about python, I have done 0 progress. Can you help me with this error: Using TensorFlow backend. Traceback (most recent call last): File "source_code_modified.py", line 65, in <mod... | Just sharing some stupid mistake for anyone else affected (by stupidity)^^: I had the error TypeError: file must have 'read' and 'readline' attributes because I used the plain text file_path instead of the opened f file object as the parameter of the pickle function. Correct: file_path = 'path/to/filename' with open(fi... | 8 | 15 |
62,314,556 | 2020-6-10 | https://stackoverflow.com/questions/62314556/how-to-install-virtualenv-on-ubuntu-20-04-gcp-instance | I am trying to install python3 virtualenv. I get the following message when I try to run virtualenv. virtualenv Command 'virtualenv' not found, but can be installed with: apt install python3-virtualenv but if I run install command, I get the following error. apt install python3-virtualenv Reading package lists... Done... | AFAIU the latest versions of Ubuntu removed Python2 altogether so Python3 is now just the Python. Try: apt-get update apt-get install python3-virtualenv | 38 | 83 |
62,409,303 | 2020-6-16 | https://stackoverflow.com/questions/62409303/how-to-handle-missing-values-nan-in-categorical-data-when-using-scikit-learn-o | I have recently started learning python to develop a predictive model for a research project using machine learning methods. I have a large dataset comprised of both numerical and categorical data. The dataset has lots of missing values. I am currently trying to encode the categorical features using OneHotEncoder. When... | You will need to impute the missing values before. You can define a Pipeline with an imputing step using SimpleImputer setting a constant strategy to input a new category for null fields, prior to the OneHot encoding: from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder from skl... | 28 | 14 |
62,295,889 | 2020-6-10 | https://stackoverflow.com/questions/62295889/how-to-set-environment-variables-in-vscode-when-running-flask-app | I have a Python Flask app and have lots of environment variables that I need to set when running my app. I normally run my app like so... python3 -m app.py I would like it so that I can set all the environment variables my app needs so that I do not need to export each time I reopen my terminal. It would be nice if it... | For Flask apps, you can create a launch.json configuration that will run your Flask app using VS Code's debugger. VS Code's launch.json supports a number of options, including the setting of environment variables that your Flask app needs. Start with installing the Python extension for VS Code, to add support for "debu... | 11 | 20 |
62,375,034 | 2020-6-14 | https://stackoverflow.com/questions/62375034/find-non-overlapping-area-between-two-kde-plots | I was attempting to determine whether a feature is important or not base on its kde distribution for target variable. I am aware how to plot the kde plot and guess after looking at the plots, but is there a more formal doing this? Such as can we calculate the area of non overlapping area between two curves? When I goog... | Here are my ideas about the computational part of the question: In order to compare the kde's, they need to be calculated with the same bandwidth. (The default bandwidth depends on the number of x-values, which can be different for both sets.) The intersection of two positive curves is just their minimum. The area of ... | 10 | 14 |
62,345,198 | 2020-6-12 | https://stackoverflow.com/questions/62345198/extract-individual-links-from-a-single-youtube-playlist-link-using-python | I need a python script that takes link to a single youtube playlist and then gives out a list containing the links to individual videos in the playlist. I realize that same question was asked few years ago, but it was asked for python2.x and the codes in the answer don't work properly. They are very weird, they work so... | It seems youtube loads sometimes different versions of the page, sometimes with html organized like you expected using links with pl-video-title-link class : <td class="pl-video-title"> <a class="pl-video-title-link yt-uix-tile-link yt-uix-sessionlink spf-link " dir="ltr" href="/watch?v=GtWXOzsD5Fw&list=PL3D7BFF1DD... | 9 | 25 |
62,390,517 | 2020-6-15 | https://stackoverflow.com/questions/62390517/no-module-named-sklearn-utils-linear-assignment | I am trying to run a project from github , every object counter applications using sort algorithm. I can't run any of them because of a specific error, attaching errors screenshot. Can anyone help me about fixing this issue? | The linear_assignment function is deprecated in 0.21 and will be removed from 0.23, but sklearn.utils.linear_assignment_ can be replaced by scipy.optimize.linear_sum_assignment. You can use: from scipy.optimize import linear_sum_assignment as linear_assignment then you can run the file and don't need to change the cod... | 26 | 77 |
62,352,670 | 2020-6-12 | https://stackoverflow.com/questions/62352670/deserialization-of-large-numpy-arrays-using-pickle-is-order-of-magnitude-slower | I am deserializing large numpy arrays (500MB in this example) and I find the results vary by orders of magnitude between approaches. Below are the 3 approaches I've timed. I'm receiving the data from the multiprocessing.shared_memory package, so the data comes to me as a memoryview object. But in these simple examples... | I found your question useful, I'm looking for best numpy serialization and confirmed that np.load() was best except it was beaten by pyarrow in my add on test below. Arrow is now a super popular data serialization framework for distributed compute (E.g. Spark, ...) """ Deserialization speed test """ import numpy as np ... | 11 | 3 |
62,393,032 | 2020-6-15 | https://stackoverflow.com/questions/62393032/custom-loss-function-with-weights-in-keras | I'm new with neural networks. I wanted to make a custom loss function in TensorFlow, but I need to get a vector of weights, so I did it in this way: def my_loss(weights): def custom_loss(y, y_pred): return weights*(y - y_pred) return custom_loss model.compile(optimizer='adam', loss=my_loss(weights), metrics=['accuracy'... | this is a workaround to pass additional arguments to a custom loss function, in your case an array of weights. the trick consists in using fake inputs which are useful to build and use the loss in the correct ways. don't forget that keras handles fixed batch dimension I provide a dummy example in a regression problem d... | 8 | 5 |
62,416,223 | 2020-6-16 | https://stackoverflow.com/questions/62416223/how-to-select-only-few-columns-in-scikit-learn-column-selector-pipeline | I was reading the scikitlearn tutorial about column transformer. The given example (https://scikit-learn.org/stable/modules/generated/sklearn.compose.make_column_selector.html#sklearn.compose.make_column_selector) works, but when I tried to select only few columns, It gives me error. MWE import numpy as np import panda... | If you don't mind mlxtend, it has built-in transformer for that. Using mlxtend from mlxtend.feature_selection import ColumnSelector pipe = ColumnSelector(mycols) pipe.fit_transform(df) For sklearn >= 0.20 Reference: https://scikit-learn.org/stable/modules/generated/sklearn.compose.ColumnTransformer.html from sklearn... | 16 | 19 |
62,418,465 | 2020-6-16 | https://stackoverflow.com/questions/62418465/why-does-djangos-apps-get-model-return-a-fake-mymodel-object | I am writing a custom Django migration script. As per the django docs on custom migrations, I should be able to use my model vis-a-vis apps.get_model(). However, when trying to do this I get the following error: AttributeError: type object 'MyModel' has no attribute 'objects' I think this has to do with the apps regis... | The fake objects are historical models. Here's the explanation from Django docs: When you run migrations, Django is working from historical versions of your models stored in the migration files. [...] Because it’s impossible to serialize arbitrary Python code, these historical models will not have any custom methods t... | 16 | 12 |
62,397,170 | 2020-6-15 | https://stackoverflow.com/questions/62397170/python-pandas-how-to-select-rows-where-objects-start-with-letters-pl | I have specific problem with pandas: I need to select rows in dataframe which start with specific letters. Details: I've imported my data to dataframe and selected columns that I need. I've also narrowed it down to row index I need. Now I also need to select rows in other column where objects START with letters 'pl'. ... | If you use a string method on the Series that should return you a true/false result. You can then use that as a filter combined with .loc to create your data subset. new_df = df.loc[df[‘Code’].str.startswith('pl')].copy() | 14 | 2 |
62,395,559 | 2020-6-15 | https://stackoverflow.com/questions/62395559/input-0-of-layer-lstm-5-is-incompatible-with-the-layer-expected-ndim-3-found-n | I am trying to create an image captioning model. Could you please help with this error? input1 is the image vector, input2 is the caption sequence. 32 is the caption length. I want to concatenate the image vector with the embedding of the sequence and then feed it to the decoder model. def define_model(vocab_size, max... | This error occurs when an LSTM layer gets input in 2D instead of 3D. For instance: (64, 100) The correct format is (n_samples, time_steps, features): (64, 5, 100) In this case, the mistake you did was that the input of dec3, which is an LSTM layer, was the output of dec2, which is also an LSTM layer. By default, the ... | 9 | 2 |
62,335,424 | 2020-6-11 | https://stackoverflow.com/questions/62335424/tkinter-how-to-bind-to-shifttab | I'm trying to bind the SHIFT+TAB keys, but I can't seem to get it to work. The widget I'm binding to is an Entry widget. I've tried binding the keys with widget.bind('<Shift_Tab>', func), but I get an error message saying: File "/usr/lib64/python3.8/tkinter/init.py", line 1337, in _bind self.tk.call(what + (sequence, ... | Not a direct answer and too long for a comment. You can solve your question by yourself with a simple trick, bind <Key> to a function, and print the key event argument passed to the bind function where you can see which key is pressed or not. Try multiple combinations of keys to see what is the state and what is their ... | 8 | 5 |
62,378,481 | 2020-6-14 | https://stackoverflow.com/questions/62378481/typeerror-input-filename-of-readfile-op-has-type-float32-that-does-not-matc | I am running this code from the tutorial here: https://keras.io/examples/vision/image_classification_from_scratch/ with a custom dataset, that is divided in 2 datasets as in the tutorial. However, I got this error: TypeError: Input 'filename' of 'ReadFile' Op has type float32 that does not match expected type of string... | Simplest way I found is to create a subfolder and copy the files to that subfolder. i.e. Lets assume your files are 0.jpg, 1.jpg,2.jpg....2000.jpg and in directory named "patterns". Seems like the Keras API does not accept it as the files are named by numbers and for Keras it is in float32. To overcome this issue, eith... | 8 | 17 |
62,303,980 | 2020-6-10 | https://stackoverflow.com/questions/62303980/python-version-in-azure-databricks | I am trying to find out the python version I am using in Databricks. To find out I tried import sys print(sys.version) And I got the output as 3.7.3 However when I went to Cluster --> SparkUI --> Environment I see that the cluster Python version is 2. Which version does this refer to ? When I tried running %sh python... | Update: This issue has been fixed. For new cluster: If you create a new cluster it will have python environment variable as 3. For existing clusters: You need to add in Environment Variables tab in Cluster Configuration > Advanced, it changes in the Environmental variable. PYSPARK_PYTHON=/databricks/python3/bin/python... | 15 | 8 |
62,316,405 | 2020-6-11 | https://stackoverflow.com/questions/62316405/how-to-get-sliding-window-of-a-values-for-each-element-in-both-direction-forwar | I have a list of values like this, lst = [1, 2, 3, 4, 5, 6, 7, 8] Desired Output: window size = 3 1 # first element in the list forward = [2, 3, 4] backward = [] 2 # second element in the list forward = [3, 4, 5] backward = [1] 3 # third element in the list forward = [4, 5, 6] backward = [1, 2] 4 # fourth element in t... | Code: arr = [1, 2, 3, 4, 5, 6, 7, 8] window = 3 for backward, current in enumerate(range(len(arr)), start = 0-window): if backward < 0: backward = 0 print(arr[current+1:current+1+window], arr[backward:current]) Output: [2, 3, 4], [] [3, 4, 5], [1] [4, 5, 6], [1, 2] [5, 6, 7], [1, 2, 3] [6, 7, 8], [2, 3, 4] [7, 8], [3,... | 29 | 15 |
62,414,423 | 2020-6-16 | https://stackoverflow.com/questions/62414423/google-drive-api-list-files-in-a-shared-folder-that-i-have-not-accessed-yet | I am trying to automate the downloading of files from a Google Drive shared folder. The contents of the folder change daily. The folder is shared to anyone with a link to the folder. My problem is that the query does not return the new files that I have not opened yet unless I open the new files in Google Drive. folder... | Yes, there is, but you need to specify that you want to include shared folders into the search This you can do by setting includeItemsFromAllDrives and supportsAllDrives to true In python you can implement it with folder_id = 'xxxx...xxx' results = drive_service.files().list(supportsAllDrives=True, includeItemsFromAllD... | 9 | 21 |
62,408,115 | 2020-6-16 | https://stackoverflow.com/questions/62408115/updating-a-matplotlib-figure-during-simulation | I try to implement a matplotlib figure that updates during the simulation of my environment. The following Classes works fine in my test but doesn't update the figure when I use it in my environment. During the simulation of the environment, the graph is shown, but no lines are plotted. My guess is that .draw() is not... | Turns out your code works the way it is set up. Here is the sole problem with the code you provided: self.vis.graphs_dict["VariableY"]["graph"].x.append(self.internal_step) self.vis.graphs_dict["VariableY"]["graph"].y.append(150) You are plotting a line and correctly updating the canvas, however, you keep appending th... | 8 | 6 |
62,403,763 | 2020-6-16 | https://stackoverflow.com/questions/62403763/how-to-add-planes-in-a-3d-scatter-plot | Using Blender created this model that can be seen in A-frame in this link This model is great and it gives an overview of what I'm trying to accomplish here. Basically, instead of having the names, I'd have dots that symbolize one specific platform. The best way to achieve it with current state of the art, at my sig... | I think you might be looking for the add_trace function in plotly so you can just create the surfaces and then add them to the figure: Also, note, there's definitely ways to simplify this code, but for a general idea: import plotly.express as px import pandas as pd import plotly.graph_objects as go import numpy as np f... | 10 | 14 |
62,401,591 | 2020-6-16 | https://stackoverflow.com/questions/62401591/python-3-3-internal-string-representation | I was looking into how Python represents string after PEP 393 and I am not understanding the difference between PyASCIIObject and PyCompactUnicodeObject. My understanding is that strings are represented with the following structures: typedef struct { PyObject_HEAD Py_ssize_t length; /* Number of code points in the stri... | PEP 373 is really the best reference for your questions, though the C-API docs are sometimes needed too. Lets address your questions one by one: You have the types right. But there is one non-obvious wrinkle: When you're using either of the "compact" types (either PyASCIIObject or PyCompactUnicodeObject), the structur... | 8 | 6 |
62,416,819 | 2020-6-16 | https://stackoverflow.com/questions/62416819/runtimeerror-given-groups-1-weight-of-size-32-3-16-16-16-expected-input | RuntimeError: Given groups=1, weight of size [32, 3, 16, 16, 16], expected input[100, 16, 16, 16, 3] to have 3 channels, but got 16 channels instead This is the portion of code I think where the problem is. def __init__(self): super(Lightning_CNNModel, self).__init__() self.conv_layer1 = self._conv_layer_set(3, 32) se... | nn.Conv3d expects the input to have size [batch_size, channels, depth, height, width]. The first convolution expects 3 channels, but with your input having size [100, 16, 16, 16, 3], that would be 16 channels. Assuming that your data is given as [batch_size, depth, height, width, channels], you need to swap the dimensi... | 14 | 17 |
62,400,420 | 2020-6-16 | https://stackoverflow.com/questions/62400420/given-two-lists-of-2d-points-how-to-find-the-closest-point-in-the-2nd-list-for | I have two large numpy arrays of randomly sorted 2d points, let's say they're A and B. What I need to do is find the number of "matches" between the two arrays, where a match is a point in A (call it A') being within some given radius R with a point in B (call it B'). This means that every point in A must match with ei... | I think there are several options. I ginned up a small comparison test to explore a few. The first couple of these only go as far as finding how many points are mutually within radius of each other to make sure I was getting consistent results on the main part of the problem. It does not answer the mail on the part of ... | 8 | 12 |
62,388,701 | 2020-6-15 | https://stackoverflow.com/questions/62388701/are-executables-produced-with-cython-really-free-of-the-source-code | I have read Making an executable in Cython and BuvinJ's answer to How to obfuscate Python code effectively? and would like to test if the source code compiled with Cython is really "no-more-there" after the compilation. It is indeed a popular opinion that using Cython is a way to protect a Python source code, see for e... | The code is found in the original pyx-file next to your exe. Delete/don't distribute this pyx-file with your exe. When you look at the generated C-code, you will see why the error message is shown by your executable: For a raised error, Cython will emit a code similar to the following: __PYX_ERR(0, 11, __pyx_L3_error)... | 26 | 30 |
62,412,976 | 2020-6-16 | https://stackoverflow.com/questions/62412976/writing-tensor-to-a-file-in-a-visually-readable-manner | In pytorch, I want to write a tensor to a file and visually read the file contents. For example, consider T = torch.tensor([3,4,5,6]). I want to write the tensor T to a file, say file_T.txt, and want to visually read the contents of the file_T.txt, which will be 3,4,5 and 6. How can I achieve this? | You can use numpy: import numpy as np np.savetxt('my_file.txt', torch.Tensor([3,4,5,6]).numpy()) | 9 | 13 |
62,412,754 | 2020-6-16 | https://stackoverflow.com/questions/62412754/python-asyncio-errors-oserror-winerror-6-the-handle-is-invalid-and-runtim | I am having some difficulties with properly with my code, as I get the following error after my code finishes executing while debugging on VSCode: Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x00000188AB3259D0> Traceback (most recent call last): File "c:\users\gam3p\appdata\local\programs\pyth... | I ran into a similar problem with asyncio. Since Python 3.8 they change the default event loop on Windows to ProactorEventLoop instead of SelectorEventLoop and their are some issues with it. so adding asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) above loop = asyncio.get_event_loop() Will ... | 8 | 10 |
62,408,749 | 2020-6-16 | https://stackoverflow.com/questions/62408749/how-to-reset-keras-metrics | To do some parameter tuning, I like to loop over some training function with Keras. However, I realized that when using tensorflow.keras.metrics.AUC() as a metric, for every training loop, an integer gets added to the auc metric name (e.g. auc_1, auc_2, ...). So actually the keras metrics are somehow stored even when c... | Your reproducible example failed in several places for me, so I changed just a few things (I'm using TF 2.1). After getting it to run, I was able to get rid of the additional metric names by specifying metrics=[AUC(name='auc')]. Here's the full (fixed) reproducible example: import numpy as np import tensorflow as tf im... | 8 | 6 |
62,390,314 | 2020-6-15 | https://stackoverflow.com/questions/62390314/how-to-call-asynchronous-function-in-django | The following doesn't execute foo and gives RuntimeWarning: coroutine 'foo' was never awaited # urls.py async def foo(data): # process data ... @api_view(['POST']) def endpoint(request): data = request.data.get('data') # How to call foo here? foo(data) return Response({}) | Found a way to do it. Create another file bar.py in the same directory as urls.py. # bar.py def foo(data): // process data # urls.py from multiprocessing import Process from .bar import foo @api_view(['POST']) def endpoint(request): data = request.data.get('data') p = Process(target=foo, args=(data,)) p.start() return... | 12 | 8 |
62,399,546 | 2020-6-16 | https://stackoverflow.com/questions/62399546/python-datetime-now-as-a-default-function-parameter-return-same-value-in-diffe | Now I got some problem that I can't explain and fix. This is my first python module TimeHelper.py from datetime import datetime def fun1(currentTime = datetime.now()): print(currentTime) and another is Main.py from TimeHelper import fun1 import time fun1() time.sleep(5) fun1() When I run the Main.py, the out put is... | I think I find the answer. Thanks for @user2864740 So I change my TimeHelper.py to this from datetime import datetime def fun1(currentTime = None): if currentTime is None: currentTime = datetime.now() print(currentTime) and anything work in my expectation. | 13 | 14 |
62,378,782 | 2020-6-14 | https://stackoverflow.com/questions/62378782/py-datatable-in-operator | I am unable to perform a standard in operation with a pre-defined list of items. I am looking to do something like this: # Construct a simple example frame from datatable import * df = Frame(V1=['A','B','C','D'], V2=[1,2,3,4]) # Filter frame to a list of items (THIS DOES NOT WORK) items = ['A','B'] df[f.V1 in items,:] ... | You could also try this out: First import all the necessary packages as, import datatable as dt from datatable import by,f,count import functools import operator Create a sample datatable: DT = dt.Frame(V1=['A','B','C','D','E','B','A'], V2=[1,2,3,4,5,6,7]) Make a list of values to be filtered among the observations, ... | 8 | 6 |
62,395,983 | 2020-6-15 | https://stackoverflow.com/questions/62395983/how-to-create-a-text-shape-with-python-pptx | I want to add a text box to a presentation with python pptx. I would like to add a text box with several paragraphs in the specific place and then format it (fonts, color, etc.). But since text shape object always comes with the one paragraph in the beginning, I cannot edit first of my paragraphs. The code sample looks... | Access the first paragraph differently, using: p = tf.paragraphs[0] Then you can add runs, set fonts and all the rest of it just like with a paragraph you get back from tf.add_paragraph(). | 10 | 12 |
62,384,215 | 2020-6-15 | https://stackoverflow.com/questions/62384215/best-way-to-construct-a-graphql-query-string-in-python | I'm trying to do this (see title), but it's a bit complicated since the string I'm trying to build has to have the following properties: mulitiline contains curly braces I want to inject variables into it Using a normal '''''' multiline string makes injecting variables difficult. Using multiple f-strings makes inject... | You can use the """ multiline string method. For injecting variables, make sure to use the $ sign while defining the string and use the variables object in the JSON parameter of the requests.post method. Here is an example. ContactInput is one of the types I defined in my GraphQL schema. query = """ mutation ($input:[C... | 31 | 42 |
62,380,562 | 2020-6-15 | https://stackoverflow.com/questions/62380562/sort-list-of-dicts-by-two-keys | I have this list of dicts: [{'score': '1.9', 'id': 756, 'factors': [1.25, 2.25, 2.5, 2.0, 1.75]}, {'score': '2.0', 'id': 686, 'factors': [2.0, 2.25, 2.75, 1.5, 2.25]}, {'score': '2.0', 'id': 55, 'factors': [1.5, 3.0, 2.5, 1.5, 1.5]}, {'score': '1.9', 'id': 863, 'factors': [1.5, 3.0, 1.5, 2.5, 1.5]}] I can sort by scor... | You can sort by a tuple: sorted(l, key=lambda k: (float(k['score']), k['id']), reverse=True) This will sort by score descending, then id descending. Note that since score is a string value, it needs to be converted to float for comparison. [ {'score': '2.0', 'id': 686, 'factors': [2.0, 2.25, 2.75, 1.5, 2.25]}, {'score... | 8 | 15 |
62,364,030 | 2020-6-13 | https://stackoverflow.com/questions/62364030/keyboard-interrupt-from-python-does-not-abort-rust-function-pyo3 | I have a Python library written in Rust with PyO3, and it involves some expensive calculations (up to 10 minutes for a single function call). How can I abort the execution when calling from Python ? Ctrl+C seems to only be handled after the end of the execution, so is essentially useless. Minimal reproducible example: ... | One option would be to spawn a separate process to run the Rust function. In the child process, we can set up a signal handler to exit the process on interrupt. Python will then be able to raise a KeyboardInterrupt exception as desired. Here's an example of how to do it: // src/lib.rs use pyo3::prelude::*; use pyo3::wr... | 9 | 3 |
62,376,164 | 2020-6-14 | https://stackoverflow.com/questions/62376164/how-to-change-max-iter-in-optimize-function-used-by-sklearn-gaussian-process-reg | I am using sklearn's GPR library, but occasionally run into this annoying warning: ConvergenceWarning: lbfgs failed to converge (status=2): ABNORMAL_TERMINATION_IN_LNSRCH. Increase the number of iterations (max_iter) or scale the data as shown in: https://scikit-learn.org/stable/modules/preprocessing.html _check_optimi... | You want to extend and/or modify the behavior of an existing Python object, which sounds like a good use case for inheritance. A solution could be to inherit from the scikit-learn implementation, and ensure that the usual optimizer is called with the arguments you'd like. Here's a sketch, but note that this is not test... | 22 | 7 |
62,377,883 | 2020-6-14 | https://stackoverflow.com/questions/62377883/how-can-i-get-user-input-in-a-python-discord-bot | I have a python discord bot and I need it to get user input after a command, how can I do this? I am new to python and making discord bots. Here is my code: import discord, datetime, time from discord.ext import commands from datetime import date, datetime prefix = "!!" client = commands.Bot(command_prefix=prefix, case... | You'll be wanting to use Client.wait_for(): @client.command(name="command") async def _command(ctx): global times_used await ctx.send(f"y or n") # This will make sure that the response will only be registered if the following # conditions are met: def check(msg): return msg.author == ctx.author and msg.channel == ctx.c... | 10 | 16 |
62,376,042 | 2020-6-14 | https://stackoverflow.com/questions/62376042/calculating-and-displaying-a-convexhull | I'm trying to calculate and show a convex hull for some random points in python. This is my current code: import numpy as np import random import matplotlib.pyplot as plt import cv2 points = np.random.rand(25,2) hull = ConvexHull(points) plt.plot(points[:,0], points[:,1], 'o',color='c') for simplex in hull.simplices: p... | Replacing np.rand() with randint(0, 10) will generate the coordinates as integers from 0,1,... to 9. Using '.' as marker will result in smaller markers for the given points. Using 'o' as marker, setting a markeredgecolor and setting the main color to 'none' will result in a circular marker, which can be used for the po... | 8 | 12 |
62,375,432 | 2020-6-14 | https://stackoverflow.com/questions/62375432/is-there-a-dunder-method-corresponding-to-pipe-equal-update-for-dicts-i | In python 3.9, dictionaries gained combine | and update |= operators. Is there a dunder/magic method which will enable this to be used for other classes? I've tried looking in the python source but found it a bit bewildering. | Yes, | and |= correspond to __or__ and __ior__. Don't look at the python source code, look at the documentation. In particular, the data model. See here And note, this isn't specific to python 3.9. | 10 | 14 |
62,372,081 | 2020-6-14 | https://stackoverflow.com/questions/62372081/what-is-the-advantage-of-using-multiple-cursors-in-psycopg2-for-postgresql-queri | What is the difference between using a single cursor in psycopg2 to perform all your queries against using multiple cursors. I.e, say I do this: import psycopg2 as pg2 con = psycopg2.connect(...) cur = con.cursor() cur.execute(...) .... .... cur.execute(...) ... and every time I wish to execute a query thereafter, I ... | The two options are comparable; you can always benchmark both to see if there's a meaningful difference, but psycopg2 cursors are pretty lightweight (they don't represent an actual server-side, DECLAREd cursor, unless you pass a name argument) and I wouldn't expect any substantial slowdown from either route. The reason... | 11 | 17 |
62,372,762 | 2020-6-14 | https://stackoverflow.com/questions/62372762/delete-an-element-from-torch-tensor | I'm trying to delete an item from a tensor. In the example below, How can I remove the third item from the tensor ? tensor([[-5.1949, -6.2621, -6.2051, -5.8983, -6.3586, -6.2434, -5.8923, -6.1901, -6.5713, -6.2396, -6.1227, -6.4196, -3.4311, -6.8903, -6.1248, -6.3813, -6.0152, -6.7449, -6.0523, -6.4341, -6.8579, -6.196... | You can first filter array through indices and then concat both t.shape torch.Size([1, 36]) t = torch.cat((t[:,:3], t[:,4:]), axis = 1) t.shape torch.Size([1, 35]) | 11 | 2 |
62,370,427 | 2020-6-14 | https://stackoverflow.com/questions/62370427/read-xlsx-from-azure-blob-storage-to-pandas-dataframe-without-creating-temporary | I am trying to read a xlsx file from an Azure blob storage to a pandas dataframe without creating a temporary local file. I have seen many similar questions, e.g. Issues Reading Azure Blob CSV Into Python Pandas DF, but haven't managed to get the proposed solutions to work. Below code snippet results in a UnicodeDecod... | Similar to what you have already done, we could use download_blob() to get the StorageStreamDownloader object into memory, then context_as_text() to decode the contents to a string. Then we can read the the contents from the CSV StringIO buffer into a pandas Dataframe with pandas.read_csv(). from io import StringIO im... | 8 | 9 |
62,369,326 | 2020-6-14 | https://stackoverflow.com/questions/62369326/what-is-the-purpose-of-floating-point-index-in-pandas | s.index=[0.0,1.1,2.2,3.3,4.4,5.5] s.index # Float64Index([0.0, 1.1, 2.2, 3.3, 4.4, 5.5], dtype='float64') s # 0.0 141.125 # 1.1 142.250 # 2.2 143.375 # 3.3 143.375 # 4.4 144.500 # 5.5 145.125 s.index=s.index.astype('float32') # s.index # Float64Index([ 0.0, 1.100000023841858, 2.200000047683716, # 3.299999952316284, 4.4... | Float indices are generally useless for label-based indexing, because of general floating point restrictions. Of course, pd.Float64Index is there in the API for completeness but that doesn't always mean you should use it. Jeff (core library contributor) has this to say on github: [...] It is rarely necessary to actual... | 9 | 8 |
62,366,211 | 2020-6-13 | https://stackoverflow.com/questions/62366211/vscode-modulenotfounderror-no-module-named-x | I am trying to build a new package, however, when I try to run any of the files from inside VSCode or from terminal, I am coming across this error: ModuleNotFoundError: No module name 'x' My current folder structure is as follows: package |---module |------__init__.py |------calculations.py |------miscfuncs.py |---tes... | Make sure you are running from the package folder (not from package/module) if you want import module.calculations to work. You can also set the PYTHONPATH environment variable to the path to the package folder. | 35 | 8 |
62,363,953 | 2020-6-13 | https://stackoverflow.com/questions/62363953/how-to-create-toggle-switch-button-in-qt-designer | I am trying to create toggle button in qt designer. I refer on internet also but i couldn't find how to do that. Can anyone know how to do toggle switch button. I have attached a sample button image. EDIT I created a text box below that i want this toggle button. When i try to add it throws me error. How to add the ... | Qt Designer to set the position and initialize some properties of the widgets in a window, but it does not work to create widgets with custom painted as the switch so you will have to implement with python. Long ago for a project implement a switch so it will show that code: from PyQt5.QtCore import QObject, QSize, QPo... | 9 | 6 |
62,363,774 | 2020-6-13 | https://stackoverflow.com/questions/62363774/python-pip-install-wheel-dependencies-from-a-folder | I know that I can create a wheel by first writing a setup.py and then typing python setup.py bdist_wheel If my wheels depend only on packages in pypi I know that I can install them by doing: pip install mypkg.whl Question: if my wheels depend on other of my wheels, can I have pip automatically install them from a fol... | pip install --find-links /path/to/wheel/dir/ pkg2 If you want to completely disable access to PyPI add --no-index: pip install --no-index --find-links /path/to/wheel/dir/ pkg2 | 18 | 30 |
62,352,767 | 2020-6-12 | https://stackoverflow.com/questions/62352767/cant-install-open3d-libraries-errorcould-not-find-a-version-that-satisfies-th | I use pyCharm software in windows 10, and when I tried to install open3d the following error appeared: ERROR: Could not find a version that satisfies the requirement open3d (from versions: none) ERROR: No matching distribution found for open3d I tried to install it using cmd but the same error appeared, also pip versi... | Solved: by installing python version 3.77 and run code using it instead of 3.8 | 9 | 4 |
62,351,462 | 2020-6-12 | https://stackoverflow.com/questions/62351462/fastapi-app-running-locally-but-not-in-docker-container | I have a FastAPI app that is working as expected when running locally, however, I get an 'Internal Server Error' when I try to run in a Docker container. Here's the code for my app: from fastapi import FastAPI from pydantic import BaseModel import pandas as pd from fbprophet import Prophet class Data(BaseModel): length... | Run the docker without the -d parameter and you'll get more clues about it. If I were to guess, I might say that you're missing some python requirement. | 12 | 7 |
62,340,498 | 2020-6-12 | https://stackoverflow.com/questions/62340498/open-database-files-db-using-python | I have a data base file .db in SQLite3 format and I was attempting to open it to look at the data inside it. Below is my attempt to code using python. import sqlite3 # Create a SQL connection to our SQLite database con = sqlite3.connect(dbfile) cur = con.cursor() # The result of a "cursor.execute" can be iterated over... | So, you analyzed it all right. After the FROM you have to put in the tablenames. But you can find them out like this: SELECT name FROM sqlite_master WHERE type = 'table' In code this looks like this: # loading in modules import sqlite3 # creating file path dbfile = '/home/niklas/Desktop/Stuff/StockData-IBM.db' # Creat... | 19 | 29 |
62,330,675 | 2020-6-11 | https://stackoverflow.com/questions/62330675/get-local-time-zone-name-on-windows-python-3-9-zoneinfo | Checking out the zoneinfo module in Python 3.9, I was wondering if it also offers a convenient option to retrieve the local time zone (OS setting) on Windows. On GNU/Linux, you can do from datetime import datetime from zoneinfo import ZoneInfo naive = datetime(2020, 6, 11, 12) aware = naive.replace(tzinfo=ZoneInfo('loc... | You don't need to use zoneinfo to use the system local time zone. You can simply pass None (or omit) the time zone when calling datetime.astimezone. From the docs: If called without arguments (or with tz=None) the system local timezone is assumed. The .tzinfo attribute of the converted datetime instance will be set t... | 12 | 10 |
62,330,374 | 2020-6-11 | https://stackoverflow.com/questions/62330374/input-image-dtype-is-bool-interpolation-is-not-defined-with-bool-data-type | I am facing this issue while using Mask_RCNN to train on my custom dataset with multiple classes. This error occurs when I start training. This is what I get: /home/parth/anaconda3/envs/compVision/lib/python3.7/site-packages/skimage/transform/_warps.py:830: FutureWarning: Input image dtype is bool. Interpolation is not... | Maybe you can try the skimage version 0.16.2。when I use the version 0.17.2, I faced the same issue.Good luck!Idont know why. | 14 | 21 |
62,328,661 | 2020-6-11 | https://stackoverflow.com/questions/62328661/what-is-the-difference-between-higher-order-functions-and-decorators | I do understand that higher-order functions are functions that take functions as parameters or return functions. I also know that decorators are functions that add some functionality to other functions. What are they exactly? Are they the functions that are passed in as parameters or are they the higher-order functions... | A higher order function is a function that takes a function as an argument OR* returns a function. A decorator in Python is (typically) an example of a higher-order function, but there are decorators that aren't (class decorators**, and decorators that aren't functions), and there are higher-order functions that aren't... | 9 | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.