Unnamed: 0
int64
0
1.91M
id
int64
337
73.8M
title
stringlengths
10
150
question
stringlengths
21
64.2k
answer
stringlengths
19
59.4k
tags
stringlengths
5
112
score
int64
-10
17.3k
4,000
2,164,069
Best way to make Django's login_required the default
<p>I'm working on a large Django app, the vast majority of which requires a login to access. This means that all throughout our app we've sprinkled:</p> <pre><code>@login_required def view(...): </code></pre> <p>That's fine, and it works great <em>as long as we remember to add it everywhere</em>! Sadly sometimes we...
<p>Middleware may be your best bet. I've used this piece of code in the past, modified from a snippet found elsewhere:</p> <pre><code>import re from django.conf import settings from django.contrib.auth.decorators import login_required class RequireLoginMiddleware(object): """ Middleware component that wrap...
python|django
103
4,001
63,223,138
How to cut bytes into separate pieces from socket
<p>Ok so the title COULD be worded better, but here is the issue</p> <p>I'm sending data REALLY quickly to a socket, and I need each piece of info sent to be separate</p> <p>For example:</p> <pre><code>import pickle #Sending side while True: data = pickle.dumps((listelement1, listelement2, listelement3)) #All list...
<p>The basic problem is that you need some way to demark messages within the TCP byte stream. This gets complicated fast. Pickled streams know their own size and if all you plan to do is pass pickled stuff back and forth, you can use that knowledge. Assuming you stick with blocking I/O, on the sending side its easy, ju...
python|sockets|pygame
2
4,002
32,539,832
Keep Jupyter notebook running after closing browser tab
<p>I use Jupyter Notebook to run a series of experiments that take some time. Certain cells take way too much time to execute so it's normal that I'd like to close the browser tab and come back later. But when I do the kernel interrupts running.</p> <p>I guess there is a workaround for this but I can't find it</p>
<p>The simplest workaround to this seems to be the <a href="http://ipython.readthedocs.io/en/stable/interactive/magics.html#cellmagic-capture" rel="noreferrer">built-in cell magic</a> <code>%%capture</code>:</p> <pre><code>%%capture output # Time-consuming code here </code></pre> <p>Save, close tab, come back later. ...
python-2.7|ipython-notebook|jupyter
65
4,003
43,982,063
Slices of start, stop indices of valid (non-NaNs) portions of a NumPy array
<p>I have a large numpy 1d array which contains nans. I need to know all the slices that do not contain any nans:</p> <pre><code> import numpy as np A=np.array([1.0,2.0,3.0,np.nan,4.0,3.0,np.nan,np.nan,np.nan,2.0,2.0,2.0]) </code></pre> <p>The expected result for the example would be:</p> <pre><code> Slices=[slice(...
<p>Here is a possibility:</p> <pre><code>import numpy as np def valid_slices(array): m = ~np.isnan(array) idx = np.arange(len(array))[m] idx_diff = np.diff(idx) idx_change = np.where(idx_diff &gt; 1)[0] idx_start = np.concatenate([[0], idx_change + 1], axis=0) idx_end = np.concatenate([idx_cha...
python|numpy
1
4,004
44,213,591
PyQt - Add a text
<p>I am using PyQt5 and I just want to add a text to my window.</p> <p>I have not found any clear help about that on the web.</p> <p>Do you know a simple way to add a text ?</p>
<p>Not sure if you really read the API but something like that should solve what you want to achieve.You could also inherit from QMainWindow or QDialog, or whatever you need. That's just an example from thousands of possibilities. </p> <pre><code>import sys from PyQt5.QtWidgets import QApplication from PyQt5.QtWidgets...
python|pyqt|pyqt5
7
4,005
27,116,264
using aggregate in R when returning matrix
<p>I want to use aggregate to apply some manipulations to a set of matrices, grouped by the <code>customer_id</code>, which is one column of my dataframe, <code>df</code>.</p> <p>For example, I want to take the subsets of <code>df</code> that correspond to different <code>customer_id</code>'s and add some columns to t...
<p><code>aggregate</code> applies the same function to multiple <em>single</em> columns. If you want to work on ensembles of columns, then use this paradigm: <code>lapply(split(df,group),function)</code>;</p> <p>Try this:</p> <pre><code>gr_TILPS &lt;- lapply( split(df, df[,"customer_id"]), FUN=km...
python|r|function|matrix|apply
2
4,006
347,010
Questions for python->scheme conversion
<p>I currently am trying to write a Python program using scheme semantics so I can later translate it into Scheme without relying on a lot of Pythonic stuff.</p> <p>I'm trying solve the sliding puzzle problem (where you have 9 slots and 8 tiles arranged in a square) using a*, depth first, and breadth first search algo...
<p>You identified that your initial problem was trying to write C semantics in Lisp. Is it not repeating the mistake to try to write scheme semantics in python? I always try to learn language X as a paradigm as much as a language and write in the most x-ish way.</p> <p>It might be justifiable if this was a business ap...
python|arrays|scheme
4
4,007
47,112,929
Build pairs from dictionary
<p>My data is a nested dicitionary of people in countries. Here's what it looks like with unimportant stuff removed:</p> <pre><code>{'DE': [{'createdTime': '2017-11-03T13:41:01.000Z', 'fields': {'Land': 'DE', 'Teilnehmer': 'James Hunt'}, 'id': 'reccgdSZXZFvAztCT'}, {'createdTime': '2017-11-04...
<p>There's not just one way to produce the pairs you want, at least, not if the number of people in a country is greater than 2. So you'll need to pick a way to select pairs so that each person is on each end exactly once.</p> <p>One simple approach is to have each person send to the person after them in the country l...
python|python-3.x
1
4,008
57,728,884
Avoiding module namespace pollution in Python
<p><strong>TL;DR:</strong> What's the cleanest way to keep implementation details out of a module's namespace?</p> <p>There are a number of similar questions on this topic already, but none seems to have a satisfactory answer relative to modern tools and language features.</p> <p>I'm designing a Python package, and I...
<p>Convert to subpackages to limit the number of classes in a place and to separate concerns. If a class or constant is not needed outside of its module, prefix it with a double underscore. Import the module name if you do not want to explicitly import many classes from it. You have laid out all the solutions.</p>
python|namespaces|package
1
4,009
58,576,229
we need to find the aboslute difference between sum of 2 diagonals. Please can u tell me where i am going wrong
<p>Print the absolute difference between the sums of the matrix's two diagonals as a single integer.</p> <p>diagonalDifference(arr): sum1=0 sum2=0</p> <pre><code>for i in range(len(arr)): for j in range(len(arr)): if (i==j): sum1=sum1+arr[i][j] if (((i+j)-1)==(len(arr))): ...
<p>your code is close, you just have the second if statement messed up, it should actually look like this:</p> <pre><code>for i in range(len(arr)): for j in range(len(arr)): if i==j: sum1 += arr[i][j] if i+j == len(arr)-1: sum2 += arr[i][j] </code></pre> <p>example:</p> <p...
python|arrays|matrix|diagonal
1
4,010
33,744,269
Unable to break from for statement in Python
<p>I am having trouble breaking out of the for loop in the following code:</p> <pre><code>def getTakeaway(): list = ['pizza', "italian", "chinese", "indian"] query = input("Please say what take away you'd like").lower() query_words = set(list).intersection(query.split()) for word in query_words: ...
<p>Your <code>break</code> breaks out of the inner <code>for</code> loop. The outer <code>for</code> loop always completes all iterations. You'll need some way to break out of the outer <code>for</code> loop. Like an exception, perhaps:</p> <pre><code>try: for word in query_words: with open('takeaway.txt')...
python|if-statement|for-loop
5
4,011
46,698,437
Parallelization in counting Spark dataframe groups in pyspark
<p>I have approximately 200 files in a single directory on a Linux machine named <code>part-0001</code>, <code>part-0002</code>, and so on. Each has approximately one million rows with the same columns (call them 'a', 'b', and so on). Let the pair 'a','b' be the key for each row (with many duplicates). </p> <p>At the ...
<p><strong>TL;DR</strong> There is <em>probably</em> nothing wrong with your deployment.</p> <blockquote> <p>I had expected to see 21 processes running </p> </blockquote> <p>Unless you specifically configured Spark to use a single core per executor JVM, there is no reason for this to happen. Unlike <code>RDD</code>...
python|apache-spark|pyspark
2
4,012
46,857,607
Calling the exit function in Python
<pre><code>import sys e = input("Do you want to continue?(Enter Y or N)?") if e == "Y": sys.exit() </code></pre> <p>I'm trying to create an exit function that allows the user to exit. Am I using the wrong format or did I mess up the syntax ?</p>
<p>Try this code:</p> <pre><code>import sys e = input("Do you want to continue?(Enter Y or N)?") if e == "Y": sys.exit() </code></pre> <p>There was an indentation problem and you were missing a <code>:</code></p> <p>Also, I'd like to recommend using this logic also:</p> <pre><code>import sys e = input("Do you...
python-3.x
1
4,013
37,758,853
Nested for loop to match vowels by iterating over strings and lists
<p>I am trying to loop over a list, and match each character in that list with characters in a string:</p> <pre><code>wordlist = ['big', 'cats', 'like', 'really'] vowels = "aeiou" count = 0 for i in range(len(wordlist)): for j in vowels: if j in wordlist[i]: count +=1 print(j,'occu...
<p>Using a collections.Counter here is probably the most pythonic way and also avoids nested for loops</p> <pre><code>import collections vowels = "aeiou" wordlist = ['big', 'cats', 'like', 'really'] letters = collections.Counter("".join(wordlist)) for letter in vowels: print(letter, "occurs", letters.get(letter, ...
python|python-3.x|for-loop
2
4,014
27,853,233
How to get Column reference from declarative table in SqlAlchemy?
<p>I use the <em>declarative</em> style to define my tables with SQLAlchemy.</p> <pre><code>Base = declarative_base() class MyTable(Base): id = Column('someone_put_a_strange_for_id', Integer) </code></pre> <p>Now, when I define <strong>ForeignKey</strong> in the class, I need to use</p> <pre><code>MyTable.__tab...
<p>There are two easy options here.</p> <p>The simplest is, just refer to the attribute on the class!</p> <pre><code>Base = declarative_base() class MyTable(Base): __tablename__ = 'mt' id = Column('someone_put_a_strange_for_id', Integer, primary_key=True) bar = Column(Integer) fk = ForeignKeyConstraint(...
python|sqlalchemy
1
4,015
65,492,928
Does not show forms errors in Django
<p>I want to show the required errors but not showing them. I made custom errors in form.py but it does not show either my current or default and why?</p> <p>When I submit a blank form I want it to appear, my created error</p> <p>this is my code --&gt;</p> <p><strong>home.html</strong></p> <pre><code>{% extends &quot;h...
<p>You are returning a clean form without the invalid data, when your form is invalid. It seems your <code>else</code> block is not correctly indented.</p> <pre><code>def home(request): if request.method==&quot;POST&quot;: form = SignUpForm(request.POST) if form.is_valid(): form.save() ...
python|html|python-3.x|django|django-3.0
0
4,016
36,775,105
Calling list items in subprocess
<p>I was trying to call list time using subprocess.call . It seems that its not working. Any better way to do that. </p> <pre><code>import os, sys import subprocess as sb files_to_remove=['*.jpg','*.txt','*.gif'] for item in files_to_remove: try: **sb.call(['rm' %s]) %item** # not working except: ...
<p>It doesn't work as expected, because it escapes the arguments. And the following works:</p> <pre class="lang-python prettyprint-override"><code>#!/usr/bin/python import os, sys import subprocess as sb files_to_remove=['*.jpg','*.txt','*.gif'] for item in files_to_remove: try: sb.check_call(['rm ' + i...
python|subprocess
0
4,017
48,776,217
Split (explode) range in dataframe into multiple rows
<p>This question is similar to <a href="https://stackoverflow.com/questions/12680754/split-explode-pandas-dataframe-string-entry-to-separate-rows">Split (explode) pandas dataframe string entry to separate rows</a> but includes a question about adding ranges.</p> <p>I have a DataFrame:</p> <pre><code>+------+---------...
<p>If I understand what you need </p> <pre><code>def yourfunc(s): ranges = (x.split("-") for x in s.split(",")) return [i for r in ranges for i in range(int(r[0]), int(r[-1]) + 1)] df.Options=df.Options.apply(yourfunc) df Out[114]: Name Options Email 0 Bob [1, 2, 4, 5, 6] bob@em...
python|pandas|numpy|dataframe
6
4,018
4,232,433
How to create a List given a variable "x" in Python?
<p>Python:</p> <p>I have a variable say x. I need to create a list of name "x"</p>
<p>Use a dict.</p> <pre><code>mylists = {} x = 'abhishek' mylists[x] = [] </code></pre> <p>That way, in <code>mylists</code> you'll have all your lists. <code>mylists[x]</code> is the list with name <code>x</code>.</p>
python
3
4,019
69,325,747
A problem with dictionary (TypeError: string indices must be integers)
<p>So, I am a new user of this site and I have a problem with dictionary function.</p> <pre><code>den = { 'first_name': 'den', 'last_name': 'elc', 'age': '16', 'city': 'slovakia', } for user, user_info in den.items(): nameo = user_info['first_name'] namei = user_info['last_name'] age = user_...
<p>In this case you don't need a for loop if you have an array of dictionaries then you need to consider using for loop. Here you can simply do like below.</p> <pre><code>den = { 'first_name': 'den', 'last_name': 'elc', 'age': '16', 'city': 'slovakia', } print(f&quot;\tFirst name:{den['first_name']}&quo...
python|python-3.x|dictionary
5
4,020
48,171,887
Only show round numbers on x-axis in point plot
<p>If I use the following code I end up with an overcrowded x-axis. I would like to show only every 10th number on the x axis. Meaning [0,10,...]. Any idea how to do this?</p> <pre><code>import pandas as pd import numpy as np import pandas as pd import seaborn as sns from matplotlib import pyplot as plt a = pd.DataFr...
<p>You may decide not to use a pointplot at all. A usual lineplot seems to suffice.</p> <pre><code>import pandas as pd import numpy as np from matplotlib import pyplot as plt a = pd.DataFrame({'y':np.random.randn(100)}) plt.plot(a.index, a.y) plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/eMHlG.png...
python|pandas|matplotlib|plot|seaborn
3
4,021
48,402,887
Retrieve item from list by string
<p>Consider this list:</p> <pre><code>l1 = ['Bio:PRJNA57967', 'Assembly:GCF_000007805.1'] l2 = ['Bio:PRJNA224116', 'Sample:SAMN07158965', 'Assembly:GCF_002318635.1'] </code></pre> <p>Without considering that 'Assembly' is always at the last position, I want to retrieve this value.</p> <p>Instead of to select the las...
<p>You can use <code>in</code> for the contains-check:</p> <pre><code>if 'Assembly' in i: print i </code></pre> <p>But, judging from your sample data, you could be more specific:</p> <pre><code>if i.startswith('Assembly'): print i </code></pre> <p>And if you want to exclude other <code>Assembly...:xxx</code...
python|python-2.7
5
4,022
51,362,648
Print sql queries in jupyter notebook with django-extensions plugin
<p>Is it possible to show SQL queries like in this command: <code>python manage.py shell_plus --print-sql</code> but in Jupyter Notebook?</p> <p>I tried this command <code>python manage.py shell_plus --notebook --print-sql</code> but it not worked.</p>
<p>It's probably a bug in Django Extensions that you don't see SQL queries. A few versions ago, someone <a href="https://stackoverflow.com/questions/14738163/hide-sql-statements-when-running-ipython-notebook-with-djangos-django-extension">asked here</a> how to disable SQL printing in Jupyter.</p> <p>As a workaround, y...
django|ipython|jupyter-notebook|manage.py|django-extensions
1
4,023
73,668,116
VSCode - Call to undefined function in imported module
<p>If I write this code:</p> <pre class="lang-py prettyprint-override"><code>import math math.abcdef() </code></pre> <p>where clearly the method <code>abcdef()</code> does not exist in the imported <code>math</code> module, why doesn't visual studio code show an error?</p> <p>Is there a way to force vscode to check tha...
<p>Such error messages in vscode are generally provided by <strong>linting</strong>.</p> <p>You can enable <strong>linting</strong> in settings. The error messages obtained by selecting different linter are not exactly the same.</p> <p><a href="https://i.stack.imgur.com/p4dyG.png" rel="nofollow noreferrer"><img src="ht...
python|visual-studio-code|python-import
0
4,024
73,777,647
Pytorch custom dataset is super slow
<p>During training it takes ages to load one batch of data. What can cause this problem? I am new to Pytorch, i had been working with tensorflow for a while, this my first attempt to create something like this. I wrote a custom dataset which gets its images from folders, it gets stored in a dataframe which will be spli...
<p>Putting the solution of the comments in a cleaner way:</p> <p>The creation of several workers was taking large amount of time. It seems that on windows the creation of processes can have weird behaviours in terms of time.</p> <p>As <code>__getitem__()</code> is not called, the problem is not in data loading per se, ...
python|pytorch|dataset
0
4,025
17,391,819
Running a python .py from lighttable, ctrl+shift+enter : nothing happens
<p>A python code is loaded in lighttable 0.4.11. ctrl+shift+enter doesn't run the code.</p> <p>From the connect tab, one can see that the code is connected to ipython: <img src="https://i.stack.imgur.com/cGviW.png" alt="enter image description here"></p>
<p>with version 0.64, on windows 7x64, this problem is still happen, but using command (<strong><kbd>CTRL</kbd>+<kbd>Space</kbd></strong>) and adding new connection (e.g. add Python27 path instead of Python33) helps the problem. </p> <p><img src="https://i.stack.imgur.com/64tpx.png" alt="enter image description here">...
python|ubuntu|lighttable
1
4,026
55,988,959
Merge multiple dataframes outputted via a FOR loop function into one single dataframe
<p>I have a FOR loop function that iterates over a list of tables and columns (zip) to get minimum and maximum values. The output is separated for each of the combination rather than one single dataframe/table. Is there a way to combine the results of FOR loop into one final output within the function? </p> <pre><code...
<p>Put all the dataframes into a list and do the union after the for-loop:</p> <pre><code>from functools import reduce from pyspark.sql import functions as f from pyspark.sql import DataFrame def minmax(tables, cols): dfs = [] for table, column in zip(tables, cols): minmax = spark.table(table...
python|python-3.x|apache-spark|pyspark|apache-spark-sql
6
4,027
64,795,941
How do I forward fill na's with condition of 2 other cells being equal in pandas?
<p>I have customer transaction data where some invoice numbers are missing. I would like to fill the missing invoice numbers with the preceding row value if both the customer id's are equal in the rows and the transaction amounts are equal. Date is not important.</p> <p>An example of what the data looks like is:</p> <p...
<p>Update: Add a specific column to ffill, thanks to @David Erickson's comment.</p> <p>You can use <code>groupby</code> and <code>ffill</code>.</p> <pre><code>df['invoice'] = df.groupby(['customer', 'amount'])['invoice'].ffill() </code></pre>
python|pandas|missing-data
4
4,028
64,050,590
Replacing elements inside a dictionary Python given a list of current items
<p>I have a dictionary which looks like the following one. What I am trying to do is to find what months are missing and add them as a new key with a value of Nan.</p> <pre><code>{'Congress': {'April': '5.902', 'August': '5.925', 'January': '5.881', 'February': '5.888', 'July': '5.920', 'June': '5.910', 'Ma...
<p>Use <code>set</code> difference to check for missing month</p> <p><strong>Ex:</strong></p> <pre><code>list_of_months ={'January','February','March','April','May','June','July','August','September','October','November','December'} for k,v in data.items(): for i in list_of_months - set(v.keys()): # Check for miss...
python-3.x|dictionary
1
4,029
64,134,197
Python Request entire HTML page, instead of initially loaded content
<p>I am trying to get some data of reviews publicly available on the PlayStore, and since the provided API only allows to get reviews for one own's apps, I am trying to scrape it from the web.</p> <p>I am using <code>requests</code> package to get the HTML page of a given app on the PlayStore and will use <code>Beautif...
<p>Would consider using a web driver to scroll down. Like so</p> <pre><code>SCROLL_PAUSE_TIME = 0.5 # Get scroll height last_height = driver.execute_script(&quot;return document.body.scrollHeight&quot;) while True: # Scroll down to bottom driver.execute_script(&quot;window.scrollTo(0, document.body.scrollHeig...
python|html|python-3.x|web|web-scraping
1
4,030
72,010,029
Excel Sumproduct in Pandas
<p>I have a df:</p> <pre><code>Type price stock a 2 2 b 4 1 b 3 3 a 1 2 a 3 1 </code></pre> <p>The result I would like to get is:</p> <pre><code>Type price*stock a 2*2+1*2+3*1 = 9 b 4*1+3*3 = 13 </code></pre> <p>I can easily do it in Excel, but how...
<p>First multiple columns and then aggregate <code>sum</code> for improve performance:</p> <pre><code>df1 = df.price.mul(df.stock).groupby(df.Type).sum().reset_index(name='price*stock') print (df1) Type price*stock 0 a 9 1 b 13 </code></pre> <p>Another idea is first crete column with multi...
excel|pandas|group-by|sumproduct
3
4,031
70,028,431
Why does the matplotlib.pyplot.quiver documentation states incorrect order of U, V parameters?
<p>Before anything, here is Google Colab link to showcase the issue: <a href="https://colab.research.google.com/drive/1sq8Dn7wdNqbfRmz2SyQnj0MfRirxmneA?usp=sharing" rel="nofollow noreferrer">https://colab.research.google.com/drive/1sq8Dn7wdNqbfRmz2SyQnj0MfRirxmneA?usp=sharing</a></p> <p>Im using matplotlib to plot some...
<p>The <code>quiver</code> function and its documentation are correct, you just mis-interpreted the output of the <a href="https://numpy.org/doc/stable/reference/generated/numpy.gradient.html" rel="nofollow noreferrer"><code>gradient</code></a> function.</p> <p>In the output, the first array (<code>np.gradient(gaussian...
python|matplotlib|gradient
1
4,032
63,400,134
How can I add a parenthesis before the number 2500?
<p>I'm trying to output the following two lines of text:</p> <blockquote> <p>The city with the most contracts is:</p> <p>Chicago (2500 contracts)</p> </blockquote> <p>this is the code I'm using:</p> <pre><code>a = 'Chicago' b = 2500 print('The city with the most contracts is:') print(a, b, 'contracts)') </code></pre> <...
<p>The easiest way is with a formatting string.</p> <pre><code>print(f'{a} ({b} contracts)') </code></pre>
python
2
4,033
61,169,488
how should i define the state for my gridworld like environment?
<p>The problem i want to solve is actually not this simple, but this is kind of a toy game to help me solve the greater problem.</p> <p>so i have a 5x5 matrix with values all equal to 0 :</p> <pre><code>structure = np.zeros(25).reshape(5, 5) </code></pre> <p>and the goal is for the agent to turn all values into 1, s...
<p>I would encode the agent position as a matrix like this:</p> <pre><code>0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 </code></pre> <p>(where the agent is in the middle). Of course you have to flatten this too for the network. So your total state is 50 input values, 25 for the cell states, and 25 for the agent...
python|machine-learning|deep-learning|reinforcement-learning|dqn
1
4,034
66,318,931
How to run tflite on CPU only
<p>I have a tflite modelthat runs in coral USB, but I it to run also in CPU (as an alternative to pass some tests when coral USB is not phisicaly available).</p> <p>I found <a href="https://stackoverflow.com/questions/56793132/how-to-run-tflite-model-on-coral-cpu">this very similar question</a> but the answers given ar...
<p>When you compile a Coral model, it maps all the operations it can to a single TPU Custom OP - for example: <img src="https://coral.ai/static/docs/images/notes/custom-op.png" alt="Coral Model" />.</p> <p>This means that this model will only work on the TPU. That being said, your TFLite interpreter can run CPU models ...
python|google-coral
0
4,035
69,276,961
How to extract loss and accuracy from logger by each epoch in pytorch lightning?
<p>I want to extract all data to make the plot, not with tensorboard. My understanding is all log with loss and accuracy is stored in a defined directory since tensorboard draw the line graph.</p> <pre><code>%reload_ext tensorboard %tensorboard --logdir lightning_logs/ </code></pre> <p><a href="https://i.stack.imgur.co...
<p>Lightning do not store all logs by itself. All it does is <em>streams</em> them into the <code>logger</code> instance and the logger decides what to do.</p> <p>The best way to retrieve all logged metrics is by having a custom callback:</p> <pre><code>class MetricTracker(Callback): def __init__(self): self.col...
logging|pytorch|tensorboard|pytorch-lightning
1
4,036
68,936,099
Accessing file in turtle (.ttl) file via Python rdflib
<p>I'm trying to parse the data in .ttl format following suggestions I found here. My approach:</p> <pre><code> from rdflib import Graph file = 'XYZ.ttl' graph = Graph() graph.parse(file, format='turtle') </code></pre> <p>However, I get the following error:</p> <pre><code>IndexError: string index ou...
<p>@aannie your code appears correct so whatever the issue is, it must be to do with your content, so to fully solve this, I would need to see the data you are trying to parse in.</p> <p>Having said that, content issues, or parsing issues, usually result in <code>BadSyntax</code> errors, so I don't really know where yo...
python|ttl|rdflib
0
4,037
69,260,885
convert xml to csv using python
<p>I am learning my way around python and right now I need a little bit of help. I have an XML file from soap api that I am failing at converting to CSV. I managed to get the data with the request library easily. My struggle is converting it to CSV, I end up with headers with no values</p> <p>My XML Data :</p> <pre><co...
<p>You probably don't need to go through ElementTree; you can feed the xml directly to pandas. If I understand you correctly, this should do it:</p> <pre><code>df = pd.read_xml(path_to_file,&quot;//*[local-name()='MainVIP']&quot;) df = df.iloc[:,:4] df </code></pre> <p>Output from your xml above:</p> <pre><code> Da...
python|xml|soap
0
4,038
59,127,909
How to turn string into matrix
<p>I'd like to turn a string, for example this one: "1,2,3;2,3,4;3,4,5" into a matrix (list inside list). I've tried it using the string.split() function but I can't seem to figure it out. For me the main problem is that there are both ; and , that are messing with my code.</p>
<p>This is horrible, but it seems to work:</p> <pre class="lang-py prettyprint-override"><code>[ [ item for item in row.split(',') ] for row in "1,2,3;2,3,4;3,4,5".split(';') ] </code></pre> <p>However, I would recommend to write this a as a for loop:</p> <pre class="lang-py prettyprint-override"><code>result = [] f...
python-3.x|string|matrix
0
4,039
62,099,121
Is there a way to covert all columns with int to float
<p>I want to convert all the columns of dataframe with dtype as int to float. How can I achieve this? I dont know the name of the columns which are int so might need to use <code>if == int</code> or something.</p>
<p>try this, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.select_dtypes.html" rel="nofollow noreferrer">select_dtypes</a></p> <pre><code>columns = df.select_dtypes(include='int').columns df[columns] = df[columns].astype(float) </code></pre>
python|pandas
0
4,040
59,826,699
I am making a Christmas Lantern with Zelle graphics.py and I want the medium circles to blink random colored lights
<p>This is my code. I wanted create a Christmas Lantern with lights. The lights are the medium circles which I commented. I can't seem to figure out how to create blinking random color lights in order to look like Christmas Lights. </p> <p>Code:</p> <pre><code>from graphics import * import random, time def lantern()...
<p>Here's a way of doing it. It's partially based on the information in the <a href="https://mcsp.wartburg.edu/zelle/python/graphics/graphics/node15.html" rel="nofollow noreferrer">Controlling Display Updates (Advanced)</a> section of the Zelle <code>graphics</code> module's online <a href="https://mcsp.wartburg.edu/ze...
python|graphics|zelle-graphics
0
4,041
49,192,100
Is it possible to trigger intents in Dialogflow using python?
<p>I want to hit an intent using python. In usual cases when a user says something, it goes to Dialogflow which via webhook send it to python. Is it possible that that python decides whether it goes to Dialogflow or not and also to trigger any specified intent.</p>
<p>In general, yes. You didn't specify which chat or voice agent platform you're using, but on all of them you can do something like this:</p> <ul> <li><p>Have the platform send the message to your python server. How it does this depends on each platform, but should be pretty well documented.</p></li> <li><p>Determine...
python|python-3.x|python-2.7|dialogflow-es
3
4,042
67,776,511
How to assign ids to sets of coordinates? -python
<p>I am working with a <code>GeoDataFrame (gdf)</code> containing a road network (Lines) that looks like the following:</p> <pre class="lang-py prettyprint-override"><code> id_road speed geometry 0 1 50.00 LINESTRING (a_lon a_lat, b_lon b_lat) 1 2 50.00 LINESTRING (b_lon b_lat, c_lon c_lat) 2 ...
<p>This is a scrappy implementation, but let me know if it helps:</p> <p>To begin you likely need some way of transforming coordinate pairs to a list of pairs from which you can index:</p> <pre><code>coordinate_pairs = df['geometry'].apply(lambda g: [g.coords[0], g.coords[-1]]) coordinates = [p for pair in coordinate_p...
python|geopandas
1
4,043
66,766,629
SQLAlchemy best way to filter a table based on values from another table
<p>I apologize in advance if my question is banal: I am a total beginner of SQL.</p> <p>I want to create a simple database, with two tables: <code>Students</code> and <code>Answers</code>. Basically, each student will answer three question (possible answers are <code>True</code> or <code>False</code> for each question)...
<p>When I asked the question, I was in a hurry. Since then, I have had the time to study <a href="https://docs.sqlalchemy.org/en/14/orm/tutorial.html" rel="nofollow noreferrer">SQLAlchemy ORM documentation</a>. There are two recommended ways to filter tables based on values from another table.</p> <p>The first way is a...
python|sql|sqlalchemy
7
4,044
42,890,467
Run OpenCV script on start with imshow
<p>I have an OpenCV/python script running at my Raspberry Pi which reads the camera and shows the stream on the RCA monitor connected to the Pi.</p> <p>Now I want the script to be loaded on boot. I already tried a cronjob @reboot, the /etc/rc.locale, /etc/profile and ~/.bash_profile.</p> <p>I see the red light of the...
<p>I know its quite an old thread, but I thought you might be still interested in a solution that worked for me. Hopefully, that can help you as well:</p> <p><a href="https://stackoverflow.com/questions/47411763/raspberry-pi-autostart-opencv-script-error-with-cvimshow/47413583#47413583">Raspberry Pi - Autostart OpenCv...
python|opencv|raspberry-pi|raspbian
0
4,045
42,838,855
Python stacked to unstacked format
<p>or also known as long to wide format.</p> <p>I have the following:</p> <pre><code>ID1 ID2 POS1 POS2 TYPE TYPEVAL --- --- ---- ---- ---- ------- A 001 1 5 COLOR RED A 001 1 5 WEIGHT 50KG A 001 1 5 HEIGHT 160CM A 002 ...
<p>You can set the index with all but the <code>'TYPEVAL'</code> column then <code>unstack</code></p> <pre><code>df.set_index( df.columns.difference(['TYPEVAL']).tolist() ).TYPEVAL.unstack('TYPE').reset_index().rename_axis(None, axis=1) </code></pre> <p><a href="https://i.stack.imgur.com/9ntXU.png" rel="nofollow ...
python|database|pandas
3
4,046
3,742,855
Python openssl problem
<p>I'm trying to write a simple mail retrieval program in python. It seems the connection is getting established. But when I try to authorize it with the username, I don't get a reply from the server. Can anyone tell me what is going wrong here? </p> <pre><code>import socket, sys from OpenSSL import SSL ctx = SSL.Con...
<p>End the string with a \r\n </p>
python|openssl
1
4,047
50,519,820
np.all() does not get executed
<p>I wrote a script:</p> <pre><code>import numpy as np a=[0,0,0] if np.all(a==0): print('All are zeros!') </code></pre> <p>but nothing gets printed out. Shouldn't <code>np.all(a==0)</code> evaluate to be True since all elements in <code>a[]</code> are <code>0</code>'s? </p>
<p>In order to avoid explicitly converting list <code>a</code> to a <code>numpy.ndarray</code>, you can call <code>numpy</code>'s comparison operators directly:</p> <pre><code>np.all(np.equals(a, 0)) </code></pre> <p>However, if your data are already a Python list, simply use Python's <code>all()</code> to get the sa...
python|numpy
3
4,048
35,203,186
NumPy docstring for function type and None type
<p>I am writing the following function:</p> <pre><code>def parse_zip_file(path, handler): """ Parse all files contained in a zip file (specified by the path parameter). Parameters ---------- path : str The path to the zip file. handler: function When looping through all the fil...
<p>I had this same question. This <a href="https://stackoverflow.com/questions/27784179/docstrings-when-nothing-is-returned">question</a> is really similar, and the accepted answer says to include it, but doesn't really make a claim about why or why not to do it, nor does it answer your particular question about where ...
python|numpy|pycharm|docstring
2
4,049
69,332,864
Find specific pattern and remove tag containing pattern
<p>I'm trying to remove (delete) the whole tag if the tag contains a text pattern. The pattern in my case should be <code>interesar:</code> (colon included). This is my code:</p> <pre><code>from bs4 import BeautifulSoup import requests import time import re import json url = &quot;https://www.globi.site/sample/&quot; ...
<p>Use <code>text=</code> parameter with compiled regex:</p> <pre class="lang-py prettyprint-override"><code>from bs4 import BeautifulSoup import requests import time import re import json url = &quot;https://www.globi.site/sample/&quot; response = requests.get(url) data = response.content soup = BeautifulSoup(data, &...
python|regex|beautifulsoup
3
4,050
57,457,982
Upgrade Tensorflow model or Retrain for SavedModel
<p>I followed "Tensorflow for poets" in 2017 and retrained my own collection of images and created "retrained_graph.pb" and "retrained_labels.txt"<br> Today I need to run this model on Tensorflow Serving. There are two options to accomplish this: </p> <ol> <li><p>Upgrade the old model to save it as under the "saved_m...
<p>In my opinion, either using <strong><code>Tensorflow Hub</code></strong> or using the <strong><code>Pre-Trained Models</code></strong> inside <strong><code>tf.keras.applications</code></strong> is preferable because, in either cases, there won't be many code changes required to Save the Model, to make it compatible ...
tensorflow|tensorflow-serving|imagenet|tensorflow-hub
0
4,051
57,529,443
Merge 2 DataFrame and sum up one of the column
<p>I have 2 Dataframes that I would like to merge in pandas (Python 2.7).</p> <p>In the merge (DataFrame C) the same ID and Sub_id must be only one line and their Views must add up.</p> <p>My DataFrame A</p> <pre><code>-------------------------------- ID | Sub_ID | Views -------------------------------- 345 | 4 | 1...
<p>IIUC, you could use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html" rel="nofollow noreferrer"><code>pandas.concat</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html" rel="nofollow noreferrer"><code>pandas.DataFrame....
pandas|python-2.7|dataframe
0
4,052
45,376,410
How to get ROC curve for decision tree?
<p>I am trying to find <em>ROC curve</em> and <em>AUROC curve</em> for decision tree. My code was something like</p> <pre><code>clf.fit(x,y) y_score = clf.fit(x,y).decision_function(test[col]) pred = clf.predict_proba(test[col]) print(sklearn.metrics.roc_auc_score(actual,y_score)) fpr,tpr,thre = sklearn.metrics.roc_cu...
<p>First of all, the <code>DecisionTreeClassifier</code> <strong>has no</strong> attribute <code>decision_function</code>.</p> <p>If I guess from the structure of your code , you saw this <a href="http://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html" rel="nofollow noreferrer">example</a></p> <p>...
python|scikit-learn|data-science|auc
7
4,053
57,265,099
How can I get the Hours from the column created_time of sample dataframe and get count of it as another dataframe
<p>sample dataframe(df) having following columns:</p> <pre><code> id created_time faid 0 21 2019-06-17 07:06:45 FF1854155 1 54 2019-04-12 08:06:03 FF30232 2 88 2019-04-20 05:36:03 FF1855531251 3 154 2019-04-26 07:09:22 FF8145292 4 ...
<p>try calculating hours from created_time.</p> <p>groupby hour and count it</p> <pre><code>df['hour'] = pd.to_datetime(df['created_time']).dt.hour res = df.groupby(['hour'],as_index=False)['faid'].count().rename(columns={"faid":"count"}) </code></pre> <pre><code>hour count 07 2 08 2 </code></pre>
pandas|pandas-groupby
1
4,054
57,091,056
Why do I keep getting the error "min() arg is an empty sequence"?
<p>I have the following code: </p> <pre><code>test_file = open("test.txt","r") numbers = test_file.readlines() numbers = map(int,numbers) print("Maximum number in list:", max(numbers)) print("Minimum number in list:", min(numbers)) test_file.close() </code></pre> <p>Can you help me please because I keep getting the e...
<p>your <code>numbers</code></p> <pre><code>numbers = map(int,numbers) </code></pre> <p>is an iterator (in python 3 that is; in python 2 you would have gotten a list and everything would have worked as expected); when you apply <code>max(numbers)</code> you exhaust the iterator; <code>min</code> has nothing to iterat...
python|max|min
6
4,055
23,801,997
Django : Doesn't look like a module path
<p>I'm new to Django and Python, but not to programming. Using Visual Studion, I'm trying to follow this toturial : <a href="http://showmedo.com/videotutorials/video?name=1100000&amp;fromSeriesID=110" rel="nofollow">http://showmedo.com/videotutorials/video?name=1100000&amp;fromSeriesID=110</a></p> <p>But as soon as I ...
<p>You should not be modifying TEMPLATE_LOADERS at all. You should be using TEMPLATE_DIRS.</p>
python|django
0
4,056
54,959,636
Simple Python code won't work (Or, and string comparisons)
<p>So I'm practising python, and doing simple tasks, so I tried making a Rock Paper Scissors game. It kept screwing up, and I've reduced most of the code to a point where the annoying code remains. When I try executing this, no matter what I input into the p_choice input, it thinks it's rock, paper, or scissors. Whethe...
<p>The <code>==</code> operator in programming languages usually compares the expression on the left with the expression on the right. Also, <code>or</code> has lower precedence. This means that the expression in your case is evaluated as: <code>(p_choice == "rock") or ("paper") or ("scissors")</code>. <code>"paper"</c...
python-3.x
2
4,057
41,016,835
Use function to modify pandas dataframe
<p>This is a follow up of the question <a href="https://stackoverflow.com/questions/41015805/how-to-use-functions-with-pandas-dataframe/41015945#41015927">here</a>: How to modify a dataframe using function? Lets say I want to make call <code>.upper()</code> on values in <code>a</code></p> <pre><code>df = pd.DataFrame(...
<p>You can call function for column <code>a</code>:</p> <pre><code>def doSomething(x): return x.upper() print (df1.a.apply(doSomething)) 0 LONDON 1 NEWYORK 2 BERLIN Name: a, dtype: object </code></pre> <hr> <pre><code>print (df1.a.apply(lambda x: x.upper())) 0 LONDON 1 NEWYORK 2 BERLIN Nam...
python|pandas
6
4,058
38,420,829
Variable column name in SQL lite and Python
<p>my question is, as the title says, how I can create a variable column in SQL lite used in Pyhton.</p> <p>Here's my code, to show you what exactly I mean:</p> <pre><code>#Table with variables def dynamic_data_entry(list_name, num, column): element_name = list_name[num] cur.execute("INSERT INTO myliltable (c...
<p>You need to use the string's <code>format()</code> method to <em>insert</em> the column name into the SQL string:</p> <pre><code>cur.execute("INSERT INTO myliltable ({}) VALUES (?)".format(column), element_name) </code></pre> <p>You can find more information in the <a href="https://docs.python.org/3.5/...
python|sqlite
3
4,059
39,968,888
I need to assume for an empty sequence in this code for python
<p>The function prints the keyword length, then prints a sorted list of all the dictionary keywords of the required length, which have the highest frequency, followed by the frequency. For example, the following code:</p> <pre><code> word_frequencies = {"fish":9, "parrot":8, "frog":9, "cat":9, "stork":1, "dog":4...
<p>Simply add a fallback condition to the <code>max()</code> call so that it never tries to find the largest of an empty iterable:</p> <pre><code>max_freq = max(right_length.values() or [0]) </code></pre> <p>If <code>right_length.values()</code> is empty, <code>[0]</code> (which is not empty) will be used instead, an...
python|list|function
1
4,060
40,088,132
Tensorflow MNIST (Weight and bias variables)
<p>I'm learning how to use Tensorflow with the MNIST tutorial, but I'm blocking on a point of the tutorial.</p> <p>Here is the code provided : </p> <pre><code>from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) x = tf.place...
<p>TensorFlow <a href="https://www.tensorflow.org/versions/r0.11/how_tos/variables/index.html" rel="noreferrer">variables</a> maintain their state from one <code>run()</code> call to the next. In your program they will be initialized to zero, and then progressively updated in the training loop.</p> <p>The code that ch...
python|python-3.x|machine-learning|tensorflow
11
4,061
39,998,424
How to delete a file without an extension?
<p>I have made a function for deleting files:</p> <pre><code>def deleteFile(deleteFile): if os.path.isfile(deleteFile): os.remove(deleteFile) </code></pre> <p>However, when passing a FIFO-filename (without file-extension), this is not accepted by the os-module. Specifically I have a subprocess create a FI...
<p><code>isfile</code> checks for <em>regular</em> file.</p> <p>You could workaround it like this by checking if it exists but not a directory or a symlink:</p> <pre><code>def deleteFile(filename): if os.path.exists(filename) and not os.path.isdir(filename) and not os.path.islink(filename): os.remove(file...
python
7
4,062
52,295,283
Scikit-learn train_test_split inside multiprocessing pool on Linux (armv7l) does not work
<p>I am experiencing some weird behaviour using the train_test_split inside a multiprocessing pool, when running Python on the Rasbperry Pi 3.</p> <p>I have something like this:</p> <pre><code>def evaluate_Classifier(model,Features,Labels,split_ratio): X_train, X_val, y_train, y_val = train_test_split(Features,Lab...
<p>Instead of setting a random state, you should try shuffling the data before splitting. You can do this by setting the parameter: shuffle=True. </p>
python|scikit-learn|raspberry-pi|multiprocessing|train-test-split
0
4,063
52,186,812
Loading Tensorflow Graph in other file not giving the same accuracy
<p>I trained a CNN in Tensorflow and it tested with 92% accuracy. I saved it as a typical ckpt file. </p> <pre><code>session = tf.Session(config=tf.ConfigProto(log_device_placement=True)) session.run(tf.global_variables_initializer()) &lt;TRAINING ETC&gt; saver.save(session, save_path_name) </code></pre> <p>In a diff...
<p>You are assigning the wrong method to <code>saver</code>. From the <a href="https://www.tensorflow.org/guide/saved_model" rel="nofollow noreferrer">TF Guide</a> you can see that you want to init session and then upload through <code>tensorflow.train.Saver()</code>.</p> <pre><code>tf.reset_default_graph() # Create ...
session|tensorflow|inference
2
4,064
52,059,137
google account login automation with selenium causes error
<p>I am trying to login to Google with selenium. The steps are simple, first you type email and hit next, then you type password and hit next. My code looks like this:</p> <pre><code>driver = webdriver.Firefox() driver.get("https://accounts.google.com/signin") driver.implicitly_wait(3) driver.find_element_by_id("ide...
<p>The problem was, I just had to wait for passwords pressence and visibility to be loaded, like this:</p> <pre><code>driver = webdriver.Firefox() driver.get("https://accounts.google.com/signin") driver.implicitly_wait(3) driver.find_element_by_id("identifierId").send_keys("email") driver.find_element_by_id("identif...
python|selenium|error-handling|automation|google-signin
2
4,065
47,834,912
Getting img source link from multiple elements
<p>I want to get a link from multiple attributes</p> <p>example :</p> <pre><code>&lt;img id="ucCPCItemList_rptItems_ucItemListLayout_0_itemImage1_0" onerror="if(this.src=='http://pics.auction.co.kr/renewa/lp/img_none.gif') return; this.src='http://pics.auction.co.kr/renewal/lp/img_none.gif';" imageresizeonload="Fals...
<p>you can use the select method also</p> <pre><code>soup.select("img#ucCPCItemList_rptItems_ucItemListLayout_0_itemImage1_0")[0]['src'] </code></pre>
python|beautifulsoup
1
4,066
38,049,357
New row based on other's row past value to current value
<p>I'm trying to create a new column called <code>move</code> in <code>df</code> that gives the value of <code>1</code> if the value in <code>x is higher</code> than its previous value and a <code>0</code> if the <code>value is lower</code>, so the first value in <code>move</code> should be a <code>NaN</code>.</p> <pr...
<p>You can compare using <code>shift</code> with a slice of the column using <code>iloc</code> and cast the boolean series to numeric dtype using <code>astype</code>:</p> <pre><code>In [82]: df['move'] = (df['x'].iloc[1:] &gt; df['x'].iloc[1:].shift()).astype(int) df Out[82]: x move 0 1 NaN 1 0 0.0 2 2 1...
python|pandas|dataframe|conditional-statements|shift
2
4,067
27,461,916
Should I use my own users table or use the admin generated one with django?
<p>I created my own user table. I've been learning how to use the admin panel and I saw there's already a user table. Should I use it or mine? (for example connection, member panel etc...) If I should use it how to update it? If I shouldn't what do I have to use it for?</p>
<p>Use the one django provides.</p> <p>If you want extra fields on your user, create an extension to the user model.</p> <p>It's really easy to do, you can just create your own model and make it inherit from the django.contrib.auth.User model, or you can also look here: <a href="https://stackoverflow.com/questions/4...
python|django|admin
4
4,068
64,330,754
My heroku app is not able to import the Phonenumber_field module
<p>I am trying to deploy a Django application to Heroku.</p> <p>This is my settings.py file:</p> <pre><code> import os import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development setting...
<p>The <em>Installation</em> part of the <code>django-phonenumber-field</code> library implies that you have to install the library via</p> <pre><code>pip install django-phonenumber-field[phonenumberslite] </code></pre> <p>Which implies that in your <code>requirements.txt</code> it should look like</p> <pre><code>djang...
python|django|heroku
3
4,069
73,012,152
ImportError: cannot import name 'app' from partially initialized module 'market' (most likely due to a circular import)
<p>I was trying to package my code as it was getting kind of complex for me to keep in one file and i encountered an import error when i tried to run the file that says circular import error, how do i solve this error? I have been analyzing the code and i cannot seem to be able to figure out what might be wrong.</p> <p...
<p>in your <code>__init__.py</code> you import <code>routes</code></p> <p>in <code>routes.py</code> you import <code>app</code> (defined in <code>__init__.py</code>)</p>
python|flask-sqlalchemy
1
4,070
73,126,542
How can I pass a positional argument to an optional argument in python functions?
<p>I am writing a gradient descent function for linear regression and want to include a default initial guess of parameters as a numpy zero array whose length is determined by the shape of an input 2D array. I tried writing the following</p> <pre><code>def gradient_descent(X,w0=np.zeros(X.shape[1])): </code></pre> <p>w...
<p>You could do this:</p> <pre class="lang-py prettyprint-override"><code>def gradient_descent(X, w0=None): if not w0: w0 = np.zeros(X.shape[1]) ... </code></pre>
python|function|parameter-passing
0
4,071
56,009,560
ModuleNotFoundError: No module nomed 'gi'
<p>Using instructions from this website <a href="https://www.gtk.org/download/windows.php" rel="nofollow noreferrer">https://www.gtk.org/download/windows.php</a> I executed the following two lines from a Windows 10 MSYS2 window: pacman -S mingw-w64-x86_64-gtk3 pacman -S mingw-w64-x86_64-python3-gobject</p> <p>No...
<p>Basically I gave up on GTK and moved my project to wxPython. It's a lot of work but so far the code works on Linux, Windows and Os X</p>
python-3.x|windows|pyinstaller|gtk3
-2
4,072
65,265,474
AttributeError: 'NoneType' object has no attribute 'text' BeautifulSoup Parsing
<blockquote> <p>I am successful in getting all the Headlines from a news site, but after it fetches all the data, the python programme crashes with the following error :</p> </blockquote> <pre><code>Traceback (most recent call last): File &quot;c:\Users\HP\Desktop\My Python Projects\pratidintime.py&quot;, line 14, in &...
<p>Change your <code>for</code> loop to</p> <pre><code>title = item.find('h2', {'class': 'title'}) if title is not None: print(title.text.strip()) </code></pre> <p>That should avoid the error.</p>
python|beautifulsoup|python-requests
0
4,073
65,240,360
Send email through AWS Workmail from Python script
<p>Is it possible to send automated email messages with Amazon Workmail through a Python script?</p> <p>My code keeps hanging and when I can the run I get a <strong>SMTP server connection error</strong>. How can I fix this? I presume, its the SMTP configuration, but does anyone know what that is?</p> <pre><code>import ...
<p>Removing <code>server.starttls()</code> from the this block fixed it:</p> <pre><code>try: server = smtplib.SMTP_SSL('smtp.mail.eu-west-1.awsapps.com', 465) server.ehlo() server.login(email_user, email_password) text = msg.as_string() server.sendmail(email_sender, email_recipient, text) print('Email sent ...
python|smtp|amazon-workmail
2
4,074
65,291,302
Please explain how does the second line of code works
<p>Please explain the second line of code.</p> <p>Code:</p> <pre><code>s_counter = collections.Counter(s).most_common() s_counter = sorted(s_counter, key=lambda x: (x[1] * -1, x[0])) </code></pre>
<p>Consider:</p> <pre><code>import collections s = [2, 2, 2, 3, 4, 4, 1, 1] s_counter = collections.Counter(s).most_common() </code></pre> <p>This gives</p> <pre><code>[(2, 3), (4, 2), (1, 2), (3, 1)] </code></pre> <p>Note that in the result, <code>(4, 2)</code> occurs before <code>(1, 2)</code>, since 4 occurs before...
python
1
4,075
65,263,918
Telethon events in multithreading not working as expected
<p>I wanted to run Telethon events in multi thread, multithreading.</p> <p>For the following code, what I expected is multi thread, cocurrent independent events. <code>await asyncio.sleep( 3 )</code> will sleep 3 seconds. So If you send any text on telegram to the account, it will wait 3 seconds and send me back &quot;...
<p>You are using sequential_updates so until the first update is not completed it will not move to other update. I guess you need to turn off sequential updates.</p>
python-3.x|python-asyncio|telethon
2
4,076
68,726,466
Cropping an image in python
<p>I am working on an object detection project using Azure Custom Vision. An example of a bounding box I got is <code>[0.053913698, 0.6198375, 0.09218301, 0.13308609]</code>.</p> <p>The selected answer <a href="https://stackoverflow.com/questions/15589517/how-to-crop-an-image-in-opencv-using-python">here</a> is not goi...
<h2>Reason</h2> <p>A bounding-box list tells you <code>[&quot;left&quot;, &quot;top&quot;, &quot;width&quot;, &quot;height&quot;]</code>, and each of them is <em><strong>in percent of the image original size</strong></em>.</p> <h2>Solution</h2> <p>Assumed that your image dimension is 800 x 600 (i.e., Image Width is 800...
python|computer-vision|object-detection|microsoft-custom-vision
3
4,077
68,665,022
Creating collisions between a Sprite and a list (that aren't sprites) in a Maze
<p>I have been working on a randomly generated maze game with enemies that move through the maze toward the player. However, I am having the issue of the player being able to move through the walls of the maze, the problem I have is that the walls of the maze aren't sprites and therefore cannot use sprite collide, or R...
<p>Calculate the rows and columns of the corner points points of the player rectangle.</p> <pre class="lang-py prettyprint-override"><code>col_l = player.rect.left // CELL_SIZE col_r = player.rect.right // CELL_SIZE row_t = player.rect.top // CELL_SIZE row_b = player.rect.bottom // CELL_SIZE </code></pre> <p>If t...
python|pygame|collision-detection|collision|maze
2
4,078
71,643,627
Get error when try to convert netcdf time to datetime in python
<p>I want to read netcdf file and convert time of unit days since to python datetime object, when i try to use num2date() function this error is occur I don't know how to handle it</p> <pre><code>import netCDF4 as nc import numpy as np import datetime as dt # from cftime import num2pydate # from netCDF4 import Dataset...
<p>Without some more information regarding your data set it's a little hard to understand the error that you have been getting. It looks like one of the variable you are putting in to num2date isn't properly set to a value and is set to <code>None</code> instead.</p> <p>There is also an error in your code, the netCDF4 ...
python|typeerror|netcdf4
0
4,079
62,634,808
Not able to "import win32com.shell.shell" in python3.8.3 to execute admin command prompt commands using python3
<p>We were using python 2 in our project and we had created various scripts that work on Windows 10 using pywin32 lib and were using <code>import win32com.shell.shell as shell</code> and then execute the shell commands like <code>shell.ShellExecuteEx(lpVerb='runas', lpFile='cmd.exe', lpParameters='/c ' + commands)</cod...
<p>win32com.shell.shell as shell would be imported exclusively on python2 if you wanted to upgrade you would have to update to a newer version of pywin32. A github repo has released v225 which supports Python 3.8.3 install the files and you should be able to use your code without any import errors</p> <p><a href="http...
python|python-3.x|cmd
0
4,080
61,778,886
Stopwatch in python tkinter
<p>i am designing a code for a mountain bike club. The club wants a way to track their races on a stopwatch that reads out live time in milliseconds for even the closest of races. Anyone have any idea where to even start when coding this</p>
<p>What I understand here is that you are trying to program a stopwatch which which times in MINUTES:SECONDS:MILLISECONDS?</p> <p>First of all, I would look up on <code>import time</code> and make sure you have an understanding of how to use that. This might help:</p> <p><a href="https://www.programiz.com/python-prog...
python|tkinter|stopwatch
0
4,081
67,460,466
How to use Bot top role position command in discord.py?
<p>Hi I want code a bot when ctx.author role position is lower than bot role , ctx.author gets error And can not use that command for example: I coded This (client is bot object)</p> <pre><code>@client.command() async def ab(ctx): if client.top_role.position &gt; ctx.author.top_role.position: await ctx.send...
<pre><code>@client.command() async def ab(ctx): if ctx.guild.me.top_role &gt;= ctx.author.top_role: await ctx.send('Error!') return </code></pre>
python|python-3.x|discord|discord.py
0
4,082
67,546,162
Print python-socketio events infos using decorators
<p>I would like to improve the <code>socketio.event</code> decorator to make it print the event fired and its parameters. I have a <code>Manager</code> class which has a <code>self.sio: socketio.Server</code> attribute. I try to define a new decorator as a <code>Manager</code> method such as it returns a function decor...
<p>I think something like this should work for you:</p> <pre class="lang-py prettyprint-override"><code> def event(self, func): def wrapper(*args, **kwargs): print(f'[{func.__name__}] : {args} {kwargs}') return func(*args, **kwargs) return self.sio.on(func.__name__, wrapper) <...
python|socket.io|python-socketio
1
4,083
71,239,375
Draw edges between nodes based on similarity using NetworkX?
<p>Here is my toy nodes dataframe:</p> <pre class="lang-py prettyprint-override"><code> import pandas as pd df = pd.DataFrame({ 'id': [1, 2, 3, 4, 5], 'a': [55, 2123, -19.3, 9, -8], 'b': ['aa', 'bb', 'ad', 'kuku', 'lulu'] }) </code></pre> <p>I am building a Graph with the nodes ...
<p>AFAIK, <code>networkx</code> does not implement calculation of similarity, so that will have to be calculated outside networkx.</p> <p>For question 1, given the mixed data types, I can recommend <a href="https://recordlinkage.readthedocs.io/en/latest/notebooks/link_two_dataframes.html" rel="nofollow noreferrer">reco...
python-3.x|pandas|graph|networkx|record-linkage
1
4,084
70,280,150
Run queries on Bigquery from Cloud functions
<p>I am trying to run a query from cloud functions and I read that I could call a scheduled query (on-demand) and I am running the code below but I am getting &quot;Requested entity was not found.&quot; error message.</p> <pre><code> def runQuery(transferid): #Source Name = 'projects/413410600298/locations/southa...
<p>I change my variable parent so that it would be as below and it worked just fine!</p> <pre><code>parent = 'projects/413410600298/locations/southamerica-east1/transferConfigs/' + transferid </code></pre>
python|google-bigquery|google-cloud-functions
0
4,085
70,156,551
Using API to update value in another python program
<p>I am currently building a raspberry pi project to monitor the surrounding temperature and buzz if it’s too high. The program is simple it reads the config (temp to buzz at) from a file and it uses it for the infinite while loop. I was thinking of making a separate program for a flask server to act as a GUI and the u...
<p>You can use functions</p> <pre><code>#file1 def buzz(config, temp): #code </code></pre> <pre><code>#file2 (gui) from file1 import buzz while True: buzz(&quot;input from gui&quot;, &quot;read temperature from raspberry pi&quot;) </code></pre>
python|flask
1
4,086
11,233,140
Is there a way to get the name of a workbook in openpyxl
<p>There is a worksheet.title method but not workbook.title method. Looking in the documentation there is no explicit way to find it, I wasn't sure if anyone knew a workaround or trick to get it.</p>
<p>A workbook doesn't really have a name - normally you'd just consider it to be the basename of the file it's saved as... <em>slight update</em> - yep, even in VB WorkBook.Name just returns "file on disk.xls"</p>
python|excel|openpyxl
2
4,087
70,685,347
How to replace values in numpy matrix columns with values from another array?
<p>I have 2 numpy arrays:</p> <pre><code>a= np.array([[2, 1, 7], [7, 7, 3], [1, 7, 4]]) b= np.array([9,-1,17]) </code></pre> <p>I would like to change the <code>7</code> in each column in <code>a</code> with the values from <code>b</code>, such that in the first column the <code>7</code> is ...
<p>Assuming the computed matrices are big, you can implement a <strong>fast parallel version using Numba</strong>. This implementation is much faster than the initial solution using pure-Python loops which create many small temporary arrays and an inefficient non-contiguous memory access pattern (eg. <code>a[:,j]</code...
python|numpy
1
4,088
56,622,397
How to convert from UTC to tzutc() timezone?
<p>I have a naive timestamp which I need to convert to <code>tzutc()</code> timedate in order to calculate time delta.</p> <p>I converted string to Date using </p> <pre><code>pd.Timestamp(x) </code></pre> <p>Then converted it to UTC using </p> <pre><code>pytz.utc.localize(x) </code></pre> <p>and got:</p> <pre><co...
<p>You can convert the timestamp to a datetime and back using the methods seen <a href="https://stackoverflow.com/questions/22825349/converting-between-datetime-and-pandas-timestamp-objects">HERE</a>.</p> <p>Here is a method for converting a datetime from local time to UTC using pytz:</p> <pre><code>def LocalToUTC(dt...
python|timestamp
0
4,089
56,522,501
running python xlwings library and it fails COMRetryObjectWrapper(DispatchEx('Excel.Application'))
<p>I have a code which basically manipulates xlsm file, presses a macro button, and then force closing it (using psutil) </p> <p>the process is: open xlsm file (MyExcel.xslm)==> write data ==> press macro button, save==> force close (with psutil).</p> <p>and the process repeats 'x' times (lets say 20000 times)</p> <...
<p>As the comment above showed, I have implemented an internal kill,</p> <p>self.workBook.app.kill()</p> <p>it seems that it has solved the issue.</p>
python-3.6|xlwings|xlsm
0
4,090
56,812,810
sympy.physics.units substitution gives TypeError
<p>I'm trying to use sympy as a backend for some conversion/math code and ran into this problem.</p> <pre class="lang-py prettyprint-override"><code>from sympy.parsing.sympy_parser import parse_expr from sympy.physics import units type(units.newton) # -&gt; sympy.physics.units.quantities.Quantity parse_expr('2*Newto...
<p>From the documentation <code>parse_expr</code> takes an optional parameter:</p> <pre><code>global_dict : dict, optional A dictionary of global variables. By default, this is initialized with from sympy import *; provide this parameter to override this behavior (for instance, to parse "Q &amp; S"). </...
python|python-3.x|sympy
2
4,091
60,825,251
how to replace a string with different string in the column of a data frame
<p>I have a dataframe <code>Adult</code> and a column in the data frame <code>workclass</code> with thousands of rows. The column contains different string objects. I would like to replace all string <code>?</code> with string <code>Private</code> I have tried different variations of the code:</p> <pre><code>Adult.loc...
<p>Try the following code: <code>Adult['workclass'] = Adult['workclass'].str.replace('?', 'Private')</code></p>
python|pandas
1
4,092
65,918,565
Django 1.11 - make column foreign key without deleting
<p>Previously we made integer field like:</p> <pre class="lang-py prettyprint-override"><code>cart_id = models.IntegerField(_('cart_id'), null=True) </code></pre> <p>But now I want to make this field foreign key:</p> <pre class="lang-py prettyprint-override"><code>cart = models.ForeignKey(Cart, null=True, db_column='ca...
<p>First add the <code>ForeignKey</code>. Set the default <code>blank=True</code> and run migrations.</p> <p>Then run this code to fill the previous instances (python manage.py shell):</p> <pre><code>m = Order.objects.all() for i in m: c = Cart.object.get(id=i.cart_id) i.cart = c i.save() </code></pre> <p>O...
python|mysql|django|django-models
0
4,093
68,239,804
Create two lists with one use of Python list comprehension?
<p>I have a list of objects that each contain several class variables. I'm interested in a couple of those class variables, and I'd like to create two separate lists, each containing a different class variable from that list of objects.</p> <p>The object class looks something like this:</p> <pre><code>class Pie: ...
<p>The very definition of a list comprehension is to produce one list object.</p> <p>Don't use list comprehensions here. Just use an ordinary loop:</p> <pre><code>list_of_array1 = [] list_of_array2 = [] for x in list: list_of_array1.append(x.array1) list_of_array2.append(x.array2) </code></pre> <p>This leaves y...
python|list|list-comprehension
5
4,094
59,063,625
How to load a file from google cloud storage to google cloud function
<p>I have to read data from a file which is stored in google cloud storage am using this method to load file inside my GCP function but this is causing error</p> <pre><code>client = storage.Client() bucket = client.get_bucket('bulk-testing') blob = bucket.get_blob("h1.csv") blob.download_to_filename("h2") </code></pr...
<p>If you need to write a file in Cloud Functions, the only writable part of the system is in /tmp. <a href="https://cloud.google.com/functions/docs/concepts/exec#file_system" rel="noreferrer">Read the documentation about this.</a> This space is backed by memory, so you will need to make sure that the function has be...
python|google-cloud-platform|google-cloud-functions|google-cloud-storage
5
4,095
59,441,470
Computing grid computations using numpy meshgrid
<p>I have used numpy meshgrids for a long time, and typically find no issues when trying to pass that meshgrid through a function. In my experience it has always been the case that I can define my coordinate space as </p> <pre><code>x,y,z = numpy.meshgrid(numpy.linspace(-10,10,10), numpy.linspac...
<p><code>np.cross</code> only accept a vector of size 3, or nd-array with the last dimension of size 3, so we need to stack <code>np.stack([x,y,z])</code> to create a <code>10*10*10*3</code> nd-array first.</p> <p>The results will be a <code>10*10*10*3</code> array, and to be able to unpack this array later, we need t...
python|arrays|numpy|simulation
0
4,096
62,360,574
PYTHON - "Love for Mathematics"
<p>I just finished a challenge on Dcoder ("Love for Mathematics") using Python. I failed two test-cases, but got one right. I used somewhat of a lower level of Python for the same as I haven't explored more yet, so I'm sorry if it looks a bit too basic.The Challenge reads:</p> <p><em>Students of Dcoder school love Mat...
<p>This problem is alike <a href="https://www.geeksforgeeks.org/minimum-number-platforms-required-railwaybus-station/" rel="nofollow noreferrer">minimum platform problem</a>.</p> <p>In that, you need to sort the min and max maths books array in ascending order respectively. Try to understand the problem from the above...
python|python-3.x|testcase|challenge-response
4
4,097
73,368,447
What is the time complexity of below code?
<p>Can some one please let me know the time complexity of below code.</p> <pre><code>nums=[1,2,4,6,180,290,1249] ll=[] l=[] for i in nums: for j in range(1,int(sqrt(i))+1): if(i%j==0): l.append(j) ll.append(l.copy()) l.clear() print(ll) pass </code></pre>
<p>There are three main operations that are going to determine the time complexity.</p> <ol> <li>The outer loop <code>for i in nums</code> is O(N) where N = len(nums)</li> <li>The inner loop <code>for j in range(1,int(sqrt(i))+1)</code></li> <li>Within the first loop we also have <code>ll.append(l.copy())</code>, where...
python|time-complexity
0
4,098
48,956,422
What is the correct way to type hint a homogenous Queue in Python3.6 (especially for PyCharm)?
<p>I'm writing a fractal generator in Python 3.6, and I use <code>multiprocessing.Queue</code>s to pass messages from the main thread to the workers. This is what I've tried so far, but PyCharm doesn't seem to be able to infer attribute types for items taken from the queues:</p> <pre><code>from typing import NamedTupl...
<p>Old Question, but I just found</p> <pre class="lang-py prettyprint-override"><code>P: "Queue[Path]" = Queue() </code></pre> <p>to work with both <code>queue.Queue</code> and <code>multiprocessing.Queue</code> in PyCharm</p>
pycharm|python-3.6|type-hinting|mypy
31
4,099
49,132,607
Can I train NER in spaCy using annotations from a wordpad or text document
<p>Can I train NER in spaCy using annotations from a wordpad or text document, because training with a sentence or paragraph doesn't meet my requirements. Thanks.</p>
<p>Yes, you can. The python library <a href="https://github.com/ieriii/spacy-annotator" rel="nofollow noreferrer">spacy-annotator</a> is your friend here.<br /> It uses ipywidgets to provide users with a user-friendly UI to annotate data.</p> <p><strong>First</strong>: install the annotator.</p> <pre><code>pip install ...
python|machine-learning|nlp|spacy|named-entity-recognition
0