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,300 | 61,357,118 | (PySpark) StringIndexer Error: py4j.protocol.Py4JJavaError: An error occurred while calling o46.fit | <p>I have a dataFrame in PySpark. I want to use StringIndexer for my label column, so I defined a function as:</p>
<pre><code>def indexer(column, dataframe):
from pyspark.ml.feature import StringIndexer
# Indexing the column
stringIndexer = StringIndexer(inputCol=column, outputCol='categoryIndex')
mo... | <p>Your error message is clearly indicating that there is an issue with the argument passed</p>
<pre><code>py4j.protocol.Py4JJavaError: An error occurred while calling o45.fit.
: java.lang.IllegalArgumentException
</code></pre>
<p>Check the <a href="https://spark.apache.org/docs/latest/api/python/pyspark.ml.html?high... | python-3.x|apache-spark|pyspark|pyspark-dataframes|py4j | -3 |
4,301 | 58,060,961 | how do I upgrade pip on Mac? | <p>I cannot upgrade pip on my Mac from the Terminal. </p>
<p>According to the documentation I have to type the command:
pip install -U pip</p>
<p>I get the error message in the Terminal:
pip: command not found</p>
<p>I have Mac OS 10.14.2, python 3.7.2 and pip 18.1.
I want to upgrade to pip 19.2.3</p> | <p>upgrading pip as of 09/2020:</p>
<pre><code>pip3 install --upgrade pip==20.2.2
</code></pre> | python-3.x | 16 |
4,302 | 57,832,721 | scrapy is not working with youtube search query ? returns 404 | <p>I am trying to search on youtube given queries and fetching video information from youtube with scrapy but somehow when I make spider write start_urls something like this:</p>
<p>start_urls = [
........,
'<a href="http://www.youtube.com/results?search_query=web+development" rel="nofollow noreferrer">http://ww... | <p>By default Scrapy will respect <code>robots.txt</code> policies (see the <a href="https://docs.scrapy.org/en/latest/topics/settings.html?#robotstxt-obey" rel="nofollow noreferrer">docs</a>).
To change this behavior, set <code>ROBOTSTXT_OBEY</code> in the <code>settings.py</code> file of your project to <code>False</... | python|scrapy | 2 |
4,303 | 56,070,353 | Understanding how the Python3 import method works | <p>I've been working on a python3 application and I ran into a strange problem that picked my curiosity after annoying me greatly.</p>
<p>My file structure is something like this:</p>
<pre><code>root/
| __init__.py
| main.py
| fuzzy/
| __init__.py
| foo.py
| dreamy/
| __init__.py
... | <p>This question seems to be terribly simple, however I did notice that other people struggled with it.</p>
<p>Though I found the answer to my question thanks to <a href="https://stackoverflow.com/users/3002139/baum-mit-augen">Baum mit Augen</a>.</p>
<p>Baum mit Augen took the time to write <a href="https://stackover... | python-3.x|python-import | 0 |
4,304 | 18,342,259 | Efficient way of computing statistics for large/imprecise amount of data | <p>I have over 65 million numeric values stored in a text file. I need to compute the maximum, minimum, average, standard deviation, as well as the 25, 50, and 75 percentiles.</p>
<p>Normally I would use the attached code, but I need a more efficient way to compute these metrics because i cannot store all value p in a... | <p>Use binary file. Then you can use <code>numpy.memmap</code> to map it to memory and can perform all sorts of algorithms, even if the dataset was larger than RAM.</p>
<p>You can even use the numpy.memmap to create a memory mapped array, and read your data in from the text file... you can work on it and when you are ... | python|performance|statistics|memory-efficient | 5 |
4,305 | 71,757,970 | ProgrammingError - relation "blog_app_post" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "blog_app_post" | <p>I have a problem with my database every time I deploy it to heroku.
The code works okay on localhost but shows ProgrammingError when deployed.</p>
<p>When ever I remove the category from the codes, it seems to work but still having another issue with the auth dashboard.</p>
<p>Here is the <em>view.py</em> code</p>
<... | <p>For this kind of issue even flushing the migrations won't work you just have to drop that table blog_app_post. After you run <code>python manage.py makemigrations app_name</code> after the migration run <code>python manage.py sqlmigrate app_name 0001_initial</code> this will generate all the schema of that particula... | python-3.x|django|heroku | 0 |
4,306 | 69,400,299 | Cumulative sum over time window frames | <p>I have this df:</p>
<pre><code>i = pd.date_range('2021-09-01', periods=8, freq='11H50min')
ts = pd.DataFrame({'animal_code_1':['A','B','C','A','A','B','','B'],
'animal_code_2':['AA','BB','','AA','AA','BB','DD','BB'],
'deaths': [1, 3, 1, 0,4,5,3,2]}, index=i)
</code></pre>
<p><co... | <p>Try:</p>
<pre><code>ts.reset_index(inplace=True)
ts['index'] = pd.to_datetime(ts['index'])
ts['date'] = pd.to_datetime(ts['index'].dt.date)
ts = ts.groupby(['date', 'animal_code_1', 'animal_code_2'])['deaths'].sum().reset_index()
ts['dummy'] = ts['date'].dt.day
ts['dummy'] = 'day' + ts['dummy'].astype(str) + '_death... | python|pandas | 0 |
4,307 | 55,512,612 | Is there a lint rule for creating python tuples without bracets? | <p>I want linter to restrict me from using tuple by mistakingly adding a comma at the end of an assignment.</p>
<p>I think that explicitly creating a tuple by using brackets is the only right way to create them.</p>
<p>I have tried 'Pylint' with option '--enable=all', it doesn't warn me of the danger.</p>
<pre class... | <p>I have found a tool that does that and even more and becomes standard: Black: <a href="https://github.com/psf/black" rel="nofollow noreferrer">https://github.com/psf/black</a>.</p> | python|python-3.x|python-2.7|pylint | 1 |
4,308 | 55,282,922 | Python don't return data when joining two tables by a field | <p>I've got a query that returns the data correctly in MySQL but in Python only returns part of the data. </p>
<p>The query is:</p>
<pre><code>select sc.* from tbl030_shots_chart sc, tbl006_player_team tc where
sc.id_fiba = tc.id_player_feb and
tc.id_team_club = 5
</code></pre>
<p>This query in MySQL returns 1030 ro... | <p>You can try creating a <a href="https://dev.mysql.com/doc/refman/8.0/en/views.html" rel="nofollow noreferrer">view</a> for this query.</p>
<pre><code>CREATE VIEW your_view AS (
SELECT
t1.id,
t1.id_game,
t1.line,
...
t2.id_team_club,
t2.id_player_feb,
...
FROM tbl030_shots_cha... | python|mysql | 1 |
4,309 | 55,529,131 | How to remove \r character from the getpass prompt | <p>I have written a code which actually matches the patter RegEx in Python.
I have used getpass library to prompt the user to enter the password.But if the user enters the wrong password[say 'HH'-which is invalid password].Once the user hits enter after typing the password,the get pass is taking "HH" and "enter as \r" ... | <p>You are too close :)</p>
<p>modify your code from:</p>
<pre><code>password.rstrip('\r')
</code></pre>
<p>to</p>
<pre><code>password = password.rstrip('\r')
</code></pre>
<p>Explanation:
from python <a href="https://docs.python.org/3/library/stdtypes.html#str.rstrip" rel="nofollow noreferrer">docs</a>, </p>
<b... | python|regex|getpass | 1 |
4,310 | 42,208,966 | Django 1.10 : view function() takes exactly 2 arguments (1 given) | <p>This is my first django project and I'm struggling to finish it.
I've been working to function that editing post. When user clicks button, it send no(int)for that article, and get information related to no and display on page. User can edit that post in the same form and when user click submit, it redirect to home.... | <p>The <code>article_no</code> arg does not magically find its way into the function call via the POST submit. You need to provide it to the <code>url</code> tag:</p>
<pre><code>{% url 'blog:edit_article' item.no %}
</code></pre>
<p>This assumes, of course, that you have a url pattern with an appropriate named group ... | python|django | 1 |
4,311 | 42,310,436 | Auto code intelligence in Python and Pycharm | <p>I am wrting a Python application for the first time and I am using Pycharm as the slected IDE. One thing that I notice I can;t see all classses and methods for the object I am using. I have coded with intelligIdea to code Scala and Java as well. They are easier to code since code intelligence is really handy but In ... | <p>There are a few of possible reasons:</p>
<ul>
<li><code>innerTree</code> doesn't actually have a <code>cssselect</code> method. Seems obvious, but this one catches me out more often than I'd like to admit.</li>
<li><p>PyCharm doesn't know what <code>innerTree</code> is an instance of.</p></li>
<li><p>You need to cl... | python|pycharm | 0 |
4,312 | 59,266,824 | is there any way to find weitage of sentence with TF-IDF in python | <p>i have one list </p>
<pre><code>x=["hello there","hello world","my name is john"]
</code></pre>
<p>i am done with vectorization with TF-IDF</p>
<p>this is output of TF-idf</p>
<pre><code> from sklearn.feature_extraction.text import TfidfVectorizer
corpus = [
"hello there","hello world","my name is jo... | <p>I believe that with TF-idf you can only calculate the weight of single words in a sentence (or document for that matter), meaning you cannot use it to calculate the weight of sentences within other sentences or documents.</p>
<p>However, from <a href="https://www.freecodecamp.org/news/how-to-process-textual-data-us... | python|machine-learning|scikit-learn | 1 |
4,313 | 54,080,923 | Val Error, x and y must have the same dimension. [I tried to do np.array but it hasn't helped] | <p>x and y must have same first dimension, but have shapes (1, 400) and (400,)</p>
<p>I have search this forum and saw that people suggested to do np.array to solve this, but it didn't seem to work.</p>
<pre><code>def function(a, v):
speedx = 0.0
yt = -1.0
val = []
for i in len(a):
xt = a[0]
vx = -2.0 * yt**2... | <p>When you return <code>np.array([val])</code>, that makes a two dimensional array because <code>val</code> is already an array. That is why the shape is (1,400) which makes it two dimensional with the size of the first dimension being 1. You can try:</p>
<pre><code>return np.array(val)
</code></pre>
<p>That may hel... | python|numpy | 0 |
4,314 | 58,599,421 | Get previous and following sentences in spaCy | <p>I am using spaCy to process sentences of a doc. Given one sentence, I'd like to get the previous and following sentence. </p>
<p>I can easily iterate over the sentences of the doc as following:</p>
<pre><code>nlp_content = nlp(content)
sentences = nlp_content.sents
for idx, sent in enumerate(sentences):
</code></p... | <p>There isn't a built-in sentence index. You would need to iterate over the sentences once to create your own list of sentence spans to access them this way.</p>
<pre><code>sentence_spans = tuple(doc.sents) # alternately: list(doc.sents)
</code></pre> | python-3.x|spacy | 1 |
4,315 | 58,392,285 | TextBlob translator cannot detect the different language in dataframe | <p>I run the language translator using TextBlob. It can translate from a string. However, I tried to loop the textblob translator for the data in a dataframe which in dataframe might have a mixed of different languages (en and es).</p>
<p>The code I used is : </p>
<pre class="lang-py prettyprint-override"><code>for c... | <p>As it is not necessary in each case that 'en' and 'es' must be different. There can be many cases in which 'es' and 'en' have the same text. So the error is being raised in the case where both of them are same. Using the try and catch statement will tackle all the cases having same texts eventually making your code ... | python|nlp | 0 |
4,316 | 58,204,814 | Can Python Be Uses to control hardware like web cams on a PC? | <p>So i am working on a project alone, and i would like to know if python can be used to <strong>control/manage hardware</strong> connected to <em>PCs</em>. It would be very helpful. (also please mention if it can work on popular Operating Systems i.e - Windows, Linux, macOS)</p>
<p>I haven't tried anything yet as i ... | <p>Python runs on Windows, Mac, and Linux.</p>
<p>Yes, you can control your web cam and other hardware.</p>
<p>To control your webcam: <a href="https://stackoverflow.com/questions/604749/how-do-i-access-my-webcam-in-python">How do I access my webcam in Python?</a></p>
<p>Mouse and keyboard: <a href="https://steemit.... | python|python-3.x|project|hardware | 1 |
4,317 | 65,098,715 | Delete all item contains word with regex | <pre><code>List = ['aleksandre', 'shopify-ecommerce', 'php-ecommerce', 'html-code', 'css-code', 'sultan', 'november']
New List = ['aleksandre', 'sultan', 'november']
</code></pre>
<p>How I can delete item contains <code>'ecommerce'</code> and <code>'code'</code> from list?</p>
<p>I try to delete with regex but i cant... | <p>try this code:</p>
<pre><code>List = ['aleksandre', 'shopify-ecommerce', 'php-ecommerce', 'html-code', 'css-code',
'sultan', 'november']
a = [ x for x in List if "ecommerce" not in x and "code" not in x]
print(a)
</code></pre>
<p>output is:</p>
<pre><code>['aleksandre', 'sultan', 'november']
<... | python|python-3.x|list | 1 |
4,318 | 65,373,376 | Checking if a key exists in an OrderedDict | <p>I am dealing with a code migration from python2 to python3. I don't have much experience with OOP and <code>OrderedDict</code> in python. Here is the issue, which I am not able to solve. Similar questions have been asked <a href="https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-di... | <p>In Python 3 <code>__cmp__</code> is not in use anymore.
You need to implement <code>__eq__</code> to your class and remove <code>__cmp__</code></p> | python|python-3.x|dictionary|python-2to3 | 1 |
4,319 | 22,527,166 | Assinging 1 character from 1 list to another python | <p>Hi i am making a decryption machine for my school project but i cant get it to work can you guys help me out?
Thanks already.</p>
<p>the error is: line 17, IndexError: list index out of range
The length of zin = 86 just so you know</p>
<p>this is what is in the file i need to decrypt: KEIGO N JIDOUBANEUOFIDNEIESUN... | <p>Since you are accessing <code>zin[key]</code>, you need to verify length of <code>zin</code> is at least <code>key+1</code>.</p> | list|python-2.7 | 0 |
4,320 | 45,294,029 | Comparing 2 string lists index with for loop python | <p>I'm trying to compare 2 string lists in python, suppose I have this 2 lists:</p>
<pre><code>list_one = ['con good', 'con good', 'tech', 'retail', 'con good',
'con good', 'retail', 'finance', 'finance', 'retail',
'retail', 'finance', 'tech', 'retail', 'tech',
'finance', 'con good', '... | <p>This can be reduced to a single line if you take advantage of the tools provided by python eg:</p>
<pre><code>>>> from collections import Counter
>>> counts = Counter(one for one, two in zip(list_one, list_two) if two == 'yes')
>>> print(counts)
Counter({'con good': 3, 'tech': 3, 'financ... | python|python-2.7|for-loop | 3 |
4,321 | 14,483,163 | Pygame text input not on screen | <p>I need to kb input onto a pygame screen
at the moment it appears on the idle shell
any advice would be appreciated.</p>
<p>This code is extracted from a larger program
mostly screen based but i need to input some
data (numeric) from the kb at times</p>
<pre><code>import sys
import pygame
from pygame.locals import ... | <p>Firstly you draw the score twice, which i assume works well.</p>
<p>The problem lies in you start function.
You are not calling any draw or update function in your while loop.
In your event foreach, you add a digit to <code>name</code>, and exit the while loop when enter is pressed. Then you draw twice with Pchange... | python|text|pygame|user-input | 0 |
4,322 | 14,681,893 | Why does adding a second attribute to a metaclass-property-closure mix change the first attribute? | <p>I want to understand python metaclasses. For practice I'm implementing a declarative way for writing classes (similar to sqlalchemy.ext.declarative). This looks promising as long as I only have one attribute.</p>
<p>But when I add another attribute, some part of the first attribute is changed and the value of the f... | <p>The problem doesn't really have anything to do with metaclasses or properties per se. It has to do with how you're defining your get/set functions. Your <code>fget</code> and <code>fset</code> reference the variable <code>pattern</code> from the enclosing function. This creates a closure. The value of <code>patt... | python|properties|closures|metaclass | 1 |
4,323 | 44,423,211 | How to filter objects by price range in Django? | <p>I have a model <code>Item</code> with field <code>price</code>.</p>
<pre><code>class Item(models.Model):
title = models.CharField(max_length=200, blank='true')
price = models.IntegerField(default=0)
</code></pre>
<p>My query may contain <code>min_price</code> & <code>max_price</code> values. So, my req... | <p>Check api reference for <a href="https://docs.djangoproject.com/en/1.11/ref/models/querysets/#range" rel="noreferrer">range</a>. Like it states </p>
<blockquote>
<p>You can use range anywhere you can use BETWEEN in SQL — for dates,
numbers and even characters.</p>
</blockquote>
<p>So, in your case:</p>
<pre><... | python|django|django-rest-framework | 10 |
4,324 | 44,649,647 | gpxpy doesn't parse time attribute of track points | <p>i'm trying to parse gpx file made by "Mission Planner". For some reason the softwere generates the gpx file of one line, which look like that:</p>
<pre><code><gpx creator="Mission Planner 1.3.48 build 1.1.6330.31130 ArduPlane V3.7.1 (22b5c415)" xmlns="http://www.topografix.com/GPX/1/1"><trk><trkseg&g... | <p>The GPX time format you posted is not correct. Let's try it with a GPX file that has the correct time format:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<gpx creator="StravaGPX" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="... | python|xml-parsing|gpx | 1 |
4,325 | 23,506,323 | Python multithreading - Global Interpreter Lock | <p>Python <a href="https://docs.python.org/2/library/threading.html" rel="nofollow">threading module</a> documentation says something like this</p>
<blockquote>
<p>In CPython, due to the Global Interpreter Lock, only one thread can
execute Python code at once (even though certain performance-oriented
libraries m... | <p>I guess, the most time expensive activity will be fetching all the urls.</p>
<p>So the answer to your question is: Yes, your app is very likely to be I/O bound.</p>
<p>You plan to scrape domains one by one, this would lead into really long processing time. You shall definitely do that concurrently. One solution is... | python|mysql|multithreading | 1 |
4,326 | 23,461,774 | More efficient text-based loading bar | <p>I am making a program that has a "loading bar" but I can't figure out how to make the code shorter. This might be a simple fix for all I know, but for the life of me, I just can't figure it out. Here is what I have tried to do so far: </p>
<pre><code>def ldbar():
print "Load: 1%"
time.sleep(0.5)
os.syst... | <p>This should work:</p>
<pre><code>def ldbar():
for i in range(1, 100):
print "Load: {}%\r".format(i),
sys.stdout.flush()
time.sleep(0.5)
ldbar()
</code></pre>
<p>It uses a <a href="https://wiki.python.org/moin/ForLoop" rel="nofollow"><code>for</code></a> loop to avoid having the same co... | python | 2 |
4,327 | 24,174,394 | Cmake is not able to find Python-libraries | <p>Getting this error:</p>
<pre><code>sudo: unable to resolve host coderw@ll
-- Could NOT find PythonLibs (missing: PYTHON_LIBRARIES PYTHON_INCLUDE_DIRS)
CMake Error at /usr/share/cmake-2.8/Modules/FindPackageHandleStandardArgs.cmake:108
(message):
Could NOT find PythonInterp (missing: PYTHON_EXECUTABLE)
Call S... | <p>You can fix the errors by appending to the <code>cmake</code> command the <code>-DPYTHON_LIBRARY</code> and <code>-DPYTHON_INCLUDE_DIR</code> flags filled with the respective folders.</p>
<p>Thus, the trick is to fill those parameters with the returned information from the python interpreter, which is the most reli... | python|python-2.7|cmake | 67 |
4,328 | 20,821,570 | Calculating a work rate in Python | <p>If I had the variables: hours, minutes, and seconds respectively representing the number of hours of work, the number of minutes of work, and the number of seconds of work, how would I calculate the salary of the rate, x</p>
<p>this is what I have:</p>
<pre><code>rate = (hours*x) + (minutes*x)*0.1 + (seconds*x)*0.... | <p>Either <code>minutes</code> or <code>x</code> is <em>not</em> an integer; most likely you have a string there instead:</p>
<pre><code>>>> minutes = 5
>>> x = '10'
>>> minutes * x
'1010101010'
>>> (minutes * x) * 0.1
Traceback (most recent call last):
File "<stdin>", line ... | python | 4 |
4,329 | 72,021,620 | Python, tkinter how to make the window click-through Linux | <p>I have seen the post about how to do it on Windows, but i need a Linux version. Is there any way? (Yes, i Googled before i came here)
What i basically want to do is to open a maximized transparent click through window, to mainly use it as a "dark reader"
here my tiny code :)</p>
<pre><code>from tkinter imp... | <h2>Simplified Explication</h2>
<p>@Z3r0ut, Your probably using <code>python 2.x</code> because that is what most Linux distributions use. If you want to run the code, you can simple start with this argument <code>python %FILENAME%.py</code>.</p>
<pre class="lang-py prettyprint-override"><code>!/usr/bin/python
-*- enco... | python|tkinter | 1 |
4,330 | 36,123,740 | Is there a way of determining how much GPU memory is in use by TensorFlow? | <p>Tensorflow tends to preallocate the entire available memory on it's GPUs. For debugging, is there a way of telling how much of that memory is actually in use?</p> | <p>(1) There is some limited support with <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/client/timeline.py" rel="noreferrer">Timeline</a> for logging memory allocations. Here is an example for its usage:</p>
<pre><code> run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRA... | gpu|tensorflow | 12 |
4,331 | 35,824,643 | Input and Arguments | <p>I've been using input a lot in a program recently and I've noticed that I can't have multiple arguments in the same line, like I can with print commands. If I tried to type, say:</p>
<pre><code>num = int(input("Number?"))
answer = input("Your number was", num)
</code></pre>
<p>I would get an error message saying ... | <p>Thats because <code>input()</code> only takes one argument which is the prompt.</p>
<p>You have provided an additional argument (<code>num</code>).</p>
<p>Also as you are trying to print the <code>num</code> back, you just need <code>print()</code>:</p>
<pre><code>print("Your number was {}".format(num))
</code></... | python | 0 |
4,332 | 36,096,135 | How correctly draw boxes in pyprocessing? | <p>I'm trying to write a very basic box drawing program using pyprocessing,
but a condition to check if the mouse is within a box fails, when the logic looks ok:</p>
<pre><code>#!/usr/bin/env python
from pyprocessing import *
S = 20
W = 5
H = 5
data = [[0] * W] * H
def setup():
size(W*(S+5),H*(S+5))
def draw()... | <p>Trying to be lazy is the issue:</p>
<pre><code>data = [[0] * W] * H
</code></pre>
<p>This doesn't simply create a nested array, it copies the <strong>references</strong> of the first array (<code>[0]</code>), so when I modify one value in one row, the whole row is modified.</p>
<p>Since I'm super experienced with... | python|pyprocessing | 1 |
4,333 | 15,461,135 | Dynamically set class attributes (model fields) while iterating a dictionary | <p>I'm trying to define the fields of a model dynamically depending on the key, value pairs contained in a dictionary.</p>
<p>I've attempted two ways:</p>
<p>the dictionary is:</p>
<pre><code>NOTIFICATION_TYPES = {
'friend_request_received': 0,
'friend_request_accepted': 1,
# eccetera
}
</code></pre>
<p... | <p>You'll need to set those extra attributes <em>after</em> defining the class:</p>
<pre><code>class EmailNotification(models.Model):
"""
User Email Notification Model
Takes care of tracking the user's email notification preferences
"""
user = models.OneToOneField(User, verbose_name=_('user'))
... | python|django|django-models|python-2.7 | 1 |
4,334 | 15,250,538 | Invoking scons from a Python script | <p>I'm new to scons and Python.
I was wondering if there's a way to invoke scons from within a python script. </p>
<p>My python script accepts from the user, a list of directories where the code to be compiled together is located (in addition to doing some other non-trivial things).
It also generates a string which is... | <p>Well, I guess it's possible in theory. The <code>scons</code> executable itself is just a python script and all it does is execute <code>SCons.Script.main()</code> after modifying the <code>sys.path</code> variable. But you would probably have to start digging deep into the source to really understand how to make it... | python|scons | 3 |
4,335 | 29,374,554 | Binary Search Tree, Determining to use Predecessor or Successor to make tree Balanced | <p>I'm fairly new to programming in python and I wanted to make a Binary Search Tree with some implementation. My last implementation I want to add is that when the user selects my 'delete' function, whatever item they want deleted, my function will come up with the best number to replace it with. Either the successor ... | <p>Python is not my preferred language so I will not try to engage at that level, but at a theoretical level I would suggest looking at the possibility having your nodes be aware of the height of each sub-tree.</p>
<p>So any time you add a node you are obviously moving down through the tree to insert, when you return ... | python|binary-tree|binary-search-tree | 0 |
4,336 | 29,463,571 | Different frequencies for sine wave generator in python | <p>I am using the code below to generate a sine wave and it works fine. However, when I try to use large frequencies 500kHz and change the time period to 0.2us I expect to get a full sine wave with time period of 0.2us but what I get is just a straight line don't know why.</p>
<pre><code>def sampled_sine_wave(freq):
... | <p>As mentioned in the comments, <strong>you probably aren't actually getting a straight line</strong>. If you <a href="https://www.wolframalpha.com/input/?i=plot+sin%285e5%2Fpi*x%29+from+0+to+2e-7" rel="nofollow">graph it</a> in that range, it looks almost like a straight line. In fact, at the edge of that range, at <... | python | 1 |
4,337 | 29,446,558 | Calculating Yearly Income in Python | <p>Right now, I wanted to make simple calculations of how much profit would a web design company make in year following the below criteria:</p>
<ol>
<li><p>The company sells themes, plugins and designs.</p></li>
<li><p>each theme costs 20, plugin costs 10 and design costs 50</p></li>
<li><p>the company steadily mainta... | <p>The first step is to organize your data into a dictionary or list. Here is an example using lists:</p>
<pre><code># list of tuples (themes, plugins, designs) with week-1 as the index
weekly_sales_quantity = [
(5, 4, 2),
(6, 5, 2),
]
</code></pre>
<p>The next step is to initialize, iterate, and sum year-to... | python | 0 |
4,338 | 46,331,371 | Obscure TensorFlow error after building for Android with Bazel | <p>I'm attempting to build a simple Android app based on the TensorFlow Android demo; however the model I'm using requires an kernel Op not included by default with the TensorFlow aar. This led me down the path of compiling the libraries from source.</p>
<p>I've gotten the apk to build through gradle, using bazel as t... | <p>It turns out this was an issue with the TensorFlow commit I was working off. When I merged in the most recent changes from the upstream TensorFlow repo the error went away.</p>
<p>I can't imagine anyone else will run into this issue; but if you do, or you run into some similarly obscure error, updating to a newer v... | android|gradle|tensorflow|bazel | 0 |
4,339 | 46,199,565 | reduce dataframe between column values | <p>I would like to compute an operation between the intervals <code>col1 = 0, col2 = 1</code> and <code>col1 = 0, col2 = 2</code> the difference between the max and min value of the col3 of the following dataframe:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'id':['id1','id1','id1','id1','id1','id1','id1',... | <p>As it appears that your <code>id</code> column already demarcates your groups, you don't even need to use <code>col1</code> or <code>col2</code>.</p>
<p>Just group on the <code>id</code> column and apply a lambda function that takes the difference between the max and min values in the group.</p>
<pre><code>>>... | python|dataframe | 3 |
4,340 | 49,468,620 | Tensorflow dataset batching for complex data | <p>I tried to follow the example in this link:</p>
<p><a href="https://www.tensorflow.org/programmers_guide/datasets" rel="nofollow noreferrer">https://www.tensorflow.org/programmers_guide/datasets</a></p>
<p>but I am totally lost about how to run the session. I understand the first argument is the operations to run,... | <p>The issue is that you packed your data into a dict when creating the dataset from tensor slices. This will result in <code>iterator.get_next()</code> returning each batch as a dict as well. If we do something like</p>
<pre><code>d = {"a": 1, "b": 2}
k1, k2 = d
</code></pre>
<p>we get <code>k1 == "a"</code> and <co... | tensorflow|iterator|dataset|batching | 2 |
4,341 | 62,759,515 | Hi, I have a bug in my program, I don't know but it keeps telling me invalid input when I entered anything | <p>okay, I was trying to build a guess the number game and I hadn't developed, only the multi-language system, I need help, can you test it in python and see if it works? if not, please edit or comment my question, Thanks!</p>
<pre><code>"""
Guess The Number
Write a program where the computer randomly ge... | <p>The <a href="https://www.w3schools.com/python/ref_string_strip.asp" rel="nofollow noreferrer">String.strip</a> is a function
So it should be used as Language.strip()</p> | python | 1 |
4,342 | 70,359,226 | Circular objects rotate angle detection | <p>I'm trying to detect angle difference between two circular objects, which be shown as 2 image below.</p>
<p>I'm thinking about rotate one of image with some small angle. Every time one image rotated, SSIM between rotated image and the another image will be calculated. The angle with maximum SSIM will be the angle di... | <p>Here's a way to do it:</p>
<ol>
<li>detect circles (for the example I assume circle is in the image center and radius is 50% of the image width)</li>
<li>unroll circle images by polar coordinates</li>
<li>make sure that the second image is fully visible in the first image, without a "circle end overflow"</... | python|opencv | 7 |
4,343 | 53,696,707 | How to do forward filling for each group in pandas | <p>I have a dataframe similar to below</p>
<pre><code>id A B C D E
1 2 3 4 5 5
1 NaN 4 NaN 6 7
2 3 4 5 6 6
2 NaN NaN 5 4 1
</code></pre>
<p>I want to do a null value imputation for columns <code>A</code>, <code>B</code>, <code>C</code> in a forward filling but for each group. That means, I w... | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.ffill.html" rel="noreferrer"><code>GroupBy.ffill</code></a> for forward filling per groups for all columns, but if first values per groups are <code>NaN</code>s there is no replace, so is possible use <a href="http://panda... | python|pandas|imputation | 21 |
4,344 | 53,662,848 | Replacing yield with returns in recursive code | <p>How would I remove the yield statements in this code, and instead use it as a normal function with return statements?</p>
<pre><code>def solve(game_board):
num_occupied, board_layout=game_board
if num_occupied < 2:
yield (None, game_board)
else:
for move in possible_moves():
new_game_bo... | <p>Accumulate everything at once and return, instead of yielding one at a time. Like I said in my comment, just replace every <code>yield</code> call with a call to <code>list.append</code>. </p>
<pre><code>def solve(game_board):
# Initialise your list.
moves = []
num_occupied, board_layout=game_board
if num_o... | python|generator|yield | 1 |
4,345 | 53,797,208 | FATAL: password authentication failed for user / but user exist | <p>I'm banging my head against a wall here. I need another set of eyes.
This is error I get:</p>
<blockquote>
<p>django.db.utils.OperationalError: FATAL: password authentication
failed for user "localproject" FATAL: password authentication failed
for user "localproject"</p>
</blockquote>
<p>I have set up the ... | <p>It works after restart.</p>
<p>Restart by using this line:</p>
<blockquote>
<p>sudo service postgresql restart</p>
</blockquote> | django|python-3.x|postgresql | 0 |
4,346 | 54,932,734 | Efficient way to implement matrix multiplication when one matrix is extremely wide? | <p>I need to multiply 3 matrices, <code>A: 3000x100, B: 100x100, C: 100x3.6MM</code>. I currently am just using normal matrix multiplication in PyTorch</p>
<pre><code>A_gpu = torch.from_numpy(A)
B_gpu = torch.from_numpy(B)
C_gpu = torch.from_numpy(C)
D_gpu = (A_gpu @ B_gpu @ C_gpu.t()).t()
</code></pre>
<p>C is very... | <p>Since you have four GPUs, you can harness them to perform efficient matrix multiplication. Notice however that the results of the multiplication has size 3000x3600000, which takes up 40GB in single precision floating point (fp32). Unless you have a large enough RAM for the CPU, you cannot store the results of this c... | python|pytorch | 1 |
4,347 | 73,648,962 | Selenium throws invalid argument exception when getting an element | <p>I'm trying to code a bot that automatically logins into a site.
This is the code for the login(I've only put the email for now)</p>
<pre><code> try:
WebDriverWait(bot, delay).until(EC.presence_of_element_located((By.XPATH, "/html/body/div[1]/div[2]/div/div[2]/div[1]/div/div[2]/div/form/form/div[3]/di... | <p>You put redundant pair of parentheses there.<br />
Instead of</p>
<pre class="lang-py prettyprint-override"><code> mail = bot.find_element((By.XPATH, "/html/body/div[1]/div[2]/div/div[2]/div[1]/div/div[2]/div/form/form/div[3]/div[1]/div/div/input"))
</code></pre>
<p>It should be</p>
<pre class="lang-py ... | python|python-3.x|selenium|selenium-webdriver|xpath | 0 |
4,348 | 13,002,877 | List out of index Error | <p>I have a for loop such as:</p>
<pre><code>staff = Staff.objects.all().order_by('person__full_name')
for k in staff:
categ = k.staff_job_categories.all()[1]
if categ.name == unicode("xxx","utf-8"):
t = categ.name
</code></pre>
<p>But for <code>categ = k.staff_job_categories.all()[1]</code>
I get an ... | <p>Seems <code>print len(k.staff_job_categories.all())</code> will output <code>0</code> or <code>1</code> because there are no staff job categories for this item or just only one category exists (which has index <code>0</code> and not <code>1</code>).</p>
<p>So if you're interesting exactly in second category if it e... | python|django-orm | 1 |
4,349 | 12,655,404 | Turning project data into a relationship matrix | <p>My data set a list of people either working together or alone.</p>
<p>I have have a row for each project and columns with names of all the people who worked on that project. If column 2 is the first empty column given a row it was a solo job, if column 4 is the first empty column given a row then there were 3 peopl... | <p>Maybe something like this would get you started?</p>
<pre><code>import csv
import collections
import itertools
grid = collections.Counter()
with open("connect.csv", "r", newline="") as fp:
reader = csv.reader(fp)
for line in reader:
# clean empty names
line = [name.strip() for name in line... | python|matrix|social-networking|stata | 1 |
4,350 | 38,233,348 | Tkinter widget layout is wrong? | <p>I've been putting a menu together using Tkinter with Python 2.7. It works functionally, but the layout is very messy. I'm usng the .grid() method to organise the widgets, but they are interfering with each other, so my listbox widget is taller than the buttons so they get spaced apart etc. What can I do to resolve t... | <p>You can tell the grid to let (force) a widget to take up multiple rows/columns with the <code>columnspan</code> argument to <code>grid()</code>, i.e.:</p>
<pre><code>...
list_box.grid(row=1, column=3, rowspan=3)
...
</code></pre>
<p>That will tell your <code>list_box</code> to cover (up to) three rows (if there's ... | python|tkinter | 2 |
4,351 | 38,406,412 | jQuery get changing the URL parameter itself | <p>I am making a get request using jquery to the local server in Flask. Here is the endpoint in Flask</p>
<pre><code>@app.route('/getNews', methods=['GET', 'POST'])
def getNews():
return jsonify(news['news'])
</code></pre>
<p>Here is the call from HTML</p>
<pre><code> $.get({
url:"http://0.0.0.0:9090/ge... | <p>Your url argument is a string, not in the data object. The second argument is the data you are passing to the endpoint. The third argument is the success handler. And the last argument is the datatype expected back.</p>
<pre><code>$.get( "http://0.0.0.0:9090/getNews", 'd', function( data ) {
console.log(data)... | jquery|python|ajax|flask|get | 1 |
4,352 | 39,926,859 | Unable to trigger a selection event in bokeh | <p>Can someone please tell me how to capture the option that is selected in the 'select' widget.
I tried the following and expected that when I change the selection in drop down menu, it should print the newly selected option. But it's not happening.</p>
<pre><code>from bokeh.models.widgets import Select
from bokeh.i... | <p>You are calling <code>on_change</code> incorrectly. It takes: the name of the property to respond to, and the callback. You don't need to pass the object, because <code>on_change</code> is already a method on the object. You want:</p>
<pre><code>select.on_change('value', call)
</code></pre>
<p>Also, I will suggest... | python-2.7|bokeh | 1 |
4,353 | 40,038,181 | Invalid datetime format in python-mysql query | <p>I wanted to fetch a record from database which is having the <code>datetime</code> field a part of primary key. I am querying from <code>python</code> using <code>mysqldb package</code> which is resulting in error </p>
<blockquote>
<p>Invalid datetime format</p>
</blockquote>
<p>wherein the same query is working... | <p>Date format should be</p>
<pre><code>'2016-09-08 00:00:00'
</code></pre>
<p>if you need to set time zone, you need a separate SQL query</p>
<pre><code>set time_zone='+00:00';
</code></pre>
<p>See also: <a href="https://stackoverflow.com/questions/930900/how-to-set-time-zone-of-mysql">How do I set the time zone ... | python|mysql|python-2.7|datetime | 1 |
4,354 | 40,245,397 | How to get integers out of QCUT while creating Categories for DataFrame Series | <p>With two ndarrays:</p>
<pre><code>import pandas as pd
import numpy as np
a = np.arange(0,100, 10)
b = np.random.random_integers(low=9000, high=10000, size=(1000,))
</code></pre>
<p>I go ahead and create the DataFrame:</p>
<pre><code>numbers = np.concatenate((a, b), axis=0)
df = pd.DataFrame({'a':numbers})
</co... | <p>Here is the solution posted by root:</p>
<pre><code>import pandas as pd
import numpy as np
a = np.arange(0,100, 10)
b = np.arange(9000, 10000)
numbers = np.concatenate((a, b), axis=0)
df = pd.DataFrame({'a':numbers})
df['cats'] = pd.qcut(df.a, 10, labels=False)
print df['cats'].value_counts()
</code></pre> | python|pandas|dataframe | 1 |
4,355 | 40,325,119 | Python) "Real time Audio signal processing" How to plot x-axis in seconds? | <p>I want to plot real time original audio signal and fft signal.</p>
<p>my code is,</p>
<pre><code>socket_server.bind(server_address)
print "Listening...\n"
while(True):
packet, client = socket_server.recvfrom(buffer_size)
count=count+1
if packet=='stop':
print "client stops to send packets... | <p>In the line where you call np.linespace(), try replacing num=(buffer_size/2), by num=len(signal)</p>
<p>The line becomes</p>
<pre><code>Time = np.linspace(0,(len(signal)*(buffer_size/2))/sample_rate, num=len(signal) )
</code></pre> | android|python|audio-processing | 0 |
4,356 | 29,007,685 | Compress in Python Decompress in C# | <p>Problem</p>
<ol>
<li>Compressing long string 4k+ in python</li>
<li>Decompress it in C#</li>
</ol>
<p>What did I try to do:
<br/>1. Python</p>
<pre><code>def deflate_and_base64_encode( string_val ):
zlibbed_str = zlib.compress( string_val )
compressed_string = zlibbed_str[2:-1]
return base64.b64encode... | <p>The problem begins when 2 characters from the beginning and one from the end are chopped off. <code>compressed_string = zlibbed_str[2:-1]</code></p>
<p>That line of code destroys header information in the first 2 characters, and even an immediate zlib.decompress can't make sense of what's left. (My guess: C#'s zlib... | c#|python|gzip|zlib | 1 |
4,357 | 8,875,081 | Prevent Server side Python Timeout? | <p>I have a website hosted by 1and1. On the server there is a folder with about 5,300 pictures. I have a python script that does some image processing. I want to run the python script on all of the pictures in the folder.</p>
<p>The only way I know to make the server run the script is to put the file on my site and th... | <p>I would advise asking the hosting service about it. Generally there will be a way to run scripts on the server.</p> | python|timeout | 1 |
4,358 | 8,583,281 | Python/Gridspec height_ratio issue | <p>I'm very new to python and matplotlib and having trouble with adjusting the height of a 2 plot subplot window. I'm trying to make the subplots aligned vertically, with one directly on top of the other. The subplot on the bottom should be half the height as the one on top. If I try and use width_ratios I get exact... | <p>These two have a ratio 3:1:</p>
<pre><code>import matplotlib.pyplot as plt
# left bott width height
rect_bot = [0.1, 0.1, 0.8, 0.6]
rect_top = [0.1, 0.75, 0.8, 0.2]
plt.figure(1, figsize=(8,8))
bot = plt.axes(rect_bot)
top = plt.axes(rect_top)
bot.plot([3, 2, 60, 4, 7])
top.plot([2, 3, 5, 3, 2, 4, ... | python|matplotlib | 3 |
4,359 | 51,845,914 | Run into a python error <generator object <genexpr> | <p>When I run</p>
<pre><code>a = ["I","love","you"]
a = {(word) for word in a}
print a
</code></pre>
<p>I get this result</p>
<pre><code>set(['I', 'you', 'love'])
</code></pre>
<p>and that's what I expect.</p>
<p>But when I run</p>
<pre><code>a = ["I","love","you"]
a = {((word) for word in c)for c in a}
print a
<... | <p>This is a syntax issue. <code>(word)</code> is equivalent to <code>word</code>. However, when you include a <code>for</code> loop in an expression surrounded by parentheses, it is considered a generator expression (<a href="https://www.python.org/dev/peps/pep-0289/" rel="nofollow noreferrer">PEP 289</a>).</p>
<p>In... | python|list|nested|set | 4 |
4,360 | 51,975,723 | Tkinter treeview widgets not properly aligned/added space between widgets | <p>I am working on this table in tkinter made from a bunch of treeveiw widgets. The idea is to get a table where I can add lines, select lines and edit them. In the code below you can add lines to the table by pushing the button. I now want to control the height of each row by configuring the style. However, when I use... | <p>Put the style configuration in the <code>__init__()</code> function and the effect will go away. I'm not clear as to why this works. </p>
<pre><code>def __init__(self):
...
s = ttk.Style()
s.configure('MyStyle.Treeview', rowheight=20)
</code></pre> | python|python-3.x|tkinter|treeview|grid-layout | 2 |
4,361 | 51,847,098 | Cannot convert bytes output to string while running praat script through subprocess python | <pre><code>sound_offset_time = subprocess.check_output(praat_command_str, shell=True).decode("utf-8")
</code></pre>
<p>gives output</p>
<pre><code># Result: - #
</code></pre>
<p>Another command</p>
<pre><code>process = subprocess.Popen(praat_command_str, stdout=subprocess.PIPE, stderr=None, shell=True)
</code></pr... | <p>It looks like your command is sending output in <code>utf-16</code> form, but you're trying to decode it as <code>utf-8</code>.</p> | python | 1 |
4,362 | 59,519,134 | Calulate the groupby (several columns) average in pandas | <p>I have a dataframe as shown below.</p>
<pre><code>Unit_ID Price Sector Contract_Date Rooms
1 20 SE1 16-10-2015 2
9 40 SE1 20-10-2015 2
2 40 SE1 16-10-2016 3
2 30 SE1 1... | <p>Use:</p>
<pre><code>( df.groupby(['Sector','Rooms',df['Contract_Date'].dt.year.rename('Year')])
.Price
.mean()
.rename('Average_Price')
.reset_index() )
Sector Rooms Year Average_Price
0 SE1 2 2015 46.666667
1 SE1 2 2016 60.000000
2 SE1 3 2015 25.00000... | pandas|pandas-groupby | 2 |
4,363 | 18,938,548 | How to cut elements from list of integer | <p>if I have a list of integer</p>
<pre><code> x=[0, 0, 119, 101, 108, 108, 99, 111, 109]
</code></pre>
<p>I'd like to cut 2 elements from left</p>
<pre><code> x=[119, 101, 108, 108, 99, 111, 109]
</code></pre>
<p>What shall I do ?</p> | <p>Use <a href="https://stackoverflow.com/questions/509211/pythons-slice-notation">Python's slice notation</a>:</p>
<pre><code>>>> x = [0, 0, 119, 101, 108, 108, 99, 111, 109]
>>> x = x[2:]
>>> x
[119, 101, 108, 108, 99, 111, 109]
</code></pre>
<p>This gets every element from the third item... | python|list|integer | 6 |
4,364 | 18,857,355 | Where are math.py and sys.py? | <p>I found all the other modules in Python33/Lib, but I can't find these. I'm sure there are others "missing" too, but these are the only ones I've noticed. They work just fine when I import them, I just can't find them. I checked sys.path and they weren't anywhere in there. Are they built-in or something?</p> | <p>The <code>math</code> and <code>sys</code> modules are builtins -- for purposes of speed, they're written in C and are directly incorporated into the Python interpreter.</p>
<p>To get a full list of all builtins, you can run:</p>
<pre><code>>>> import sys
>>> sys.builtin_module_names
</code></pre... | python|python-3.x|python-module | 21 |
4,365 | 69,270,647 | Add "nan" to numpy histogram python | <p>I am using random library to generate 5000 data points from a Gaussian distribution and then using the data to compute histogram with 10 bins, see code below.</p>
<pre><code>s = np.random.normal(mu, sigma, 5000)
arrHist = np.histogram(s, 10)
print(arrHist)
</code></pre>
<p>Output is:</p>
<pre><code>(array([ 9, 4... | <p>Try this:</p>
<pre><code>result=[]
max_len=max([len(x) for x in arrHist])
for x in arrHist:
if len(x)!=max_len:
x=x.astype('float')
x=np.pad(x, (0,max_len-len(x)), 'constant', constant_values=(np.nan, ))
result.append(x)
</code></pre> | python|arrays|numpy|histogram | 1 |
4,366 | 62,236,313 | Performing for loop in pandas | <p>I have a CSV like the below:</p>
<pre><code>i,ix,iz,iy,u'
0,1,1,1,-0.8696748576752853
1,1,1,2,2.3557976585107454
2,1,1,3,0.47209618683697663
3,1,1,4,-1.930481713597933
4,1,1,5,-1.7868247414530511
5,1,1,6,-0.5603642778861779
6,1,1,7,0.24540750240253573
7,1,1,8,0.5505270314521304
8,1,1,9,-0.1954277406567968
9,1,1,10,... | <p>Generally, conditional statements can be written like this:</p>
<pre><code>df[
(df['ix'] == ix) &
(df['iy'] == iy) &
(df['iz'] == iz)
]["u'"]
</code></pre>
<p>In order to also iterate over the items in the mentioned lists, you can use <a href="https://docs.python.org/2/library/itertools.html#itertool... | python|pandas | 2 |
4,367 | 62,419,771 | Trying to convert a string to a list of complex numbers | <p>I am trying to convert a string to a list of complex numbers. (If you were to read it without quotes, it would be a list of complex numbers.) I've written a function to do this, but I'm getting this error:</p>
<pre><code>Traceback (most recent call last):
File "complex.py", line 26, in <module>
pr... | <p>Amazingly, this is something Python can do without needing any functions written, with its inbuilt complex number class.</p>
<pre><code>listIn = '1.111 + 2.222j, 3.333 + 4.444j'
listOut = eval(listIn)
print(listOut[0])
print(listOut[0].imag,listOut[0].real)
</code></pre> | python|python-3.x | 2 |
4,368 | 67,254,910 | I have the following problem when using autocomplete_fields field under django3.2 | <p>The following problems will occur:</p>
<p><img src="https://i.stack.imgur.com/DS5M4.png" alt="screenshot" /></p>
<p>When I use the version below django3.2, everything is normal. I don't know if this is my problem?</p>
<p>And django will raise the following error:</p>
<pre><code> During handling of the above excep... | <p>Run</p>
<pre><code>python manage.py collectstatic
</code></pre>
<p>See <a href="https://code.djangoproject.com/ticket/32659" rel="nofollow noreferrer">https://code.djangoproject.com/ticket/32659</a></p> | python|django | 2 |
4,369 | 63,508,747 | Data Preprocessing steps with pandas and numpy not working | <p>I am having trouble following <a href="https://towardsdatascience.com/marketing-channel-attribution-with-markov-chains-in-python-part-2-the-complete-walkthrough-733c65b23323" rel="nofollow noreferrer">this Tutorial regarding Markov Chains in Python.</a></p>
<p>As advised, I have installed Anaconda to be used with vs... | <p>FIrst, it is correct,</p>
<p><code>import numpy as pd</code></p>
<p>it should be</p>
<p><code>import numpy as np</code></p>
<p>Then, try:</p>
<pre><code>df_paths['path'] = np.where( df_paths['conversion'] == 0,
['Start, '] + df_paths['channel'].apply(', '.join) + [', Null'],
['Start, '] + df_paths['channel'].apply('... | python-3.x|pandas|numpy|anaconda|data-science | 1 |
4,370 | 63,655,589 | How to load resources file without giving entire path in Python | <p>I want to read the <code>properties</code> file in Python without giving the entire path. Because if my code is deployed somewhere else then my package would fail if I pass the hardcore value. So below is my code to read the properties file by giving the entire path:</p>
<pre><code>import configparser
config = confi... | <p>if the file will always be in the same place relative to your python file, you can do the following:</p>
<pre><code>props = os.path.join(
os.path.dirname(__name__), # folder where the python file is
'relative/path/to/configs.properties'
)
</code></pre> | python | 0 |
4,371 | 36,261,676 | When can I access instance variables of init method? | <p>Why I cannot access instance variables g of mnc method?</p>
<pre><code>class yy(object):
k="suri"
def __init__(self,a,b):
self.h="amruth"
print a
print b
def mnc(self,x):
self.g="tamu"
yy.k="yyy"
m=yy('gg','yy')
print m.h
print m.g
</code></pre> | <p>You have to call/invoke 'mnc' method first before access 'g'</p>
<pre><code>m=yy('gg','yy')
m.mnc('some value')
print m.h
print m.g
</code></pre> | python-2.7 | 1 |
4,372 | 43,569,559 | can i create a icon to start my cython compiled program (python) | <p>python program compiled to cython</p>
<ul>
<li>not open the terminal</li>
<li>point to my virtualenv</li>
<li><code>>>> import my_program</code></li>
</ul>
<p>Instead would like to make it more user friendly
and start the program from an icon</p> | <p>I'm not sure what operating system you are on. However, the answer is simular for both.</p>
<p><strong>On Windows:</strong></p>
<p>You need to create a .bat file. The are <a href="https://stackoverflow.com/questions/4571244/creating-a-bat-file-for-python-script">already questions about how to do this to use Python... | python|cython|compiled | 2 |
4,373 | 9,539,052 | How to dynamically change base class of instances at runtime? | <p><a href="http://www.linuxjournal.com/node/4540" rel="noreferrer">This article</a> has a snippet showing usage of <code>__bases__</code> to dynamically change the inheritance hierarchy of some Python code, by adding a class to an existing classes collection of classes from which it inherits. Ok, that's hard to read,... | <p>Ok, again, this is not something you should normally do, this is for informational purposes only. </p>
<p>Where Python looks for a method on an instance object is determined by the <code>__mro__</code> attribute of the class which defines that object (the <strong>M</strong> ethod <strong>R</strong> esolution <stro... | python|inheritance|dynamic | 41 |
4,374 | 39,186,843 | get both unique count and max in group-by of pandas dataframe | <p>Using Pandas data frame group by feature and I want to group by column <code>c_b</code> and (1) calculate unique count for column <code>c_a</code> and column <code>c_c</code>, (2) and get the max value of column c_d. Wondering if there is any solution to write one line of group by code to achieve both goals? I tried... | <p>You can pass a dict to <code>agg()</code>:</p>
<pre><code>df.groupby('c_b').agg({'c_a':'nunique', 'c_c':'nunique', 'c_d':'max'})
</code></pre>
<p>If you don't want <code>c_b</code> as index, you can pass <code>as_index=False</code> to <code>groupby</code>:</p>
<pre><code>df.groupby('c_b', as_index=False).agg({'c_... | python|python-2.7|pandas|dataframe|group-by | 3 |
4,375 | 55,433,605 | Python 3.7: How to avoid stackoverflow for this recursive approach? | <h3>1. The situation</h3>
<p>I'm working on a project in Python, and I got the following style of functions quite a lot:</p>
<pre class="lang-py prettyprint-override"><code>from PyQt5.QtCore import *
import functools
...
def myfunc(self, callback, callbackArg):
'''
This function hasn't finished ... | <p>You did not include the code for <code>item.foobar</code> and <code>self.foo</code>. Assuming that these calls do not cause deep recursion, the maximum stack depth during execution of this code will not increase with the length of the list.</p>
<p><code>functools.partial</code> does not immediately call the <code>... | python|python-3.x|recursion|tail-recursion | 1 |
4,376 | 52,540,413 | Force tkinter listbox to highlight item when selected before task is started | <p>I have a tkinter listbox, when I select a item it performs a few actions then returns the results, while that is happening the item I selected does not show as selected, is there a way to force it to show selected immediately so it's obvious to the user they selected the correct one while waiting on the returned res... | <p>The item does show as selected right away because the time consuming actions are executed before updating the GUI. You can force the GUI to update before executing the actions by using <code>window.update_idletasks()</code>.</p> | python|tkinter|listbox | 0 |
4,377 | 37,227,909 | Print Last Line of File Read In with Python | <p>How could I <code>print</code> the final line of a text file read in with python?</p>
<pre><code>fi=open(inputFile,"r")
for line in fi:
#go to last line and print it
</code></pre> | <p>One option is to use <code>file.readlines()</code>:</p>
<pre><code>f1 = open(inputFile, "r")
last_line = f1.readlines()[-1]
f1.close()
</code></pre>
<p>If you don't need the file after, though, it is recommended to use contexts using <code>with</code>, so that the file is automatically closed after:</p>
<pre><cod... | python | 17 |
4,378 | 33,991,857 | Conversion from Roman numerals in Dive into Python seems to output an extra character | <p>I am learning Python 2.7 by <em>Dive to Python</em>. Here are the codes of "Converting between Roman Numerals and Arabic numerals":</p>
<pre><code>romanNumeralMap = (('M',1000),
('CM',900),
('D',500),
('CD',400),
('C',100),
('XC',90),
('L',50),
('XL',40),
... | <p><code>numeral</code> is equal to <code>CM</code> and <code>len(cm) == 2</code>. <code>s[1: 1 + 2] == s[1:3] == 'CM'</code></p>
<p>Since the numeral is actually two characters, you read two characters of the input to match against.</p> | python|arrays|roman-numerals | 0 |
4,379 | 34,001,574 | How to read timestamp from excel list in python | <p>I am quite new to python and already struggling with an easy task like importing the timestamps of a series of measurement from an excel list.
The excel file has one column for date and one for time. I need the data for further calculation like time difference etc. </p>
<p>I tried to different ways how to get the ... | <p>Regarding your first solution, <code>strptime</code> takes only one date string as input.
You should join <code>input_date</code> and <code>input_time</code>:</p>
<pre><code>input_time = '18:20:00'
input_date = 'Mon, 30 Nov 2015'
time = datetime.datetime.strptime(' '.join([input_date, input_time]), "%a, %d %b %Y %H... | python|excel|timestamp|timedelta | 1 |
4,380 | 66,176,851 | Dictionary unique values in comprehension | <p>I have a little task which I solved.</p>
<p>Task: find all PAIRS in a sequence which sum up to a certain number.</p>
<p>For example (1,2,3,4) and target 3 yields one pair (1,2).</p>
<p>I came up with a solution:</p>
<pre><code>def pair(lst, find):
res = []
for i in lst:
if (find - i) in lst:
res.append([... | <p>Because dict hashes its keys then store them in a set-like data structure. As a result the newly created {key :value} overrides the older one and in your case the duplicates. I think this may be a duplicate question</p> | python|dictionary|dictionary-comprehension | 2 |
4,381 | 7,022,631 | Python: "breaking out" of if statement inside a for loop | <p>I understand that one cannot "break" an if statement and only from a loop, however, I'm trying to conceptually stop an if statement from evaluating after it finds a "true" the first time when it's inside a for loop.</p>
<pre><code># Import XML Parser
import xml.etree.ElementTree as ET
# Parse XML directly from the... | <pre><code> if randomValue <= sum(i.freq for i in diceList[0:i+1]):
print 'O', i, 'randomValue', randomValue, 'prob container', sum(i.freq for i in diceList[0:i+1])
break
</code></pre>
<p><a href="http://docs.python.org/reference/simple_stmts.html#the-break-statement">Break</a> will term... | python|if-statement|for-loop|break | 12 |
4,382 | 16,313,121 | How do I convert this into a comprehension? (Python) | <p>This function produces the sum of the first n values, the sum of the second n values...etc.</p>
<p>Here is the function:</p>
<pre><code>def collect_sum(iterable,n):
for e in range(1,len(ite)+1):
if e%n==0:
yield sum(iterable[e-n:e])
for i in c_sum(range(1,21),5):
print(i,end=' ')
</... | <pre><code>def collect_sum(i,n):
return (sum(g) for (_,g ) in groupby(i,key=lambda _,c=count():floor(next(c)/n)))
for v in collect_sum(range(1,21),5):
print(v)
</code></pre>
<p>Produces:</p>
<pre><code>15
40
65
90
>>>
</code></pre> | python|list-comprehension|python-2.x | 2 |
4,383 | 16,197,322 | How do I specify a header/footer for html2pdf to use when rendering a pdf? | <p>I'm using the html2pdf python library, and would like to define a header and a footer to apply to each page (including fun things, like a page count for the footer). What is the most expedient method I can use to specify headers/footers with html2pdf?</p> | <p>See if this is what needs friend. The header and footer is fixed and informs the count of pages.</p>
<pre><code><?php
/**
* HTML2PDF Librairy - example
*
* HTML => PDF convertor
* distributed under the LGPL License
*
* @author Laurent MINGUET <webmaster@html2pdf.fr>
*
* isset($_GET['vuehtml... | python|html2pdf | 7 |
4,384 | 31,736,653 | Python Check if Variable is Duplicated in list | <p>I want to see if there is a way to tell if a variable has an equivalent variable in a list.</p>
<pre><code>a = 'hi'
b = 'ji'
c = 'ki'
d = 'li'
e = 'hi'
letters = [a, b, c, d, e]
</code></pre>
<p>Is there a way to check if any variable(<code>a</code>) is equal to any other variable(<code>e</code>). In this cas... | <p>You can try using the following -</p>
<pre><code>len(letters) != len(set(letters))
</code></pre>
<p>When you convert a list to set, it removes duplicate elements from the list, so if any element is there more than once, in letters, the length of <code>set(letters)</code> would be less than the length of the origin... | python|list|variables|duplicates | 4 |
4,385 | 38,743,079 | Pandas Converter on Data strptime() | <p>I am trying to plot this points, however I am getting that error. Do I need another converter for the date data? The x-axis should be the date, and y axis should be the time value. Thank you.</p>
<p>TypeError: strptime() argument 1 must be str, not Timestamp</p>
<pre><code>df = pd.read_csv('file.csv', sep=',', par... | <p><code>datetime.strptime()</code> is for <em>parsing</em> strings into <code>datetime.datetime</code> objects. As such it makes no sense to apply it to a <code>pandas.tslib.Timestamp</code> object, which is what would be passed in by <code>[date_to_days(d) for d in dates]</code> because <code>dates</code> contains th... | python | 0 |
4,386 | 38,570,044 | Ignore null/blank cells with filter | <p>I'm trying to filter the 22nd column with numbers between <code>0.10</code> and <code>1.00</code> into <code>Day.csv</code>. But some of those cells are blank with no number at all and cause an error:</p>
<p><code>ValueError: could not convert string to float:</code></p>
<p>Here is what I tried:</p>
<pre><code>re... | <p>Presumably you therefore need your filter to return False when the cell in question contains no value? Try:</p>
<pre><code>filteredDay = filter(lambda p: p[23] != "" and
0.10 <= float(p[23]) <= 1.00, reader)
</code></pre> | python|csv|lambda | 3 |
4,387 | 2,161,575 | Executing multiple commands using Popen.stdin | <p>I'd like to execute multiple commands in a standalone application launched from a python script, using pipes. The only way I could reliably pass the commands to the stdin of the program was using Popen.communicate but it closes the program after the command gets executed. If I use Popen.stdin.write than the command ... | <p>If I understand your problem correctly, you want to interact (i.e. send commands and read the responses) with a console application.</p>
<p>If so, you may want to check an Expect-like library, like pexpect for Python: <a href="http://pexpect.sourceforge.net" rel="nofollow">http://pexpect.sourceforge.net</a></p>
<p... | python|popen | 1 |
4,388 | 1,780,922 | How do I encode a 4-byte string as a single 32-bit integer? | <p>First, a disclaimer. I'm not a CS grad nor a math major, so simplicity is important. </p>
<p>I have a four-character string (e.g. "isoy") that I need to pass as a single 32-bit integer field. Of course at the other end, I need to decode it back to a string. The string will only contain A-Z, and case is not importan... | <p>To 32-bit unsigned integer:</p>
<pre><code>uint x = BitConverter.ToUInt32(Encoding.ASCII.GetBytes("isoy"), 0); // 2037347177
</code></pre>
<p>To string:</p>
<pre><code>string s = Encoding.ASCII.GetString(BitConverter.GetBytes(x)); // "isoy"
</code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/s... | c#|python|algorithm|powershell | 10 |
4,389 | 63,150,553 | couldn't find tensorflow version | <p>I am working with python3.7 and trying to download Tensor flow library but it gives me following error</p>
<p><em>ERROR: Could not find a version that satisfies the requirement tensorflow (from versions: none)
ERROR: No matching distribution found for tensorflow</em></p>
<p>I am using pip installation as:</p>
<pre><... | <p>Try conda install if you are using Anaconda.
Go to your anaconda prompt by searching same in windows search. After Opening Anaconda prompt, try this command <strong>conda install -c conda-forge tensorflow</strong></p>
<p>Hope error wont come now.</p> | python|python-3.x|tensorflow | 1 |
4,390 | 32,515,404 | How to update two subplots in a loop in ipython notebook within one cell | <p>I have the following code:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
#
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)
plt.close('all')
for i in range (0,3):
y = y + np.pi/2
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True, figsize=(10, 4))
ax1.plot(x, y... | <p>Is this what you want to do?</p>
<p><a href="https://i.stack.imgur.com/xn6o7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xn6o7.png" alt="plot"></a></p>
<p>If you don't want to create more than one plot figure, you have to pull the <code>plt.subplots(...)</code> call out of the scope of the f... | python|matplotlib|ipython | 1 |
4,391 | 32,300,191 | django.db.utils.OperationalError: parser stack overflow | <p>I have a re-usable django application which should support <code>python2.7</code>, <code>python 3.x</code> and <code>pypy</code>. I developed it in <code>python 2.7</code> at the beginning and all of my tests are worked very well. I also made them worked in <code>python3.3</code> too. But I have a problem with <code... | <p>The default <a href="https://www.sqlite.org/compile.html#yystackdepth" rel="nofollow">sqlite3 parser stack size</a> is 100 lexical items. They think <em>"it is likely to be well beyond the ability of any human to comprehend"</em>. I see many nested levels in your example: 15 parenheses, 9 "SELECT", 9 "WHERE", 9 "IN"... | django|python-3.x|sqlite|pypy | 0 |
4,392 | 32,899,881 | How to create a sequential combined list in python? | <p>I've got a list ['a', 'b', 'c', 'd'] and I need a list ['a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd'].</p>
<p>I've been looking at <a href="https://docs.python.org/2/library/itertools.html#itertools.product" rel="nofollow noreferrer">itertools</a>, but I'm not seeing how to make this work.</p>
<p>For... | <p>Quite simply:</p>
<pre><code>stuff = ['a','b','c','d']
print([''.join(stuff[i:j]) for i in range(len(stuff)) for j in range(i+1, len(stuff)+1)])
</code></pre>
<p>Gives</p>
<pre><code>['a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd']
</code></pre> | python|itertools | 5 |
4,393 | 14,066,877 | SyntaxError: invalid syntax in mfs.cgi | <p>I run MooseFS CGI Server based on Python in my RedHat server, and I get an weird
syntax error:</p>
<pre><code>Traceback (most recent call last):
File "/usr/sbin/mfscgiserv", line 300, in run_cgi
execfile(self.file_name)
File "/usr/share/mfscgi/mfs.cgi", line 129
return "%s%.1f%s" % (("~" if n != rn els... | <p>The failing expression uses python <a href="http://docs.python.org/2/reference/expressions.html#conditional-expressions" rel="nofollow">conditional_expression</a>, which was added in <a href="http://docs.python.org/2/whatsnew/2.5.html" rel="nofollow">Python 2.5</a>.</p>
<p>Your best bet is to upgrade to a supported... | python|cgi|moosefs | 3 |
4,394 | 14,078,755 | Django custom model fields: to_python() not called | <p>I am quite new to Python and Django, and totally new on Stack Overflow, so I hope I won't break any rules here and I respect the question format.</p>
<p>I am facing a problem trying to implement a custom model field with Django (Python 3.3.0, Django 1.5a1), and I didn't find any similar topics, I am actually quite ... | <p>In python 3 the module-global <code>__metaclass__</code> variable is no longer supported. You must use:</p>
<pre><code>class CardContainerField(models.CommaSeparatedIntegerField, metaclass=models.SubfieldBase):
...
</code></pre> | python|django | 11 |
4,395 | 34,579,647 | Scrapy CrawlSpider - Start crawl on next URL only after first URL is complete | <p>I have a spider which looks something like this</p>
<pre><code>class SomeSpider(CrawlSpider):
name = 'grablink'
allowed_domains = ['www.yellowpages.com', 'sports.yahoo.com']
start_urls = ['http://www.yellowpages.com/', 'http://sports.yahoo.com']
rules = (Rule(LinkExtractor(allow=allowed_domains), ca... | <p>You have several options: </p>
<ul>
<li>Write Site specific spiders, like one for Yellow Pages, one for Yahoo!</li>
<li>Write a generic spider and take arguments while running the spider to decide which site to crawl. </li>
<li>If you want to do it manually, you can just change the url by hand and run it. </li>
</u... | python|scrapy|web-crawler | 2 |
4,396 | 27,088,460 | Cython error: declaration does not declare anything | <p>I'm writing some cython code, and I've come across an odd problem. When I try to pass an object straight from python to C as a struct, cython generates the code fine, but gcc doesn't like the code output and gives me the following error: <code>error: declaration does not declare anything</code>. Here is my test code... | <p>Yes, I think you are right that this is a bug in Cython 0.21. First, testing with Cython 0.20 (because that is what my linux distribution ships) and it gives me</p>
<pre><code>cake.pyx:16:15: Cannot convert Python object to 'Cake'
</code></pre>
<p>I suppose this is because the conversion feature was missing or inc... | python|c++|cython | 2 |
4,397 | 27,161,466 | Why is "which python" not showing me the local python? | <p>I am using Mac OSX Mavericks and have installed Python3 with</p>
<pre><code>brew install python3
</code></pre>
<p>now I am trying to see which python is used with</p>
<pre><code>which python
</code></pre>
<p>But this does not give me the local python. I have my paths set correctly as you can see below:</p>
<pre... | <pre><code>which python3
</code></pre>
<p>gives me the local path. Thanks to BrenBarn for pointing it out!</p> | python|path|local|homebrew | 0 |
4,398 | 22,950,670 | Python module equivalent to the unix command "fmt"? | <p>There is some module with similar functionality to the unix command <a href="http://www.openbsd.org/cgi-bin/man.cgi?query=fmt&apropos=0&sektion=0&manpath=OpenBSD%20Current&arch=i386&format=html" rel="nofollow">"fmt"</a>?. <code>fmt</code> is pretty intelligent reflowing text and I would like to u... | <pre><code>import textwrap
with open('long_text.txt', 'r') as f:
long_text = f.read()
# Get a list of wrapped lines (default width 70)
long_text_lines = textwrap.wrap(long_text)
# Get a single string containing the wrapped text
# Same as: "\n".join(textwrap.wrap(long_text, ...))
long_text_string = textwrap.fill(... | python|unix|python-module | 0 |
4,399 | 23,096,681 | Tk() from python tkinter only works with sudo on kali/debian linux | <p>I just got my Kali live USB up and running and wanted to get familiar with the system by working on some code I have been writing on my windows box. Long story short I couldn't get some very basic tkinter code to work so I went super basic. Turns out I can only get it to run if I'm root or the sudo. see below.</p... | <p>It all depends on what your <code>DISPLAY</code> environment variable is set to. That indicates the socket that represents the connection to the display server; for <code>:0.0</code>, that's a Unix-domain socket (typically <code>/tmp/.X11-unix/X0</code>, but not necessarily; it's up to an agreement between your Xser... | python|tkinter|tk | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.