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
10,400
58,975,107
Program not able to find file even though the file is in the same folder (text file)
<p><a href="https://i.stack.imgur.com/Raz13.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Raz13.png" alt=" The image is the way the files are stored."></a> I am making a programming project with school and everything else is working; However, the program cannot find the file even though it is in th...
<p>It's a working directory problem. You probably are executing it from a different folder. To see where you are running it from use:</p> <pre><code>import os print(os.getcwd()) </code></pre> <p>So to locate <code>songs_artists.txt</code> based on <code>Project Code.py</code> path use this:</p> <pre><code>import os ...
python|python-3.x
2
10,401
73,375,218
How to convert upper-case name to formal name?
<p>I have a list of car brands in upper case, (MERCEDES-BENZ', 'BMW', 'CHEVROLET', 'MG', 'FORD'...etc), what is the best way to get the formal names, like:</p> <pre><code>MERCEDES-BENZ ===&gt; Mercedes-Benz BMW ===&gt; BMW CHEVROLET ===&gt; Chevrolet MG ===&gt; MG JOSS ===&gt; JOSS </code></pre> <p>i am thinking of som...
<p>From the sample list of brands, this list comprehension might work:</p> <pre><code>lis = ['MERCEDES-BENZ', 'BMW', 'CHEVROLET', 'MG', 'JOSS'] print([e.title() if len(e)&gt;4 else e for e in lis]) </code></pre> <p>Output</p> <pre><code>['Mercedes-Benz', 'BMW', 'Chevrolet', 'MG', 'JOSS'] </code></pre>
python|string
1
10,402
15,584,972
Python for loop parameters
<p>Hi im just wondering what the 4 would do in this code</p> <pre><code>for y in range(0, height, 4): </code></pre> <p>Thanks</p>
<p>Range with just one parameter: end.</p> <p>Range with two parameters: start, end.</p> <p>Range with three parameters: start, end, step.</p> <p>So in your specific case</p> <pre><code> for y in range(0, height, 4) </code></pre> <p>0, 4, 8, ..., n, where n &lt; height.</p>
python|jes
3
10,403
15,963,815
Python add a string to all set's elements
<p>I'm wondering what is the Python way to perform the following - Given a set :</p> <pre><code>s = {'s1','s2','s3'} </code></pre> <p>I would like to perform something like :</p> <pre><code>s.addToAll('!') </code></pre> <p>to get</p> <pre><code>{'s1!','s2!','s3!'} </code></pre> <p>Thanks!</p>
<p>For an actual set:</p> <pre><code>&gt;&gt;&gt; s = {'s1','s2','s3'} &gt;&gt;&gt; {x + '!' for x in s} set(['s1!', 's2!', 's3!']) </code></pre> <p>That method is 2.7+, If you are using Python 2.6 you would have to do this instead:</p> <pre><code>&gt;&gt;&gt; s = set(['s1','s2','s3']) &gt;&gt;&gt; set(x + '!' for x...
python|string|set|set-operations
7
10,404
59,536,386
Python MySql API
<p>I am creating an API for mysql using python. I am trying to get multiple columns. In SQL query, you would generally do something like SELECT col1, col2.... FROM tablename; My python API for the same looks something like this:</p> <pre><code>def get_multiple_columns(self, tablename, limit, *colname): sql = '...
<p>In your method <code>get_multiple_columns</code>, argument <code>colname</code> comes in as a <code>tuple</code>, so you want:</p> <pre><code>sql = 'Select {} From {} limit {}'.format(', '.join(colname), tablename, limit) </code></pre>
python|pymysql
0
10,405
25,191,322
getting an error 'AttributeError:' in Python
<p>I have written the below script using python:</p> <pre><code>class Fruit: def __init__(self,name): self.name = name print "Initialized Fruit Name: %s" % self.name def tell(self): print "U have entered the fruit as %s" % self.name class Sweet(Fruit): def __init__(self,name,taste,price): ...
<p>You need <code>self.price=price</code> in the <code>__init__</code> methods - currently you are just throwing that parameter away.</p>
python
4
10,406
60,203,543
python:add month date to the column by 10 months
<p>I have a dataset with a START_DATE column and a string column like this:</p> <pre><code>START_DATE string 2017-03-31 a 2017-04-30 b 2017-05-30 c </code></pre> <p>I want to transform it into this format like this:</p> <pre><code>START_DATE string...
<p>I don't know for how long this should go on, but you could use a for loop that spans over a certain time window, adding one month to the current date at every iteration and get the last day of the month.</p> <p>In order to get the last day of the month, see <a href="https://stackoverflow.com/questions/42950/get-las...
python|dataframe|datetime
0
10,407
3,003,845
KindError: Property r must be an instance of SecondModel, why?
<pre><code>class FirstModel(db.Model): p = db.StringProperty() r=db.ReferenceProperty(SecondModel) class SecondModel(db.Model): r = db.ReferenceProperty(FirstModel) class sss(webapp.RequestHandler): def get(self): a=FirstModel() a.p='sss' a.put() b=SecondModel() b.r=a b.put() ...
<p>The code you show shouldn't even compile - you can't instantiate a reference property with a class that isn't yet defined - unless you have another definition of SecondModel somewhere that you haven't included, in which case the issue is that FirstModel has a reference to the original SecondModel, but you're passing...
python|google-app-engine|model|properties
0
10,408
67,790,385
Adding a UserCreationForm to html in Django
<p>I am creating a registration page for my website. I have a bootstrap/html template with a form (Down Bellow), and I want to replace the html form with a <code>UserCreationForm</code> that I have already made in my forms.py file. The tutorial says to replace the html input fields with my user creation fields, but th...
<p>I would advise you to look toward the following approach, if you can and willing to modify your <code>UserCreationForm</code> a bit:</p> <pre><code>class UserCreationForm(forms.Form): # other fields as needed... username = forms.CharField( max_legth=100, widget=forms.T...
python|html|css|django
1
10,409
30,344,804
Why can't I import PyQt in Python files?
<p>I have installed PyQt using brew but when I am trying to import it, I just receive errors as follows:</p> <pre><code>&gt;&gt;&gt; from PyQt4 import QtCore, QtGui Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named PyQt4 &gt;&gt;&gt; from PyQt5 import QtC...
<p>The most painless way to do python without messing around with modules is to install distributions. Two very good ones are <a href="https://www.enthought.com/products/canopy/" rel="nofollow">Canopy Python</a> and <a href="http://continuum.io/downloads" rel="nofollow">Anaconda</a>. They have most, if not all, modules...
python|qt|pyqt|pycharm
0
10,410
66,910,416
How to change a discord nickname to whatever the user writes using a bot discord.py
<pre><code>if message.content.startswith(f'Imagine having a name as dumb as {#name}'): Nick = (#message author) #change nickname of Nick to {#name} await message.channel.send('Ikr') </code></pre> <p>How do I do this?</p>
<p>Just use a simple regex</p> <pre class="lang-py prettyprint-override"><code>import re @bot.event async def on_message(message): content = message.content.lower() # The actual content of the message in lowercase pattern = &quot;imagine having a name as dumb as (.{0,32})&quot; # Max length for nicks is 32 cha...
python-3.x|discord.py
0
10,411
66,803,573
Group all keys with the same value in a dictionary of sets
<p>I am trying to transform a dictionary of sets as the values with duplication to a dictionary with the unique sets as the value and at the same time join the keys together.</p> <pre><code>dic = {'a': {1, 2, 3}, 'b': {1, 2}, 'c': {1, 3, 2}, 'd': {1, 2, 3}} </code></pre> <p>Should be changed to</p> <pre><code>{'a-c-d':...
<p>You can &quot;invert&quot; the input dictionary into a dictionary mapping frozensets into a set of keys.</p> <pre><code>import collections dic = {'a': {1, 2, 3}, 'b': {1, 2}, 'c': {1, 3, 2}, 'd': {1, 2, 3}} keys_per_set = collections.defaultdict(list) for key, value in dic.items(): keys_per_set[frozenset(value...
python|dictionary|set
6
10,412
72,418,691
How to change this time data into H:M in python
<p>Have a dataset with a duration column with time data listed as an object shown below</p> <pre><code>df['duration'].head(10) 0 60 min. 1 1 hr. 13 min. 2 1 hr. 10 min. 3 52 min. 4 1 hr. 25 min. 5 45 min. 6 45 min. 7 60 min. 8 ...
<p>Here is a way to get a string version in <code>%H:%M</code> format and a timedelta version:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({'duration':['60 min.', '1 hr. 13 min.', '1 hr. 10 min.']}) print(df) df['parts']=df.duration.str.findall('\d+') df['timedelta']=df.pa...
python|time|numeric
1
10,413
65,747,952
Integer YYYYMMDD to DateTime (e.g. 01JAN2021)
<p>I'm having some difficulties converting an integer-type column of a Pandas DataFrame representing dates (in YYYYMMDD format) to a DateTime type column and parsing the result in a specific format (e.g., 01JAN2021). Here's a sample DataFrame to get started:</p> <pre><code>import pandas as pd df = pd.DataFrame(data={&...
<p>Do this:</p> <pre><code>In [1347]: df[&quot;CUS_DATE&quot;] = pd.to_datetime(df['CUS_DATE'], format='%Y%m%d') In [1359]: df[&quot;CUS_DATE&quot;] = df[&quot;CUS_DATE&quot;].apply(lambda x: x.strftime('%d%b%Y').upper()) In [1360]: df Out[1360]: CUS_DATE 0 03JUL1955 1 12DEC1963 2 19MAR1972 3 05FEB1989 4 26J...
python|python-3.x|pandas|datetime
2
10,414
50,956,659
ModuleNotFoundError on psycopg2 only on compiled script
<p>I am currently working through a tutorial on database entry using psycopg2 but I can't seem to get my script to find it. Used pip install and my script is written in Atom. When I import psycopg2 in the command prompt it works fine but my Atom script wont run:</p> <p><strong>ATOM SCRIPT</strong></p> <pre><code>impo...
<p>First you are showing this in your code, adding a path to <code>sys.path</code>:</p> <pre><code>sys.path.append('c:\\users\j.meiring\appdata\local\programs\python\python36-32\lib\site-packages') </code></pre> <p>Your error appears differently, however. I've added line breaks to the path it provides, for readabilit...
python|python-3.x|python-3.6|atom-editor|psycopg2
0
10,415
50,785,588
Detecting system suspend in a loop
<p>I'm trying to detect system suspend using the following algorithm:</p> <pre><code>while True: lastchecked = now() if now() - lastchecked &gt; 1s: print "suspend detected!" </code></pre> <p>But I ran into a problem: If suspend happens between 2nd and 3rd line, then the loop catches it. But if suspend happen...
<p>First of all, <a href="https://stackoverflow.com/questions/31841096/get-a-signal-once-a-subprocess-ends/31841282#31841282">polling is inferiour to notifications</a> because it wastes system resources that could instead be spent on useful work (and your current loop is a <a href="https://en.wikipedia.org/wiki/Busy_wa...
python|algorithm
1
10,416
50,837,113
Override __getitem__ to update
<p>I am implementing a class that inherits from UserDict. This class acts completely as expected but I would like to extend its features. I would like it to pass through all methods that have been overriden when acting upon the dictionary. An example would be:</p> <pre><code>from collections import UserDict class Du...
<p>You can wrap the inner dictionaries you're given as values in another instance of your class. If you want this to happen automatically, I'd suggest doing it for any dictionary value you're passed in <code>__setitem__</code>, since that lets you mutate the wrapper object in place later, while you keep a reference to ...
python|dictionary|subclass
1
10,417
3,628,663
Setting up orbited development environment on windows
<p>I am developing a comet application using python orbited and django. But I don't know how to setup the development environment. Can any one please help me out? I looked at the documentations and tutorials... But I found them confusing... What I am looking is a walk-through kind of information.</p>
<p>Perhaps this can get you started - <a href="http://mischneider.net/?p=125" rel="nofollow">Django, Orbited, Stomp and Co.</a></p>
python|orbited
0
10,418
4,013,452
How do I take integer keys in shelve?
<p>I want to store an integer key in shelve. But when I try to store integer key in shelve it give me an error</p> <pre> Traceback (most recent call last): File "./write.py", line 12, in data[id] = {"Id": id, "Name": name} File "/usr/lib/python2.5/shelve.py", line 124, in __setitem__ self.dict[key] = f.ge...
<p>In your example the keys in your database will always be integers, so it should work fine to convert them to strings,</p> <p>data[str(id)] = {"Id": id, "Name": name}</p> <p>My test code</p> <pre><code>def shelve_some_data(filename): db = shelve.open(filename, flag="c") try: # note key has to be a ...
python|file-io|dictionary|shelve|persistent-storage
2
10,419
3,815,746
How to write a script (for Windows XP) to run a python program?
<p>Basically, I'd like to run a script (versus typing python program.py) or even have a shortcut that I could click on and start the program. Any ideas?</p>
<p>From <a href="http://www.python.org/doc//current/tutorial/interpreter.html#the-interpreter-and-its-environment" rel="nofollow">python.org</a>:</p> <blockquote> <p>On Windows systems, there is no notion of an “executable mode”. The Python installer automatically associates <code>.py</code> files with python....
python|windows-xp
2
10,420
50,399,683
Using Python to parse header string from a file with a unique header printing technique (.inp extension)
<p>I am looking to use Python to parse a dataframe from a file (for those who might've used, its SWMM model input / inp file). The file header is printed in a rather unique way which has made it very difficult to completely parse it. An example of the dataframe with the troublesome header) I am trying to read from the...
<p>Since your data doesn't fit the interpolations in <code>read_fwf</code> you can scan and parse the header yourself. Once you've worked out column names and widths you can pass them to <code>read_fwf</code> with the file pointer open on the first real row. The dashed line separators between header and data is a good ...
python|pandas|parsing|header
2
10,421
35,302,446
Prepare data for multioutput regression in Caffe
<p>I need to write python script that prepare data to feed it to a caffe solver. My input is images(<code>X</code>) and vector of ints(<code>Y</code>) (I have multioutput regression problem not single <code>Y</code> for each <code>X</code>) and I try to modify Lenet to my task.</p> <p><a href="http://vision.stanford.e...
<p>Caffe expects its input images to be 4-D <code>B</code>-by-<code>C</code>-by-<code>H</code>-by-<code>W</code>:</p> <ul> <li><code>B</code> is the "batch size", the number of images you process simultaneously </li> <li><code>C</code> is the number of channels, usually 3 for BGR (most nets conforms to opencv BGR for...
python|hdf5|deep-learning|caffe
1
10,422
26,649,723
Scapy unable to fragment IPv6 packet
<p>I am currently working on a project regarding IPv6 security. I'm trying to replicate the results found in this document found here: <a href="https://www.tno.nl/downloads/testing_the_security_of_IPv6_implementations.pdf" rel="nofollow">https://www.tno.nl/downloads/testing_the_security_of_IPv6_implementations.pdf</a><...
<p>There is something called scapy6:</p> <p><a href="http://www.secdev.org/conf/scapy-IPv6_HITB06.pdf" rel="nofollow">http://www.secdev.org/conf/scapy-IPv6_HITB06.pdf</a></p> <p>Try taking a look at page 128 and forward to see if you can get it to work, it should support IPv6.</p>
python|ipv6|scapy|ip-fragmentation
0
10,423
45,113,361
Postgres mogrify adding binary to SQL string
<p>I am trying to save data using the example in the python project <a href="https://github.com/dedupeio/dedupe-examples/blob/master/pgsql_example/pgsql_example.py" rel="nofollow noreferrer">dedupe</a>. The error I am getting is towards the end when trying insert data back into the database. </p> <p>The error I get is...
<p>I'm guessing that <code>args_str</code> isn't actually of the type string. Are you using a proper debugger like <code>pycharm</code>? If so, can you inspect the variable to confirm it is a string before you try to interpolate it?</p>
python|postgresql|binary
0
10,424
64,682,900
Problems running web scraper in Spyder IDE
<p>I have a code that is using Scrpay framework and here's the code</p> <pre><code>import scrapy from scrapy.crawler import CrawlerProcess class DemoSpider(scrapy.Spider): name = &quot;DemoSpider&quot; def start_requests(self): urls = ['http://quotes.toscrape.com/page/1/', 'http://quotes.toscrape....
<p>(Spyder maintainer here) Please go to the menu <code>Run &gt; Configuration per file</code> and activate the option <code>Execute in an external system terminal</code>.</p> <p>That will run your code in a regular Python interpreter, which will avoid the problems you're having to start the server that runs the scrape...
python|scrapy|spyder
2
10,425
61,447,140
Simulate a Long Network Request for Python Testing
<p>I need to test a device update function. The function opens a socket on a host and sends a block of text. </p> <p>The update can take up to 120 seconds. It returns a code for success/failure. To allow continued functioning of the program the update is launched in a thread.</p> <p>I cannot control the response of t...
<p>I wrote this up based on rdas's pointer. </p> <pre><code>import json import logging import socket import socketserver import threading import time log = logging.getLogger(__name__) log.setLevel(logging.INFO) class LongRequestHandler(socketserver.BaseRequestHandler): def handle(self): # Echo the back ...
python|testing|server
0
10,426
58,158,971
Dependency error messages when running luigi pipeline
<p>Im trying to create a pipeline that starts off with a class that separates one file into multiple csvs based on the state a user is in, then looks at the files created representing the different states and tries to determine whether a user moved from one state to another returning a 1 if the user did and 0 if s/he d...
<p>After reviewing your updates, I noticed that your first task doesn't actually have any parameters. You just have a couple of objects. You shouldn't run <code>pd.read_csv</code> inside of variable declaration. Instead, you should have it in the <code>run</code> method (unless you need to require things based off the ...
python|luigi
0
10,427
57,844,239
How to keep an input accepting python script running all day long after crontab started it?
<p>I have a python script that I want to run everyday at 7:00AM. It has to keep running all day long until I stop it. All it does it takes input and does something with it. Crontab will run the script but after the first input the script ends. How can I keep the script running?</p> <p>Here is the crontab line</p> <pr...
<blockquote> <p>In this case , (if your OS is windows) you can use "Task Scheduler" .</p> <blockquote> <p>so:</p> <blockquote> <ol> <li>go to "Task Scheduler" 2.select "create basic task" 3.make sure the Trigger part is set to daily at 7:00AM 4.select your script 5.finished!!</li> ...
python|cron
0
10,428
56,389,939
Python - Why wont wildcard bits work here?
<p>So I am trying to put wildcard bits in a path to a network folder. The path is here: </p> <pre><code>r"\\10.180.22.211\\Data\\DS~109803~Company~name of site\\Database" </code></pre> <p>The part between DATA and Database changes, but the rest of the path stays the exact same. So when I actually put the entire path...
<p>you have two ways:</p> <p>use list dir:</p> <pre><code>for filename in os.listdir(path): ...... </code></pre> <p>or use glob:</p> <pre><code>import glob path = "\10.180.22.211\Data\*\Database" for filename in glob.glob(path): .... </code></pre> <p>get newest file:</p> <pre><code> list_of_files = glo...
python|wildcard
0
10,429
18,330,197
cv::MatIterator equivalent in numpy
<p>What is the equivalent of a cv::MatIterator for an RGB image in numpy? I read about <code>numpy.nditer</code> but I'm not able to formulate my requirement exactly using it.</p> <p>For example consider the below C++ code using OpenCV iterating over each pixel and assigning an RGB value:</p> <pre><code>cv::Mat rgbIm...
<p>One easy way to iterate over an array is by using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndenumerate.html" rel="nofollow"><code>np.ndenumerate</code></a> and one for loop, then you can modify your image inside of it, here is an example of how to use it:</p> <pre><code>import numpy as np ...
python|opencv|numpy
0
10,430
18,308,384
vlc mac python binding no video output
<p>I am using vlc python binding to play a video. Then I got these errors: </p> <pre><code>[0x3d0c58] main window error: corrupt module: /Applications/VLC.app/Contents/MacOS/plugins/libmacosx_plugin.dylib [0x3c9af8] vout_macosx vout display error: No drawable-nsobject nor vout_window_t found, passing over. [0x3178a98]...
<p>The mentioned solution (use -I macosx) works because it launches an interface, which provides a NSObject (macosx window handle) to the vout_macosx module. When launching from libvlc, no such interface/window is present by default. It works on other platforms because the video output modules know how to create their ...
python|macos|video|vlc|corrupt
1
10,431
71,669,964
How do I use both the OR condition and the '<=' and '>=' functions in a single line
<p>Beginner here. I've posted all code but I believe the error is contained to the two specific lines of code at the bottom in bold. Clearly my syntax is wrong but I can't understand how; I've tried re-specifying INT for numbers and/or putting each side of the OR condition in parentheses, but nothing works. The error m...
<p>You just have to repeat the variable before each condition. Besides, python syntax does not requires parentheses. Try this:</p> <pre><code>if final_score &lt;= 10 or final_score &gt;= 90: print(f&quot;Your score is {final_score}, you go together like coke and mentos.&quot;) if final_score &gt;= 40 and final_score ...
python|conditional-statements|operators
0
10,432
71,527,765
My Automated Python script loses so much performance over time
<p>This is my code, i know its long and messy code, but basically. At start its pretty fast and stuff, but after while you can notice really huge performance jumps, after 6 hours, i came back. and one click of keyboard button took like 10 seconds, can anybody help me find why is it slowing so much. If you dont understa...
<p>The code is barely legible, split it in functions or classes, and avoid global variables. Chances are you are overflowing the RAM of your computer or something like that, if you are appending information to a variable, remember deleting it after if it grows to much or storing it in a database-like system.</p> <p>Som...
python|performance|while-loop|pyautogui
0
10,433
69,485,917
Time between web3.eth.sendRawTransaction and transaction validated time on Bscscan
<p>I'm making web3py contract transaction, using this code:</p> <pre><code>txn = contract.functions.bid( tokenId, price ).buildTransaction({ 'chainId': 56, 'gas': gasLimit, 'gasPrice': web3.toWei('5', 'gwei'), 'nonce': nonce }) signed_txn = web3.eth.account.sign_transaction(txn, private_key=pr...
<h2>HOW TO HANDLE TRANSACTION SPEED?</h2> <p>For greater speed adjust the gas price (transaction fee) for your transaction. However, be aware that <strong>Higher GWEI = Higher Speed = Higher Rates.</strong></p> <p><a href="https://i.stack.imgur.com/vz0TA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.co...
python|blockchain|web3|web3py|bscscan
0
10,434
57,525,700
Importing a function from one file to another gives me error
<p>I have 2 files. One is called <strong>file.py</strong>, and the other is <strong>secondfile.py</strong>.</p> <p>In <strong>file.py</strong> I currently have the code:</p> <pre><code>def getTrain(data): trainList = [] for list in data: for train in list['HorarioDetalhe']: trainDict = {} ...
<p>The problem is that <code>trainList</code> variable is not defined in secondfile.py and only as a scope in the getTrain function in the first file. Also you should not use <code>file.py</code> as a name when you import a file as it is a standard name in python. You should use something like firstfile.py</p> <p>You ...
python|python-3.x
1
10,435
58,369,158
Converting from SPSS to Pandas...result gives "b'var_name'" for all variables
<p><a href="https://i.stack.imgur.com/8oK3u.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8oK3u.jpg" alt="enter image description here"></a>I'm trying to convert an SPSS file to Pandas, which is working fine. However, all variables present as "b'variable_name'". It puts a 'b' in front of each varia...
<p>For a quick fix, to that :</p> <pre class="lang-py prettyprint-override"><code>header = list(map(str, df.iloc[0])) </code></pre> <p>So the b'' mean that all your header name are byte, not string. It's maybe du to the function used to read. Sav filw</p>
python|pandas|dataframe|spss
1
10,436
58,571,840
how to combine two integer columns in python
<p>I want to combine 2 column values having integers with a '_' between them and set it as my index column to my output dataset. 'ID' will be my index.</p> <p>Sample Data:</p> <p><a href="https://i.stack.imgur.com/6rBd7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6rBd7.png" alt="inp"></a></p> ...
<p>Convert index and column to strings and join by <code>_</code>, also <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pop.html" rel="nofollow noreferrer"><code>DataFrame.pop</code></a> is used for extract column, so then <code>drop</code> is not necessary:</p> <pre><code>df.index ...
python|pandas
5
10,437
58,214,788
How to replace a variable with nothing if certain conditions are met using a if statement (Python 3)
<p>I'm trying to make a completing the square calculator. I replicated some of the lengthy code to show where im getting my issue:</p> <pre><code>a=1 if (a == 1): print () </code></pre> <p><code>print ("bcdf" + str(a))</code> </p> <p>Output: bcdf1</p> <p>In this case, I want it to output bcdf</p> <p>I genuinely...
<p>Since <code>a</code> is a number you could set it to <code>None</code> to reset its value. Also, if you are using Python>3.6 you have <a href="https://www.python.org/dev/peps/pep-0498/" rel="nofollow noreferrer">f-strings</a> to print what you want nicely in one line:</p> <pre><code>a = 1 if a == 1: a = None pr...
python-3.x
0
10,438
45,449,827
Is there a way to "recreate" data with scikit-learn?
<p>My question is about scikit-learn in python. Let's say that I have 3 features <em>A</em>, <em>B</em> and <em>C</em>, with <em>A</em> and <em>B</em> capable of predicting <em>C</em> in such code:</p> <pre><code>exampleModel.fit(AandB, C) exampleModel.predict(C) </code></pre> <p>Is there a way for me to input some <...
<p>Yes, it's possible!</p> <p>But you need to be <em>very</em> clear in what you want: How are <em>A</em>, <em>B</em> and <em>C</em> related - decide what is the appropriate prediction model.</p> <p>You also need to realize that there can't be a "perfect" reconstruction. <em>A</em> and <em>B</em> are in general a ric...
python|machine-learning|scipy|scikit-learn|prediction
1
10,439
28,522,990
where Py_FileSystemDefaultEncoding is set in python source code
<p>i am curious about how python source code set the value of Py_FileSystemDefaultEncoding. And i have receive a strange thing.</p> <p>Since python <a href="https://docs.python.org/2/library/sys.html#sys.getfilesystemencoding" rel="nofollow">doc</a> about sys.getfilesystemencoding() said that:</p> <blockquote> <p>O...
<p>Summary: <code>sys.getfilesystemencoding()</code> behaves as documented. The confusion is due to the difference between <code>setlocale(LC_CTYPE, "")</code> (user's preference) and the default C locale.</p> <hr> <p>The script always starts with the default C locale:</p> <pre><code>&gt;&gt;&gt; import locale &gt;&...
python|python-2.7|locale
5
10,440
14,802,197
Can I get the browser width and height in Pyramid?
<p>Is it possible to get the user's browser width and height in Pyramid? I've searched through the response object and Googled.</p> <p>If it's not available in Pyramid, I'll just grab it in javascript</p>
<p>No, that is not possible to determine with server-side code only. Browsers do not share that information when making HTTP requests to the server.</p> <p>You'll have to do this with JavaScript.</p>
python|pyramid
7
10,441
41,259,830
Python Basic If Statement
<pre><code>def main_loop(): print "where are you from?" loc = raw_input() print "so your from " + loc + "?" ans = raw_input() def isittrue(): if ans == "yes": print "We all love " + loc else: print "Where did you say you were from again?" main_loop() isittrue() </code></pre> <p>Im trying ...
<p>your <code>ans</code> variable is local to function main_loop(), so its not acessible within <code>isittrue</code> function</p> <p>you can make ans variable global by adding below into top of <code>main_loop</code> function, then ans will be acessible from <code>isittrue</code> function. However, its not so recomme...
python|function|if-statement
1
10,442
44,661,068
QueryIncompleteError: Your query did not finish in 300 seconds. Most likely something is wrong on our side
<p>When making an extraction query using the Python Keen client, we're consistentently encountering the same error:</p> <p><strong>Message:</strong> Your query did not finish in 300 seconds. Most likely something is wrong on our side. Please let us know at team@keen.io.</p> <p><strong>Code:</strong> QueryIncompleteEr...
<p>Your guess is correct! This 504 error happens when your query times out (runs longer than 5 minutes). Here are ways to reduce the runtime of your query:</p> <p><strong>1. Shorten the timeframe in your query</strong></p> <p>The smaller the timeframe, the faster the query. A query on one week of data will be 4X fast...
python|keen-io
5
10,443
20,829,697
Python dependencies inside a package
<p>I know there are various discussions around this subject already, but I have a specific, slightly different question (most existing questions I have found focus on external (inter-)dependencies of other packaging, while my interest is mostly in my own direct package).</p> <p>I have found a variety of tools that hel...
<p>wrt to pycallgraph, I ended up with something somewhat useful, coming from basically the same point as you.</p> <ol> <li><p>hack pycallgraph to save the intermediate <strong>dot</strong> file somewhere you can see it.</p></li> <li><p>run <code>egrep -v</code> to trim out the stuff you don't care about in the dot. ...
python
1
10,444
71,824,091
Keywords with total combination of words and character input given by user using a word in Python
<p>I am new user learning python. I have query if it can be done or not. If user input a word suppose &quot;Dance&quot; and character &quot;$&quot;, he would get a all possibilities of word and character combination for example ['D$a$n$c$e', 'Da$n$c$e', 'D$an$c$e', 'Danc$e'], etc. It should give a combinations.</p> <p>...
<p>For each combination, whether or not there is a character between two certain letters can be represented as either: a 1 (there is a character), or 0 (there is not). In this way, each combination can be represented as a binary number, and to get all possible combinations, we simply need to count up in binary, and con...
python|string|list|combinations
0
10,445
35,815,397
When to use ExtSlice node in Python's AST?
<p><a href="http://greentreesnakes.readthedocs.org/en/latest/index.html" rel="nofollow noreferrer">Green Tree Snakes</a> gives <a href="http://greentreesnakes.readthedocs.org/en/latest/nodes.html?highlight=subscript#ExtSlice" rel="nofollow noreferrer">an example</a> of using <code>ExtSlice</code>:</p> <pre><code>&gt;&...
<p>The <em>syntax</em> works fine in the shell, it is just that <em><code>list</code> objects</em> don't support extended slicing. What you tried raised a <code>TypeError</code>, not a <code>SyntaxError</code>.</p> <p>Many <a href="http://www.numpy.org/" rel="nofollow">Numpy</a> array types do; that project was instru...
python|abstract-syntax-tree|internals
6
10,446
36,094,682
python - combinig two unequal lists and create a dictionary
<p>can you let me know how I can do the below</p> <pre><code>a = ['x'] b = ['y', 'z'] </code></pre> <p>I want to combine the above 2 list and create dictionary like below</p> <pre><code>c = {'x': ['y', 'z']} </code></pre> <p>I tried below code but that didn't work</p> <pre><code>from itertools import cycle c = d...
<p><code>a</code> just contain one key? If so, create it directly:</p> <pre><code>a = ['x'] b = ['y', 'z'] d = {a[0]: b} print(d) </code></pre>
python|dictionary
1
10,447
29,465,973
Epiphany browser open URLs in the same tab in python
<p>I am using epiphany webbrowser in my Raspberry Pi project. According to the requirement I need to open a link on the same tab using python webbrowser module. But each time a new tab is opened although I've given the parameter new=0</p> <pre><code>import webbrowser import time b = webbrowser.get('epiphany') b.open('...
<p>i had the same problem with epiphany, get yourself firefox(iceweasel) for raspbian(is anyway quicker): </p> <pre><code>sudo apt-get install iceweasel </code></pre> <p>then you need to install selenium</p> <pre><code>pip install selenium </code></pre> <p>i tested this snippet on pi2+:</p> <pre><code>import selen...
python-2.7|raspberry-pi|epiphany
3
10,448
29,464,263
Python Pretty Table output to text file
<p>Is there a way to redirect pretty table output to a text file rather than just the screen?</p> <p>From <a href="https://code.google.com/p/prettytable/wiki/Tutorial" rel="noreferrer">https://code.google.com/p/prettytable/wiki/Tutorial</a></p> <pre><code>from prettytable import PrettyTable x = PrettyTable(["City na...
<p>Just write the contents of variable <code>x</code> to that file.</p> <pre><code>from prettytable import PrettyTable x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"]) x.align["City name"] = "l" # Left align city names x.padding_width = 1 # One space between column edges and contents (default) x...
python
10
10,449
21,149,125
IntelliJ how to change the PYTHONPATH
<p>I've installed OpenCV using brew and added the following to my .bash_profile. </p> <pre><code>export PYTHONPATH=/usr/local/Cellar/opencv/2.4.6.1/lib/python2.7/site-packages:$PYTHONPATH </code></pre> <p>If I run Python on a "Terminal" I can import cv and cv2 without any issues. </p> <p>However, when I try to do th...
<p>You need to go into the run/debug configuration (i.e. edit configurations) and add PYTHONPATH to the environment variables. Mine already had PYTHONUNBUFFERED 1, so I went into dialog and added another entry for PYTHONPATH with value /usr/local/lib/python2.7/site-packages.</p> <p>Hope that helps.</p>
python|opencv|intellij-idea|homebrew|pythonpath
2
10,450
70,191,246
How do I un-format my Python code using a keybind or function in VSCode?
<p>I want this:</p> <pre><code>variable = { 1: &quot;one&quot;, 2: &quot;two&quot;, 3: &quot;three&quot; } </code></pre> <p>To become this:</p> <pre><code>variable = {1: &quot;one&quot;, 2: &quot;two&quot;, 3: &quot;three&quot;} </code></pre> <p>Without having to manually backspace and remove the extra new ...
<p>This is not a Python specific question. Also depends in your IDE.</p> <p>Generally, you can try to use a formatter such as <a href="https://github.com/psf/black" rel="nofollow noreferrer">Python Black</a>.</p> <p>Also many tools/IDEs offer their own code reformatters/beautifiers. Since you're using VSCode, have a lo...
python|visual-studio-code
0
10,451
53,693,340
How to avoid duplication of records in the database?
<p>There are following models:</p> <pre><code>class Parameter (models.Model): id_parameter = models.IntegerField(primary_key=True) par_rollennr = models.IntegerField(default=0) par_definition_id = models.IntegerField(default=0) #not FK par_name = models.CharField(max_length=200) class Measurements (m...
<p>You need to use a better data structure than a list to prevent duplication.</p> <pre><code>from itertools import zip_longest def handle_parameters_upload(request, file): wb = openpyxl.load_workbook(file, read_only=True) first_sheet = wb.get_sheet_names()[0] ws = wb.get_sheet_by_name(first_sheet) r...
python|sql|django|database|backend
0
10,452
45,924,860
django - Get the exact GET url that was used to call a django view (including params)
<p>I have a view which accepts GET params (accessible via the <code>request.GET</code> and that are present in the uri)</p> <p>Inside the view I want to get the exact uri that was used to call that view maintaining order</p> <p>Example:</p> <p>If a call was made to <code>http://best.site.ever/?this=that&amp;that=thi...
<p>The Django request objects have a helper method available, called <a href="https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.HttpRequest.build_absolute_uri" rel="nofollow noreferrer"><code>build_absolute_uri</code></a>:</p> <pre><code>request.build_absolute_uri() </code></pre>
python|django
3
10,453
55,091,741
Pygame Random Coordinates Spawning
<p>In the game I'm trying to create, I want to spawn mummies outside of the screen and have them run towards the player. The problem I'm getting is that it won't take one variable for both the x and y coordinates. How can I make it so I can use just one variable for both the x and y coordinates?</p> <pre><code>screenx...
<p>You can use the * operator to unpack the coordinates tuple:</p> <pre><code>mummy = enemy(*random.choice(mummy_Spawn), 134, 134) </code></pre>
python|list|random|coordinates
0
10,454
33,204,018
HTML structure diff in Python
<p>I want to diff html files by structure and not by content. For example: b and a are identical with this diff because the structures of them are equal.</p> <p>Anyone knows tool (I prefer in python) or implementation do it ?</p>
<p>You need to parse the HTML/XMLto a DOM tree and then compare those trees. The preferred solution for parsin in Python for this is lxml library. For comparison I am not sure any lib exist but below is a guidelining source code.</p> <p>Here is one XML comparison function from Ian Bicking (orignal source, under Python...
python|html|dom|diff|lxml
0
10,455
33,329,642
Filter Python list
<p>I have an list in Python that looks like this:</p> <pre><code>myarray = [('31.10', 'John', 'Smith', 'ZK'),('01.11', 'John', 'Smith', 'OK'),('31.10', 'John', 'Doe', 'ZK'),('01.11', 'John', 'Doe', 'ZK')] </code></pre> <p>I would like to filter by 2 keys. The 2 Name keys.</p> <p>ex. filter myarray contains John and ...
<p>You'll need to test each tuple in the list:</p> <pre><code>for entry in myarray: if entry[1:3] == ('John', 'Doe'): print ' '.join(entry) </code></pre> <p>I used slicing to select just the parts at index <code>1</code> and <code>2</code> there, but you could also use tuple unpacking:</p> <pre><code>for...
python|list
1
10,456
73,647,906
cv2.perspectiveTransform() not performing the operation
<p>I want to apply a transformation matrix to a set of points. So the set of points:</p> <pre><code>points = np.array([[0 ,20], [0, 575], [0, 460]]) </code></pre> <p>And I want to use the matrix I calculated with <code>cv2.getPerspectiveTransform()</code> which is a 3x3 matrix.</p> <pre><code>matrix = np.array([ [ ...
<p>We may solve it with one line of code:</p> <pre><code>transformed_point = cv2.perspectiveTransform(np.array([points], np.float64), matrix)[0] </code></pre> <hr /> <p>As Micka commented <code>cv2.perspectiveTransform</code> takes a list of points (and returns a list of points as output).</p> <ul> <li><code>np.array([...
python|opencv
1
10,457
13,018,266
Cronjob to periodically refresh cache for django view
<p>I've had some trouble trying to reset my cache every hour for a particular django view.</p> <p>Right now, I am using the cache_page decorator to cache my view using Memcached. But the cache expires after a while and the request is uncached from some users.</p> <p>@cache_page(3600)<br> def my_view(request):<br> ...
<p>In your app, you can create a folder called <code>management</code> which contains another folder <code>commands</code> and an empty <code>__init__.py</code> file. Inside <code>commands</code> you create another <code>__init__.py</code> and a file where you write your custom command. Let's called it <code>refresh.py...
python|django|cron|memcached
2
10,458
24,912,661
How to return to the calling parse function while using yield in scrapy?
<p>Here's what I want to achieve:</p> <pre><code>class Hello(Spider): #some stuff def parse(self, response): #get a list of url of cities using pickle and store in a list #Now for each city url I have to get list of monuments (using selenium) which is achieved by the below loops for c i...
<p><code>Request</code> is an object, not a method. Scrapy will process the yielded Request object and execute the callback asychronously. You can view Request as a thread object.</p> <p>The solution is by doing the reverse, you pass the data that you need from <code>parse</code> method to the Request instead, so you ...
python|scrapy|yield
0
10,459
41,088,628
PyCharm won't accept code completion on enter
<p>since yesterday PyCharm 2016.3 won't accept selected lines from the list of code completion:</p> <p>If I hit enter, a new line will be set into the editor rather than the selected line of the popup window. Is there any setting for this behaviour? Until now I couldn't find anything.</p>
<p>I noticed on a few occasions the GUI going somehow off-rails, including in ways similar to the one described. I couldn't determine a pattern in the occurences. Just closing and re-opening the project didn't always help.</p> <p>What worked pretty reliably for me in the end was exiting PyCharm (giving it ample time t...
python|pycharm|code-completion
0
10,460
38,190,468
Installation of python google api in Ubuntu
<p>Below command is used for installing Google-API in python for Linux.</p> <pre><code> pip install --upgrade google-api-python-client </code></pre> <p>Below errors are shown by above command</p> <blockquote> <p>File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main</p> <p>status = sel...
<p>Always remember there would be many errors and disparencies if you try to install packages without virtual environment in python.</p> <p>I would like you to create a virtual environment as specified in the link and then try it out.</p> <p><a href="http://docs.python-guide.org/en/latest/dev/virtualenvs/" rel="nofol...
python|google-api|ubuntu-14.04
1
10,461
31,119,983
AppleScript to process incoming emails in Mac Mail.app
<p>actually my problem is the same as <a href="https://stackoverflow.com/questions/4565784/automator-applescript-to-process-incoming-emails-in-mac-mail">this one</a> and the answer already brought me very much forward. (Summary: I want my python script running on every incoming email with a certain subject and extract ...
<p>Try this. Note that you shouldn't use <code>tell application "Mail"</code>, because this event is triggered by Mail, and so you have access to all the functionality provided by Mail. <code>using terms from application "Mail"</code> is all you need in this case. You can find some more information by typing <kbd>comma...
python|macos|email|applescript
1
10,462
40,290,949
A Python3.5 pacakge for MS SQL similar to psycopg2
<p>Can anyone suggest a python 3.5 compatible package for MS SQL that is similar to psycopg2 for postgres? </p> <p>Specifically looking to have multiple cursors doing multiple inserts/updates, per the psycopg2 pypi docs "It [psycopg2] was designed for heavily multi-threaded applications that create and destroy lots of...
<p>you can use "pymssql,pyodbc" which are similar to psycopg2</p>
python|sql-server
0
10,463
40,186,628
flatMap in dask
<p>Many functional languages define <code>flatMap</code> function which works like <code>map</code> but can <em>flatten</em> returning values. Spark/pyspark has it <a href="http://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.RDD.flatMap" rel="nofollow">http://spark.apache.org/docs/latest/api/python/pysp...
<p>You probably want the <a href="http://dask.pydata.org/en/latest/bag-api.html#dask.bag.Bag.flatten" rel="nofollow noreferrer">.flatten method</a></p> <pre><code>In [1]: import dask.bag as db In [2]: b = db.from_sequence([1, 2, 3, 4, 5]) In [3]: def f(i): ...: return list(range(i)) ...: In [4]: b.map(f)...
python|python-3.x|dask
3
10,464
29,300,620
Overwrite global variables
<p>I have two modules:</p> <p><strong>constants.py</strong></p> <pre><code>def define_sizes(supersample): global SUPERSAMPLE global WIDTH global HEIGHT global LINE_WIDTH SUPERSAMPLE = supersample WIDTH = 1280*SUPERSAMPLE HEIGHT = 854*SUPERSAMPLE LINE_WIDTH = 1*SUPERSAMPLE define_...
<p>In this situation I'd probably do</p> <pre><code>class Sizes(object): def __init__(self, supersample=1) self.SUPERSAMPLE = supersample def resize(self, supersample) self.SUPERSAMPLE = supersample @property def WIDTH(self): return 1280*self.SUPERSAMPLE @property def HEIGHT(sel...
python
1
10,465
51,984,649
Django social authentication with registration extra fields
<p>I want to do a social authentication with Google and Facebook. For that I have use social-auth-app-django. When I login with using Google it will directly create an account in django user model and redirect to my URL. But I want to fill extra required details of user, after entering detail create user after user's c...
<p>That's basically the purpose of the <code>partial pipelines</code> feature on <code>python-social-auth</code> (<a href="https://python-social-auth.readthedocs.io/en/latest/pipeline.html#partial-pipeline" rel="nofollow noreferrer">docs</a>). The idea is to pause the authentication flow at any time and resume it later...
python|django|python-social-auth
2
10,466
51,584,300
python discord bot create_channel commmand adding an arg to command to make bot add a specific member of the server to the perms of the channel
<pre><code>elif cmd_args[0].upper() == "D!CREATECHANNEL": everyone = discord.PermissionOverwrite(read_messages=False, send_messages=False, create_instant_invite=False, manage_channel=False, manage_permissions=False, manage_webhooks=False, send_TTS_messages=False, manage_messages=False, embed_links=False, attac...
<p>You can get all of the mentioned members from <code>message.member</code>, then build a <code>(target, PermissionOverwrite)</code> tuple for each of them and pass that to <code>create_channel</code>. </p> <pre><code>elif cmd_args[0].upper() == "D!CREATECHANNEL": everyone = discord.PermissionOverwrite(read_messa...
python|discord.py
0
10,467
51,992,254
Python - Get HTML Source Code of a Web Page
<p>I want to get the HTML source from a site ('example.com' for example).</p> <p>I tried the following:</p> <pre><code>import urllib2 response = urllib2.urlopen("https://example.com") page_source = response.read() </code></pre> <p>It says:</p> <blockquote> <p>'No module named urllib2'</p> </blockquote> <p>How c...
<p>why you don't use requests module ? :</p> <pre><code>import requests r = requests.get("https://example.com") print r.text </code></pre> <p>or for answer correctly to you'r question , you can download the urllib2 module using pip and easy_install :</p> <pre><code>pip install urllib2 easy_isntall urllib2 </code></...
python|urllib2
12
10,468
19,276,281
How to create a list of list from a txt file
<p>I am working in Python 3.3.2. right now I am trying to create a list of lists from a txt file. For example:</p> <p>I have a txt file with this data: </p> <pre><code>361263.236 1065865.816 361270.699 1065807.970 361280.158 1065757.748 361313.821 1065761.301 </code></pre> <p>I want python to generate a list of list...
<p>I'd encourage use of the <code>with</code> statement in new programmers, it's a good habit to get into.</p> <pre><code>def read_list(filename): out = [] # The `with` statement will close the opened file when you leave # the indented block with open(filename, 'r') as f: # f can be iterated li...
python|list|python-3.x
2
10,469
62,171,004
Reduce the execution time of django view
<p>I have a django view which returns all the products of Product model. Situation is discount is dependent on product as well as user so it has to be calculated every time at runtime. I have added only 3500 products yet and server is taking 40-50 seconds to respond. I wonder how much time will it take when i will add...
<p>try paginating the response. I think that would be your best bet.</p> <p><a href="https://docs.djangoproject.com/en/3.0/topics/pagination/" rel="nofollow noreferrer">https://docs.djangoproject.com/en/3.0/topics/pagination/</a></p>
python|django|gunicorn
2
10,470
62,370,386
Correlation heatmap of many datasets
<p>I am working with niftis (Neuroimaging format) looking at 3D volumes of the brain.</p> <p>I want to compare experiments with brain activity.</p> <p>Therefore I have about 20 experiment files in nifti format.</p> <p>and 4 brain activity files also in nifti format.</p> <p>They have the same dimension of the brain ...
<p>If you want to plot the correlation matrix using sns/seaborn you need to first extract the BOLD signal in the image(.nii) format that you have.</p> <p>You can use the nilearn package to extract the BOLD time series signal for a specific atlas of interest (like AAL atlas which consists of 90 ROIs)</p> <p>Then you can...
python|seaborn|heatmap|correlation|nifti
0
10,471
67,441,723
YouTube automation with selenium and python, problem in selecting from the searched video
<p>Currently I am working on automation of Youtube with Python and Selenium, after searching on Youtube. I want to select from the searched video per user demands i.e first video, the second or third video, etc. But I tried almost all selectors, they have the same attributes, they play the first video. So if you have a...
<p>The below should work:</p> <pre><code>driver.get(&quot;https://www.youtube.com/results?search_query=decorater&quot;) video_number = 2 driver.find_element_by_xpath(f&quot;(//a[@id='video-title'])[{video_number}]&quot;).click() </code></pre> <p>This uses <a href="https://realpython.com/python-f-strings/" rel="nofoll...
python|selenium|automation|webautomation
1
10,472
63,585,355
How to collapse multiple rows into one and create series of column elements Python Pandas
<p>I have a dataframe such as one below:</p> <pre><code> tags categories classification 0 label ['legislative', 'law, govt and politics', 'exe... None 0 document ['legislative', ...
<p>I didn't get your question completely. But do you want something like this?</p> <p><strong>df:</strong></p> <pre><code> trial_num subject samples 0 1 1 [-1.74, -0.78, -0.11] 1 2 1 [0.86, 0.21, -0.01] 2 3 1 [2.04, 0.6, -0.79] 3 1 2 [0.52, 0....
python|pandas|group-by|jupyter-notebook|series
0
10,473
19,773,101
Compare two text files files and return what lines and columns the 1st difference is on
<p>I've got a program which compares two text files and prints the difference to a new text file, but I want to modify it so it just prints out the line and column where the first difference occurs. Here is what I have so far:</p> <pre><code>f1 = open("file1.txt", "r") f2 = open("file2.txt", "r") fileOne = f1.readlin...
<p>Just <code>break</code> after the first match. </p> <pre><code>for i in fileOne: if i != fileTwo[x]: outFile.write(i+" &lt;&gt; "+fileTwo[x]) break x += 1 </code></pre>
python|python-2.7
1
10,474
21,958,227
Python: Compare elements in a list to each other
<p>I'm currently looking for a way to compare elements of a list to one another going from left to right.</p> <p>Here is my list:</p> <pre><code>mylist = [[15], [14, 15], [19, 20], [13], [3], [65, 19], [19, 20, 31]] </code></pre> <p>I need to compare the first element to all others and check if any of the values mat...
<p>The naive solution is to loop over every pair, which is slow. However, you can do something along the lines of this:</p> <ul> <li>Create a dict that will map ints (elements in your nested list) to lists containing the indices of the lists in your master.</li> <li>Loop over the master list, and for each sublist, add...
python|list
4
10,475
43,701,995
How come cell value is not being printed or modified using openpyxl?
<p>Here is my code. path2 is the path of the new file that is created and being modified. There are indeed cells inside the .xlsx file that contain "4/1/2017"</p> <pre><code>wb = openpyxl.load_workbook(path2, read_only=False) ws = wb.active for row in ws.iter_rows(): for cell in row: if cell.internal_valu...
<p>You are comparing the cell value against the string <code>"4/1/2017"</code>, but it is likely that the cell actually contains a date value that is formatted by Excel to look like <code>4/1/2017' in the spreadsheet. If the cell actually contains a date, then</code>openpyxl<code>will read it as a</code>datetime` objec...
python|excel|openpyxl
1
10,476
52,694,261
Python module loading with Spyder
<p>I am new to using Python for machine learning and I am trying to learn ZhuSuan using Spyder. </p> <p>I have downloaded and installed Zhusuan as descibed here: <a href="https://zhusuan.readthedocs.io/en/latest/" rel="nofollow noreferrer">https://zhusuan.readthedocs.io/en/latest/</a>.</p> <p>I have also tried insta...
<p>I have solved the problem. The additional dependencies had not installed correctly for some reason. Running a full reinstall fixed the problem, and the program now runs successfully with the original code. Thanks to Carlos for his comment.</p>
python|tensorflow|import|module|spyder
0
10,477
52,675,224
Writing into csv files using python
<p>Guys I was trying to write into a csv file using python and the code I used for it is as follows</p> <pre><code> with open(csvfile,'a') as csv_file: writer = csv.writer(csv_file) writer.writerow(row) </code></pre> <p>so after this when I tried to use this code</p> <pre><code>with open(filen...
<p>You can check whether row is empty or not by adding <code>print (row)</code>.<br> If you check that row is empty, you can pass it by many ways.<br> Such as, <code>if len(row) == 0: continue;</code>. </p>
python
0
10,478
52,562,215
How to make a program end on a blank line in python?
<p>So i have an assignment where we had to create a program to calculate pay and have it loop, the prof wanted us to have it end if we input a blank line for either the pay or hours. So far this is what I have </p> <pre><code>answer = 'yes' while answer == 'yes': hourly_pay = float(input('Enter hourly pay: ')) if...
<p>You can check if it's empty before you convert to float or int. For example:</p> <pre><code>answer = 'yes' while answer == 'yes': hourly_pay = input('Enter hourly pay: ') if not hourly_pay: print('empty line so quit') break else: hourly_pay = float(hourly_pay) if hourly_pay...
python|python-3.x
2
10,479
52,822,265
Input Validation to be a string and exception
<pre><code>x = input("Enter state 1") y = input("Enter state 2") z = input("Enter state 3") # The three states are strings among a list For example: state_1 = ['Light', 'Medium', 'Heavy'] state_2 = ['Small', 'Medium', 'Large'] state_3 = ['Blue', 'Red', 'Black'] If x != 'Light' or 'Medium' or 'Heavy': ...
<p>Your problem is in the comparsion statement <code>if x != 'Light' or 'Medium' or 'Heavy':</code> which actually is only doing a check for <code>x != 'Light'</code> and then whether or not the string <code>'Medium'</code> or <code>'Heavy'</code> are true (which they will because strings greater then length 0 evaluate...
python|string|list|validation|input
0
10,480
52,467,711
type error: 'module' object is not callable
<p>I just started using python and I get an error when I try to copy an object:</p> <pre><code>import numpy import copy c = numpy.zeros(10) t = copy(c) </code></pre> <p>Running the code I encountered this error that I can not solve, could you help me? Thank you all</p> <pre><code>Traceback (most recent call last): ...
<p>You might be invoking a module as a function (as suggested by the error message).</p> <pre><code>&gt;&gt;&gt; import copy &gt;&gt;&gt; type(copy) &lt;type 'module'&gt; </code></pre> <p>Instead, what you seem to need is the <a href="https://docs.python.org/2/library/copy.html#copy.copy" rel="nofollow noreferrer">co...
python|module|typeerror
1
10,481
52,514,171
How can I get a list with m tails? Python
<p>So I need to create a list with m tails. The elements of the list will be a random choice between tail and head. I did like :</p> <pre><code>Def S(m): list=[] counter=0 signs=["head","tail"] while counter&lt;(m): list.append(random.choice(signs)) for k in list: if k=="tai...
<p>this will work:</p> <pre><code>from random import choice def S(m): lst = [] counter = 0 signs = ["head", "tail"] while counter &lt; m: toss = choice(signs) lst.append(toss) if toss == 'tail': counter += 1 return lst lst = S(10) print(lst) # ['...
python|list|random|coin-flipping
3
10,482
47,905,932
Lighttpd web server not displaying .png or.jpg image
<p>I am trying to create a button on my lighttpd webserver that is based from a <code>.png</code> image.</p> <p>The problem is that when I put my Raspberry Pi IP address in to the address bar the image does not show up. If I were to open the file index.html straight from the directories the image will show up.</p> <...
<pre><code>&lt;img src="/var/www/html/forwardbutton.png" id="t" onmousedown="forward()"&gt; </code></pre> <p>This is not how the web works. The <code>src</code> attribute should be a URL, which the browser can use to fetch the image. It cannot be a local path on your web server, because the browser can't access files ...
python|html|raspberry-pi|lighttpd
1
10,483
47,836,266
Error when diagonalising large matrices using anaconda scipy
<p>I have recently switched from using homebrew python on mac OS X to using anaconda, and I have started getting an error when diagonalising large(ish) matrices. Calling <code>scipy.linalg.eigvalsh(A)</code> with matrices above about 3000x3000 entries gives an error:</p> <pre><code>$HOME/anaconda2/lib/python2.7/site-p...
<p>This is, as it stands, an MKL bug which has been kindly reported by <a href="https://github.com/brd4790" rel="nofollow noreferrer">@brd490</a> as per the discussion in <a href="https://github.com/scipy/scipy/issues/8205" rel="nofollow noreferrer">SciPy issue 8205</a> and is <a href="https://software.intel.com/en-us/...
python|scipy|anaconda|lapack
2
10,484
37,465,087
Python 3: Iterating over a dictionary
<p>I would've created a more specific title but I'm not sure how to formulate my question. </p> <pre><code>{ "playerStatSummaries": [ { "playerStatSummaryType": "AramUnranked5x5", "aggregatedStats": { "totalChampionKills": 2250, "totalAssists": 6199, "tota...
<p>Try something like:</p> <pre><code>for item in ranked_stats_json['playerStatSummaries']: ##This iterates the list if 'wins' in item and item['wins'] == 44: ##This checks your condition ##Do whatever here, or break or whatever you want #Put your action here </code></pre> <p>Consider this example:</p> <pr...
python|json|dictionary
0
10,485
34,401,316
Python: Wrong directory
<p>I have written code on python for sentiment analysis of movie reviews</p> <pre><code>import re import nltk from multiprocessing import Pool import numpy as np from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer from sklearn.linear_model import LogisticRegression from sklearn.feature_ex...
<p>The error is clear: <code>No such file or directory: 'small_valid.txt'</code>. Move your file into this path: </p> <pre><code>C:\Users\jre\Desktop\SentimentAnalysis-master\SentimentAnalysis-master </code></pre> <p>or update the next code lines to use an absolute path:</p> <pre><code>train = open('C:\..path_to_fil...
python
1
10,486
34,380,003
Serving video website based onTornado
<p>I'm new to tornado and I want build a simple website for watching movie. Of course,hello world website is successful and I want to add a movie in the empty website.Therefore I write a html using video label in html 5.</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;video autoplay=true&gt; &lt;source src="aa.mp4" typ...
<p><code>StaticFileHandler</code> should be able to handle large files.</p> <p>From <a href="http://www.tornadoweb.org/en/stable/web.html#tornado.web.StaticFileHandler" rel="nofollow"><code>StaticFileHandler</code> docs</a>:</p> <blockquote> <p>This handler is intended primarily for use in development and light-dut...
python|html|web|tornado
1
10,487
72,622,508
Code inside Django template if statement appears all the time
<p>I have a Django template that contains a message with a variable, but the words that are not in the variable appear all the time. I think it has something to do with the conditional <code>if closeListing == True</code>. I explicitly state when I want it to be <code>True</code>, so I don't know what's happening.</p> ...
<p>If the intended behaviour is to have <code>closeListing = True</code> when the query of <code>get_list_or_404(CloseListing, Q(user=request.user) &amp; Q(listings=listing))</code> returned some result or if <code>request.POST.get('close')</code> then you should probably modify here:</p> <pre><code>if has_closed: ...
python|django|django-templates
0
10,488
32,054,511
How to replace string with certain format in python
<p>i am trying to do string manipulation based on format. str.replace(old,new) alllows changing by specific string pattern. is it possible to find and replace by format? for example, i want to find all datetime like value in a long string and replace it with another format assuming % is wildcard for number and datetime...
<p>The easiest way to do this is probably using a combination of regular expression syntax, applying <a href="https://docs.python.org/2/library/re.html#re.sub" rel="nofollow"><code>re.sub</code></a> and using the fact that the <code>repl</code> parameter can be a function that takes a <code>match</code> and returns a s...
python|string
0
10,489
31,829,623
Create variables in Django views.py and access them at later point
<p>Let's say I have the following two functions in views.py:</p> <pre><code>def foo(request): class_instance = SomeClass() return HttpResponse('whatever') def bar(request): # here I want to access class_instance </code></pre> <p>Initially, <code>foo()</code> is called, and at a later point <code>bar()</c...
<p>You can put your variable as a module constant, especially if it's not prone to changing much.</p> <pre><code>CLASS_INSTANCE = SomeClass() def foo(request): return HttpResponse('whatever') def bar(request): # here I want to access CLASS_INSTANCE </code></pre> <p>Then both methods will have access to that...
python|django
0
10,490
26,392,219
Cannot launch appengine SDK, even after re-install
<p>Today when I attempted to launch the appengine SDK (python) I saw the error "Errors occurred" - see image below. More details:</p> <ol> <li>The log file referenced in the error message does not exist at that location</li> <li>I tried uninstalling the SDK entirely, and re-installing 1.9.13.msi (python)</li> <li>It's...
<p>Found the answer here: <a href="https://groups.google.com/forum/#!msg/google-appengine/Uphb04hV2tg/K6vL4osY_xgJ" rel="nofollow">https://groups.google.com/forum/#!msg/google-appengine/Uphb04hV2tg/K6vL4osY_xgJ</a></p> <p>I renamed the file 'google_appengine_launcher.ini' at users/[my profile]/Goolge</p>
python|windows|google-app-engine
1
10,491
44,247,269
Convert a lists that is a bytes into a list of ints
<p>I'm attempting to convert a bytes list into a list of <code>int</code>, the data that I'm pulling resemble:</p> <pre><code>test = b'[[9126, 0.2812168002128601], [9514, 0.2675456404685974], [9342, 0.26063060760498047], [8999, 0.23802196979522705], [9056, 0.23092836141586304], [9053, 0.22339123487472534], [9019, 0.22...
<pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; test = b'[[9126, 0.2812168002128601], [9514, 0.2675456404685974], [9342, 0.26063060760498047], [8999, 0.23802196979522705], [9056, 0.23092836141586304], [9053, 0.22339123487472534], [9019, 0.2215365171432495], [9225, 0.21875709295272827]]' &gt;&gt;&gt; new_list = json.lo...
python-3.x
0
10,492
44,052,834
Tensorflow Reading CSV - What's the best approach
<p>So I've been trying out different ways of reading a CSV file with 97K lines and each line with 500 features (about 100 mb).</p> <p>My first approach was to read all data into memory using a numpy:</p> <p><em>raw_data = genfromtxt(filename, dtype=numpy.int32, delimiter=',')</em></p> <p>This command had taken so lo...
<p>A solution can be to convert the data in the <code>tensorflow</code> binary format using <code>TFRecords</code>.</p> <p>See <a href="https://indico.io/blog/tensorflow-data-inputs-part1-placeholders-protobufs-queues/%20for%20a%20good%20tutorial." rel="nofollow noreferrer">TensorFlow Data Input (Part 1): Placeholders...
python|csv|numpy|tensorflow
2
10,493
33,036,686
Zoomed inset in matplotlib without re-plotting data
<p>I'm working on some matplotlib plots and need to have a zoomed inset. This is possible with the <code>zoomed_inset_axes</code> from the <code>axes_grid1</code> toolkit. See the example <a href="http://matplotlib.org/1.3.1/mpl_toolkits/axes_grid/users/overview.html" rel="noreferrer" title="here">here</a>:</p> <pre><...
<p>I think the following does what you want. Note that you use the returned handle to the first <code>imshow</code> and add it to the axis for the insert. You need to make a copy so you have a separate handle for each figure,</p> <pre><code>import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.inset_locator im...
python|matplotlib|plot
4
10,494
23,107,224
How do I search a file, count the number of hits and write the number to column B in a .csv?
<p>Here is my script. It currently finds all the files in <em>path</em> which contain * <em>cycle</em> * <em>.log</em> and then finds all the lines in those files that contain "timeout of" and pasts them into outfilecamera as well as the name of the file that it found it in.</p> <pre><code>i = 0 ii = "\n" for i in r...
<p>The number of times its found is hidden here:</p> <pre><code>f_out.writelines(line for line in f_in if "timeout of" in line) </code></pre> <p>So, all you have to do is consume the generator first, say into a list:</p> <pre><code>matched_lines = list(line for line in f_in if "timeout of" in line) f_out.writelines(...
python|search|csv|count
1
10,495
396,856
Calling a class method raises a TypeError in Python
<p>I don't understand how classes are used. The following code gives me an error when I try to use the class.</p> <pre><code>class MyStuff: def average(a, b, c): # Get the average of three numbers result = a + b + c result = result / 3 return result # Now use the function `average` from th...
<p>You can instantiate the class by declaring a variable and calling the class as if it were a function:</p> <pre><code>x = mystuff() print x.average(9,18,27) </code></pre> <p>However, this won't work with the code you gave us. When you call a class method on a given object (x), it always passes a pointer to the obj...
python|python-3.x|class|methods
88
10,496
41,899,610
Inference results depend on order of images in training batch
<p>I've trained the same network two times on the same dataset of 5 images. For the first time, the images in a batch for each step were in the same order. For the second time, the batch was shuffled before every training step. Both models overfit. Both models were tested on shuffled images from training dataset. The f...
<p>The mistake was in the testing code. This lines</p> <pre><code>images_batch = images_batch.eval() labels_batch = labels_batch.eval() </code></pre> <p>run separately, so images and labels were actually from different batches. If batches were identical, labels correspond to images and testing results were perfect. O...
tensorflow
0
10,497
47,271,961
Randomly select unique row from dataframe in Pandas
<p>Say I have a dataframe of the form where <code>rn</code> is the row index</p> <pre><code> A1 | A2 | A3 ----------------- r1 x | 0 | t r2 y | 1 | u r3 z | 1 | v r4 x | 2 | w r5 z | 2 | v r6 x | 2 | w </code></pre> <p>If I wanted to subset this da...
<p>Shuffle the DataFrame first and then drop the duplicates:</p> <pre><code>df.sample(frac=1).drop_duplicates(subset='A2') </code></pre> <p>If the order of the rows is important you can use <code>sort_index</code> as @cᴏʟᴅsᴘᴇᴇᴅ suggested:</p> <pre><code>df.sample(frac=1).drop_duplicates(subset='A2').sort_index() </c...
python|pandas|dataframe
8
10,498
47,091,592
2 Axes of the same size in Matplotlib figure
<p>When I try to place two Axes with equal heights next to each other with <code>Gridspec</code>, they end up at the top of the figure instead of taking up all the vertical space:</p> <p><a href="https://i.stack.imgur.com/SXprY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SXprY.png" alt="enter im...
<p>If you want to have squared axes you might want to give adequate figsize instead of playing with gridspecs:</p> <pre><code>fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(600/dpi, 300/dpi), dpi=dpi) </code></pre> <p>Note that x dim in figsize should be y * 2.</p> <p>This would fill the whole fig space and keep the ...
python|matplotlib
2
10,499
37,763,175
Python GPIO add_event_detect each state individually
<p>I currently have a few lever-type on off switch that I would like to have the status printed as soon as it switches on/off independantly off all the other switches.</p> <p>So far, I have come this far:</p> <pre><code>import RPi.GPIO as GPIO from time import sleep GPIO.setmode(GPIO.BCM) GPIO.setup(7, GPIO.IN) # s...
<p>I don't have a raspberry-pi on me right now so I can't test this, but I'm pretty sure the following is what you need.</p> <pre><code>lever_num_by_pin = {7: 2, 11: 3} def printOn(pin): print("switch", lever_num_by_pin[pin], "on") def printOff(pin): print("switch", lever_num_by_pin[pin], "off") for pin in leve...
python|raspberry-pi|gpio
2