title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
sequence |
---|---|---|---|---|---|---|---|---|---|
Should python script files be executable? | 40,030,811 | <p>Should python script files be executable?</p>
<p>Suppose I'm developing a small tool. I have the following files:</p>
<pre><code>my_tool.py
my_lib.py
my_other_lib.py
....
</code></pre>
<p>Occasionally I run my tool with <code>python my_tool.py</code>.</p>
<p>Is there a convention that the first file should be executable, while all "libraries" should not be? If I have multiple entry points, should all of them be marked executable?</p>
| 1 | 2016-10-13T20:55:12Z | 40,033,007 | <p>You only need to make a python script executable if it has a hashbang at the top. Python doesn't require that <a href="http://docs.python.org/tutorial/modules.html" rel="nofollow">modules</a> you intend to import or any scripts passed as arguments are flagged as executable.</p>
<p>As for naming conventions, you should only flag files that actually have the hashbang in them as executable. And if you want to better separate the modules from the executables, you should use directories as specified in section 6.4 of the <a href="http://docs.python.org/tutorial/modules.html" rel="nofollow">module tutorial</a>.</p>
| 0 | 2016-10-14T00:13:50Z | [
"python",
"naming-conventions"
] |
Python: How do I 'pull' a list through a function | 40,030,875 | <p>I am trying to find the 'peak' in list of numbers. I tried the following;</p>
<pre><code>list = [5, 12, 34, 25, 13, 33]
n = range(len(list))
def func(n):
if list[n] >= list[n-1] and list[n] >= list[n+1]:
print list[n]
print func(n)
</code></pre>
<p>I get back the error 'list indices must be integers, not list'</p>
| -6 | 2016-10-13T20:58:44Z | 40,031,046 | <p>you define n = range(...) so n = [0, 1,...] when you call func(n) and in your function:</p>
<pre><code>if list[n] >= ....
</code></pre>
<p>becomes:</p>
<pre><code>if list[ [0, 1, ...] ] >= ...
</code></pre>
<p>This is the reason why you get error 'list indices must be integers, not list'</p>
| -1 | 2016-10-13T21:09:28Z | [
"python",
"python-2.7"
] |
Python: How do I 'pull' a list through a function | 40,030,875 | <p>I am trying to find the 'peak' in list of numbers. I tried the following;</p>
<pre><code>list = [5, 12, 34, 25, 13, 33]
n = range(len(list))
def func(n):
if list[n] >= list[n-1] and list[n] >= list[n+1]:
print list[n]
print func(n)
</code></pre>
<p>I get back the error 'list indices must be integers, not list'</p>
| -6 | 2016-10-13T20:58:44Z | 40,031,180 | <p>change 'list' to something else, say 'lst' and by peak if you mean max element then: </p>
<pre><code>lst = [5, 12, 34, 25, 13, 33]
print max(lst)
</code></pre>
| -1 | 2016-10-13T21:19:08Z | [
"python",
"python-2.7"
] |
Python: How do I 'pull' a list through a function | 40,030,875 | <p>I am trying to find the 'peak' in list of numbers. I tried the following;</p>
<pre><code>list = [5, 12, 34, 25, 13, 33]
n = range(len(list))
def func(n):
if list[n] >= list[n-1] and list[n] >= list[n+1]:
print list[n]
print func(n)
</code></pre>
<p>I get back the error 'list indices must be integers, not list'</p>
| -6 | 2016-10-13T20:58:44Z | 40,031,258 | <p>Your issue is that you're trying to pass a range as an argument. Range(len(list)), in this case, is going to give you this list: [0,1,2,3,4,5]</p>
<p>Your function is expecting a single number, but you're passing a list. To check every number, change this line:</p>
<pre><code> print(func(n))
</code></pre>
<p>to this:</p>
<pre><code>for number in n:
print(func(number))
</code></pre>
| -1 | 2016-10-13T21:25:05Z | [
"python",
"python-2.7"
] |
How to add to an existing plot a marker for points in the chart | 40,030,881 | <p>So hello community,
I have a program which includes several functions and they all have 5-6 fix points. On those points i always want to have whether a square or diamond marker style. I can do it in the program but i want to have it in the script so they already appear when i run the program. ANy ideas?</p>
| -1 | 2016-10-13T20:59:06Z | 40,031,202 | <p>So the answer is described on this website and much more.
<a href="https://bespokeblog.wordpress.com/2011/07/07/basic-data-plotting-with-matplotlib-part-2-lines-points-formatting/" rel="nofollow">https://bespokeblog.wordpress.com/2011/07/07/basic-data-plotting-with-matplotlib-part-2-lines-points-formatting/</a></p>
<p>basically the command is just:</p>
<pre><code>ax1f1.plot(x, y, marker='s', linestyle='-', color='k')
</code></pre>
| 0 | 2016-10-13T21:21:10Z | [
"python",
"matplotlib",
"marker"
] |
Python webscraping using beautiful soup | 40,030,943 | <p><img src="https://i.stack.imgur.com/3BNrE.png" alt="Extract between span span"></p>
<pre><code>nameList = soup.find_all("span", {"class":"answer-number"})
for item in nameList:
print('item.content[0]')
</code></pre>
<p>I wrote the above code, but it is not working. Please help. I want the number 6a from it.</p>
| -1 | 2016-10-13T21:03:03Z | 40,031,175 | <p>Try changing your print statement to item.text</p>
| -1 | 2016-10-13T21:18:52Z | [
"python",
"html",
"parsing",
"beautifulsoup"
] |
Python webscraping using beautiful soup | 40,030,943 | <p><img src="https://i.stack.imgur.com/3BNrE.png" alt="Extract between span span"></p>
<pre><code>nameList = soup.find_all("span", {"class":"answer-number"})
for item in nameList:
print('item.content[0]')
</code></pre>
<p>I wrote the above code, but it is not working. Please help. I want the number 6a from it.</p>
| -1 | 2016-10-13T21:03:03Z | 40,031,620 | <pre><code>>>> soup.findAll('span',{'class':'badgecount'})
[<span class="badgecount">9</span>, <span class="badgecount">23</span>, <span class="badgecount">51</span>, <span class="badgecount">8</span>, <span class="badgecount">40</span>, <span class="badgecount">83</span>, <span class="badgecount">20</span>, <span class="badgecount">88</span>, <span class="badgecount">104</span>, <span class="badgecount">3</span>, <span class="badgecount">22</span>, <span class="badgecount">39</span>, <span class="badgecount">1</span>, <span class="badgecount">12</span>, <span class="badgecount">45</span>]
>>> spans=soup.findAll('span',{'class':'badgecount'})
>>> for span in spans:
print span.text
9
23
51
8
40
83
20
88
104
3
22
39
1
12
45
</code></pre>
| -1 | 2016-10-13T21:53:12Z | [
"python",
"html",
"parsing",
"beautifulsoup"
] |
Using BeautifulSoup to scrape li's and id's in same method | 40,030,963 | <p>How would i modify the parameters of the findAll method to read both li's and id's? li's are elements and id's are attributes correct?</p>
<pre><code>#Author: David Owens
#File name: soupScraper.py
#Description: html scraper that takes surf reports from various websites
import csv
import requests
from bs4 import BeautifulSoup
###################### SURFLINE URL STRINGS AND TAG ###########################
slRootUrl = 'http://www.surfline.com/surf-report/'
slSunsetCliffs = 'sunset-cliffs-southern-california_4254/'
slScrippsUrl = 'scripps-southern-california_4246/'
slBlacksUrl = 'blacks-southern-california_4245/'
slCardiffUrl = 'cardiff-southern-california_4786/'
slTagText = 'observed-wave-range'
slTag = 'id'
#list of surfline URL endings
slUrls = [slSunsetCliffs, slScrippsUrl, slBlacksUrl, slCardiffUrl]
###############################################################################
#################### MAGICSEAWEED URL STRINGS AND TAG #########################
msRootUrl = 'http://magicseaweed.com/'
msSunsetCliffs = 'Sunset-Cliffs-Surf-Report/4211/'
msScrippsUrl = 'Scripps-Pier-La-Jolla-Surf-Report/296/'
msBlacksUrl = 'Torrey-Pines-Blacks-Beach-Surf-Report/295/'
msTagText = 'rating-text text-dark'
msTag = 'li'
#list of magicseaweed URL endings
msUrls = [msSunsetCliffs, msScrippsUrl, msBlacksUrl]
###############################################################################
'''
This method iterates through a list of urls and extracts the surf report from
the webpage dependent upon its tag location
rootUrl: The root url of each surf website
urlList: A list of specific urls to be appended to the root url for each
break
tag: the html tag where the actual report lives on the page
returns: a list of strings of each breaks surf report
'''
def extract_Reports(rootUrl, urlList, tag, tagText):
#empty list to hold reports
reports = []
#loop thru URLs
for url in urlList:
try:
#request page
request = requests.get(rootUrl + url)
#turn into soup
soup = BeautifulSoup(request.content, 'lxml')
#get the tag where report lives
reportTag = soup.findAll(id = tagText)
for report in reportTag:
reports.append(report.string.strip())
#notify if fail
except:
print 'scrape failure'
pass
return reports
#END METHOD
slReports = extract_Reports(slRootUrl, slUrls, slTag, slTagText)
msReports = extract_Reports(msRootUrl, msUrls, msTag, msTagText)
print slReports
print msReports
</code></pre>
<p>As of right now, only slReports prints correctly because i have it explicitly set to id = tagText. I am also aware that my tag paramater is not used currently.</p>
| 0 | 2016-10-13T21:04:03Z | 40,032,977 | <p>So the problem is that you want to search the parse tree for elements that have either a class name of <code>rating-text</code> (it turns out you do not need <code>text-dark</code> to identify the relevant elements in the case of Magicseaweed) or an ID of <code>observed-wave-range</code>, using a single <code>findAll</code> call.</p>
<p>You can use a <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-function" rel="nofollow">filter function</a> to achieve this:</p>
<pre><code>def reportTagFilter(tag):
return (tag.has_attr('class') and 'rating-text' in tag['class']) \
or (tag.has_attr('id') and tag['id'] == 'observed-wave-range')
</code></pre>
<p>Then change your <code>extract_Reports</code> function to read:</p>
<pre><code> reportTag = soup.findAll(reportTagFilter)[0]
reports.append(reportTag.text.strip())
</code></pre>
| 0 | 2016-10-14T00:10:17Z | [
"python",
"html",
"web-scraping",
"beautifulsoup"
] |
Sending email with Python script Output and using crontab to send weekly | 40,031,004 | <p>I have a Python script and I am trying to write a crontab and have the output from the Python script to be outputed to a file which then sends that output to an email address (to the body of the email not the title) that is specified. My system details and crontab entry is below:</p>
<pre><code>System details:
Python: 2.7
OSX : 10.11
host$ crontab -l
11 11 13 10 4 2016 python pythonscript.py >> weekly.log | mail -s weekly.log [email protected]
</code></pre>
<p>Although when the crontab executes, the email sends me an email message with the subject line saying "weekly.log" with no body.</p>
<p>I have also tried crontab with below settings:</p>
<pre><code>07 22 13 10 4 2016 /root/python/osversion_weekly.py | tee /root/python/osversion`date +\%Y-\%m-\%d-\%H:\%M:\%S`-cron.log | mailx -s "OSLEVEL Report" [email protected]
</code></pre>
<p>Although I only get an email with Title "OSLEVEL Report" with an empty body</p>
<p>Update:
The error I seem to be getting from /var/log/cron is showing "orphan no passwd entry." Not quite sure what does means, and I havent seen any answers online to resolve this...</p>
| 1 | 2016-10-13T21:06:21Z | 40,031,126 | <p>The <code>>></code> makes the python output get appended to the file <code>weekly.log</code>, after that no input is pushed forward to <code>mail</code>. </p>
<p>You could remove <code>>> weekly.log</code> and not have a log file or use the program <code>tee</code> in the pipe. <code>tee</code> writes to standard output and a file.</p>
<p>Like this:<br>
<code>python pythonscript.py | tee -a weekly.log | mail -s weekly.log [email protected]</code></p>
| 0 | 2016-10-13T21:15:48Z | [
"python",
"linux",
"osx",
"crontab"
] |
Python Watchdog Measure Time Events | 40,031,080 | <p>I'm trying to implement a module called <a href="https://github.com/gorakhargosh/watchdog" rel="nofollow">Watchdog</a> into a project. I'm looking for a way I can measure time between event calls within Watchdog.</p>
<pre><code>if timebetweenevents == 5 seconds:
dothething()
</code></pre>
<p>Thank you,</p>
<p>Charles</p>
<hr>
<p>Edit:</p>
<p>I'm using Python 3.5.0</p>
<p>Here's what the code I was working on <a href="http://pastebin.com/GvSWxymb" rel="nofollow">LINK</a>.</p>
<p>I can print out the current time of the event, but what is the best way to hold on to the time from the last event and then measure the time between since the last event?</p>
| 0 | 2016-10-13T21:12:24Z | 40,047,644 | <p>You can modify your Handler class to have a record of the time of the last call.</p>
<p><strong>init</strong> method just initialises the value to the current time.
You will also need to make the method on_any_event a non static method</p>
<pre><code>class Handler(FileSystemEventHandler):
event_time=0
def __init__(self):
self.event_time=time.time()
def on_any_event(self, event):
now=time.time()
timedelta=now-self.event_time
self.event_time=now
print(timedelta)
</code></pre>
| 0 | 2016-10-14T16:10:24Z | [
"python",
"watchdog"
] |
How to call function between optimization iterations in pyOpt? | 40,031,152 | <p>I was wondering if there is a way that I can pass pyOpt a function that
should be called at the end of each iteration? </p>
<p>The reason I need something like this is that I am running a FEA
simulation in each function evaluation, and I would like to output the
FEA results (displacements, stresses) to an ExodusII file after each
optimization iteration. I originally placed my writeExodus function at
the end of the "function evaluation" function, my problem with this is
that a new "pseudo time-step" gets written to my exodus file each time
the function is evaluated rather than only at the end of each iteration,
so this obviously would lead to extra unncessary output to the exodus
file for numerical differentiation (finite difference, complex step) and
for optimizers that make multiple function evaluations per iteration
(i.e. GCMMA when checking if approximation is conservative).</p>
<p>So, is there a way I can tell pyOpt to execute a function (i.e. my
exodusWrite function) at the end of each iteration? Or alternatively,
is there anyway I can track the optimizer iterations in pyOpt so that
inside of my "function evaluation" function I can keep track of the
optimizer iterations and only write the exodus output when the iteration number changes?</p>
| 0 | 2016-10-13T21:17:10Z | 40,032,149 | <p>you could either put your function into a component that you put at the end of your model. Since it won't have any connections, you'll want to <a href="http://openmdao.readthedocs.io/en/1.7.2/srcdocs/packages/core/group.html?highlight=set_order#openmdao.core.group.Group.set_order" rel="nofollow">set the run order</a> manually for your group. </p>
<p>Alternatively, you could just hack the pyopt_sparse driver code to manually call your function. You would just add a call to your method of choice at the end if <a href="https://github.com/OpenMDAO/OpenMDAO/blob/master/openmdao/drivers/pyoptsparse_driver.py#L423" rel="nofollow">this call</a> and it would then get called any time pyopt_sparse asks for an objective evaluation</p>
| 0 | 2016-10-13T22:36:09Z | [
"python",
"optimization",
"openmdao"
] |
How to give automatically generated buttons names in Tkinter? | 40,031,193 | <p>So i am genertaing a grid of 3x3 buttons for a Tic Tac Toe game im making, and i want to to end up so that when a button is pressed it changes to either a X or O, however i dont know how to give each button a unique identifier so i know which button to change.</p>
<p>Heres the code for the buttons.</p>
<pre><code>num=1
for row in range(3):
for column in range(3):
Button(TTTGrid,bg="#ffffff", width=20,height = 6, command=lambda row=row, column=column: TTTGridPress(row, column),relief=SUNKEN).grid(row=row, column=column, sticky=W)
num=num+1
</code></pre>
| 0 | 2016-10-13T21:20:18Z | 40,031,241 | <p>Use a dictionary or list. For example:</p>
<pre><code>buttons = {}
for row in range(3):
for column in range(3):
buttons[(row, column)] = Button(...)
buttons[(row, column)].grid(...)
</code></pre>
<p>Later, you can refer to the button in row 2, column one as:</p>
<pre><code>buttons[(2 1)].configure(...)
</code></pre>
<hr>
<p>Note: you need to call <code>grid</code> (or <code>pack</code>, or <code>place</code>) in a separate statement, because they return <code>None</code>. If you do it on the same statement (eg: <code>Button(...).grid(...)</code>), the value that gets saved is <code>None</code> rather than the instance of the button.</p>
| 1 | 2016-10-13T21:23:52Z | [
"python",
"tkinter"
] |
How to set a fixed size in PyQt5 for any widget without breaking layout when resizing | 40,031,197 | <p>Haven't found this exact problem anywhere, or maybe I just don't recognize it from others. As still pretty much a beginner in programming but not totally oblivious, I am attempting to create an application with PyQt5 but I am having trouble setting up the layout properly before doing any more serious coding in the future.</p>
<p>As you will see, I am trying to do my main layout by use of a QHBoxLayout with two QVBoxLayout layouts inside of it. I've thrown some random widgets into each vertical layout, which work perfectly on their own except when I try to give them a fixed size. The ListWidget and LineEdit in the left vertical layout do not stay where I want them to be or how I want them to be, when given a fixed width/height/size, once I manually resize the app windon as seen in pictures. Obviously I want them to stay put in topleft corner and any subsequent widget right under the first, second, etc. Same happens with the tabswidget whenever I try applying same.</p>
<p>I've toyed around with geometry, sizehints, alignments, etc. but I just can't seem to figure it out.
Enclosing links to two pictures of the problem:</p>
<p><img src="https://imgur.com/EpD0UEN.png" alt="before resizing"></p>
<p><img src="https://imgur.com/snDQpVt.png" alt="after resizing"></p>
<p>And enclosing the important part of the code:</p>
<pre><code>class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.initUI()
self.createactions()
self.createmenus()
self.createtoolbar()
self.container = FrameContainer()
self.setCentralWidget(self.container)
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(100,100,800,600)
self.statusBar().showMessage("Statusbar - awaiting user control")
self.show()
class FrameContainer(QWidget):
def __init__(self):
super(QWidget, self).__init__()
self.setContentsMargins(0,0,0,0)
self.mainlayout = QHBoxLayout(self)
self.mainlayout.setSpacing(0)
self.mainlayout.setContentsMargins(0, 0, 0, 0)
self.verticalwidgets()
self.mainlayout.addLayout(self.box_layout1)
self.mainlayout.addLayout(self.box_layout2)
def verticalwidgets(self):
# Left side
self.box_layout1 = QVBoxLayout()
self.box_layout1.setContentsMargins(0,0,0,0)
self.box_layout1.setSpacing(0)
self.list_widget = QListWidget()
self.list_widget.setFixedSize(200,500)
self.list_widget.sizeHintForColumn(0)
self.someWidget3 = QLineEdit()
self.someWidget3.setFixedWidth(200)
self.box_layout1.addWidget(self.list_widget, Qt.AlignLeft)
self.box_layout1.addWidget(self.someWidget3, Qt.AlignLeft)
# Right side
self.box_layout2 = QVBoxLayout()
self.box_layout2.setContentsMargins(0,0,0,0)
self.box_layout2.setGeometry(QRect(0, 0, 800, 680))
self.tabs_widget = TabsWidget(self)
self.box_layout2.addWidget(self.tabs_widget)
class TabsWidget(QWidget):
def __init__(self, child):
super(QWidget, self).__init__()
self.layout = QHBoxLayout(self)
self.layout.setContentsMargins(0,0,0,0)
self.tabs = QTabWidget()
self.tabs.setTabsClosable(True)
self.tab1 = QWidget()
self.tab2 = QWidget()
self.tab3 = QWidget()
# Add tabs
self.tabs.addTab(self.tab1, "Tab 1")
self.tabs.addTab(self.tab2, "Tab 2")
self.tabs.addTab(self.tab3, "Tab 3")
# Create first tab
self.tab1.layout = QVBoxLayout(self)
self.pushButton1 = QPushButton("Button 1")
self.pushButton2 = QPushButton("Button 2")
self.pushButton3 = QPushButton("Button 3")
self.tab1.layout.addWidget(self.pushButton1)
self.tab1.layout.addWidget(self.pushButton2)
self.tab1.layout.addWidget(self.pushButton3)
self.tab2.layout = QVBoxLayout(self)
self.tab2.layout.addWidget(QLabel("Peterpaned"))
self.tab2.layout.addWidget(QLineEdit())
self.tab1.setLayout(self.tab1.layout)
self.tab2.setLayout(self.tab2.layout)
# Add tabs to widget
self.layout.addWidget(self.tabs)
</code></pre>
<p>What am I doing wrong? Don't need to necessarily give me the code answer, unless you feel like it, a serious nudge in the right direction would do I think, or at least I hope it would.</p>
| 0 | 2016-10-13T21:20:29Z | 40,031,570 | <p>You can add spacers in your layout (horizontal or vertical, depending where you put them) and set a non-fixed size policy for them. This way whenever the window is resized only the spacers will stretch (or shorten).</p>
| 1 | 2016-10-13T21:49:00Z | [
"python",
"layout",
"pyqt5",
"qvboxlayout"
] |
Matrix operations with rows of pandas dataframes | 40,031,287 | <p>I have a pandas dataframe that contains three columns corresponding to x, y and z coordinates for positions of objects. I also have a transformation matrix ready to rotate those points by a certain angle. I had previously looped through each row of the dataframe performing this transformation but I found that that is very, very time consuming. Now I just want to perform the transformations all at once and append the results as additional columns. </p>
<p>I'm looking for a working version of this line (which always returns a shape mismatch):</p>
<pre><code>largest_haloes['X_rot', 'Y_rot', 'Z_rot'] = np.dot(rot,np.array([largest_haloes['X'], largest_haloes['Y'], largest_haloes['Z']]).T)
</code></pre>
<p>Here's a minimum working example:</p>
<pre><code>from __future__ import division
import math
import pandas as pd
import numpy as np
def unit_vector(vector):
return vector / np.linalg.norm(vector)
largest_haloes = pd.DataFrame()
largest_haloes['X'] = np.random.uniform(1,10,size=30)
largest_haloes['Y'] = np.random.uniform(1,10,size=30)
largest_haloes['Z'] = np.random.uniform(1,10,size=30)
normal = np.array([np.random.uniform(-1,1),np.random.uniform(-1,1),np.random.uniform(0,1)])
normal = unit_vector(normal)
a = normal[0]
b = normal[1]
c = normal[2]
rot = np.array([[b/math.sqrt(a**2+b**2), -1*a/math.sqrt(a**2+b**2), 0], [(a*c)/math.sqrt(a**2+b**2), b*c/math.sqrt(a**2+b**2), -1*math.sqrt(a**2+b**2)], [a, b, c]])
largest_haloes['X_rot', 'Y_rot', 'Z_rot'] = np.dot(rot,np.array([largest_haloes['X'], largest_haloes['Y'], largest_haloes['Z']]).T)
</code></pre>
<p>So the goal is that each row of largest_haloes['X_rot', 'Y_rot', 'Z_rot'] should be populated with a rotated version of the corresponding row of largest_haloes['X','Y','Z']. How can I do this without looping through rows? I've also tried df.dot but there is not much documentation on it and it didn't seem to do what I wanted.</p>
| 2 | 2016-10-13T21:27:03Z | 40,035,491 | <p>If you mean matrix multiplication by rotation.</p>
<p>You can convert both to numpy arrays and perform it as</p>
<pre><code>lh = largest_haloes.values
rotated_array = lh.dot(rot)
</code></pre>
<p>You can also do</p>
<pre><code>x = pd.DataFrame(data=rot,index=['X','Y','Z'])
rotated_df = largest_haloes.dot(x)
</code></pre>
| 0 | 2016-10-14T05:24:50Z | [
"python",
"pandas",
"matrix",
"dataframe"
] |
How can I find all known ingredient strings in a block of text? | 40,031,406 | <p>Given a string of ingredients:</p>
<pre class="lang-python prettyprint-override"><code>text = """Ingredients: organic cane sugar, whole-wheat flour,
mono & diglycerides. Manufactured in a facility that uses nuts."""
</code></pre>
<p>How can I extract the ingredients from my postgres database, or find them in my elasticsearch index, without matching tokens like <code>Ingredients:</code> or <code>nuts</code>?</p>
<p>The expected output would be:</p>
<pre class="lang-python prettyprint-override"><code>ingredients = process(text)
# ['cane sugar', 'whole wheat flour', 'mono diglycerides']
</code></pre>
| 3 | 2016-10-13T21:35:28Z | 40,032,158 | <p>This Python code gives me this output: <code>['organic cane sugar', 'whole-wheat flour', 'mono & diglycerides']</code>
It requires that the ingredients come after "Ingredients: " and that all ingredients are listed before a ".", as in your case.</p>
<pre><code>import re
text = """Ingredients: organic cane sugar, whole-wheat flour,
mono & diglycerides. Manufactured in a facility that uses nuts."""
# Search everything that comes after 'Ingredients: ' and before '.'
m = re.search('(?<=Ingredients: ).+?(?=\.)', text, re.DOTALL) # DOTALL: make . match newlines too
items = m.group(0).replace('\n', ' ').split(',') # Turn newlines into spaces, make a list of items separated by ','
items = [ i.strip() for i in items ] # Remove leading whitespace in each item
print items
</code></pre>
| 0 | 2016-10-13T22:37:13Z | [
"python",
"postgresql",
"parsing",
"elasticsearch",
"nlp"
] |
Python - Convert intergers to floats within a string | 40,031,547 | <p>I have an equation in the form of a string, something like this:</p>
<pre><code>(20 + 3) / 4
</code></pre>
<p>I can easily solve this equation by using <code>eval()</code>, but it will give me an answer of <code>5</code>, not the correct answer of <code>5.75</code>. I know this is because <code>20</code>, <code>3</code>, and <code>4</code> are integers. So I was wondering, is there any way to just tack a <code>.0</code> onto the end of them? Or is there some other trick I should use to make <code>eval()</code> think they are floats?<br>
<strong>Note:</strong> the numbers will not always be integers, so it would be great if the solution could detect if they are integers and treat them accordingly.</p>
<p><strong>Note #2:</strong> I'm using python 2.7</p>
<p><strong>Note #3:</strong> I already know that "Python 2 is legacy, Python 3 is the future."</p>
<p>Thanks!</p>
| -1 | 2016-10-13T21:47:10Z | 40,031,612 | <p>You could use <a href="http://docs.sympy.org/dev/index.html" rel="nofollow"><code>sympy</code></a> to parse the string using <a href="http://docs.sympy.org/dev/modules/parsing.html" rel="nofollow"><code>sympy_parser.parse_expr</code></a> and then solve/simplify it:</p>
<pre><code>>>> from sympy.parsing import sympy_parser
>>> exp = '(20 + 3) / 4'
>>> sympy_parser.parse_expr(exp).round(2)
5.75
</code></pre>
<p>This would also work for other valid mathematical expressions.</p>
| 4 | 2016-10-13T21:52:43Z | [
"python",
"string",
"python-2.7"
] |
Calculating the time difference between events | 40,031,569 | <p>I have a df</p>
<pre><code>df = pd.DataFrame({'State': {0: "A", 1: "B", 2:"A", 3: "B", 4: "A", 5: "B", 6 : "A", 7: "B"},
'date': {0: '2016-10-13T14:10:41Z', 1: '2016-10-13T14:10:41Z', 2:'2016-10-13T15:26:19Z',
3: '2016-10-14T15:26:19Z', 4: '2016-10-15T15:26:19Z', 5: '2016-10-18T15:26:19Z',
6 :'2016-10-17T15:26:19Z', 7: '2016-10-13T15:26:19Z'}}, columns=['State', 'date'])
</code></pre>
<p>I need to get an average of the time between each a event and the following b event. I'm trying to use shift to generate a series of differences to average it but I can't quite get it to work.</p>
<p>Thank you!</p>
| 2 | 2016-10-13T21:48:59Z | 40,031,676 | <p>First, convert the dates to datetimes, then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.diff.html" rel="nofollow"><code>DataFrame.diff</code></a>:</p>
<pre><code>df.date = pd.to_datetime(df.date)
df.date.diff()
</code></pre>
<p>yields:</p>
<pre><code>0 NaT
1 0 days 00:00:00
2 0 days 01:15:38
3 1 days 00:00:00
4 1 days 00:00:00
5 3 days 00:00:00
6 -1 days +00:00:00
7 -4 days +00:00:00
Name: date, dtype: timedelta64[ns]
</code></pre>
<p>If you want the average, you can do something like</p>
<pre><code>df.date.diff().mean() # or possibly df.date.diff().abs().mean()
# Timedelta('0 days 00:10:48.285714')
</code></pre>
| 2 | 2016-10-13T21:57:00Z | [
"python",
"pandas"
] |
python selenium-webdriver select option does not work | 40,031,592 | <p>The selection of Calgary in Canadian Cities list does not work, it will always return All cities in the search result after clicking search button pro grammatically. Here is my code:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
# Initialize
driver = webdriver.Firefox()
driver.get('https://sjobs.brassring.com/TGWebHost/searchopenings.aspx?partnerid=25222&siteid=5011')
# Select city name Calgary
calgaryOptionXpath = ".//*[@id='Question4138__FORMTEXT62']/option[37]"
calgaryOptionElement = WebDriverWait(driver, 10).until(lambda driver:driver.find_element_by_xpath(calgaryOptionXpath))
calgaryOptionElement.click()
# click submit button "Search"
driver.find_element_by_id('ctl00_MainContent_submit1').click()
</code></pre>
<p>Thanks in advance!</p>
| 1 | 2016-10-13T21:50:22Z | 40,033,377 | <pre><code>from selenium import webdriver
from selenium.webdriver.support.ui import Select
import time
# Initialize
driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(10)
driver.get('https://sjobs.brassring.com/TGWebHost/searchopenings.aspx?partnerid=25222&siteid=5011')
# Select city name Calgary
text = "Calgary" # what ever you want to select in dropdown
currentselection = driver.find_element_by_id("Question4138__FORMTEXT62")
select = Select(currentselection)
select.select_by_visible_text(text)
select.deselect_by_visible_text("All")
print("Selected Calgary by visible text")
driver.find_element_by_id('ctl00_MainContent_submit1').click()
</code></pre>
<p>Hope this helps</p>
| 0 | 2016-10-14T01:05:36Z | [
"python",
"selenium-webdriver",
"drop-down-menu"
] |
How to detect when a maximum number is rolled? | 40,031,690 | <p>This question seems like it would be easily answered by just making an if statement for my maximum in the range, BUT please take a second to read before calling me an idiot. I am making a program that lets the user choose between many different dice. I am wondering if there is an easy way to detect when the maximum value is rolled from any of the options without setting if statements for all of the different dice.</p>
<pre><code>def inphandle(choice):
if choice==4:
roll = random.randint(1,4)
elif choice==6:
roll = random.randint(1,6)
elif choice==8:
roll = random.randint(1,8)
elif choice==10:
roll = random.randint(1,10)
elif choice==20:
roll = random.randint(1,20)
return roll
def dice(roll):
min = 0
if roll==1:
print("Min roll! Try again!")
min = min+1
if roll
def mainmenu():
print("Please choose from the following options:")
print("Roll | EXIT")
option = input()
if option=="EXIT" or option=="exit" or option=="Exit"
print("You rolled" + max + "max rolls and " + min + " min rolls! Goodbye!")
def main():
choice = int(input("Please enter a number corresponding to the number of faces on your dice. E.x. 4 for 4-Sided: "))
cont = input("Would you like to roll the dice? Y or N: ")
while cont=="y" or cont=="Y":
roll = inphandle(choice)
dice(roll)
cont = input("Would you like to roll again? Y or N: ")
while cont=="n" or cont=="N":
easteregg()
cont = input("Do I get bunus points now?!?")
main()
</code></pre>
<p>I do have random imported, but this is simply a section of the whole program. I understand if there is no shortcut to this, but I wanted to check before typing it all out since it might not be necessary. </p>
| -2 | 2016-10-13T21:58:10Z | 40,031,799 | <p>Just use </p>
<pre><code>def inphandle(choice):
roll = random.randint(1, choice)
return roll == choice
</code></pre>
| -1 | 2016-10-13T22:04:54Z | [
"python",
"if-statement",
"random"
] |
How to detect when a maximum number is rolled? | 40,031,690 | <p>This question seems like it would be easily answered by just making an if statement for my maximum in the range, BUT please take a second to read before calling me an idiot. I am making a program that lets the user choose between many different dice. I am wondering if there is an easy way to detect when the maximum value is rolled from any of the options without setting if statements for all of the different dice.</p>
<pre><code>def inphandle(choice):
if choice==4:
roll = random.randint(1,4)
elif choice==6:
roll = random.randint(1,6)
elif choice==8:
roll = random.randint(1,8)
elif choice==10:
roll = random.randint(1,10)
elif choice==20:
roll = random.randint(1,20)
return roll
def dice(roll):
min = 0
if roll==1:
print("Min roll! Try again!")
min = min+1
if roll
def mainmenu():
print("Please choose from the following options:")
print("Roll | EXIT")
option = input()
if option=="EXIT" or option=="exit" or option=="Exit"
print("You rolled" + max + "max rolls and " + min + " min rolls! Goodbye!")
def main():
choice = int(input("Please enter a number corresponding to the number of faces on your dice. E.x. 4 for 4-Sided: "))
cont = input("Would you like to roll the dice? Y or N: ")
while cont=="y" or cont=="Y":
roll = inphandle(choice)
dice(roll)
cont = input("Would you like to roll again? Y or N: ")
while cont=="n" or cont=="N":
easteregg()
cont = input("Do I get bunus points now?!?")
main()
</code></pre>
<p>I do have random imported, but this is simply a section of the whole program. I understand if there is no shortcut to this, but I wanted to check before typing it all out since it might not be necessary. </p>
| -2 | 2016-10-13T21:58:10Z | 40,031,800 | <p>first change <code>inphandle</code></p>
<pre><code>def inphandle(choice):
return random.randint(1,choice)
</code></pre>
<p>and then change</p>
<pre><code> while cont=="y" or cont=="Y":
roll = inphandle(choice)
dice(roll,choice)
...
def dice(roll,max_val):
if roll == max_val:print "MAX"
elif roll == 1:print "MIN"
</code></pre>
| 0 | 2016-10-13T22:04:56Z | [
"python",
"if-statement",
"random"
] |
How to detect when a maximum number is rolled? | 40,031,690 | <p>This question seems like it would be easily answered by just making an if statement for my maximum in the range, BUT please take a second to read before calling me an idiot. I am making a program that lets the user choose between many different dice. I am wondering if there is an easy way to detect when the maximum value is rolled from any of the options without setting if statements for all of the different dice.</p>
<pre><code>def inphandle(choice):
if choice==4:
roll = random.randint(1,4)
elif choice==6:
roll = random.randint(1,6)
elif choice==8:
roll = random.randint(1,8)
elif choice==10:
roll = random.randint(1,10)
elif choice==20:
roll = random.randint(1,20)
return roll
def dice(roll):
min = 0
if roll==1:
print("Min roll! Try again!")
min = min+1
if roll
def mainmenu():
print("Please choose from the following options:")
print("Roll | EXIT")
option = input()
if option=="EXIT" or option=="exit" or option=="Exit"
print("You rolled" + max + "max rolls and " + min + " min rolls! Goodbye!")
def main():
choice = int(input("Please enter a number corresponding to the number of faces on your dice. E.x. 4 for 4-Sided: "))
cont = input("Would you like to roll the dice? Y or N: ")
while cont=="y" or cont=="Y":
roll = inphandle(choice)
dice(roll)
cont = input("Would you like to roll again? Y or N: ")
while cont=="n" or cont=="N":
easteregg()
cont = input("Do I get bunus points now?!?")
main()
</code></pre>
<p>I do have random imported, but this is simply a section of the whole program. I understand if there is no shortcut to this, but I wanted to check before typing it all out since it might not be necessary. </p>
| -2 | 2016-10-13T21:58:10Z | 40,031,897 | <p>Let me suggest creating a class which handles different types of dice:</p>
<pre><code>class Die(object):
def __init__(self, num_faces):
self.num_faces = num_faces
def roll(self):
return random.randint(1, self.num_faces)
def is_min(self, number):
return number == 1
def is_max(self, number):
return number == self.num_faces
</code></pre>
<p>I would say this is a valid situation for that and you get to learn about classes ;)</p>
<p>Then use the class:</p>
<pre><code>def main():
minimums = maximums = 0
choice = int(input("Please enter a number corresponding to the"
" number of faces on your dice. E.x. 4 for 4-Sided: "))
die = Die(choice)
cont = input("Would you like to roll the dice? Y or N: ")
while cont.lower() == "y":
number = die.roll()
if die.is_min(number):
minimums += 1
if die.is_max(number):
maximums += 1
cont = input("Would you like to roll again? Y or N: ")
main()
</code></pre>
<p>Note that I moved your <code>min</code> & <code>max</code> counters to main, because the alternative is to make globals which is bad.</p>
<p>I also renamed them, because <code>min</code> and <code>max</code> are names of built-in functions. It is better to learn not to hide those.</p>
| 0 | 2016-10-13T22:13:07Z | [
"python",
"if-statement",
"random"
] |
How to detect when a maximum number is rolled? | 40,031,690 | <p>This question seems like it would be easily answered by just making an if statement for my maximum in the range, BUT please take a second to read before calling me an idiot. I am making a program that lets the user choose between many different dice. I am wondering if there is an easy way to detect when the maximum value is rolled from any of the options without setting if statements for all of the different dice.</p>
<pre><code>def inphandle(choice):
if choice==4:
roll = random.randint(1,4)
elif choice==6:
roll = random.randint(1,6)
elif choice==8:
roll = random.randint(1,8)
elif choice==10:
roll = random.randint(1,10)
elif choice==20:
roll = random.randint(1,20)
return roll
def dice(roll):
min = 0
if roll==1:
print("Min roll! Try again!")
min = min+1
if roll
def mainmenu():
print("Please choose from the following options:")
print("Roll | EXIT")
option = input()
if option=="EXIT" or option=="exit" or option=="Exit"
print("You rolled" + max + "max rolls and " + min + " min rolls! Goodbye!")
def main():
choice = int(input("Please enter a number corresponding to the number of faces on your dice. E.x. 4 for 4-Sided: "))
cont = input("Would you like to roll the dice? Y or N: ")
while cont=="y" or cont=="Y":
roll = inphandle(choice)
dice(roll)
cont = input("Would you like to roll again? Y or N: ")
while cont=="n" or cont=="N":
easteregg()
cont = input("Do I get bunus points now?!?")
main()
</code></pre>
<p>I do have random imported, but this is simply a section of the whole program. I understand if there is no shortcut to this, but I wanted to check before typing it all out since it might not be necessary. </p>
| -2 | 2016-10-13T21:58:10Z | 40,031,967 | <p>This is what I would do:</p>
<p>change the inphandle to this:</p>
<pre><code>def inphandle(choice):
roll = random.randrange(1,choice+1,1)
return roll
</code></pre>
<p>And change main() to:</p>
<pre><code>def main():
choice = int(input("Please enter a number corresponding to the number of faces on your dice. E.x. 4 for 4-Sided: "))
valid_inputs = [4,6,8,10,12]
if choice not in valid_inputs:
print('Valid inputs are: 4,6,8,10,12. Try again.')
main()
cont = input("Would you like to roll the dice? Y or N: ")
while cont=="y" or cont=="Y":
roll = inphandle(choice)
dice(roll)
cont = input("Would you like to roll again? Y or N: ")
while cont=="n" or cont=="N":
easteregg()
cont = input("Do I get bunus points now?!?")
</code></pre>
<p>Just a bit of clarification on the random.randrange:</p>
<pre><code>random,randrange('from','to','increments')
</code></pre>
<p>from is the minimum value and to is the maximum value EXCEPT it self.
so if u want a range of 1 to 4, put 1 to 5.
increment: put 1 for increments of "1", so possible outputs with be 1, 2, 3 or 4 instead of like 1.3252342 or 2.446211</p>
| 0 | 2016-10-13T22:19:18Z | [
"python",
"if-statement",
"random"
] |
server 500 error python (visualstudio) | 40,031,724 | <p>I'm developing a python app using Djgango and I'm getting the server 500 error. I believe my paths are set correctly, the python manage.py runserver returns that the server is running. When I look at developer tools on the page it says "Failed to load resource: the server responded with a status of 404 (not found) <a href="http://localhost:64915/favicon.co" rel="nofollow">http://localhost:64915/favicon.co</a>" and "failed to load resource: the server responded with a status of 500 (internal server error) <a href="http://localhost:64915/" rel="nofollow">http://localhost:64915/</a>." </p>
<p>I don't know what is going on? I'm new to Django coming from asp.net which runs without all the go around. can you help me? Here is my wsgi.py file code. </p>
<pre><code>"""
WSGI config for SmartShopper project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "SmartShopper.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
</code></pre>
<p>here is my settings.py file code</p>
<pre><code>"""
Django settings for SmartShopper project.
"""
from os import path
PROJECT_ROOT = path.dirname(path.abspath(path.dirname(__file__)))
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = (
'localhost',
)
ADMINS = (
# ('Your Name', '[email protected]'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': path.join(PROJECT_ROOT, 'db.sqlite3'),
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
LOGIN_URL = '/login'
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = path.join(PROJECT_ROOT, 'static').replace('\\', '/')
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'n(bd1f1c%e8=_xad02x5qtfn%wgwpi492e$8_erx+d)!tpeoim'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'SmartShopper.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'SmartShopper.wsgi.application'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or
# "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'app',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
# Specify the default test runner.
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
</code></pre>
<p>when running with debug = true it says I have an error in the view.py on line 19 - the render line. This is an autogenerated view by visual studio. I already had to change the url.py to reflect an upated django format. I wonder if you guys can help me spot the same here. here is my code for the views.py.</p>
<pre><code>Definition of views.
"""
from django.shortcuts import render
from django.http import HttpRequest
from django.template import RequestContext
from datetime import datetime
def home(request):
"""Renders the home page."""
assert isinstance(request, HttpRequest)
return render(
request,
'app/index.html',
context_instance = RequestContext(request,
{
'title':'Home Page',
'year':datetime.now().year,
})
)
def contact(request):
"""Renders the contact page."""
assert isinstance(request, HttpRequest)
return render(
request,
'app/contact.html',
context_instance = RequestContext(request,
{
'title':'Contact',
'message':'Your contact page.',
'year':datetime.now().year,
})
)
def about(request):
"""Renders the about page."""
assert isinstance(request, HttpRequest)
return render(
request,
'app/about.html',
context_instance = RequestContext(request,
{
'title':'About',
'message':'Your application description page.',
'year':datetime.now().year,
})
)
</code></pre>
<p>here is the traceback.</p>
<pre><code>Environment:
Request Method: GET
Request URL: http://localhost:64625/
Django Version: 1.10.2
Python Version: 3.5.2
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'app')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\handlers\exception.py" in inner
39. response = get_response(request)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response
249. response = self._get_response(request)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\handlers\base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\core\handlers\base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\USER\Documents\GitHub\Capstone\SmartShopper\SmartShopper\app\views.py" in home
19. 'year':datetime.now().year,
Exception Type: TypeError at /
Exception Value: render() got an unexpected keyword argument 'context_instance'
</code></pre>
| 2 | 2016-10-13T21:59:55Z | 40,032,646 | <p>For <code>render()</code>, you can pass context as a plain dictionary. If you're going to use a keyword argument, use <code>context</code> not <code>context_instance</code> <a href="https://docs.djangoproject.com/en/1.10/topics/http/shortcuts/#render" rel="nofollow">(docs)</a>. That's why you're getting <code>render() got an unexpected keyword argument 'context_instance'</code>:</p>
<pre><code>def home(request):
"""Renders the home page."""
assert isinstance(request, HttpRequest)
return render(request, 'app/index.html', context={'title':'Home Page', 'year':datetime.now().year})
</code></pre>
| 0 | 2016-10-13T23:28:00Z | [
"python",
"django",
"visual-studio"
] |
Python Removing full sentences of words from a novel-long string | 40,031,823 | <p>I have pasted a novel into a text file.
I would like to remove all the lines containing of the following sentences as they keep occurring at the top of each page (just removing their occurrences in those lines will do as well):</p>
<blockquote>
<p>"Thermal Molecular Movement in , Order and Probability" </p>
<p>"Molecular and Ionic Interactions as the Basis for the Formation" </p>
<p>"Interfacial Phenomena and Membranes"</p>
</blockquote>
<p>My first attempt is as follows:</p>
<pre><code>mystring = file.read()
mystring=mystring.strip("Molecular Structure of Biological Systems")
mystring=mystring.strip("Thermal Molecular Movement in , Order and Probability")
mystring=mystring.strip("Molecular and Ionic Interactions as the Basis for the Formation")
mystring=mystring.strip("Interfacial Phenomena and Membranes")
new_file=open("no_refs.txt", "w")
new_file.write(mystring)
file.close()
</code></pre>
<p>However this had no effect on the output text file... the contents were completely unchanged... I find this strange as the following toy example works fine:</p>
<pre><code>>>> "Hello this is a sentence. Please read it".strip("Please read it")
'Hello this is a sentence.'
</code></pre>
<p>As the above didn't work I tried the following instead:</p>
<pre><code>file=open("novel.txt", "r")
mystring = file.readlines()
for lines in mystring:
if "Thermal Molecular Movement in , Order and Probability" in lines:
mystring.replace(lines, "")
elif "Molecular and Ionic Interactions as the Basis for the Formation" in lines:
mystring.replace(lines, "")
elif "Interfacial Phenomena and Membranes" in lines:
mystring.replace(lines, "")
else:
continue
new_file=open("no_refs.txt", "w")
new_file.write(mystring)
new_file.close()
file.close()
</code></pre>
<p>But for this attempt I get this error:</p>
<p>TypeError: expected a string or other character buffer object</p>
| 0 | 2016-10-13T22:06:55Z | 40,031,915 | <ul>
<li>First <code>str.strip()</code> only removes the pattern if found at the <em>start</em> or the <em>end</em> of the string which explains that it seems to work in your test, but in fact is not what you want.</li>
<li>Second, you're trying to perform a replace on a list not on the current line (and you don't assign back the replacement result)</li>
</ul>
<p>Here's a fixed version which successfully removes the patterns of the lines:</p>
<pre><code>with open("novel.txt", "r") as file:
mystring = file.readlines()
for i,line in enumerate(mystring):
for pattern in ["Thermal Molecular Movement in , Order and Probability","Molecular and Ionic Interactions as the Basis for the Formation","Interfacial Phenomena and Membranes"]:
if pattern in line:
mystring[i] = line.replace(pattern,"")
# print the processed lines
print("".join(mystring))
</code></pre>
<p>Note the <code>enumerate</code> construct, which allows to iterate on the values & index. Iterating only on the values would allow to find the patterns but not to modify them in the original list.</p>
<p>Also note the <code>with open</code> construct, that closes the file as soon as you leave the block.</p>
<p>Here's a version which completely removes the lines containing the patterns (hang on, there's some one-liner functional programming stuff in there):</p>
<pre><code>with open("novel.txt", "r") as file:
mystring = file.readlines()
pattern_list = ["Thermal Molecular Movement in , Order and Probability","Molecular and Ionic Interactions as the Basis for the Formation","Interfacial Phenomena and Membranes"]
mystring = "".join(filter(lambda line:all(pattern not in line for pattern in pattern_list),mystring))
# print the processed lines
print(mystring)
</code></pre>
<p>explained: filter list of lines according of the condition: none of the unwanted patterns must be in the line.</p>
| 2 | 2016-10-13T22:15:19Z | [
"python",
"string"
] |
Is it possible to dynamically create a metaclass for a class with several bases, in Python 3? | 40,031,906 | <p>In Python 2, with a trick it is possible to create a class with several bases, although the bases have metaclasses that are <em>not</em> subclass of each other.</p>
<p>The trick is that these metaclasses have themselves a metaclass (name it a "metametaclass"), and this metametaclass provides the metaclasses with a call method that dynamically creates a common sub-metaclass of the base metaclasses, if necessary. Eventually, a class results whose metaclass is the new sub-metaclass. Here is the code:</p>
<pre><code>>>> class MetaMeta(type):
... def __call__(mcls, name, bases, methods):
... metabases = set(type(X) for X in bases)
... metabases.add(mcls)
... if len(metabases) > 1:
... mcls = type(''.join([X.__name__ for X in metabases]), tuple(metabases), {})
... return mcls.__new__(mcls, name, bases, methods)
...
>>> class Meta1(type):
... __metaclass__ = MetaMeta
...
>>> class Meta2(type):
... __metaclass__ = MetaMeta
...
>>> class C1:
... __metaclass__ = Meta1
...
>>> class C2:
... __metaclass__ = Meta2
...
>>> type(C1)
<class '__main__.Meta1'>
>>> type(C2)
<class '__main__.Meta2'>
>>> class C3(C1,C2): pass
...
>>> type(C3)
<class '__main__.Meta1Meta2'>
</code></pre>
<p>This example (of course changing the syntax to <code>class C1(metaclass=Meta1)</code> etc) doesn't work in Python 3.</p>
<p><strong>Question 1:</strong> Do I understand correctly that in Python 2, first <code>C3</code> is constructed, using the metaclass of the first base, and an error would only result if <code>type(C3)</code> were not a common subclass of <code>type(C1)</code> and <code>type(C2)</code>, whereas in Python 3 the error is raised earlier?</p>
<p><strong>Question 2:</strong> (How) Is it possible to make the above example work in Python 3? I did try to use a subclass of <code>abc.ABCMeta</code> as metametaclass, but even though using a custom <code>__subclasscheck__</code> makes <code>issubclass(Meta1, Meta2)</code> return <code>True</code>, the creation of C3 would still result in an error.</p>
<p><strong>Note:</strong> Of course I could make Python 3 happy by statically defining <code>Meta1Meta2</code> and explicitly using it as a metaclass for <code>C3</code>. However, that's not what I want. I want that the common sub-metaclass is created dynamically.</p>
| 3 | 2016-10-13T22:13:40Z | 40,032,153 | <p>Here's an example that shows some options that you have in python3.x. Specifically, <code>C3</code> has a metaclass that is created dynamically, but in a lot of ways, explicitly. <code>C4</code> has a metaclass that is created dynamically within it's metaclass <em>function</em>. <code>C5</code> is just to demonstrate that it too has the same metaclass properies that <code>C4</code> has. (We didn't lose anything through inheritance which <em>can</em> happen if you use a function as a metaclass instead of a <code>type</code> ...)</p>
<pre><code>class Meta1(type):
def foo(cls):
print(cls)
class Meta2(type):
def bar(cls):
print(cls)
class C1(object, metaclass=Meta1):
"""C1"""
class C2(object, metaclass=Meta2):
"""C2"""
class C3(C1, C2, metaclass=type('Meta3', (Meta1, Meta2), {})):
"""C3"""
def meta_mixer(name, bases, dct):
cls = type('MixedMeta', tuple(type(b) for b in bases), dct)
return cls(name, bases, dct)
class C4(C1, C2, metaclass=meta_mixer):
"""C4"""
C1.foo()
C2.bar()
C3.foo()
C3.bar()
C4.foo()
C4.bar()
class C5(C4):
"""C5"""
C5.foo()
C5.bar()
</code></pre>
<p>It should be noted that we're playing with fire here (the same way that you're playing with fire in your original example). There is no guarantee that the metaclasses will play nicely in cooperative multiple inheritance. If they weren't designed for it, chances are that you'll run into bugs using this at <em>some</em> point. If they <em>were</em> designed for it, there'd be no reason to be doing this hacky runtime mixing :-).</p>
| 0 | 2016-10-13T22:36:39Z | [
"python",
"metaclass"
] |
Is it possible to dynamically create a metaclass for a class with several bases, in Python 3? | 40,031,906 | <p>In Python 2, with a trick it is possible to create a class with several bases, although the bases have metaclasses that are <em>not</em> subclass of each other.</p>
<p>The trick is that these metaclasses have themselves a metaclass (name it a "metametaclass"), and this metametaclass provides the metaclasses with a call method that dynamically creates a common sub-metaclass of the base metaclasses, if necessary. Eventually, a class results whose metaclass is the new sub-metaclass. Here is the code:</p>
<pre><code>>>> class MetaMeta(type):
... def __call__(mcls, name, bases, methods):
... metabases = set(type(X) for X in bases)
... metabases.add(mcls)
... if len(metabases) > 1:
... mcls = type(''.join([X.__name__ for X in metabases]), tuple(metabases), {})
... return mcls.__new__(mcls, name, bases, methods)
...
>>> class Meta1(type):
... __metaclass__ = MetaMeta
...
>>> class Meta2(type):
... __metaclass__ = MetaMeta
...
>>> class C1:
... __metaclass__ = Meta1
...
>>> class C2:
... __metaclass__ = Meta2
...
>>> type(C1)
<class '__main__.Meta1'>
>>> type(C2)
<class '__main__.Meta2'>
>>> class C3(C1,C2): pass
...
>>> type(C3)
<class '__main__.Meta1Meta2'>
</code></pre>
<p>This example (of course changing the syntax to <code>class C1(metaclass=Meta1)</code> etc) doesn't work in Python 3.</p>
<p><strong>Question 1:</strong> Do I understand correctly that in Python 2, first <code>C3</code> is constructed, using the metaclass of the first base, and an error would only result if <code>type(C3)</code> were not a common subclass of <code>type(C1)</code> and <code>type(C2)</code>, whereas in Python 3 the error is raised earlier?</p>
<p><strong>Question 2:</strong> (How) Is it possible to make the above example work in Python 3? I did try to use a subclass of <code>abc.ABCMeta</code> as metametaclass, but even though using a custom <code>__subclasscheck__</code> makes <code>issubclass(Meta1, Meta2)</code> return <code>True</code>, the creation of C3 would still result in an error.</p>
<p><strong>Note:</strong> Of course I could make Python 3 happy by statically defining <code>Meta1Meta2</code> and explicitly using it as a metaclass for <code>C3</code>. However, that's not what I want. I want that the common sub-metaclass is created dynamically.</p>
| 3 | 2016-10-13T22:13:40Z | 40,032,300 | <p>In Python3 at the time the metaclass is used it have to be ready, and it can't know about the bases of the final (non-meta) class in order to dynamically create a metaclass at that point. </p>
<p>But ynstead of complicating things (I confess I could not wrap my head around your need for a meta-meta-class) - you can simply use normal class hierarchy with collaborative use of <code>super</code> for your metaclasses.
You can even build the final metaclass dynamically with a simple
call to <code>type</code>: </p>
<pre><code>class A(type):
def __new__(metacls, name, bases,attrs):
attrs['A'] = "Metaclass A processed"
return super().__new__(metacls, name, bases,attrs)
class B(type):
def __new__(metacls, name, bases,attrs):
attrs['B'] = "Metaclass A processed"
return super().__new__(metacls, name, bases,attrs)
C = type("C", (A, B), {})
class Example(metaclass=C): pass
</code></pre>
<p>And:</p>
<pre><code>In[47] :Example.A
Out[47]: 'Metaclass A processed'
In[48]: Example.B
Out[48]: 'Metaclass A processed'
</code></pre>
<p>If your metaclasses are not designed to be collaborative in the first place, it will be very tricky to create any automatic method to combine them - and it would possibly involve monkey-patching the call to <code>type.__new__</code> in some of the metaclasses constructors. </p>
<p>As for not needing to explictly build <code>C</code>, you can use a normal function as the metaclass parameter, that will inspect the bases and build a dynamic derived metaclass. :</p>
<pre><code>def Auto(name, bases, attrs):
basemetaclasses = []
for base in bases:
metacls = type(base)
if isinstance(metacls, type) and metacls is not type and not metacls in basemetaclasses:
basemetaclasses.append(metacls)
dynamic = type(''.join(b.__name__ for b in basemetaclasses), tuple(basemetaclasses), {})
return dynamic(name, bases, attrs)
</code></pre>
<p>(This code is very similar to yours - but I used a three-line explicit <code>for</code> instead of a <code>set</code> in order to preserve the metaclass order - which might matter)</p>
<p>You have them to pass Auto as an metaclass for derived classes, but otherwise it works as in your example:</p>
<pre><code>In [61]: class AA(metaclass=A):pass
In [62]: class BB(metaclass=B):pass
In [63]: class CC(AA,BB): pass
---------------------------------------------------------------------------
...
TypeError: metaclass conflict
...
In [66]: class CC(AA,BB, metaclass=Auto): pass
In [67]: type(CC)
Out[67]: __main__.AB
In [68]: CC.A
Out[68]: 'Metaclass A processed'
</code></pre>
| 1 | 2016-10-13T22:53:02Z | [
"python",
"metaclass"
] |
Is it possible to dynamically create a metaclass for a class with several bases, in Python 3? | 40,031,906 | <p>In Python 2, with a trick it is possible to create a class with several bases, although the bases have metaclasses that are <em>not</em> subclass of each other.</p>
<p>The trick is that these metaclasses have themselves a metaclass (name it a "metametaclass"), and this metametaclass provides the metaclasses with a call method that dynamically creates a common sub-metaclass of the base metaclasses, if necessary. Eventually, a class results whose metaclass is the new sub-metaclass. Here is the code:</p>
<pre><code>>>> class MetaMeta(type):
... def __call__(mcls, name, bases, methods):
... metabases = set(type(X) for X in bases)
... metabases.add(mcls)
... if len(metabases) > 1:
... mcls = type(''.join([X.__name__ for X in metabases]), tuple(metabases), {})
... return mcls.__new__(mcls, name, bases, methods)
...
>>> class Meta1(type):
... __metaclass__ = MetaMeta
...
>>> class Meta2(type):
... __metaclass__ = MetaMeta
...
>>> class C1:
... __metaclass__ = Meta1
...
>>> class C2:
... __metaclass__ = Meta2
...
>>> type(C1)
<class '__main__.Meta1'>
>>> type(C2)
<class '__main__.Meta2'>
>>> class C3(C1,C2): pass
...
>>> type(C3)
<class '__main__.Meta1Meta2'>
</code></pre>
<p>This example (of course changing the syntax to <code>class C1(metaclass=Meta1)</code> etc) doesn't work in Python 3.</p>
<p><strong>Question 1:</strong> Do I understand correctly that in Python 2, first <code>C3</code> is constructed, using the metaclass of the first base, and an error would only result if <code>type(C3)</code> were not a common subclass of <code>type(C1)</code> and <code>type(C2)</code>, whereas in Python 3 the error is raised earlier?</p>
<p><strong>Question 2:</strong> (How) Is it possible to make the above example work in Python 3? I did try to use a subclass of <code>abc.ABCMeta</code> as metametaclass, but even though using a custom <code>__subclasscheck__</code> makes <code>issubclass(Meta1, Meta2)</code> return <code>True</code>, the creation of C3 would still result in an error.</p>
<p><strong>Note:</strong> Of course I could make Python 3 happy by statically defining <code>Meta1Meta2</code> and explicitly using it as a metaclass for <code>C3</code>. However, that's not what I want. I want that the common sub-metaclass is created dynamically.</p>
| 3 | 2016-10-13T22:13:40Z | 40,032,877 | <p>In 95% of cases, it should be possible to use the machinery introduced in Python 3.6 due to <a href="https://www.python.org/dev/peps/pep-0447" rel="nofollow">PEP 447</a> to do <em>most</em> of what metaclasses can do using special new hooks. In that case, you will not need to combine metaclasses since your hooks can call super and their behavior is combined due to inheritance.</p>
<p>As for your general case, I believe that mgilson is right and that you are probably making things too complicated. I have yet to see a case for combining metaclasses that is not covered by PEP 447.</p>
| 0 | 2016-10-13T23:57:28Z | [
"python",
"metaclass"
] |
main() not running functions properly | 40,031,988 | <pre><code>def load():
global name
global count
global shares
global pp
global sp
global commission
name=input("Enter stock name OR -999 to Quit: ")
count =0
while name != '-999':
count=count+1
shares=int(input("Enter number of shares: "))
pp=float(input("Enter purchase price: "))
sp=float(input("Enter selling price: "))
commission=float(input("Enter commission: "))
name=input("\nEnter stock name OR -999 to Quit: ")
totalpr=0
def calc():
global amount_paid
global amount_sold
global profit_loss
global commission_paid_sale
global commission_paid_purchase
global totalpr
amount_paid=shares*pp
commission_paid_purchase=amount_paid*commission
amount_sold=shares*sp
commission_paid_sale=amount_sold*commission
profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase)
totalpr=totalpr+profit_loss
def display():
print("\nStock Name:", name)
print("Amount paid for the stock: $", format(amount_paid, '10,.2f'))
print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f'))
print("Amount the stock sold for: $", format(amount_sold, '10,.2f'))
print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f'))
print("Profit (or loss if negative): $", format(profit_loss, '10,.2f'))
def main():
load()
calc()
display()
main()
print("\nTotal Profit is $", format(totalpr, '10,.2f'))
</code></pre>
<p>I need the main(): to call load(),calc() and display() in that order. However, the program stops after load. The output will merely loop the load without calc or print.</p>
<p>I have been instructed specifically to NOT place calc() and display() in the while loop block, tempting as that may be. Also note, that solves the problem but that is not the solution I am specifically looking for.</p>
<p>What do I need to do to make this program work properly?</p>
<p>OUTPUT SHOULD LOOK LIKE THIS:</p>
<pre><code>Enter stock name OR -999 to Quit: APPLE
Enter number of shares: 10000
Enter purchase price: 400
Enter selling price: 800
Enter commission: 0.04
Stock Name: APPLE
Amount paid for the stock: $ 4,000,000.00
Commission paid on the purchase: $ 160,000.00
Amount the stock sold for: $ 8,000,000.00
Commission paid on the sale: $ 320,000.00
Profit (or loss if negative): $ 3,520,000.00
Enter stock name OR -999 to Quit: FACEBOOK
Enter number of shares: 10000
Enter purchase price: 5
Enter selling price: 500
Enter commission: 0.04
Stock Name: FACEBOOK
Amount paid for the stock: $ 50,000.00
Commission paid on the purchase: $ 2,000.00
Amount the stock sold for: $ 5,000,000.00
Commission paid on the sale: $ 200,000.00
Profit (or loss if negative): $ 4,748,000.00
Enter stock name OR -999 to Quit: -999
Total Profit is $ 14,260,000.00
</code></pre>
<p>HERE IS THE OUTPUT I AM GETTING(THAT I DO NOT WANT):</p>
<pre><code>====== RESTART: C:\Users\Elsa\Desktop\Homework 3, Problem 1.py ======
Enter stock name OR -999 to Quit: YAHOO!
Enter number of shares: 10000
Enter purchase price: 10
Enter selling price: 100
Enter commission: 0.04
Enter stock name OR -999 to Quit: GOOGLE
Enter number of shares: 10000
Enter purchase price: 15
Enter selling price: 150
Enter commission: 0.03
Enter stock name OR -999 to Quit: -999
Stock Name: -999
Amount paid for the stock: $ 150,000.00
Commission paid on the purchase: $ 4,500.00
Amount the stock sold for: $ 1,500,000.00
Commission paid on the sale: $ 45,000.00
Profit (or loss if negative): $ 1,300,500.00
Total Profit is $ 1,300,500.00
>>>
</code></pre>
| -2 | 2016-10-13T22:21:16Z | 40,032,221 | <p>I think this is the solution (one of many) you could probably take:</p>
<pre><code> def load():
shares=int(input("Enter number of shares: "))
pp=float(input("Enter purchase price: "))
sp=float(input("Enter selling price: "))
commission=float(input("Enter commission: "))
return shares, pp, sp, commission
def calc(totalpr, shares, pp, sp, commission):
amount_paid=shares*pp
commission_paid_purchase=amount_paid*commission
amount_sold=shares*sp
commission_paid_sale=amount_sold*commission
profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase)
totalpr=totalpr+profit_loss
return (amount_paid, commission_paid_purchase, amount_sold,
commission_paid_sale, profit_loss, totalpr)
def display(name, amount_paid, commission_paid_purchase,
amount_sold, commission_paid_sale, profit_loss):
print("\nStock Name:", name)
print("Amount paid for the stock: $", format(amount_paid, '10,.2f'))
print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f'))
print("Amount the stock sold for: $", format(amount_sold, '10,.2f'))
print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f'))
print("Profit (or loss if negative): $", format(profit_loss, '10,.2f'))
def main():
totalpr = 0
name=input("Enter stock name OR -999 to Quit: ")
while name != '-999':
shares, pp, sp, commission = load()
am_paid, com_paid_purch, am_sold, \
com_paid_sale, profit_loss, totalpr = calc(totalpr, shares, pp, sp, commission)
display(name, am_paid, com_paid_purch,
am_sold, com_paid_sale, profit_loss)
name=input("Enter stock name OR -999 to Quit: ")
return totalpr
totalpr = main()
print("\nTotal Profit is $", format(totalpr, '10,.2f'))
</code></pre>
| 1 | 2016-10-13T22:44:13Z | [
"python",
"function",
"python-3.x"
] |
How to convert to Time Duration | 40,032,041 | <p>The time duration is being described using four sets of double digits numbers separated with columns such as <code>00:02:01:16</code>.
I know that this represents a time interval or a time duration.
I would like to translate it to a single number that represents a time duration in a more common form such as "120 seconds" or "12 minutes". What approach should be taken here?</p>
| 0 | 2016-10-13T22:25:39Z | 40,032,070 | <pre><code>", ".join((a+b for a,b in zip(time_s.split(":")," hour(s), min(s), second(s), ms".split(","))))
</code></pre>
| 1 | 2016-10-13T22:28:29Z | [
"python"
] |
How to convert to Time Duration | 40,032,041 | <p>The time duration is being described using four sets of double digits numbers separated with columns such as <code>00:02:01:16</code>.
I know that this represents a time interval or a time duration.
I would like to translate it to a single number that represents a time duration in a more common form such as "120 seconds" or "12 minutes". What approach should be taken here?</p>
| 0 | 2016-10-13T22:25:39Z | 40,032,096 | <p>You need to use <code>timedelta</code>.</p>
<pre><code>from datetime import timedelta
</code></pre>
<p>Assume your time 00:02:01:16 is stored in <code>a</code>, which comes from <code>end_time - start_time</code></p>
<p>This will be automatically be a timedelta object. Then you can use <code>a.total_seconds()</code> to get the seconds information.</p>
<p>Check <a href="https://docs.python.org/3.6/library/datetime.html#datetime.timedelta.total_seconds" rel="nofollow">Timedelta Documentation</a> for more usage and examples</p>
| 0 | 2016-10-13T22:31:13Z | [
"python"
] |
Python Guess game how to repeat | 40,032,043 | <p>I have been working on this guessing game but i just cant get it to repeat the game when the player says yes. The game gives you 5 attempts to guess the number that it thought of and then after it asks you if you would like to play again but when you say 'YES' it just keeps repeating the sentence and when you say 'NO' it does what its supposed to which is break the code</p>
<pre><code>def main():
game = "your game"
print(game)
play_again()
import random #imports random number function
print("Welcome to the number guessing game!")
counter=1 #This means that the score is set to 0
number = int(random.randint(1,10))
while counter >0 and counter <=5:
guess=int(input("Try and guess the number\n"))#tells the user to try and guess the number
if guess!=number and guess>number:
print("wrong number! Try again you are too high")#tells you that you were wrong and that that you were too high
counter=counter+1#adds 1 count for every attempt it took you to guess the number
elif guess!=number and guess<number:
print("wrong number! Try again you are too low!")#tells you that you were wrong and tells you that you were too low
counter=counter+1#adds 1 count for every attempt it took you to guess the number
else:
print("Well done! You have guessed the number i was thinking of! The number was ",number)#Prints this out when you guessed the number
print("it took you ",counter, "attempts!")#tells you how many attempts it took you to guess the number
if counter==2:
print("4 attempts left before program ends")
if counter==3:
print("3 attempts left before program ends")
if counter==4:
print("2 attempts left before program ends")
if counter==5:
print("1 attempts left before program ends")
def play_again():
while True:
play_again = input("Would you like to play again?(yes or no) : ")
if play_again == "yes":
main()
if play_again == "no":
exit()
else:
print("I'm sorry I could not recognize what you entered")
main()
</code></pre>
| 0 | 2016-10-13T22:26:04Z | 40,032,304 | <p>It's because your game code isn't in the function. Try it in this manner:</p>
<pre><code><import statements>
def game():
<insert all game code>
def main():
while True:
play_again = input("Would you like to play again?(yes or no) : ")
if play_again == "yes":
game()
if play_again == "no":
exit()
else:
print("I'm sorry I could not recognize what you entered")
</code></pre>
| 1 | 2016-10-13T22:53:42Z | [
"python",
"helper",
"python-3.5.2"
] |
Python Guess game how to repeat | 40,032,043 | <p>I have been working on this guessing game but i just cant get it to repeat the game when the player says yes. The game gives you 5 attempts to guess the number that it thought of and then after it asks you if you would like to play again but when you say 'YES' it just keeps repeating the sentence and when you say 'NO' it does what its supposed to which is break the code</p>
<pre><code>def main():
game = "your game"
print(game)
play_again()
import random #imports random number function
print("Welcome to the number guessing game!")
counter=1 #This means that the score is set to 0
number = int(random.randint(1,10))
while counter >0 and counter <=5:
guess=int(input("Try and guess the number\n"))#tells the user to try and guess the number
if guess!=number and guess>number:
print("wrong number! Try again you are too high")#tells you that you were wrong and that that you were too high
counter=counter+1#adds 1 count for every attempt it took you to guess the number
elif guess!=number and guess<number:
print("wrong number! Try again you are too low!")#tells you that you were wrong and tells you that you were too low
counter=counter+1#adds 1 count for every attempt it took you to guess the number
else:
print("Well done! You have guessed the number i was thinking of! The number was ",number)#Prints this out when you guessed the number
print("it took you ",counter, "attempts!")#tells you how many attempts it took you to guess the number
if counter==2:
print("4 attempts left before program ends")
if counter==3:
print("3 attempts left before program ends")
if counter==4:
print("2 attempts left before program ends")
if counter==5:
print("1 attempts left before program ends")
def play_again():
while True:
play_again = input("Would you like to play again?(yes or no) : ")
if play_again == "yes":
main()
if play_again == "no":
exit()
else:
print("I'm sorry I could not recognize what you entered")
main()
</code></pre>
| 0 | 2016-10-13T22:26:04Z | 40,032,455 | <p>There's a few problems with your code that I'd like to point out.
The main one being that your game does not run again when typing yes. All it will do is run <code>main()</code> which will print <code>your game</code> and then ask you if you want to retry once again. It's easier if you put your game inside a definition that way you can call it whenever necessary.
<p> Also, I don't know if it's just me, but if you guess the correct number, it will <em>still</em> ask you to guess a number. You need to exit your loop by putting your <code>play_again()</code> method in your <code>else</code> block.
<p> Below is the code. I've polished it up a little just for optimization. </p>
<pre><code>import random #imports random number function
def main():
print("Welcome to the number guessing game!")
game = "your game"
print(game)
run_game()
play_again()
def run_game():
counter = 1
number = random.randint(1, 10)
while counter > 0 and counter <= 5:
guess=int(input("Try and guess the number\n"))#tells the user to try and guess the number
if guess!=number and guess > number:
print("wrong number! Try again you are too high")#tells you that you were wrong and that that you were too high
counter=counter+1#adds 1 count for every attempt it took you to guess the number
elif guess != number and guess < number:
print("wrong number! Try again you are too low!")#tells you that you were wrong and tells you that you were too low
counter=counter+1#adds 1 count for every attempt it took you to guess the number
else:
print("Well done! You have guessed the number i was thinking of! The number was " + str(number))#Prints this out when you guessed the number
print("it took you " + str(counter) + " attempts!")#tells you how many attempts it took you to guess the number
play_again()
if counter == 2:
print("4 attempts left before program ends")
if counter == 3:
print("3 attempts left before program ends")
if counter == 4:
print("2 attempts left before program ends")
if counter == 5:
print("1 attempts left before program ends")
def play_again():
while True:
retry = input("Would you like to play again?(yes or no) : ")
if retry == "yes":
main()
if retry == "no":
exit()
else:
print("I'm sorry I could not recognize what you entered")
main()
</code></pre>
| 1 | 2016-10-13T23:07:32Z | [
"python",
"helper",
"python-3.5.2"
] |
How to insert sleep into a list | 40,032,081 | <p>I am looking to create just a small module to implement the ability to text scroll. I've tried a few things so far and this is what I'm sitting on:</p>
<pre><code>from time import sleep
def text_scroll(x):
x = x.split()
#here is where I'd like to add the sleep function
x = " ".join(x)
print x
text_scroll("hello world.")
</code></pre>
<p>With all this I am hoping to have it print "hello", sleep for a second, "world". The best I've gotten so far is it returning None instead of actually pausing.</p>
| -1 | 2016-10-13T22:29:34Z | 40,032,103 | <pre><code>for word in x.split():
print word,
time.sleep(1)
</code></pre>
<p>Comma prevents <em>print</em> from adding line feed to your output</p>
| -2 | 2016-10-13T22:32:08Z | [
"python",
"sleep"
] |
How to insert sleep into a list | 40,032,081 | <p>I am looking to create just a small module to implement the ability to text scroll. I've tried a few things so far and this is what I'm sitting on:</p>
<pre><code>from time import sleep
def text_scroll(x):
x = x.split()
#here is where I'd like to add the sleep function
x = " ".join(x)
print x
text_scroll("hello world.")
</code></pre>
<p>With all this I am hoping to have it print "hello", sleep for a second, "world". The best I've gotten so far is it returning None instead of actually pausing.</p>
| -1 | 2016-10-13T22:29:34Z | 40,032,204 | <p>Try the following code:</p>
<pre><code>from time import sleep
from sys import stdout
def text_scroll(text):
words = text.split()
for w in words:
print w,
stdout.flush()
sleep(1)
</code></pre>
<p>The comma at the end of the print does not add new line '\n'.
The flush() function flushes the word into the screen (standard output).</p>
| 2 | 2016-10-13T22:41:52Z | [
"python",
"sleep"
] |
How to insert sleep into a list | 40,032,081 | <p>I am looking to create just a small module to implement the ability to text scroll. I've tried a few things so far and this is what I'm sitting on:</p>
<pre><code>from time import sleep
def text_scroll(x):
x = x.split()
#here is where I'd like to add the sleep function
x = " ".join(x)
print x
text_scroll("hello world.")
</code></pre>
<p>With all this I am hoping to have it print "hello", sleep for a second, "world". The best I've gotten so far is it returning None instead of actually pausing.</p>
| -1 | 2016-10-13T22:29:34Z | 40,032,208 | <p>If it is python 2.7, you can do the following, which is what volcano suggested.</p>
<pre><code>from time import sleep
def text_scroll(x):
for word in x.split():
print word,
sleep(1)
text_scroll("Hello world")
</code></pre>
<p>This works because it splits the input into individual words and then prints them, sleeping between each word. The <code>print word,</code> is python 2.7 for print <code>word</code>, without a newline <code>,</code>.</p>
<p>Yours doesn't work for several reasons:</p>
<pre><code>def text_scroll(x):
x = x.split()
#here is where I'd like to add the sleep function
x = " ".join(x)
</code></pre>
<p>this function doesn't do anything with the variable that it makes, and it mangles it:</p>
<pre><code>def text_scroll(x):
x = x.split() # x = ["Hello", "world"]
#here is where I'd like to add the sleep function
x = " ".join(x) # x = "Hello world"
</code></pre>
<p>It doesn't actually do anything with the result, so it gets thrown away. But it's also important to realize that because it is a <code>def</code>, it doesn't execute until it is called.</p>
<p>when you <code>print x</code>, <code>x</code> hasn't been set, so it should give you a <code>NameError: name 'x' is not defined</code></p>
<p>Finally, you call your function <code>text_scroll("hello world.")</code> which doesn't output anything, and it finishes.</p>
| 0 | 2016-10-13T22:42:54Z | [
"python",
"sleep"
] |
Regex extract everything after and before a specific text | 40,032,127 | <p>I need to extract from this:</p>
<pre><code><meta content=",\n\n\nÃscar Mauricio Lizcano Arango,\n\n\n\n\n\n\n\nBerner León Zambrano Eraso,\n\n\n\n\n" name="keywords"><meta content="Congreso Visible - Toda la información sobre el Congreso Colombiano en un solo lugar" property="og:title"/><meta content="/static/img/logo-fb.jpg"
</code></pre>
<p>The names shown in there: Ãscar Mauricio Lizcano Arango and Berner León Zambrano Eraso.</p>
<p>So it would be something like everything after </p>
<pre><code><meta content="
</code></pre>
<p>and before </p>
<pre><code>name="keywords".
</code></pre>
<p>Also, using python, I would like to put every name as an element of a list. I would repeat this many times for different strings and the amount of names vary (it could be 4 names instead of 2 as in this case).</p>
<p>How could I do this?</p>
| -1 | 2016-10-13T22:34:12Z | 40,032,286 | <p>I was able to do it by doing</p>
<pre><code>re.findall(r'(?<=content=",)[^.]+(?=name=)', names)
</code></pre>
| 1 | 2016-10-13T22:51:52Z | [
"python",
"regex"
] |
Regex extract everything after and before a specific text | 40,032,127 | <p>I need to extract from this:</p>
<pre><code><meta content=",\n\n\nÃscar Mauricio Lizcano Arango,\n\n\n\n\n\n\n\nBerner León Zambrano Eraso,\n\n\n\n\n" name="keywords"><meta content="Congreso Visible - Toda la información sobre el Congreso Colombiano en un solo lugar" property="og:title"/><meta content="/static/img/logo-fb.jpg"
</code></pre>
<p>The names shown in there: Ãscar Mauricio Lizcano Arango and Berner León Zambrano Eraso.</p>
<p>So it would be something like everything after </p>
<pre><code><meta content="
</code></pre>
<p>and before </p>
<pre><code>name="keywords".
</code></pre>
<p>Also, using python, I would like to put every name as an element of a list. I would repeat this many times for different strings and the amount of names vary (it could be 4 names instead of 2 as in this case).</p>
<p>How could I do this?</p>
| -1 | 2016-10-13T22:34:12Z | 40,032,594 | <p>This might help you:</p>
<pre><code># -*- coding: utf-8 -*-
import re
or_str = '<meta content=",\n\n\nÃscar Mauricio Lizcano Arango,\n\n\n\n\n\n\n\nBerner León Zambrano Eraso,\n\n\n\n\n" name="keywords"><meta content="Congreso Visible - Toda la información sobre el Congreso Colombiano en un solo lugar" property="og:title"/><meta content="/static/img/logo-fb.jpg"'
new_str = or_str.replace("\n","")
li = re.findall('meta content=",(.*)" name="keywords"', new_str);
new_str = ''.join(li)
print re.findall('(.*?),',new_str)
</code></pre>
<p>I used <code>replace()</code> method to change all the newline characters <code>\n</code> to <code>NULL</code>. <br/>Then, I used <code>findall</code> to look for the names and put it in a list, and again used <code>findall</code> to store every name as an element of a list, since <code>findall</code> returns a list.</p>
| 1 | 2016-10-13T23:23:07Z | [
"python",
"regex"
] |
Find max UDP payload -- python socket send/sendto | 40,032,171 | <p>How can I find the maximum length of a UDP payload in Python (Python 2), preferably platform-independent?</p>
<p>Specifically, I want to avoid <code>[Errno 90] Message too long</code> AKA <code>errno.EMSGSIZE</code>.</p>
<h3>Background</h3>
<ul>
<li>The maximum allowed by the UDP packet format <a href="http://stackoverflow.com/a/9853152/461834">is 65536</a>).</li>
<li><p>The maximum allowed by the IPv4 packet format <a href="http://stackoverflow.com/a/1098940/461834">seems to be 65507</a>.</p></li>
<li><p>Yet it seems that <a href="http://stackoverflow.com/a/35335138/461834">some systems set the limit lower</a>.</p></li>
</ul>
<h3>What I am not asking</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/1098897/what-is-the-largest-safe-udp-packet-size-on-the-internet">What is the largest Safe UDP Packet Size on the Internet</a>?</li>
<li>What is the maximum UDP payload that can fit in one IPv4 datagram?</li>
<li>What is the maximum UDP payload that can fit in one Ethernet frame?</li>
</ul>
<h3>Demo Code</h3>
<p>To see the error in action:</p>
<pre><code>import socket
msg_len = 65537 # Not even possible!
ip_address = "127.0.0.1"
port = 5005
msg = "A" * msg_len
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(msg, (ip_address, port))
</code></pre>
| 0 | 2016-10-13T22:38:30Z | 40,033,837 | <p>Well, there's always the try-it-and-see approach... I wouldn't call this elegant, but it is platform-independent:</p>
<pre><code>import socket
def canSendUDPPacketOfSize(sock, packetSize):
ip_address = "127.0.0.1"
port = 5005
try:
msg = "A" * packetSize
if (sock.sendto(msg, (ip_address, port)) == len(msg)):
return True
except:
pass
return False
def get_max_udp_packet_size_aux(sock, largestKnownGoodSize, smallestKnownBadSize):
if ((largestKnownGoodSize+1) == smallestKnownBadSize):
return largestKnownGoodSize
else:
newMidSize = int((largestKnownGoodSize+smallestKnownBadSize)/2)
if (canSendUDPPacketOfSize(sock, newMidSize)):
return get_max_udp_packet_size_aux(sock, newMidSize, smallestKnownBadSize)
else:
return get_max_udp_packet_size_aux(sock, largestKnownGoodSize, newMidSize)
def get_max_udp_packet_size():
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ret = get_max_udp_packet_size_aux(sock, 0, 65508)
sock.close()
return ret
print "Maximum UDP packet send size is", get_max_udp_packet_size()
</code></pre>
| 1 | 2016-10-14T02:13:25Z | [
"python",
"sockets",
"networking",
"udp"
] |
Find max UDP payload -- python socket send/sendto | 40,032,171 | <p>How can I find the maximum length of a UDP payload in Python (Python 2), preferably platform-independent?</p>
<p>Specifically, I want to avoid <code>[Errno 90] Message too long</code> AKA <code>errno.EMSGSIZE</code>.</p>
<h3>Background</h3>
<ul>
<li>The maximum allowed by the UDP packet format <a href="http://stackoverflow.com/a/9853152/461834">is 65536</a>).</li>
<li><p>The maximum allowed by the IPv4 packet format <a href="http://stackoverflow.com/a/1098940/461834">seems to be 65507</a>.</p></li>
<li><p>Yet it seems that <a href="http://stackoverflow.com/a/35335138/461834">some systems set the limit lower</a>.</p></li>
</ul>
<h3>What I am not asking</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/1098897/what-is-the-largest-safe-udp-packet-size-on-the-internet">What is the largest Safe UDP Packet Size on the Internet</a>?</li>
<li>What is the maximum UDP payload that can fit in one IPv4 datagram?</li>
<li>What is the maximum UDP payload that can fit in one Ethernet frame?</li>
</ul>
<h3>Demo Code</h3>
<p>To see the error in action:</p>
<pre><code>import socket
msg_len = 65537 # Not even possible!
ip_address = "127.0.0.1"
port = 5005
msg = "A" * msg_len
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(msg, (ip_address, port))
</code></pre>
| 0 | 2016-10-13T22:38:30Z | 40,033,932 | <p>Some of your premises need a minor correction. </p>
<p>As a result of the IP header containing a 16 bit field for length, the largest size an IPv4 message can be is <code>65535</code> bytes And that includes the IP header itself.</p>
<p>The IP packet itself has at least a 20 byte header. Hence 65535 - 20 == <code>65515</code> is the largest size of the <strong>payload</strong> of an IP message. The payload can be a UDP datagram.</p>
<p>The UDP datagram itself is typically an 8 byte header. Hence 65515 - 8 == <code>65507</code>. So even if the UDP header could theoretically contain an amount higher than 65507 in its own length field, the IPv4 message can't contain it.</p>
<p>But if your system adds any more headers to the IP header (option fields via socket ioctls or whatever), then the limit of the UDP application payload will get reduced by a corresponding amount.</p>
<p>In practice, any IP message above the MTU size of your network adapter (~1500 bytes), will trigger the UDP packet to undergo IP fragmentation. So if your ethernet card has a 1500 byte message size, a a UDP datagram containing 65507 bytes of application data will get fragmented into approximately 43 separate ethernet frames. Each frame is a fragmented IP packet containing a subset of the UDP bytes, but with a seperate header. When all the IP fragments are received on the remote end, it logically gets delivered to the application as 65507 byte datagram. Fragmentation is transparent to applications.</p>
<p>I would suggest running your code with Wireshark and send to a real IP address out of the network. You can observe and study how IP fragmentation works.</p>
| 2 | 2016-10-14T02:24:12Z | [
"python",
"sockets",
"networking",
"udp"
] |
What am I doing wrong, python loop not repeating? | 40,032,219 | <p>I just had this working, and now, for the life of me, I cannot get the loop to continue, as it only produces the outcome of the first input. Where did I go wrong? I know im an amateur, but whatever help you might have would be awesome! Thanks. </p>
<pre><code>sequence = open('sequence.txt').read().replace('\n','')
enzymes = {}
fh = open('enzymes.txt')
print('Restriction Enzyme Counter')
inez = input('Enter a Restricting Enzyme: ')
def servx():
for line in fh:
(name, site, junk, junk) = line.split()
enzymes[name] = site
if inez in fh:
xcr = site
print('Active Bases:', site)
for line in sequence.split():
if xcr in line:
bs = (sequence.count(xcr))
print('Enzyme', inez, 'appears', bs, 'times in Sequence.')
servx()
def servy():
fh.seek(0);
qust = input('Find another Enzyme? [Yes/No]: ')
if qust == 'Yes':
inez = input('Enter a Restricting Enzyme: ')
servx()
servy()
elif qust == 'No':
print('Thanks!')
elif qust != 'Yes''No':
print('Error, Unknown Command')
servy()
fh.close()
</code></pre>
| 2 | 2016-10-13T22:43:55Z | 40,032,656 | <p>This an issue of scope. By default Python variables are local in scope. In servy, where you set inez to a new value, Python assumes this is a new local variable because you have not specifically declared it to be global. Therefore when you call serx the second time, the global variable inez is unchanged. Here is a simpler example to illustrate the issue.</p>
<pre><code>a = "hello"
def b():
print(a)
def c():
a = "world"
print(a)
b()
b()
c()
</code></pre>
<p>That is a nasty bug that has tripped me up many times. One of the great reasons to avoid global variables if at all possible.</p>
<p>There are other issues with the above code, such as using recursion where a loop should probably be used. I would suggest reading about python's scoping rules (<a href="http://stackoverflow.com/questions/291978/short-description-of-scoping-rules">Short Description of Scoping Rules</a>), try restructuring to avoid recursion and then posting your code on <a href="http://codereview.stackexchange.com">http://codereview.stackexchange.com</a>.</p>
| 2 | 2016-10-13T23:29:15Z | [
"python"
] |
spark dataframe keep most recent record | 40,032,276 | <p>I have a dataframe similar to: </p>
<pre><code>id | date | value
--- | ---------- | ------
1 | 2016-01-07 | 13.90
1 | 2016-01-16 | 14.50
2 | 2016-01-09 | 10.50
2 | 2016-01-28 | 5.50
3 | 2016-01-05 | 1.50
</code></pre>
<p>I am trying to keep the most recent values for each id, like this:</p>
<pre><code>id | date | value
--- | ---------- | ------
1 | 2016-01-16 | 14.50
2 | 2016-01-28 | 5.50
3 | 2016-01-05 | 1.50
</code></pre>
<p>I have tried sort by date desc and after drop duplicates:</p>
<pre><code>new_df = df.orderBy(df.date.desc()).dropDuplicates(['id'])
</code></pre>
<p>My questions are, <code>dropDuplicates()</code> will keep the first duplicate value that it finds? and is there a better way to accomplish what I want to do? By the way, I'm using python.</p>
<p>Thank you.</p>
| 0 | 2016-10-13T22:50:34Z | 40,038,443 | <p>The window operator as suggested works very well to solve this problem:</p>
<pre><code>from datetime import date
rdd = sc.parallelize([
[1, date(2016, 1, 7), 13.90],
[1, date(2016, 1, 16), 14.50],
[2, date(2016, 1, 9), 10.50],
[2, date(2016, 1, 28), 5.50],
[3, date(2016, 1, 5), 1.50]
])
df = rdd.toDF(['id','date','price'])
df.show()
+---+----------+-----+
| id| date|price|
+---+----------+-----+
| 1|2016-01-07| 13.9|
| 1|2016-01-16| 14.5|
| 2|2016-01-09| 10.5|
| 2|2016-01-28| 5.5|
| 3|2016-01-05| 1.5|
+---+----------+-----+
df.registerTempTable("entries") // Replaced by createOrReplaceTempView in Spark 2.0
output = sqlContext.sql('''
SELECT
*
FROM (
SELECT
*,
dense_rank() OVER (PARTITION BY id ORDER BY date DESC) AS rank
FROM entries
) vo WHERE rank = 1
''');
output.show();
+---+----------+-----+----+
| id| date|price|rank|
+---+----------+-----+----+
| 1|2016-01-16| 14.5| 1|
| 2|2016-01-28| 5.5| 1|
| 3|2016-01-05| 1.5| 1|
+---+----------+-----+----+
</code></pre>
| 2 | 2016-10-14T08:25:33Z | [
"python",
"apache-spark"
] |
Pandas sort dataframe by column with strings and integers | 40,032,341 | <p>I have a dataframe with a column containing both integers and strings:</p>
<pre><code>>>> df = pd.DataFrame({'a':[2,'c',1,10], 'b':[5,4,0,6]})
>>> df
a b
0 2 5
1 c 4
2 1 0
3 10 6
</code></pre>
<p>I want to sort the dataframe by column a, treating the strings and integers separately, with strings first:</p>
<pre><code>>>> df
a b
1 c 4
2 1 0
0 2 5
3 10 6
</code></pre>
<p>...but Python doesn't allow comparing integers to strings.</p>
<pre><code>TypeError: unorderable types: int() > str()
</code></pre>
<p>If I first convert all the integers to strings, I don't get what I want:</p>
<pre><code>>>> df.a = df.a.astype(str)
>>> df.sort(columns='a')
a b
0 1 0
3 10 6
2 2 5
1 c 4
</code></pre>
<p>Does anyone know of a one-line way to tell Pandas that I want it to sort strings first, then integers, without first breaking the dataframe into pieces?</p>
| 0 | 2016-10-13T22:57:08Z | 40,032,613 | <p>One option would be to group the data frame by the data type of column <code>a</code> and then sort each group separately:</p>
<pre><code>df.groupby(df.a.apply(type) != str).apply(lambda g: g.sort('a')).reset_index(drop = True)
</code></pre>
<p><a href="https://i.stack.imgur.com/cwuCV.png" rel="nofollow"><img src="https://i.stack.imgur.com/cwuCV.png" alt="enter image description here"></a></p>
| 1 | 2016-10-13T23:24:53Z | [
"python",
"sorting",
"pandas"
] |
Pandas Date Range Monthly on Specific Day of Month | 40,032,371 | <p>In Pandas, I know you can use anchor offsets to specify more complicated reucrrences:
<a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#anchored-offset" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/timeseries.html#anchored-offset</a></p>
<p>I want to specify a date_range such that it is monthly on the nth day of each month. What is the best syntax to do that with? I'm imaginging something similar to this which specifies a recurrence every 2 weeks on Friday:</p>
<pre><code>schedule = pd.date_range(start=START_STR, periods=26, freq="2W-FRI")
</code></pre>
| 0 | 2016-10-13T22:59:45Z | 40,040,932 | <p>IIUC you can do it this way:</p>
<pre><code>In [18]: pd.DataFrame(pd.date_range('2016-01-01', periods=10, freq='MS') + pd.DateOffset(days=26), columns=['Date'])
Out[18]:
Date
0 2016-01-27
1 2016-02-27
2 2016-03-27
3 2016-04-27
4 2016-05-27
5 2016-06-27
6 2016-07-27
7 2016-08-27
8 2016-09-27
9 2016-10-27
</code></pre>
| 1 | 2016-10-14T10:27:24Z | [
"python",
"datetime",
"pandas"
] |
I need to vectorize the following in order for the code can run faster | 40,032,382 | <p>This portion I was able to vectorize and get rid of a nested loop.</p>
<pre><code>def EMalgofast(obsdata, beta, pjt):
n = np.shape(obsdata)[0]
g = np.shape(pjt)[0]
zijtpo = np.zeros(shape=(n,g))
for j in range(g):
zijtpo[:,j] = pjt[j]*stats.expon.pdf(obsdata,scale=beta[j])
zijdenom = np.sum(zijtpo, axis=1)
zijtpo = zijtpo/np.reshape(zijdenom, (n,1))
pjtpo = np.mean(zijtpo, axis=0)
</code></pre>
<p>I wasn't able to vectorize the portion below. I need to figure that out</p>
<pre><code> betajtpo_1 = []
for j in range(g):
num = 0
denom = 0
for i in range(n):
num = num + zijtpo[i][j]*obsdata[i]
denom = denom + zijtpo[i][j]
betajtpo_1.append(num/denom)
betajtpo = np.asarray(betajtpo_1)
return(pjtpo,betajtpo)
</code></pre>
| 0 | 2016-10-13T23:00:30Z | 40,034,157 | <p>I'm guessing Python is not your first programming language based on what I see. The reason I'm saying this is that in python, normally we don't have to deal with manipulating indexes. You act directly on the value or the key returned. Make sure not to take this as an offense, I do the same coming from C++ myself. It's a hard to remove habits ;).</p>
<p>If you're interested in performance, there is a good presentation by Raymond Hettinger on what to do in Python to be optimised and beautiful :
<a href="https://www.youtube.com/watch?v=OSGv2VnC0go" rel="nofollow">https://www.youtube.com/watch?v=OSGv2VnC0go</a></p>
<p>As for the code you need help with, is this helping for you? It's unfortunatly untested as I need to leave...
ref:
<a href="http://stackoverflow.com/questions/6967463/iterating-over-a-numpy-array">Iterating over a numpy array</a></p>
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.true_divide.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.true_divide.html</a></p>
<pre><code> def EMalgofast(obsdata, beta, pjt):
n = np.shape(obsdata)[0]
g = np.shape(pjt)[0]
zijtpo = np.zeros(shape=(n,g))
for j in range(g):
zijtpo[:,j] = pjt[j]*stats.expon.pdf(obsdata,scale=beta[j])
zijdenom = np.sum(zijtpo, axis=1)
zijtpo = zijtpo/np.reshape(zijdenom, (n,1))
pjtpo = np.mean(zijtpo, axis=0)
betajtpo_1 = []
#manipulating an array of numerator and denominator instead of creating objects each iteration
num=np.zeros(shape=(g,1))
denom=np.zeros(shape=(g,1))
#generating the num and denom real value for the end result
for (x,y), value in numpy.ndenumerate(zijtpo):
num[x],denom[x] = num[x] + value *obsdata[y],denom[x] + value
#dividing all at once after instead of inside the loop
betajtpo_1= np.true_divide(num/denom)
betajtpo = np.asarray(betajtpo_1)
return(pjtpo,betajtpo)
</code></pre>
<p>Please leave me some feedback !</p>
<p>Regards,</p>
<p>Eric Lafontaine</p>
| 0 | 2016-10-14T02:51:47Z | [
"python",
"python-2.7",
"python-3.x",
"numpy"
] |
Python(jupyter) for prime numbers | 40,032,408 | <pre><code>primes=[]
for i in range(3,6):
is_prime=True
for j in range(2,i):
if i%j ==0:
is_prime=False
if is_prime=True:
primes= primes + [i]
primes
</code></pre>
<p>The code seems logical to me but I keep getting a syntax error at the 2nd last sentence <code>if is_prime=True</code>.</p>
| 2 | 2016-10-13T23:02:51Z | 40,032,433 | <p><code>=</code> is the assignment operator. For equality checks, you should use the <code>==</code> operator:</p>
<pre><code>if is_prime == True:
</code></pre>
<p>Or better yet, since <code>is_prime</code> is a boolean expression in its own right, just evaluate it:</p>
<pre><code>if is_prime:
</code></pre>
| 2 | 2016-10-13T23:05:38Z | [
"python",
"syntax-error"
] |
Selecting all elements that meet a criteria using selenium (python) | 40,032,560 | <p>Using selenium, is there a way to have the script pick out elements that meet a certain criteria? </p>
<p>What I'm exactly trying to do is have selenium select all Twitch channels that have more than X viewers. If you inspect element, you find this: </p>
<pre><code><p class="info"
562
viewers on
<a class="js-profile-link" href="/hey_jase/profile"
data-tt_content="live_channel" data-tt_content_index="1"
data-tt_medium="twitch_directory" data-ember-action="1471">
Hey_Jase
</a>
</p>
</code></pre>
| 0 | 2016-10-13T23:19:01Z | 40,032,691 | <p>It is hard to give an exact code as we only get a small sample of the HTML, but this should work if you tweak it a bit.</p>
<pre><code>from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://www.website.com')
source = driver.page_source
location = source.find('<p class="info"')
source = source[location+16:] #adjust the +16 to maybe +15 or w/e depending on the exact source page you get
location_second = source.find('viewers on') #assuming there is a space between the actual number of viewers and the
source = int(source[:location_second-1]) #adjust the -1 to maybe -2 or w/e depending on the exact source page you get
if source > x: # replace x with whatever number is your minimum viewers
driver.find_element_by_class_name('js-profile-link') #might need to use x-path if you have multiple instances of the same class name
</code></pre>
| 0 | 2016-10-13T23:32:58Z | [
"python",
"selenium",
"selenium-webdriver"
] |
Selecting all elements that meet a criteria using selenium (python) | 40,032,560 | <p>Using selenium, is there a way to have the script pick out elements that meet a certain criteria? </p>
<p>What I'm exactly trying to do is have selenium select all Twitch channels that have more than X viewers. If you inspect element, you find this: </p>
<pre><code><p class="info"
562
viewers on
<a class="js-profile-link" href="/hey_jase/profile"
data-tt_content="live_channel" data-tt_content_index="1"
data-tt_medium="twitch_directory" data-ember-action="1471">
Hey_Jase
</a>
</p>
</code></pre>
| 0 | 2016-10-13T23:19:01Z | 40,032,889 | <p>First of all, you can find all twitch channel links. Then, filter them based on the view count.</p>
<p>Something along these lines:</p>
<pre><code>import re
from selenium import webdriver
THRESHOLD = 100
driver = webdriver.Firefox()
driver.get("url")
pattern = re.compile(r"(\d+)\s+viewers on")
for link in driver.find_elements_by_css_selector("p.info a[data-tt_content=live_channel]"):
text = link.find_element_by_xpath("..").text # get to the p parent element
match = pattern.search(text) # extract viewers count
if match:
viewers_count = int(match.group(1))
if viewers_count >= THRESHOLD:
print(link.text, viewers_count)
</code></pre>
| 1 | 2016-10-13T23:59:58Z | [
"python",
"selenium",
"selenium-webdriver"
] |
strip whitespace in pandas MultiIndex index columns values | 40,032,612 | <p>i have a MultiIndex dataframe of mix datatypes. One of the index columns values has trailing whitespaces. How can i strip these trailing whitespace for the index columns. here is the sample code:</p>
<pre><code>import pandas as pd
idx = pd.MultiIndex.from_product([['1.0'],['NY ','CA ']], names=['country_code','state'])
df = pd.DataFrame({'temp':['78','85']},index = idx)
</code></pre>
<p>One solution is to reset the index, strip the whitespaces for the desired column and again set index. Something like below:</p>
<pre><code>df = df.reset_index()
df['state'] = df['state'].str.strip()
df = df.set_index(['country_code','state'],drop=True)
</code></pre>
<p>but this is a roundabout way, is there a more direct way to strip the whitespaces in the index itself?</p>
| 0 | 2016-10-13T23:24:51Z | 40,032,663 | <p>You can use <code>.index.set_levels()</code> and <code>.index.get_level_values()</code> to manipulate the index at a specific level:</p>
<pre><code>df.index.set_levels(df.index.get_level_values(level = 1).str.strip(),
level = 1, inplace=True)
df.index
# MultiIndex(levels=[['1.0'], ['NY', 'CA']],
# labels=[[0, 0], [1, 0]],
# names=['country_code', 'state'])
</code></pre>
| 1 | 2016-10-13T23:30:01Z | [
"python",
"string",
"pandas",
"multi-index"
] |
strip whitespace in pandas MultiIndex index columns values | 40,032,612 | <p>i have a MultiIndex dataframe of mix datatypes. One of the index columns values has trailing whitespaces. How can i strip these trailing whitespace for the index columns. here is the sample code:</p>
<pre><code>import pandas as pd
idx = pd.MultiIndex.from_product([['1.0'],['NY ','CA ']], names=['country_code','state'])
df = pd.DataFrame({'temp':['78','85']},index = idx)
</code></pre>
<p>One solution is to reset the index, strip the whitespaces for the desired column and again set index. Something like below:</p>
<pre><code>df = df.reset_index()
df['state'] = df['state'].str.strip()
df = df.set_index(['country_code','state'],drop=True)
</code></pre>
<p>but this is a roundabout way, is there a more direct way to strip the whitespaces in the index itself?</p>
| 0 | 2016-10-13T23:24:51Z | 40,032,671 | <p>Similar to the other answer:</p>
<pre><code>df.index.set_levels(df.index.map(lambda x: (x[0], x[1].strip())), inplace=True)
</code></pre>
| 1 | 2016-10-13T23:30:49Z | [
"python",
"string",
"pandas",
"multi-index"
] |
Why does re.VERBOSE prevent my regex pattern from working? | 40,032,632 | <p>I want to use the following regex to get modified files from svn log, it works fine as a single line, but since it's complex, I want to use <code>re.VERBOSE</code> so that I can add comment to it, then it stopped working. What am I missing here? Thanks!</p>
<pre><code>revision='''r123456 | user | 2013-12-22 11:21:41 -0700 (Thu, 22 Dec 2013) | 1 line
Changed paths:
A /trunk/abc/python/test/module
A /trunk/abc/python/test/module/__init__.py
A /trunk/abc/python/test/module/usage.py
A /trunk/abc/python/test/module/logger.py
copied from test
'''
import re
# doesn't work
print re.search('''
(?<=Changed\spaths:\n)
((\s{3}[A|M|D]\s.*\n)*)
[(?=\n)|]
''', revision, re.VERBOSE).groups()
# works
print re.search('(?<=Changed\spaths:\n)((\s{3}[A|M|D]\s.*\n)*)[(?=\n)|]', revision).groups()[0]
</code></pre>
<p>The string I want to extract is: </p>
<pre><code> A /trunk/abc/python/test/module
A /trunk/abc/python/test/module/__init__.py
A /trunk/abc/python/test/module/usage.py
A /trunk/abc/python/test/module/logger.py
</code></pre>
| 3 | 2016-10-13T23:26:53Z | 40,032,792 | <p>Use a raw string literal:</p>
<pre><code>re.search(r'''
(?<=Changed\spaths:\n)
(?:\s{3}[AMD]\s.*\n)*
(?=\n)
''', revision, re.VERBOSE)
</code></pre>
<p>See this fixed <a href="http://ideone.com/xlYIMF" rel="nofollow">Python demo</a>. </p>
<p>The main issue is that you have to pass it as a raw string literal, or use <code>\\n</code> instead of <code>\n</code>. Otherwise, <code>\n</code> (being a literal newline) is ignored inside the regex pattern, is treated as formatting whitespace (read more about that in the <a href="https://docs.python.org/2/library/re.html#re.VERBOSE" rel="nofollow">Python <code>re</code> docs</a>).</p>
<p>Also, note you corrupted the lookahead by enclosing it with <code>[...]</code> (it became a character class part) and the <code>|</code> inside character classes are treated as literal pipes (thus, here, they should be removed).</p>
| 2 | 2016-10-13T23:46:57Z | [
"python",
"regex",
"parsing",
"svn"
] |
perimeter of a polygon with given coordinates | 40,032,641 | <p>i am trying to find the perimeter of 10 point polygon with given coordinates. </p>
<p>This is what ive got so far</p>
<p>however keep getting an error</p>
<pre><code>poly = [[31,52],[33,56],[39,53],[41,53],[42,53],[43,52],[44,51],[45,51]]
x=row[0]
y=row[1]
``def perimeter(poly):
"""A sequence of (x,y) numeric coordinates pairs """
return abs(sum(math.hypot(x0-x1,y0-y1) for ((x0, y0), (x1, y1)) in segments(poly)))
print perimeter(poly)
</code></pre>
| -1 | 2016-10-13T23:27:29Z | 40,032,956 | <p><code>poly</code> is a list, to index an element in this list, you need to supply a single index, not a pair of indices, which is why <code>poly[x,y]</code> is a syntax error. The elements are lists of length 2. If <code>p</code> is one of those elements, then for that point <code>(x,y) = (p[0],p[1])</code>. The following might give you an idea. <code>enumerate</code> allows you to simultaneously loop through the indices (needed to get the next point in the polygon) and the points:</p>
<pre><code>>>> for i,p in enumerate(poly):
print( str(i) + ": " + str((p[0],p[1])))
0: (31, 52)
1: (33, 56)
2: (39, 53)
3: (41, 53)
4: (42, 53)
5: (43, 52)
6: (44, 51)
7: (45, 51)
</code></pre>
| 0 | 2016-10-14T00:07:26Z | [
"python"
] |
Concatenate two separate strings from arrays in a for loop | 40,032,673 | <p>Okay so I have two lists, they can be anywhere from just one value long to 20, but they will always have the same amount as eachother.</p>
<p>e.g </p>
<pre><code>alphabet = ['a', 'b', 'c', 'd', 'e']
numbers = ['1', '2', '3', '4', '5']
</code></pre>
<p>Now my objective is to create a for loop that would go through both lists, and add the corresponding values from each list to each other. So..</p>
<pre><code>['a1', 'b2', 'c3', 'd4', '5e']
</code></pre>
<p>Just to give another example.</p>
<pre><code>names = ['john', 'harry', 'joe']
IDs = ['100', '200', '300']
output: ['john100', 'harry200', 'joe300']
</code></pre>
<p>Would anyone be able to point me in the right direction? </p>
| 0 | 2016-10-13T23:31:05Z | 40,032,692 | <p>You can use <code>zip</code> and <code>join</code>:</p>
<pre><code>[''.join(p) for p in zip(alphabet, numbers)]
# ['a1', 'b2', 'c3', 'd4', 'e5']
</code></pre>
<p>As for the second example:</p>
<pre><code>[''.join(p) for p in zip(names, IDs)]
# ['john100', 'harry200', 'joe300']
</code></pre>
| 3 | 2016-10-13T23:33:01Z | [
"python",
"concatenation"
] |
Concatenate two separate strings from arrays in a for loop | 40,032,673 | <p>Okay so I have two lists, they can be anywhere from just one value long to 20, but they will always have the same amount as eachother.</p>
<p>e.g </p>
<pre><code>alphabet = ['a', 'b', 'c', 'd', 'e']
numbers = ['1', '2', '3', '4', '5']
</code></pre>
<p>Now my objective is to create a for loop that would go through both lists, and add the corresponding values from each list to each other. So..</p>
<pre><code>['a1', 'b2', 'c3', 'd4', '5e']
</code></pre>
<p>Just to give another example.</p>
<pre><code>names = ['john', 'harry', 'joe']
IDs = ['100', '200', '300']
output: ['john100', 'harry200', 'joe300']
</code></pre>
<p>Would anyone be able to point me in the right direction? </p>
| 0 | 2016-10-13T23:31:05Z | 40,032,818 | <p>As an alternative to @Psidom one-liner solution you could just use <code>zip()</code>:</p>
<pre><code>>>>[i+j for i, j in zip(alphabet, numbers)]
>>>['a1', 'b2', 'c3', 'd4', 'e5']
</code></pre>
<p>Or if you perfef to use a regular for loop:</p>
<pre><code>res = []
for i, j in zip(alphabet, numbers):
res.append(i+j)
</code></pre>
<p>You could also make this more general, and put it in a function:</p>
<pre><code># method one
def concancate_elements(list1, list2):
return [i+j, for i, j in zip(alphabet, numbers)]
# method two
def concancate_elements(list1, list2):
res = []
for i, j in zip(alphabet, numbers):
res.append(i+j)
return res
</code></pre>
| 1 | 2016-10-13T23:51:12Z | [
"python",
"concatenation"
] |
Error trying to use super().__init__ | 40,032,756 | <p>I am fairly new to Python and have taken the code excerpt below from a book I'm working with. </p>
<p>It is listed below <strong>exactly</strong> as it is written and explained in the book but yet it throws the following error:</p>
<pre><code>TypeError: super() takes at least 1 argument (0 given)
</code></pre>
<p>When I try to give <code>super</code> an argument, it tells me it needs to be of type.</p>
<p>I've searched multiple threads and haven't had any luck yet.</p>
<pre><code>class Car():
"""A simple attempt to represent a car"""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year)
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
</code></pre>
| 0 | 2016-10-13T23:42:29Z | 40,032,870 | <p>You're running Python 2, not Python 3. <a href="https://docs.python.org/2/library/functions.html#super" rel="nofollow">Python 2's <code>super</code></a> requires at least one argument (the type in which this method was defined), and usually two (current type and <code>self</code>). Only <a href="https://docs.python.org/3/library/functions.html#super" rel="nofollow">Python 3's <code>super</code></a> can be called without arguments.</p>
<p>Confirm by adding the following to the top of your script, which will report the actual version you're running under:</p>
<pre><code>import sys
print(sys.version_info)
</code></pre>
<p>Note: Since you're not doing anything in <code>ElectricCar</code>'s <code>__init__</code> aside from delegating to <code>Car</code>'s <code>__init__</code> with the same arguments, you can skip defining <code>__init__</code> for <code>ElectricCar</code> entirely. You only need to override <code>__init__</code> with explicit delegation if initializing <code>ElectricCar</code> involves doing something different from initializing a <code>Car</code>, otherwise, <code>Car</code>s initializer is called automatically when initializing a <code>Car</code> subclass that does not define <code>__init__</code>. As written, you could simplify <code>ElectricCar</code> to:</p>
<pre><code>class ElectricCar(Car):
pass
</code></pre>
<p>and it would behave identically (it would run slightly faster by avoiding the unnecessary interception and delegation of <code>__init__</code>, that's all).</p>
| 1 | 2016-10-13T23:56:38Z | [
"python",
"inheritance",
"init",
"super"
] |
count lines and create new file | 40,032,791 | <p>So basically I have to call the text file, and create the new file while adding some strings.</p>
<p>For example if my input text is:</p>
<p>Hello</p>
<p>World</p>
<p>Nice to Meet You</p>
<p>my output text has to be:</p>
<p>1: Hello</p>
<p>2: World</p>
<p>3: Nice to Meet You</p>
<p>Below is the code that I have been trying to figure out. When I try it, there is no error, but it does not create the new file too. </p>
<pre><code>with open('filetext') as f:
content=f.readlines()
for count in f:
count+=1
with open('newfiletext', 'a+') as f:
f.write(counts)
f.write(': ')
f.write(content)
f.write('\n')
</code></pre>
<p>I appreciate if I can get a help. Thank you in advance.</p>
| 0 | 2016-10-13T23:46:47Z | 40,032,825 | <p>textfile:</p>
<pre><code>Hello
World
Nice to Meet You
</code></pre>
<p>code:</p>
<pre><code>with open('test.txt') as f:
for i , line in enumerate(f.readlines()):
print "{0}:{1}".format(i+1,line)
</code></pre>
<p>output:</p>
<pre><code>1:Hello
2:World
3:Nice to Meet You
</code></pre>
<p>then you can store in string and write the to file or another file</p>
| 1 | 2016-10-13T23:51:51Z | [
"python"
] |
count lines and create new file | 40,032,791 | <p>So basically I have to call the text file, and create the new file while adding some strings.</p>
<p>For example if my input text is:</p>
<p>Hello</p>
<p>World</p>
<p>Nice to Meet You</p>
<p>my output text has to be:</p>
<p>1: Hello</p>
<p>2: World</p>
<p>3: Nice to Meet You</p>
<p>Below is the code that I have been trying to figure out. When I try it, there is no error, but it does not create the new file too. </p>
<pre><code>with open('filetext') as f:
content=f.readlines()
for count in f:
count+=1
with open('newfiletext', 'a+') as f:
f.write(counts)
f.write(': ')
f.write(content)
f.write('\n')
</code></pre>
<p>I appreciate if I can get a help. Thank you in advance.</p>
| 0 | 2016-10-13T23:46:47Z | 40,032,862 | <p>First you open the file:</p>
<pre><code>with open('filetext') as f:
</code></pre>
<p>Then you read the whole thing into a list:</p>
<pre><code>content=f.readlines()
</code></pre>
<p>Then you attempt to iterate over the now-empty file object:</p>
<pre><code>for count in f:
</code></pre>
<p>Since it's empty, nothing in the following block will execute, even once. Make sure you keep track of variable names and use a unique one for each unique object you want to manipulate - notably, <code>f</code> and <code>count</code> are reused when they shouldn't be:</p>
<pre><code>with open('filetext') as f, open('newfiletext', 'a+') as output:
count = 0
for line in f:
count += 1
output.write(count)
output.write(': ')
output.write(line)
</code></pre>
| 1 | 2016-10-13T23:56:04Z | [
"python"
] |
Generating Plots from .csv file | 40,032,800 | <p>I'm trying to make several plots of Exoplanet data from NASA's Exoplanet Archive. The problem is nothing I do will return the columns of the csv file with the headers on the first line of the csv file.</p>
<p>The Error I get is</p>
<pre><code> NameError: name 'pl_orbper' is not defined
</code></pre>
<p><a href="https://i.stack.imgur.com/JPKpF.png" rel="nofollow">The DATA I need to use.</a></p>
<p>The code I have currently has not worked though I'm sure I'm close.</p>
<pre><code> import matplotlib.pyplot as plt
import numpy as np
data = np.genfromtxt("planets.csv",delimiter=',',names=True, unpack=True)
plt.plot(pl_orbper,pl_bmassj)
plt.title('Mass vs Period')
plt.ylabel('Period')
plt.xlabel('Mass')
plt.show()
</code></pre>
<p>If anyone has a better solution with csv.reader or any other ways to read csv files I'd be open to it.</p>
| 0 | 2016-10-13T23:49:06Z | 40,033,796 | <p>Change the following line:</p>
<pre><code>plt.plot(pl_orbper,pl_bmassj)
</code></pre>
<p>to </p>
<pre><code>plt.plot(data['pl_orbper'],data['pl_bmassj'])
</code></pre>
<p>With the following data:</p>
<pre class="lang-none prettyprint-override"><code>rowid,pl_orbper,pl_bmassj
1, 326.03, 0.320
2, 327.03, 0.420
3, 328.03, 0.520
4, 329.03, 0.620
5, 330.03, 0.720
6, 331.03, 0.820
</code></pre>
<p>this is the result</p>
<p><a href="https://i.stack.imgur.com/ML88q.png" rel="nofollow"><img src="https://i.stack.imgur.com/ML88q.png" alt="Mass vs Period Plot"></a></p>
| 0 | 2016-10-14T02:06:20Z | [
"python",
"csv",
"matplotlib"
] |
Calling C's hello world from Python | 40,032,904 | <p>My C script:</p>
<pre><code>/* Hello World program */
#include <stdio.h>
int main() {
printf("Hello, World! \n");
return 0;
}
</code></pre>
<p>I want to see <code>Hello, World!</code> get printed directly in my Python IDE (Rodeo IDE) in the <strong>easiest</strong> way possible. </p>
<p>So far, I've come up with the following approach, but it doesn't seem to work (and is kind of cumbersome since it requires me to go to the Terminal):</p>
<p>First, I do <code>gcc helloworld.c</code> in the Terminal to generate the executable <code>a.out*</code>, and then I do:</p>
<pre><code>from subprocess import call
call(["./a.out"])
</code></pre>
<p>But instead of printing <code>Hello, World!</code> to the Python console, I just get <code>0</code> (which means success). How can I instead make the C output print <em>directly</em> to the Python console, and how can I possibly simplify it even more (e.g., by avoiding a Terminal detour)? I know I need to make the executable first (which is why I use Terminal) but maybe there's a sleeker way to do it within the Python IDE? </p>
<p><strong>FOR USERS WONDERING WHAT THE b STANDS FOR... @happydave's solution is tested here and thanks to @Mark Tolonen for explaining the b</strong></p>
<pre><code>Python 3.5.2 |Anaconda 4.2.0 (x86_64)| (default, Jul 2 2016, 17:52:12)
[GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> print(subprocess.check_output("./a.out"))
b'Hello, World! \n'
</code></pre>
<p>It is very strange where the <code>b</code> comes from...</p>
| -1 | 2016-10-14T00:01:26Z | 40,032,940 | <p>You could just print the text right to the Python Module by using the following code:</p>
<pre><code>print("Hello, world!")
</code></pre>
| -2 | 2016-10-14T00:05:41Z | [
"python",
"c",
"rodeo"
] |
Calling C's hello world from Python | 40,032,904 | <p>My C script:</p>
<pre><code>/* Hello World program */
#include <stdio.h>
int main() {
printf("Hello, World! \n");
return 0;
}
</code></pre>
<p>I want to see <code>Hello, World!</code> get printed directly in my Python IDE (Rodeo IDE) in the <strong>easiest</strong> way possible. </p>
<p>So far, I've come up with the following approach, but it doesn't seem to work (and is kind of cumbersome since it requires me to go to the Terminal):</p>
<p>First, I do <code>gcc helloworld.c</code> in the Terminal to generate the executable <code>a.out*</code>, and then I do:</p>
<pre><code>from subprocess import call
call(["./a.out"])
</code></pre>
<p>But instead of printing <code>Hello, World!</code> to the Python console, I just get <code>0</code> (which means success). How can I instead make the C output print <em>directly</em> to the Python console, and how can I possibly simplify it even more (e.g., by avoiding a Terminal detour)? I know I need to make the executable first (which is why I use Terminal) but maybe there's a sleeker way to do it within the Python IDE? </p>
<p><strong>FOR USERS WONDERING WHAT THE b STANDS FOR... @happydave's solution is tested here and thanks to @Mark Tolonen for explaining the b</strong></p>
<pre><code>Python 3.5.2 |Anaconda 4.2.0 (x86_64)| (default, Jul 2 2016, 17:52:12)
[GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> print(subprocess.check_output("./a.out"))
b'Hello, World! \n'
</code></pre>
<p>It is very strange where the <code>b</code> comes from...</p>
| -1 | 2016-10-14T00:01:26Z | 40,032,953 | <pre><code>>>> import subprocess
>>> subprocess.check_output("./a.out")
'Hello World!\n'
</code></pre>
<p>Regarding your second question, you could also just call gcc using subprocess. In that case, call is probably the right thing to use, since you presumably want to check for failure before running a.out.</p>
<p>Here's a full script:</p>
<pre><code>import subprocess
status = subprocess.call(["gcc","hello.c"])
if status == 0:
print(subprocess.check_output("./a.out").decode('utf-8'))
else:
print("Failed to compile")
</code></pre>
<p>hello.c:</p>
<pre><code>#include "stdio.h"
int main() {
printf("Hello world!");
}
</code></pre>
<p>Output:
Hello world!</p>
| 4 | 2016-10-14T00:07:03Z | [
"python",
"c",
"rodeo"
] |
Calling C's hello world from Python | 40,032,904 | <p>My C script:</p>
<pre><code>/* Hello World program */
#include <stdio.h>
int main() {
printf("Hello, World! \n");
return 0;
}
</code></pre>
<p>I want to see <code>Hello, World!</code> get printed directly in my Python IDE (Rodeo IDE) in the <strong>easiest</strong> way possible. </p>
<p>So far, I've come up with the following approach, but it doesn't seem to work (and is kind of cumbersome since it requires me to go to the Terminal):</p>
<p>First, I do <code>gcc helloworld.c</code> in the Terminal to generate the executable <code>a.out*</code>, and then I do:</p>
<pre><code>from subprocess import call
call(["./a.out"])
</code></pre>
<p>But instead of printing <code>Hello, World!</code> to the Python console, I just get <code>0</code> (which means success). How can I instead make the C output print <em>directly</em> to the Python console, and how can I possibly simplify it even more (e.g., by avoiding a Terminal detour)? I know I need to make the executable first (which is why I use Terminal) but maybe there's a sleeker way to do it within the Python IDE? </p>
<p><strong>FOR USERS WONDERING WHAT THE b STANDS FOR... @happydave's solution is tested here and thanks to @Mark Tolonen for explaining the b</strong></p>
<pre><code>Python 3.5.2 |Anaconda 4.2.0 (x86_64)| (default, Jul 2 2016, 17:52:12)
[GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> print(subprocess.check_output("./a.out"))
b'Hello, World! \n'
</code></pre>
<p>It is very strange where the <code>b</code> comes from...</p>
| -1 | 2016-10-14T00:01:26Z | 40,033,022 | <p>If you compile the C script (say, to <code>a.out</code>):</p>
<pre><code>#include <stdio.h>
int main(void) {
printf("Hello, World! \n");
return 0;
}
</code></pre>
<p>You can easily call it by using <a href="https://docs.python.org/3/library/ctypes.html" rel="nofollow">CTypes</a>:</p>
<pre><code># hello.py
import ctypes
beach = "./a.out"
seashell = ctypes.cdll.LoadLibrary(beach)
seashell.main()
</code></pre>
<p>Calling the following Python script will call your <code>main()</code> in your C script:</p>
<pre><code>$ python hello.py
Hello, World!
</code></pre>
<p>You can subprocess and capture the output using, for instance, <a href="https://docs.python.org/3/library/subprocess.html#popen-objects" rel="nofollow">communicate</a>, but there's no need to spawn a shell to accomplish what you're after.</p>
| 4 | 2016-10-14T00:15:54Z | [
"python",
"c",
"rodeo"
] |
for loop right-triangles not separating | 40,032,909 | <pre><code>base=int(input("Enter the triangle size: "))
for i in range(1, base + 1):
print (('*' * i) + (' ' * (base - i)))
for i in range(1, base + 1)[::-1]:
print (('*' * i) + (' ' * (base - i)))
for i in range(1, base + 1):
print (' ' * (base - i) + ('*' * i))
for i in range(1, base + 1)[::-1]:
print (' ' * (base - i) + ('*' * i))
</code></pre>
<p>The output looks like this: </p>
<pre><code>Enter the triangle size: 4
*
**
***
****
****
***
**
*
*
**
***
****
****
***
**
*
>>>
</code></pre>
<p>But I need it to look like this: </p>
<pre><code>Enter the triangle size: 4
*
**
***
****
****
***
**
*
*
**
***
****
****
***
**
*
>>>
</code></pre>
<p>I tried everything to create a new line after each for loop but it just outputted a mess. Is there any way I can tweak my program to allow for those spaces? Thanks!</p>
| 2 | 2016-10-14T00:01:39Z | 40,032,985 | <p>I've just added prints between triangles to reproduce the expected output. Is that what you want ?</p>
<pre><code>base=int(input("Enter the triangle size: "))
for i in range(1, base + 1):
print (('*' * i) + (' ' * (base - i)))
print()
for i in range(1, base + 1)[::-1]:
print (('*' * i) + (' ' * (base - i)))
for i in range(1, base + 1):
print (' ' * (base - i) + ('*' * i))
print()
for i in range(1, base + 1)[::-1]:
print (' ' * (base - i) + ('*' * i))
</code></pre>
<p>Output:</p>
<pre><code>Enter the triangle size: 4
*
**
***
****
****
***
**
*
*
**
***
****
****
***
**
*
</code></pre>
| 0 | 2016-10-14T00:11:08Z | [
"python",
"python-3.x",
"for-loop"
] |
how to tell sphinx that source code is in this path and build in that path | 40,032,930 | <p>I want to run sphinx on a library in a conda virtual environment with path</p>
<pre><code>/anaconda/envs/test_env/lib/site-packages/mypackage
</code></pre>
<p>and put the html files in the path</p>
<pre><code>/myhtmlfiles/myproject
</code></pre>
<p>where my <code>conf.py</code> and <code>*.rst</code> files are in the path</p>
<pre><code>/sphinx/myproject
</code></pre>
<hr>
<p><strong><em>question</em></strong><br>
What are the <code>conf.py</code> settings I need to edit to make this happen when I run</p>
<pre><code>make html
</code></pre>
| 0 | 2016-10-14T00:04:06Z | 40,033,437 | <p><code>make</code> is not a sphinx command. That command actually runs either a <code>make</code> with a Makefile or <code>make.bat</code> (depending on your operating system), which then locates the relevant files before invoking <code>sphinx-build</code>. You will need to modify the make files and/or set the proper environmental variables.</p>
| 1 | 2016-10-14T01:14:52Z | [
"python",
"python-sphinx"
] |
How to get the answer for exponents questions | 40,032,955 | <p>I'm new to python. I'm also a beginner on this subject. So any help would be great! </p>
<p>I'm trying to write a code for calculating the answer for questions like 3^2 = 9 , 2^3 = 8, etc. </p>
<p>I know there is a ** for this. But I need to use while loops and for loops for this. </p>
<p>I don't know what I'm doing wrong and what I need for these loops. I also need the loop to tell the user it's the wrong answer if they enter in a number less than zero. I need to know how it would start the loop from the beginning again if they inputted the wrong answer. Any help would be appreciated!</p>
<p>Here is what I have so far: </p>
<pre><code>base1 = int(input("Base:"))
base2 = 1
exponent = int(input("Exponent:"))
ExpNeeded = True
while ExpNeeded:
for hat in range(exponent):
base2 = base2 * base1
print("Answer:" , base2)
ExpNeeded = False
else:
print("Please enter a number greater than zero")
</code></pre>
| 0 | 2016-10-14T00:07:13Z | 40,033,212 | <p>i used your code also you can use <code>while</code> without ExpNeeded and <code>break</code> loop(<code>while</code>) i.e <code>while True:</code></p>
<pre><code>ExpNeeded = True
while ExpNeeded :
base2 = 1
base1=int(input("Base:"))
while base1<=0:
print "Please enter a number greater than zero"
base1=int(input("Base:"))
exponent=int(input("Exponent:"))
while exponent<=0:
print "Please enter a number greater than zero"
exponent=int(input("exponent:"))
for hat in range(exponent):
base2 = base2 * base1
print 'answer: ' , base2
print "to repeat press 1 else press 0"
if int(input(" "))==1:
pass
else:
ExpNeeded =False
</code></pre>
<p>output:</p>
<pre><code>Base:2
Exponent:5
answer: 32
to repeat press 1 else press 0
1
Base:-2
Please enter a number greater than zero
Base:6
Exponent:2
answer: 36
to repeat press 1 else press 0
0
</code></pre>
| 0 | 2016-10-14T00:43:00Z | [
"python",
"python-3.x",
"for-loop",
"while-loop",
"exponential"
] |
Python - Beginner questions | 40,032,988 | <p>I am at the beginning of Python programming and have a few questions.
When I run the code, I get this compile error:</p>
<blockquote>
<p>IndentationError: unindent does not match any outer indentation level</p>
</blockquote>
<ol>
<li>I think the error comes, because of the <code>return</code> in the last line. What should I do differently?</li>
<li>And I don't understand this line. What does this mean?
<blockquote>
<p>print "%d : %7d" % (i,2**i)</p>
</blockquote></li>
</ol>
<p>I know, what the print command does, but what does the rest mean?</p>
<pre><code>def whileexample():
n=15;i=0; # Mit Semikolon = Variablen in einer Zeile schreiben
while i<=n:
if n>20:
print n, "ist zu groÃ"
break
print "%d : %7d" % (i,2**i)
i=i+1
else:
print n+1, "Zweierpotenzen berechnet."
return
whileexample()
</code></pre>
| 0 | 2016-10-14T00:11:56Z | 40,033,024 | <p>In Python, the whitespace at the beginning of the line is significant. Statements at the same logical level <em>must</em> be indented the same amount.</p>
<p>In your case, the final line has an extra space character at the beginning of the line. Make sure what the <code>w</code> in the last line is all the way to the let, in the very first column.</p>
| 1 | 2016-10-14T00:16:11Z | [
"python",
"printing",
"compiler-errors",
"return"
] |
Python - Beginner questions | 40,032,988 | <p>I am at the beginning of Python programming and have a few questions.
When I run the code, I get this compile error:</p>
<blockquote>
<p>IndentationError: unindent does not match any outer indentation level</p>
</blockquote>
<ol>
<li>I think the error comes, because of the <code>return</code> in the last line. What should I do differently?</li>
<li>And I don't understand this line. What does this mean?
<blockquote>
<p>print "%d : %7d" % (i,2**i)</p>
</blockquote></li>
</ol>
<p>I know, what the print command does, but what does the rest mean?</p>
<pre><code>def whileexample():
n=15;i=0; # Mit Semikolon = Variablen in einer Zeile schreiben
while i<=n:
if n>20:
print n, "ist zu groÃ"
break
print "%d : %7d" % (i,2**i)
i=i+1
else:
print n+1, "Zweierpotenzen berechnet."
return
whileexample()
</code></pre>
| 0 | 2016-10-14T00:11:56Z | 40,033,041 | <p>Your final piece of code: whileexample()
You added a redundant space in this first column.</p>
| 0 | 2016-10-14T00:18:28Z | [
"python",
"printing",
"compiler-errors",
"return"
] |
Python - Beginner questions | 40,032,988 | <p>I am at the beginning of Python programming and have a few questions.
When I run the code, I get this compile error:</p>
<blockquote>
<p>IndentationError: unindent does not match any outer indentation level</p>
</blockquote>
<ol>
<li>I think the error comes, because of the <code>return</code> in the last line. What should I do differently?</li>
<li>And I don't understand this line. What does this mean?
<blockquote>
<p>print "%d : %7d" % (i,2**i)</p>
</blockquote></li>
</ol>
<p>I know, what the print command does, but what does the rest mean?</p>
<pre><code>def whileexample():
n=15;i=0; # Mit Semikolon = Variablen in einer Zeile schreiben
while i<=n:
if n>20:
print n, "ist zu groÃ"
break
print "%d : %7d" % (i,2**i)
i=i+1
else:
print n+1, "Zweierpotenzen berechnet."
return
whileexample()
</code></pre>
| 0 | 2016-10-14T00:11:56Z | 40,033,090 | <p>@Robᵩ is correct with the whitespacing. As for your other question, %d and %7d are place holders for whatever is in the parentheses. </p>
<p>The 'd' in this case means you want whatever is displayed in the parentheses to be formatted as a decimal. </p>
<p>The '7' indicates how much whitespace before the next variable. </p>
<p>The 2**i means 2 raised to the i (2^i).</p>
<p>Ex:</p>
<pre><code>>>> print "%d : %7d" % (5, 2**5)
5 : 32
</code></pre>
| 1 | 2016-10-14T00:24:57Z | [
"python",
"printing",
"compiler-errors",
"return"
] |
Returning inncorrect variables in python | 40,033,006 | <p>I am trying to make a simple project where balls bounce around the screen using object oriented. However, I can not get the correct variable to return. If I am tryin to return an integer, it instead returns: main.ball instance at 0x000000000924B648>></p>
<pre><code>def functionCallback(event):
lB.append(ball(event.x, event.y, event.x+50, event.y+50))
L.append(can.create_oval(event.x, event.y, event.x+50, event.y+50, fill = 'blue'))
class ball():
def __init__(self,x,y,x2,y2):
self.x=x
print self.x
self.y=y
self.x2=x2
self.y2=y2
self.xVel=random.randint(-15,15)
self.yVel=random.randint(-15,15)
def getX(self):
xx=self.x
print xx
return int(xx)
def getY(self):
return int(self.y)
def getX2(self):
return int(self.x2)
def getY2(self):
return int(self.y2)
def getXV(self):
return int(self.xVel)
def getYV(self):
return int(self.yVel)
def setXV(self, num):
self.xVel=self.xVel*num
def setYV(self, num):
self.yVel=self.yVel*num
#this line is in a while loop and caused the error. It I replace any of the method calls with any of the return methods, I get the same error.
can.move(oval, lB[oval-1].getX, lB[oval-1].getY)
</code></pre>
<p>I have played around with casting it and setting other variables equal to it (which I know really wouldn't do anything). Any help would be appreciated.</p>
| -1 | 2016-10-14T00:13:41Z | 40,034,078 | <p>I managed to find the problem. I needed to add () behind the method calls like: <code>can.move(oval, lB[oval-1].getX2(), lB[oval-1].getY())
</code></p>
| 0 | 2016-10-14T02:39:37Z | [
"python",
"return",
"object-oriented-analysis"
] |
Using SimpleHTTPServer to interpret failed requests and dynamically create JSON pages? | 40,033,015 | <p>I have a python program that takes and validates user input <strong><em>(flightNumber,dateStamp)</em></strong> and performs three api lookups: </p>
<pre><code>1. get flight info,
2: find flightId,
3: track flightID and return up to date JSON.
</code></pre>
<p>I should now like to make this information available to the web at </p>
<pre><code>mysite.com/flightNumber/dateStamp
</code></pre>
<p>to any user passing a <strong><em>'Valid'</em></strong> flightNumber and dateTime.</p>
<p>Is it possible to:</p>
<p>Setup a SimpleHTTPServer at mysite.com and log all paths attempted.</p>
<p>When a connection is made to any path, it will fail as there's nothing there. (unless/until I cache)</p>
<p>But, I simply send a user a hold message, use 're' Python script to check if the url is <strong><em>'Valid'</em></strong> (flightNumber, dateStamp)</p>
<p>If not <strong><em>'Valid'</em></strong>, I return an error.</p>
<p>If <strong><em>'Valid'</em></strong> I parse the relevant url info into parts of my existing program.</p>
<p>The results I get back from my existing api calls create a JSON readable page at</p>
<pre><code> /flightNumber/dateStamp
</code></pre>
<p>Now I forward the user to the page.</p>
<p>Is this possible? it seems an interesting way to achieve what I'm after</p>
| 0 | 2016-10-14T00:15:24Z | 40,033,078 | <p>Yes, this all sounds possible, even pretty simple, especially given the lack of detail you have provided.</p>
| 0 | 2016-10-14T00:22:49Z | [
"python",
"json",
"url",
"redirect",
"simplehttpserver"
] |
Run a python application/script on startup using Linux | 40,033,066 | <p>I've been learning Python for a project required for work. We are starting up a new server that will be running linux, and need a python script to run that will monitor a folder and handle files when they are placed in the folder.</p>
<p>I have the python "app" working, but I'm having a hard time finding how to make this script run when the server is started. I know it's something simple, but my linux knowledge falls short here.</p>
<p>Secondary question: As I understand it I don't need to compile or install this application, basically just call the start script to run it. Is that correct?</p>
| 2 | 2016-10-14T00:21:55Z | 40,033,097 | <p>You can set up the script to run via <code>cron</code>, configuring time as <code>@reboot</code></p>
<p>With python scripts, you will not need to compile it. You might need to install it, depending on what assumptions your script makes about its environment. </p>
| 2 | 2016-10-14T00:25:57Z | [
"python",
"linux"
] |
DLL Load failed: %1 is not a valid Win32 Application for StatsModel | 40,033,108 | <p>Similar to <a href="http://stackoverflow.com/questions/19019720/importerror-dll-load-failed-1-is-not-a-valid-win32-application-but-the-dlls">ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there</a>
...</p>
<p>This has been 4 hours of my life, so any help is appreciated: </p>
<p>I'm running Python 2.7.12 :: Anaconda 4.2.0 (64-bit) and trying to import statsmodels</p>
<p>When trying to import it i get the error that concludes with: </p>
<pre><code>ImportError: DLL load failed: %1 is not a valid Win32 application.
</code></pre>
<p>I've tried verifying that all versions are the same bit-levels, I've tried uninstalling and reinstalling statsmodels from CMD, I've tried installing .exe binaries from the statsmodels site for both 32 and 64, I've tried installing the model from .whl, and I've tried updating all the dependencies. Oh I also tried adding a system PATH referencing the libraries. </p>
<p>Thank you</p>
| 0 | 2016-10-14T00:27:18Z | 40,048,512 | <p>Figured this out after talking it through with others who had similar problems. </p>
<p>Don't know if these steps were necessary but, to be sure I uninstalled Python then specifically reinstalled the 64 bit version. Then I uninstalled Anacondas and reinstalled specifically the 64 bit version. Note I believe Python defaults to a 32 bit version. </p>
<p>Then, despite reinstalling Anaconda, I still had the same error. So, for every package that I was getting an error from, I installed the package out of
<a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/</a></p>
<p>So for me personally, I was throwing an error from statsmodels, so I installed it out of the above link. </p>
<p>Installation method is
1) Download correct file from above link
2) open CMD, type <code>pip install</code> then drag the file from the downloads folder into the CMD, and hit enter</p>
<p>Thank you!</p>
| 0 | 2016-10-14T17:07:17Z | [
"python",
"dll",
"statsmodels"
] |
Multiple MySQL JOINs and duplicated cells | 40,033,167 | <p>I have two MySQL queries that give the results that I'm looking for. I'd ultimately like to combine these two queries to produce a single table and I'm stuck.</p>
<p>QUERY 1:</p>
<pre><code>SELECT scoc.isr, outcome_concept_id, concept_name as outcome_name
FROM standard_case_outcome AS sco INNER JOIN concept AS c
ON sco.outcome_concept_id = c.concept_id
INNER JOIN standard_case_outcome_category AS scoc
ON scoc.isr = sco.isr
WHERE scoc.outc_code = 'CA'
</code></pre>
<p>RESULT 1:</p>
<p><a href="https://i.stack.imgur.com/ZEoRc.png" rel="nofollow"><img src="https://i.stack.imgur.com/ZEoRc.png" alt="RESULT OF QUERY 1 (TRUNCATED)"></a></p>
<p>QUERY 2:</p>
<pre><code>SELECT scoc.isr, drug_seq, concept_id, concept_name as drug_name
FROM standard_case_drug AS scd INNER JOIN concept AS c
ON scd.standard_concept_id = c.concept_id
INNER JOIN standard_case_outcome_category AS scoc
ON scoc.isr = scd.isr
WHERE scoc.outc_code = 'CA'
</code></pre>
<p>RESULT 2:</p>
<p><a href="https://i.stack.imgur.com/zjJDM.png" rel="nofollow"><img src="https://i.stack.imgur.com/zjJDM.png" alt="RESULT OF QUERY 2 (TRUNCATED)"></a></p>
<p>DESIRED RESULT:
<a href="https://i.stack.imgur.com/MKlMJ.png" rel="nofollow"><img src="https://i.stack.imgur.com/MKlMJ.png" alt="DESIRED RESULT"></a></p>
<p>I'm pretty sure I can figure out how to do it using Python/pandas, but I was wondering if there is (a) a way to do this MySQL (b) any benefit to doing it with MySQL.</p>
<p>** If you're curious, <a href="http://datadryad.org/resource/doi:10.5061/dryad.8q0s4" rel="nofollow">this is the entire dataset</a>.</p>
<p>Here's the db structure for the pertinent tables:</p>
<pre><code># Dump of table concept
# ------------------------------------------------------------
CREATE TABLE `concept` (
`concept_id` int(11) NOT NULL,
`concept_name` varchar(255) NOT NULL,
`domain_id` varchar(20) NOT NULL,
`vocabulary_id` varchar(20) NOT NULL,
`concept_class_id` varchar(20) NOT NULL,
`standard_concept` varchar(1) DEFAULT NULL,
`concept_code` varchar(50) NOT NULL,
`valid_start_date` date NOT NULL,
`valid_end_date` date NOT NULL,
`invalid_reason` varchar(1) DEFAULT NULL,
PRIMARY KEY (`concept_id`),
UNIQUE KEY `idx_concept_concept_id` (`concept_id`),
KEY `idx_concept_code` (`concept_code`),
KEY `idx_concept_vocabluary_id` (`vocabulary_id`),
KEY `idx_concept_domain_id` (`domain_id`),
KEY `idx_concept_class_id` (`concept_class_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
# Dump of table standard_case_drug
# ------------------------------------------------------------
CREATE TABLE `standard_case_drug` (
`primaryid` varchar(512) DEFAULT NULL,
`isr` varchar(512) DEFAULT NULL,
`drug_seq` varchar(512) DEFAULT NULL,
`role_cod` varchar(512) DEFAULT NULL,
`standard_concept_id` int(11) DEFAULT NULL,
KEY `idx_standard_case_drug_primary_id` (`primaryid`(255),`drug_seq`(255)),
KEY `idx_standard_case_drug_isr` (`isr`(255),`drug_seq`(255)),
KEY `idx_standard_case_drug_standard_concept_id` (`standard_concept_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
# Dump of table standard_case_outcome
# ------------------------------------------------------------
CREATE TABLE `standard_case_outcome` (
`primaryid` varchar(512) DEFAULT NULL,
`isr` varchar(512) DEFAULT NULL,
`pt` varchar(512) DEFAULT NULL,
`outcome_concept_id` int(11) DEFAULT NULL,
`snomed_outcome_concept_id` int(11) DEFAULT NULL,
KEY `idx_standard_case_outcome_primary_id` (`primaryid`(255)),
KEY `idx_standard_case_outcome_isr` (`isr`(255)),
KEY `idx_standard_case_outcome_outcome_concept_id` (`outcome_concept_id`),
KEY `idx_standard_case_outcome_snomed_outcome_concept_id` (`snomed_outcome_concept_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
# Dump of table standard_case_outcome_category
# ------------------------------------------------------------
CREATE TABLE `standard_case_outcome_category` (
`primaryid` varchar(512) DEFAULT NULL,
`isr` varchar(512) DEFAULT NULL,
`outc_code` varchar(512) DEFAULT NULL COMMENT 'Code for a patient outcome (See table below) CODE MEANING_TEXT ----------------DE Death LT Life-ThreateningHO Hospitalization - Initial or ProlongedDS DisabilityCA Congenital AnomalyRI Required Intervention to Prevent PermanentImpairment/DamageOT Other Serious (Important Medical Event) NOTE: The outcome from the latest version of a case is provided. If there is more than one outcome, the codes willbe line listed.',
`snomed_concept_id` int(11) DEFAULT NULL,
KEY `idx_standard_case_outcome_category_primary_id` (`primaryid`(255)),
KEY `idx_standard_case_outcome_category_isr` (`isr`(255)),
KEY `idx_standard_case_outcome_category_snomed_concept_id` (`snomed_concept_id`,`outc_code`(255))
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
</code></pre>
| 0 | 2016-10-14T00:35:42Z | 40,033,260 | <p>This should get you the desired results.</p>
<pre><code>SELECT
`scoc`.`isr` AS `isr`,
`sco` .`outcome_concept_id` AS `outcome_concept_id`,
`c1` .`concept_name` AS `outcome_name`,
`scd` .`drug_seq` AS `drug_seq`,
`scd` .`concept_id` AS `concept_id`,
`c2` .`concept_name` AS `drug_name`
FROM
`standard_case_outcome` AS `sco`
INNER JOIN
`concept` AS `c1`
ON
`sco`.`outcome_concept_id` = `c1`.`concept_id`
LEFT JOIN
`standard_case_drug` AS `scd`
ON
`sco`.`isr` = `scd`.`isr`
INNER JOIN
`concept` AS `c2`
ON
`scd`.`outcome_concept_id` = `c2`.`concept_id`
INNER JOIN
`standard_case_outcome_category` AS `scoc`
ON
`scoc`.`isr` = `sco`.`isr`
WHERE
`scoc`.`outc_code` = 'CA'
</code></pre>
<p><strong>EDIT</strong></p>
<p>Note that I left out the <code>concept</code> table, as you are not selecting anything from it, or filtering the results with it.</p>
<p><strong>SECOND EDIT</strong></p>
<p>Updated to include the <code>concept</code> table. Updated question showed that it is in fact needed in the <code>SELECT</code>.</p>
<p><strong>THIRD EDIT</strong></p>
<p>Needs to select <code>concept</code>.<code>name</code> for <code>sco</code>, and <code>scd</code> respectively.</p>
| 1 | 2016-10-14T00:50:29Z | [
"python",
"mysql",
"sql",
"pandas"
] |
Merge keys with the same value in dictionary of lists | 40,033,176 | <p>I have a dictionary of lists and would like to obtain just one key in case of keys with duplicated values. For example:</p>
<pre><code>dic1 = {8: [0, 4], 1: [0, 4], 7:[3], 4:[1, 5], 11:[3]}
</code></pre>
<p>resulting dictionary</p>
<pre><code>dic2 = {1: [0, 4], 7:[3], 4:[1, 5]}
</code></pre>
<p>The strategy would be to reverse the values in keys, which would become unique, and then again reverse the keys to their respective values:</p>
<pre><code>dic2 = {y: x for x, y in dic.items()}
</code></pre>
<p>But an error occurred because lists are not hashables. What I could do to obtain a dictionary with only one key in case of keys with the same value?</p>
| 0 | 2016-10-14T00:37:56Z | 40,033,208 | <p>Turn the lists into tuples, which are hashable.</p>
<pre><code>dic2 = {tuple(y): x for x, y in dic.items()}
</code></pre>
<p>You can convert back into a list afterward if you like:</p>
<pre><code>result = {v:list(k) for k,v in dic2.items()}
</code></pre>
| 4 | 2016-10-14T00:42:35Z | [
"python",
"list",
"dictionary"
] |
Using Boto3 in python to acquire results from dynamodb and parse into a usable variable or dictionary | 40,033,189 | <p>I used to be a SQL query master in MySQL and SQL server, but I'm far from mastering nosql and dynamo db just seems very over simplified. Anyways no rants, I'm trying to just acquire the most recent entry into dynamo db or to parse out the results I get so I can skim the most recent item off the top.</p>
<p>this is my code</p>
<pre><code>from __future__ import print_function # Python 2/3 compatibility
import boto3
import json
import decimal
from boto3.dynamodb.conditions import Key, Attr
# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
if o % 1 > 0:
return float(o)
else:
return int(o)
return super(DecimalEncoder, self).default(o)
dynamodb = boto3.resource('dynamodb', region_name='us-west-2',
endpoint_url="https://foo.foo.foo/aws")
table = dynamodb.Table('footable')
response = table.scan(
Select="ALL_ATTRIBUTES",
)
for i in response['Items']:
print(json.dumps(i, cls=DecimalEncoder))
</code></pre>
<p>My results are a lot of the following that I'd like to either parse or if someone knows the code to just select the top entry that would be great.</p>
<pre><code>{"MinorID": 123, "Location": "123westsideave"}
{"MinorID": 321, "Location": "456nowhererd"}
{"MinorID": 314, "Location": "123westsideave"}
</code></pre>
| 0 | 2016-10-14T00:40:43Z | 40,065,671 | <p>at the end of my code where it says "print(json.dumps(i, cls=DecimalEncoder))" I changed that to "d = ast.literal_eval((json.dumps(i, cls=DecimalEncoder)))" I also added import ast at the top. It worked beautifully.</p>
<pre><code>import ast
table = dynamodb.Table('footable')
response = table.scan(
Select="ALL_ATTRIBUTES",
)
for i in response['Items']:
d = ast.literal_eval((json.dumps(i, cls=DecimalEncoder)))
</code></pre>
| 0 | 2016-10-16T00:39:06Z | [
"python",
"json",
"amazon-web-services",
"amazon-dynamodb",
"boto"
] |
Pandas Grouping - Values as Percent of Grouped Totals Not Working | 40,033,190 | <p>Using a data frame and pandas, I am trying to figure out what each value is as a percentage of the grand total for the "group by" category</p>
<p>So, using the tips database, I want to see, for each sex/smoker, what the proportion of the total bill is for female smoker / all female and for female non smoker / all female (and the same thing for men)</p>
<p>For example,</p>
<p>If the complete data set is:</p>
<pre><code>Sex, Smoker, Day, Time, Size, Total Bill
Female,No,Sun,Dinner,2, 20
Female,No,Mon,Dinner,2, 40
Female,No,Wed,Dinner,1, 10
Female,Yes,Wed,Dinner,1, 15
</code></pre>
<p>The values for the first line would be (20+40+10)/(20+40+10+15), as those are the other 3 values for non smoking females</p>
<p>So the output should look like</p>
<pre><code>Female No 0.823529412
Female Yes 0.176470588
</code></pre>
<p>However, I seem to be having some trouble</p>
<p>When I do this,</p>
<pre><code>import pandas as pd
df=pd.read_csv("https://raw.githubusercontent.com/wesm/pydata- book/master/ch08/tips.csv", sep=',')
df.groupby(['sex', 'smoker'])[['total_bill']].apply(lambda x: x / x.sum()).head()
</code></pre>
<p>I get the following:</p>
<pre><code> total_bill
0 0.017378
1 0.005386
2 0.010944
3 0.012335
4 0.025151
</code></pre>
<p>It seems to be ignoring the group by and just calculating it for each line item</p>
<p>I am looking for something more like </p>
<pre><code>df.groupby(['sex', 'smoker'])[['total_bill']].sum()
</code></pre>
<p>Which will return</p>
<pre><code> total_bill
sex smoker
Female No 977.68
Yes 593.27
Male No 1919.75
Yes 1337.07
</code></pre>
<p>But I want this expressed as percentages of totals for the total of the individual sex/smoker combinations or </p>
<pre><code>Female No 977.68/(977.68+593.27)
Female Yes 593.27/(977.68+593.27)
Male No 1919.75/(1919.75+1337.07)
Male Yes 1337.07/(1919.75+1337.07)
</code></pre>
<p>Ideally, I would like to do the same with the "tip" column at the same time.</p>
<p>What am I doing wrong and how do I fix this? Thank you!</p>
| 0 | 2016-10-14T00:40:54Z | 40,033,348 | <p>You can add another grouped by process after you get the <code>sum</code> table to calculate the percentage:</p>
<pre><code>(df.groupby(['sex', 'smoker'])['total_bill'].sum()
.groupby(level = 0).transform(lambda x: x/x.sum())) # group by sex and calculate percentage
#sex smoker
#Female No 0.622350
# Yes 0.377650
#Male No 0.589455
# Yes 0.410545
#dtype: float64
</code></pre>
| 1 | 2016-10-14T01:02:29Z | [
"python",
"pandas",
"dataframe",
"aggregate",
"aggregation"
] |
how do I pip uninstall package beginning with special character '-e ...'? | 40,033,218 | <p>pip freeze:</p>
<pre><code> ...
howdoi==1.1.9
**-e git+https://github.com/fredzannarbor/howdoi21.git@0efdd53947bb233d529225db30aba2e1e4e2cc6e#egg=howdoi21**
html5lib==0.999
...
</code></pre>
<p>How do I delete the package whose name begins '-e ...'? I tried </p>
<pre><code> pip uninstall '\-e git+https://github.com/fredzannarbor/howdoi21.git@0efdd53947bb233d529225db30aba2e1e4e2cc6e#egg=howdoi21
'
Invalid requirement: '\-e git+https://github.com/fredzannarbor/howdoi21.git@0efdd53947bb233d529225db30aba2e1e4e2cc6e#egg=howdoi21'
It looks like a path. Does it exist ?
</code></pre>
| 0 | 2016-10-14T00:43:31Z | 40,034,083 | <p>Try <code>pip uninstall howdoi21</code></p>
<ul>
<li>Usually the 'egg=[PackageName][-dev][-version]' part contains the project name. </li>
<li>If the github repository was not deleted, you can find the project name from <code>setup.py</code> file. </li>
<li><a href="http://stackoverflow.com/questions/17346619/how-to-uninstall-editable-packages-with-pip-installed-with-e">How to uninstall editable packages with pip (installed with -e)</a></li>
</ul>
| 0 | 2016-10-14T02:40:04Z | [
"python",
"pip"
] |
Edit scikit-learn decisionTree | 40,033,222 | <p>I would like to edit sklearn decisionTree,
e.g. change conditions or cut node/leaf etc.</p>
<p>But there seems to be no functions to do that, if I could export to a file, edit it to import.</p>
<p>How can I edit decisionTree?</p>
<p>Environment:</p>
<ul>
<li>Windows10</li>
<li>python3.3</li>
<li>sklearn 0.17.1</li>
</ul>
| 0 | 2016-10-14T00:43:54Z | 40,033,698 | <p>Even though the docs say that the <code>splitter</code> kwarg for <code>DecisionTreeClassifier</code> is a string, you could give it a class as well. Evidence:</p>
<p><a href="https://github.com/scikit-learn/scikit-learn/blob/412996f/sklearn/tree/tree.py#L353-L360" rel="nofollow">https://github.com/scikit-learn/scikit-learn/blob/412996f/sklearn/tree/tree.py#L353-L360</a></p>
<p>Looks like you could subclass one of the Splitter classes found here: </p>
<p><a href="https://github.com/scikit-learn/scikit-learn/blob/0.17.X/sklearn/tree/_splitter.pyx" rel="nofollow">https://github.com/scikit-learn/scikit-learn/blob/0.17.X/sklearn/tree/_splitter.pyx</a></p>
<p>And do:</p>
<pre><code>my_decision_tree = sklearn.tree.DecisionTreeClassifier(splitter=mySplitter)
</code></pre>
| 1 | 2016-10-14T01:49:55Z | [
"python",
"scikit-learn"
] |
Edit scikit-learn decisionTree | 40,033,222 | <p>I would like to edit sklearn decisionTree,
e.g. change conditions or cut node/leaf etc.</p>
<p>But there seems to be no functions to do that, if I could export to a file, edit it to import.</p>
<p>How can I edit decisionTree?</p>
<p>Environment:</p>
<ul>
<li>Windows10</li>
<li>python3.3</li>
<li>sklearn 0.17.1</li>
</ul>
| 0 | 2016-10-14T00:43:54Z | 40,033,721 | <p>If you are thinking of editing a model, I don't think there's an easy way of doing this. There's been discussions on exporting (rather visualising) the rule set<a href="http://stackoverflow.com/questions/20224526/how-to-extract-the-decision-rules-from-scikit-learn-decision-tree"> [1]</a>,<a href="http://stackoverflow.com/questions/20156951/how-do-i-find-which-attributes-my-tree-splits-on-when-using-scikit-learn"> [2]</a>, but not on importing the rule set. However, what's the point of manually trying to edit the rule set, when it fits for the most optimal solution? Then again if you really know the conditions, you can simply use a set of nested if-else conditions without using scikit-learn at all.</p>
<p>If you need to change the Impl of the splitter, you can do as @zemekeneng suggested.</p>
| 1 | 2016-10-14T01:54:04Z | [
"python",
"scikit-learn"
] |
How to use optional positional arguments with nargs='*' arguments in argparse? | 40,033,261 | <p>As shown in the following code, I want to have an optional positional argument <code>files</code>, I want to specify a default value for it, when paths are passed in, use specified path.</p>
<p>But because <code>--bar</code> can have multiple arguments, the path passed in didn't go into <code>args.files</code>, how do I fix that? Thanks!</p>
<pre><code>import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo')
parser.add_argument('--bar', nargs='*')
parser.add_argument('files', nargs='?')
cmd = '--foo a --bar b c d '
print parser.parse_args(cmd.split())
# Namespace(bar=['b', 'c', 'd'], files=None, foo='a')
cmd = '--foo a --bar b c d /path/to/file1'
print parser.parse_args(cmd.split())
# Namespace(bar=['b', 'c', 'd', '/path/to/file1'], files=None, foo='a')
</code></pre>
| 0 | 2016-10-14T00:50:45Z | 40,033,371 | <p>Your argument spec is inherently ambiguous (since <code>--bar</code> can take infinite arguments, there is no good way to tell when it ends, particularly since <code>files</code> is optional), so it requires user disambiguation. Specifically, <code>argparse</code> can be told "this is the end of the switches section, all subsequent argument are positional" by putting <code>--</code> before the positional only section. If you do:</p>
<pre><code>cmd = '--foo a --bar b c d -- /path/to/file1'
print parser.parse_args(cmd.split())
</code></pre>
<p>You should get:</p>
<pre><code>Namespace(bar=['b', 'c', 'd'], files='/path/to/file1', foo='a')
</code></pre>
<p>(Tested on Py3, but should apply to Py2 as well)</p>
<p>Alternatively, the user can pass the positional argument anywhere it's unambiguous by avoiding putting positional arguments after <code>--bar</code> e.g.:</p>
<pre><code>cmd = '/path/to/file1 --foo a --bar b c d'
</code></pre>
<p>or</p>
<pre><code>cmd = '--foo a /path/to/file1 --bar b c d'
</code></pre>
<p>Lastly, you could avoid using <code>nargs='*'</code> for switches, given the ambiguity it introduces. Instead, define <code>--bar</code> to be accepted multiple times with a single value per switch, accumulating all uses to a <code>list</code>:</p>
<pre><code>parser.add_argument('--bar', action='append')
</code></pre>
<p>then you pass <code>--bar</code> multiple times to supply multiple values one at a time, instead of passing it once with many values:</p>
<pre><code>cmd = '--foo a --bar b --bar c --bar d /path/to/file1'
</code></pre>
| 1 | 2016-10-14T01:04:47Z | [
"python",
"parsing",
"argparse",
"optparse",
"optional-arguments"
] |
csv write doesn't work correctly | 40,033,353 | <p>Any idea why is this always writing the same line in output csv?</p>
<pre><code> 21 files = glob.glob(path)
22 csv_file_complete = open("graph_complete_reddit.csv", "wb")
23 stat_csv_file = open("test_stat.csv", "r")
24 csv_reader = csv.reader(stat_csv_file)
25 lemmatizer = WordNetLemmatizer()
26 for file1, file2 in itertools.combinations(files, 2):
27 with open(file1) as f1:
28 print(file1)
29 f1_text = f1.read()
30 f1_words = re.sub("[^a-zA-Z]", ' ', f1_text).lower().split()
31 f1_words = [str(lemmatizer.lemmatize(w, wordnet.VERB)) for w in f1_words if w not in stopwords]
32 print(f1_words)
33 f1.close()
34 with open(file2) as f2:
35 print(file2)
36 f2_text = f2.read()
37 f2_words = re.sub("[^a-zA-Z]", ' ', f2_text).lower().split()
38 f2_words = [str(lemmatizer.lemmatize(w, wordnet.VERB)) for w in f2_words if w not in stopwords]
39 print(f2_words)
40 f2.close()
41
42 a_complete = csv.writer(csv_file_complete, delimiter=',')
43 print("*****")
44 print(file1)
45 print(file2)
46 print("************************************")
47
48 f1_head, f1_tail = os.path.split(file1)
49 print("************")
50 print(f1_tail)
51 print("**************")
52 f2_head, f2_tail = os.path.split(file2)
53 print(f2_tail)
54 print("********************************")
55 for row in csv_reader:
56 if f1_tail in row:
57 file1_file_number = row[0]
58 file1_category_number = row[2]
59 if f2_tail in row:
60 file2_file_number = row[0]
61 file2_category_number = row[2]
62
63 row_complete = [file1_file_number, file2_file_number, file1_category_number, file2_category_number ]
64 a_complete.writerow(row_complete)
65
66 csv_file_complete.close()
</code></pre>
<p>Those prints show different filenames!</p>
<p>This is test_stat.csv file which the code uses as input:</p>
<pre><code> 1 1,1bmmoc.txt,1
2 2,2b3u1a.txt,1
3 3,2mf64u.txt,2
4 4,4x74k3.txt,5
5 5,lsspe.txt,3
6 6,qbimg.txt,4
7 7,w95fm.txt,2
</code></pre>
<p>And here's what the code outputs:</p>
<pre><code> 1 7,4,2,5
2 7,4,2,5
3 7,4,2,5
4 7,4,2,5
5 7,4,2,5
6 7,4,2,5
7 7,4,2,5
8 7,4,2,5
9 7,4,2,5
10 7,4,2,5
11 7,4,2,5
12 7,4,2,5
13 7,4,2,5
14 7,4,2,5
15 7,4,2,5
16 7,4,2,5
17 7,4,2,5
18 7,4,2,5
19 7,4,2,5
20 7,4,2,5
21 7,4,2,5
</code></pre>
<p>please comment or suggest fixes.</p>
| 0 | 2016-10-14T01:03:02Z | 40,033,461 | <p>You're never rewinding <code>stat_csv_file</code>, so eventually, your loop over <code>csv_reader</code> (which is a wrapper around <code>stat_csv_file</code>) isn't looping at all, and you write whatever you found on the last loop. Basically, the logic is:</p>
<ol>
<li>On first loop, look through all of <code>csv_reader</code>, find hit (though you keep looking even when you find it, exhausting the file), write hit</li>
<li>On all subsequent loops, the file is exhausted, so the inner search loop doesn't even execute, and you end up writing the same values as last time</li>
</ol>
<p>The slow, but direct way to fix this is to add <code>stat_csv_file.seek(0)</code> before you search it:</p>
<pre><code> 53 print(f2_tail)
54 print("********************************")
stat_csv_file.seek(0) # Rewind to rescan input from beginning
55 for row in csv_reader:
56 if f1_tail in row:
57 file1_file_number = row[0]
58 file1_category_number = row[2]
59 if f2_tail in row:
60 file2_file_number = row[0]
61 file2_category_number = row[2]
</code></pre>
<p>A likely better approach would be to load the input CSV into a <code>dict</code> once, then perform lookup there as needed, avoiding repeated (slow) I/O in favor of fast <code>dict</code> lookup. The cost would be higher memory use; if the input CSV is small enough, that's not an issue, if it's huge, you may need to use a proper database to get the rapid lookup without blowing memory.</p>
<p>It's a little unclear what the logic should be here, since your inputs and outputs don't align (your output should start with a repeated digit, but it doesn't for some reason?). But if the intent is that the input contains <code>file_number, file_tail, category_number</code>, then you could begin your code (above the top level loop) with:</p>
<pre><code># Create mapping from second field to associated first and third fields
tail_to_numbers = {ftail: (fnum, cnum) for fnum, ftail, cnum in csv_reader}
</code></pre>
<p>Then replace:</p>
<pre><code> for row in csv_reader:
if f1_tail in row:
file1_file_number = row[0]
file1_category_number = row[2]
if f2_tail in row:
file2_file_number = row[0]
file2_category_number = row[2]
row_complete = [file1_file_number, file2_file_number, file1_category_number, file2_category_number ]
a_complete.writerow(row_complete)
</code></pre>
<p>with the simpler and much faster:</p>
<pre><code>try:
file1_file_number, file1_category_number = tail_to_numbers[f1_tail]
file2_file_number, file2_category_number = tail_to_numbers[f2_tail]
except KeyError:
# One of the tails wasn't found in the lookup dict, so don't output
# (variables would be stale or unset); optionally emit some error to stderr
continue
else:
# Found both tails, output associated values
row_complete = [file1_file_number, file2_file_number, file1_category_number, file2_category_number]
a_complete.writerow(row_complete)
</code></pre>
| 1 | 2016-10-14T01:18:11Z | [
"python",
"file",
"csv",
"itertools"
] |
Labeling y-axis with multiple x-axis' | 40,033,370 | <p>I've set up a plot with 3 x-axis' on different scales, however when i attempt to use a Y-label i get the error: </p>
<p>AttributeError: 'function' object has no attribute 'ylabel'</p>
<p>I've tried a number of options, however I am not sure why this error appears.</p>
<p>My code:</p>
<pre><code>fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.30)
ax1 = ax.twiny()
ax2 = ax.twiny()
ax1.set_frame_on(True)
ax1.patch.set_visible(False)
ax1.xaxis.set_ticks_position('bottom')
ax1.xaxis.set_label_position('bottom')
ax1.spines['bottom'].set_position(('outward', 60))
ax.plot(temp1, depth1, "r-")
ax1.plot(v1, depth1, "g-.")
ax2.plot(qc1, depth1, "b--")
ax1.axis((0, 200, 0, 20))
ax.invert_yaxis()
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.set_xlabel('Temperature [\N{DEGREE SIGN}C]', color='r')
ax1.set_xlabel('Volumetric moisture content [%]', color='g')
ax2.set_xlabel('Cone tip resistance [MPa]', color='b')
ax.set.ylabel('Depth [m]')
for tl in ax.get_xticklabels():
tl.set_color('r')
for tl in ax1.get_xticklabels():
tl.set_color('g')
for tl in ax2.get_xticklabels():
tl.set_color('b')
ax.tick_params(axis='x', colors='r')
ax1.tick_params(axis='x', colors='g')
ax2.tick_params(axis='x', colors='b'
</code></pre>
<p>)</p>
| 0 | 2016-10-14T01:04:43Z | 40,033,415 | <p>you are typing ax.set.ylabel, you should be doing ax.set_ylabel</p>
| 0 | 2016-10-14T01:11:07Z | [
"python",
"multiple-axes"
] |
Finding the Min and Max of User Inputs | 40,033,454 | <p>I'm learning Python, and in trying to find out the min and max values of user number inputs, I can't seem to figure it out.</p>
<pre><code>count = 0
x = []
while(True):
x = input('Enter a Number: ')
high = max(x)
low = min(x)
if(x.isdigit()):
count += 1
else:
print("Your Highest Number is: " + high)
print("Your Lowest Number is: " + low)
break
</code></pre>
| 0 | 2016-10-14T01:16:54Z | 40,033,544 | <p>break your program into small manageable chunks start with just a simple function to get the number</p>
<pre><code>def input_number(prompt="Enter A Number:"):
while True:
try: return int(input(prompt))
except ValueError:
if not input: return None #user is done
else: print("That's not an integer!")
</code></pre>
<p>then write a function to continue getting numbers from the user until they are done entering numbers</p>
<pre><code>def get_minmax_numbers(prompt="Enter A Number: "):
maxN = None
minN = None
tmp = input_number(prompt)
while tmp is not None: #keep asking until the user enters nothing
maxN = tmp if maxN is None else max(tmp,maxN)
minN = tmp if minN is None else min(tmp,minN)
tmp = input_number(prompt) # get next number
return minN, maxN
</code></pre>
<p>then just put them together</p>
<pre><code> print("Enter Nothing when you are finished!")
min_and_max = get_numbers()
print("You entered Min of {0} and Max of {1}".format(*min_and_max)
</code></pre>
| 1 | 2016-10-14T01:30:37Z | [
"python",
"python-3.x"
] |
Finding the Min and Max of User Inputs | 40,033,454 | <p>I'm learning Python, and in trying to find out the min and max values of user number inputs, I can't seem to figure it out.</p>
<pre><code>count = 0
x = []
while(True):
x = input('Enter a Number: ')
high = max(x)
low = min(x)
if(x.isdigit()):
count += 1
else:
print("Your Highest Number is: " + high)
print("Your Lowest Number is: " + low)
break
</code></pre>
| 0 | 2016-10-14T01:16:54Z | 40,033,555 | <pre><code>inp=input("enter values seperated by space")
x=[int(x) for x in inp.split(" ")]
print (min(x))
print (max(x))
</code></pre>
<p>output:</p>
<pre><code>Python 3.5.2 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
enter values seperated by space 20 1 55 90 44
1
90
</code></pre>
| 1 | 2016-10-14T01:31:56Z | [
"python",
"python-3.x"
] |
Finding the Min and Max of User Inputs | 40,033,454 | <p>I'm learning Python, and in trying to find out the min and max values of user number inputs, I can't seem to figure it out.</p>
<pre><code>count = 0
x = []
while(True):
x = input('Enter a Number: ')
high = max(x)
low = min(x)
if(x.isdigit()):
count += 1
else:
print("Your Highest Number is: " + high)
print("Your Lowest Number is: " + low)
break
</code></pre>
| 0 | 2016-10-14T01:16:54Z | 40,033,816 | <p><code>x</code> is a list, and to append an item to a list, you must call the <code>append</code> method on the list, rather than directly assigning an item to the list, which would override the list with that item.</p>
<p>Code:</p>
<pre><code>count = 0
x = []
while(True):
num = input('Enter a Number: ')
if(num.isdigit()):
x.append(int(num))
count += 1
elif(x):
high = max(x)
low = min(x)
print("Your Highest Number is: " + str(high))
print("Your Lowest Number is: " + str(low))
break
else:
print("Please enter some numbers")
break
</code></pre>
| 0 | 2016-10-14T02:10:36Z | [
"python",
"python-3.x"
] |
Import os doesn't not work in linux | 40,033,460 | <p>I just want to install the <a href="https://pypi.python.org/pypi/suds" rel="nofollow">suds library</a>, but suddenly it wasn't proceeding because it was not finding the <code>os</code> library, so I tried to open my python and it results me an error. When I import the <code>os</code> library and there are some errors during the opening as well. Please, see the snapshot of my error when importing the library mentioned.</p>
<p><a href="https://i.stack.imgur.com/Q4S7e.png" rel="nofollow"><img src="https://i.stack.imgur.com/Q4S7e.png" alt="enter image description here"></a></p>
<p>Is there any solution for this? Or do I need to reinstall python?</p>
| 1 | 2016-10-14T01:18:03Z | 40,033,983 | <p>You need to <a href="https://www.python.org/downloads/" rel="nofollow">install a more recent version of Python - version 2.7.12 or later</a>. <a href="http://www.snarky.ca/stop-using-python-2-6" rel="nofollow">All versions of Python 2.6 have been end-of-lifed and any use of Python 2.6 is actively discouraged</a>.</p>
| 0 | 2016-10-14T02:28:47Z | [
"python",
"linux",
"operating-system",
"suds"
] |
Getting SettingWithCopyWarning warning even after using .loc in pandas | 40,033,471 | <pre><code>df_masked.loc[:, col] = df_masked.groupby([df_masked.index.month, df_masked.index.day])[col].\
transform(lambda y: y.fillna(y.median()))
</code></pre>
<p>Even after using a .loc, I get the foll. error, how do I fix it? </p>
<pre><code>Anaconda\lib\site-packages\pandas\core\indexing.py:476: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
self.obj[item] = s
</code></pre>
| 2 | 2016-10-14T01:19:23Z | 40,033,661 | <p>You could get this UserWarning if <code>df_masked</code> is a sub-DataFrame of some other DataFrame.
In particular, if data had been <em>copied</em> from the original DataFrame to <code>df_masked</code> then, Pandas emits the UserWarning to alert you that modifying <code>df_masked</code> will not affect the original DataFrame. </p>
<p>If you do not intend to modify the original DataFrame, then you are free to ignore the UserWarning.</p>
<p><a href="http://stackoverflow.com/a/38810015/190597">There are ways</a> to shut off the UserWarning on a per-statement basis. In particular, you could use <code>df_masked.is_copy = False</code>. </p>
<p>If you run into this UserWarning a lot, then instead of silencing the UserWarnings one-by-one, I think it is better to leave them be as you are developing your code. Be aware of what the UserWarning means, and if the modifying-the-child-does-not-affect-the-parent issue does not affect you, then ignore it. When your code is ready for production, or if you are experienced enough to not need the warnings, shut them off entirely with</p>
<pre><code>pd.options.mode.chained_assignment = None
</code></pre>
<p>near the top of your code.</p>
<hr>
<p>Here is a simple example which demonstrate the problem and (a) solution:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'swallow':['African','European'], 'cheese':['gouda', 'cheddar']})
df_masked = df.iloc[1:]
df_masked.is_copy = False # comment-out this line to see the UserWarning
df_masked.loc[:, 'swallow'] = 'forest'
</code></pre>
<hr>
<p>The reason why the UserWarning exists is to help alert new users to the fact that
<a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#why-does-assignment-fail-when-using-chained-indexing" rel="nofollow">chained-indexing</a> such as</p>
<pre><code>df.iloc[1:].loc[:, 'swallow'] = 'forest'
</code></pre>
<p>will not affect <code>df</code> when the result of the first indexer (e.g. <code>df.iloc[1:]</code>)
returns a copy. </p>
| 1 | 2016-10-14T01:44:17Z | [
"python",
"pandas"
] |
gdb python on mac: error of "/usr/local/bin/python": not in executable format | 40,033,536 | <p>I have the latest gdb installed on mac</p>
<pre><code> qiwu$ brew install gdb
Warning: gdb-7.12 already installed
</code></pre>
<p>Then I am trying to attach to a python3.5 process</p>
<pre><code>qiwu$ gdb python 4411
GNU gdb (GDB) 7.12
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-apple-darwin15.6.0".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
"/usr/local/bin/python": not in executable format: File format not recognized
Attaching to process 4411
Can't attach to process 4411: No such process (3)
/Users/qiwu/4411: No such file or directory.
(gdb)
</code></pre>
| 0 | 2016-10-14T01:29:45Z | 40,033,928 | <p>Could be because unix systems recognize <code>#!/usr/local/bin/python</code> not <code>/usr/local/bin/python</code></p>
| 0 | 2016-10-14T02:23:43Z | [
"python",
"osx",
"gdb"
] |
Tree view row activated with ONE click | 40,033,539 | <p>I am creating a graphical interface with glade that contents a treeview. </p>
<p>I want to have a button that is initially enabled by doing a simple click on a row of the treeview. </p>
<p>I am using <code>row-activated</code>, but when I activate a row for the first time I have to double click the row.</p>
<p>Which signal should I use to detect the click to activate the row with a single click? </p>
| 0 | 2016-10-14T01:30:13Z | 40,046,133 | <p>GtkTreeView as an <code>activate-on-single-click</code> property.</p>
<p><a href="https://developer.gnome.org/gtk3/stable/GtkTreeView.html#GtkTreeView--activate-on-single-click" rel="nofollow">https://developer.gnome.org/gtk3/stable/GtkTreeView.html#GtkTreeView--activate-on-single-click</a></p>
| 0 | 2016-10-14T14:52:35Z | [
"python",
"signals",
"glade"
] |
Returning multiple values in a view using Flask (Python) | 40,033,595 | <p>I'm struggling to even understand this in my head from a broad point of view, but I'll try explain as best as I can, if anything isn't clear please comment asking for more information.</p>
<p>Right now I have a python function that fetches a users name and their user ID from an internal API in my workplace that is tied to the username of each worker, this is then routed to a web page with a table like so. (I use the username as the main way of retrieving the data, i guess it could be considered the primary key?)</p>
<pre><code>@app.route('/user/<username>')
def issue(username)
json = get_json(username)
_user = get_username(json)
_id = get_id(json)
print "User: " + _user
print "ID: " + _id
</code></pre>
<p>(The <code>get_username()</code> and <code>get_id()</code> functions parse through the JSON file and retrieve the data that I need)</p>
<p>The way users get to this page is at the main page of the webapp there is a text field, they type in a username, it then redirects them to the page 127.0.0.1:5000/user/username , which in turn calls that function above. </p>
<p>This gives a very simple web page with just the username and the ID. However, how could I render multiple names and ID's with one request.</p>
<p>So for example:</p>
<pre><code>1. User goes to home page
2. User enters "John Doe, Harry Smith, Alex Boggs" into the text box and hit submit
3. They are then presented with this information
User: John Doe
ID: 127
User: Harry Smith
ID: 412
User: Alex Boggs
ID: 322
</code></pre>
<p>I'm not really sure where to even begin to do this, as I only really know how to pass one argument at a time. </p>
<p><strong>Note: Ideally the data wouldn't actually be tied to a URL, and instead would just generate below the search box on the homepage, but I will settle for any solution.</strong> </p>
| 0 | 2016-10-14T01:36:39Z | 40,033,822 | <p>If user enters <code>John Doe, Harry Smith, Alex Boggs</code> in text box then you should get <code>John Doe, Harry Smith, Alex Boggs</code> in Flask and you have to split it <code>"John Doe, Harry Smith, Alex Boggs".split(", ")</code> to get list of names. </p>
<p>Now you can use <code>for</code> loop to print User, ID for every name.</p>
| 1 | 2016-10-14T02:11:28Z | [
"python",
"flask",
"views"
] |
Returning multiple values in a view using Flask (Python) | 40,033,595 | <p>I'm struggling to even understand this in my head from a broad point of view, but I'll try explain as best as I can, if anything isn't clear please comment asking for more information.</p>
<p>Right now I have a python function that fetches a users name and their user ID from an internal API in my workplace that is tied to the username of each worker, this is then routed to a web page with a table like so. (I use the username as the main way of retrieving the data, i guess it could be considered the primary key?)</p>
<pre><code>@app.route('/user/<username>')
def issue(username)
json = get_json(username)
_user = get_username(json)
_id = get_id(json)
print "User: " + _user
print "ID: " + _id
</code></pre>
<p>(The <code>get_username()</code> and <code>get_id()</code> functions parse through the JSON file and retrieve the data that I need)</p>
<p>The way users get to this page is at the main page of the webapp there is a text field, they type in a username, it then redirects them to the page 127.0.0.1:5000/user/username , which in turn calls that function above. </p>
<p>This gives a very simple web page with just the username and the ID. However, how could I render multiple names and ID's with one request.</p>
<p>So for example:</p>
<pre><code>1. User goes to home page
2. User enters "John Doe, Harry Smith, Alex Boggs" into the text box and hit submit
3. They are then presented with this information
User: John Doe
ID: 127
User: Harry Smith
ID: 412
User: Alex Boggs
ID: 322
</code></pre>
<p>I'm not really sure where to even begin to do this, as I only really know how to pass one argument at a time. </p>
<p><strong>Note: Ideally the data wouldn't actually be tied to a URL, and instead would just generate below the search box on the homepage, but I will settle for any solution.</strong> </p>
| 0 | 2016-10-14T01:36:39Z | 40,034,072 | <p>Use "path" converter like this <code>@app.route('/something/<path:name_list>')</code>
So when user request the URL: <code>site/something/name1/name2/name3</code>
you will get a name list</p>
<p>Or you can create your own converter by create a converter class.</p>
<pre><code>from werkzeug.routing import BaseConverter
class ListConverter(BaseConverter):
def to_python(self, data):
return data.split(',')
def to_url(self, data)
','.join([BaseConverter.to_url(each) for each in data])
</code></pre>
<p>Then add this converter to application converter dict like this:</p>
<pre><code>app.url_map.converters['list']=ListConverter
</code></pre>
<p>Now you can use your list converter to implement that function:</p>
<pre><code>app.route('/something/<list:name_list>')
</code></pre>
<p>And user can request the URL like: <code>site/something/name1,name2,name3</code></p>
| 0 | 2016-10-14T02:39:15Z | [
"python",
"flask",
"views"
] |
Error in expected output: Loop is not correctly working | 40,033,670 | <p>I am still struggling to link the second 'for' variable in this together. The first 'for' loop works correctly, but the second half is stuck on a single variable, which is not allowing it to function correctly in a later repeatable loop. How might I write this better, so that the functions of the text are global, so that the variable 'xcr' isnt local. I know I am a beginner, but any help is always appreciated!! Thanks!</p>
<pre><code>sequence = open('sequence.txt').read().replace('\n','')
enzymes = {}
fh = open('enzymes.txt')
print('Restriction Enzyme Counter')
def servx():
inez = input('Enter a Restricting Enzyme: ')
for line in fh.readlines():
(name, site, junk, junk) = line.split()
enzymes[name] = site
global xcr
xcr = site
if inez in line:
print(xcr)
print('Active Bases:', xcr)
for lines in sequence.split():
if xcr in lines:
bs = (sequence.count(xcr))
print(bs)
print('Enzyme', inez, 'appears', bs, 'times in Sequence.')
</code></pre>
| 0 | 2016-10-14T01:46:13Z | 40,033,743 | <p>I think you need to specify global inside the <code>servy</code> function and not outside, but even better would be to pass inez as a parameter to <code>servx</code>:</p>
<pre><code>def servy():
global inez
fh.seek(0); #veryyyyy important
qust = input('Find another Enzyme? [Yes/No]: ')
qust = qust.lower()
if qust == 'yes':
inez = input('Enter a Restricting Enzyme: ')
servx()
servy()
elif qust == 'no':
print('Thanks!')
elif qust not in ('yes', 'no'):
print('Error, Unknown Command')
</code></pre>
<hr>
<p>Or</p>
<pre><code>def servx(inez):
. . .
def servy():
fh.seek(0); #veryyyyy important
qust = input('Find another Enzyme? [Yes/No]: ')
quest = qust.lower()
if qust == 'yes':
inez = input('Enter a Restricting Enzyme: ')
servx(inez)
servy()
elif qust == 'no':
print('Thanks!')
elif qust not in ('yes', 'no'):
print('Error, Unknown Command')
</code></pre>
| 0 | 2016-10-14T01:56:57Z | [
"python"
] |
Django REST Custom View Parameters in Viewset with CoreAPI | 40,033,671 | <p>If I define a django-rest-framework view framework as:</p>
<pre><code>class ProblemViewSet(viewsets.ModelViewSet):
queryset = Problem.objects.all()
serializer_class = ProblemSerializer
@detail_route(methods=['post'], permission_classes=(permissions.IsAuthenticated,))
def submit(self, request, *args, **kwargs):
# my code here
return Response(...)
</code></pre>
<p>When I look at the CoreAPI schema that is defined, I find this:</p>
<pre><code>problems: {
create(title, text, value, category, hint)
destroy(pk)
list([page])
partial_update(pk, [title], [text], [value], [category], [hint])
retrieve(pk)
submit(pk)
update(pk, title, text, value, category, hint)
}
</code></pre>
<p>I'd like the <code>submit</code> API endpoint to take an additional parameter, called <code>answer</code>, but so far I haven't figured out how to add such a custom parameter. I know I can just pass in the POST array, but that seems inelegant and un-RESTful. Any ideas?</p>
| 0 | 2016-10-14T01:46:19Z | 40,033,984 | <p>I don't understand your question, but I think that you want to add in the input the filed <code>answer</code> to django-rest form or raw, you can do this adding in the serializer <code>ProblemSerializer</code> the next:</p>
<pre><code>from rest_framework import serializers
...
class CustomerSerializer(serializers.ModelSerializer):
answer = serializers.SerializerMethodField()
class Meta:
model = Problem
fields = ['answer', 'my-normal-params',...]
def get_answer(self, problem):
if hasattr(problem, 'answer'):
request = self.context['request']
return answer
</code></pre>
<p>In get_answer method you will display in the json the value that you want, or you can return None (null) if you want, </p>
<p>If that is not your problem, please say me, I'll help you.</p>
| 0 | 2016-10-14T02:28:51Z | [
"python",
"django",
"rest",
"django-rest-framework"
] |
python 2.7 word generator | 40,033,724 | <p>Algorithm: take input on how many letters to go back, for loop to loop a-z, lock the first character, loop the second character, lock the first two, loop the third, and so on and so forth. The out put will look like a, b, c, d... aa, ab, ac, ad... aaa, aab, aac... and so on. I am very new to python. I have something that cycles through the alphabet, but my problem is to lock the first and cycle the second and so on.</p>
<pre><code>w = 'abcdefghijklmnopqrstuvwxyz'
n = input ("# of characters: ")
for a in range(0,n):
for i in w:
print i
</code></pre>
| 0 | 2016-10-14T01:54:30Z | 40,034,053 | <pre><code>alphabet = 'abcdefghijklmnopqrstuvwxyz'
l= ['']
for i in range(input):
l = [letter + item for letter in alphabet for item in l]
for item in l:
print(item)
</code></pre>
<p>I think this is what you're looking for</p>
| 0 | 2016-10-14T02:37:24Z | [
"python",
"python-2.7"
] |
python 2.7 word generator | 40,033,724 | <p>Algorithm: take input on how many letters to go back, for loop to loop a-z, lock the first character, loop the second character, lock the first two, loop the third, and so on and so forth. The out put will look like a, b, c, d... aa, ab, ac, ad... aaa, aab, aac... and so on. I am very new to python. I have something that cycles through the alphabet, but my problem is to lock the first and cycle the second and so on.</p>
<pre><code>w = 'abcdefghijklmnopqrstuvwxyz'
n = input ("# of characters: ")
for a in range(0,n):
for i in w:
print i
</code></pre>
| 0 | 2016-10-14T01:54:30Z | 40,034,419 | <p>To avoid huge RAM requirements, use <a href="https://docs.python.org/2/library/itertools.html#itertools.combinations" rel="nofollow"><code>itertools.combinations</code></a> to generate a single output at a time, handling the "locking" for you:</p>
<pre><code>from future_builtins import map # Not needed on Py3, only on Py2
from itertools import combinations
w = 'abcdefghijklmnopqrstuvwxyz'
# Don't use input on Py2; it's an implicit eval, which is terrible
# raw_input gets str, and you can explicitly convert to int
n = int(raw_input("# of characters: "))
# You want 1-n inclusive on both ends, not 0-n exclusive at the end, so tweak range
for wdlen in xrange(1, n+1):
# Generator based map with ''.join efficiently converts the tuples
# from combinations to str as you iterate
for wd in map(''.join, combinations(w, wdlen)):
print wd
</code></pre>
| 0 | 2016-10-14T03:21:57Z | [
"python",
"python-2.7"
] |
In numpy, why multi dimension array d[0][0:2][0][0] returning not two elements | 40,033,734 | <pre><code>In [136]: d = np.ones((1,2,3,4))
In [167]: d[0][0][0:2][0]
Out[167]: array([ 1., 1., 1., 1.])
</code></pre>
<p>as shown above, why it's not returning exactly 2 elements</p>
| 0 | 2016-10-14T01:55:57Z | 40,033,797 | <p>Look at the array itself. It should be self explanatory</p>
<pre><code>>>> d
array([[[[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.]],
[[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.]]]])
# first you grab the first and only element
>>> d[0]
array([[[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.]],
[[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.]]])
# then you get the first element out of the two groups
>>> d[0][0]
array([[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.]])
# thirdly, you get the two first elements as a list
>>> d[0][0][0:2]
array([[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.]])
# finally, you get the first element of the list
>>> d[0][0][0:2][0]
array([ 1., 1., 1., 1.])
</code></pre>
| 0 | 2016-10-14T02:06:31Z | [
"python",
"arrays",
"numpy"
] |
Installing package using pip command | 40,033,891 | <p>I am trying to install basemap using the pip command. My command is here ( I am using anaconda):</p>
<pre><code>pip install "C:\Users\hh\Downloads\basemap-1.0.8-cp35-none-win32.whl"
</code></pre>
<p>The error message I get is: </p>
<pre><code>basemap-1.0.8-cp35-none-win32.whl is not a supported wheel on this platform.
</code></pre>
<p>How would I fix this as I need to install base map. I already have python 3.5 and all the neccesary dependencies. I am using this post: <a href="http://stackoverflow.com/questions/35716830/basemap-with-python-3-5-anaconda-on-windows">Basemap with Python 3.5 Anaconda on Windows</a> as a reference.</p>
| 0 | 2016-10-14T02:20:03Z | 40,034,344 | <p>If you are using a 64-bit version of Windows you should download the 64bit version package (basemap-1.0.8-cp35-none-win_amd64.whl)</p>
| 1 | 2016-10-14T03:13:06Z | [
"python"
] |
Arrow animation in Python | 40,033,948 | <p>First of all, I am just starting to learn Python. I have been struggling during the last hours trying to update the arrow properties in order to change them during a plot animation.</p>
<p>After thoroughly looking for an answer, I have checked that it is possible to change a circle patch center by modifying the attribute 'center' such as <code>circle.center = new_coordinates</code>. However, I don't find the way to extrapolate this mechanism to an arrow patch...</p>
<p>The code so far is:</p>
<pre><code>import numpy as np, math, matplotlib.patches as patches
from matplotlib import pyplot as plt
from matplotlib import animation
# Create figure
fig = plt.figure()
ax = fig.gca()
# Axes labels and title are established
ax = fig.gca()
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_ylim(-2,2)
ax.set_xlim(-2,2)
plt.gca().set_aspect('equal', adjustable='box')
x = np.linspace(-1,1,20)
y = np.linspace(-1,1,20)
dx = np.zeros(len(x))
dy = np.zeros(len(y))
for i in range(len(x)):
dx[i] = math.sin(x[i])
dy[i] = math.cos(y[i])
patch = patches.Arrow(x[0], y[0], dx[0], dy[0] )
def init():
ax.add_patch(patch)
return patch,
def animate(t):
patch.update(x[t], y[t], dx[t], dy[t]) # ERROR
return patch,
anim = animation.FuncAnimation(fig, animate,
init_func=init,
interval=20,
blit=False)
plt.show()
</code></pre>
<p>After trying several options, I thought that the function update could somehow take me closer to the solution. However, I get the error:</p>
<pre><code>TypeError: update() takes 2 positional arguments but 5 were given
</code></pre>
<p>If I just add one more patch per step by defining the animate function as shown below, I get the result shown in the image attached.</p>
<pre><code>def animate(t):
patch = plt.Arrow(x[t], y[t], dx[t], dy[t] )
ax.add_patch(patch)
return patch,
</code></pre>
<p><a href="https://i.stack.imgur.com/fE2B1.png" rel="nofollow">Wrong animation</a></p>
<p>I have tried to add a patch.delete statement and create a new patch as update mechanism but that results in an empty animation...</p>
<p>I would be really grateful if anyone could bring some fresh air to this issue :)</p>
<p>Thanks in advance!</p>
| 4 | 2016-10-14T02:25:45Z | 40,034,280 | <p>I found this by mimicking the code in <a href="https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/patches.py#L1125" rel="nofollow"><code>patches.Arrow.__init__</code></a>:</p>
<pre><code>import numpy as np
import matplotlib.patches as patches
from matplotlib import pyplot as plt
from matplotlib import animation
import matplotlib.transforms as mtransforms
# Create figure
fig, ax = plt.subplots()
# Axes labels and title are established
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_ylim(-2,2)
ax.set_xlim(-2,2)
ax.set_aspect('equal', adjustable='box')
N = 20
x = np.linspace(-1,1,N)
y = np.linspace(-1,1,N)
dx = np.sin(x)
dy = np.cos(y)
patch = patches.Arrow(x[0], y[0], dx[0], dy[0])
def init():
ax.add_patch(patch)
return patch,
def animate(t):
L = np.hypot(dx[t], dy[t])
if L != 0:
cx = float(dx[t]) / L
sx = float(dy[t]) / L
else:
# Account for division by zero
cx, sx = 0, 1
trans1 = mtransforms.Affine2D().scale(L, 1)
trans2 = mtransforms.Affine2D.from_values(cx, sx, -sx, cx, 0.0, 0.0)
trans3 = mtransforms.Affine2D().translate(x[t], y[t])
trans = trans1 + trans2 + trans3
patch._patch_transform = trans.frozen()
return patch,
anim = animation.FuncAnimation(fig, animate,
init_func=init,
interval=20,
frames=N,
blit=False)
plt.show()
</code></pre>
| 1 | 2016-10-14T03:06:01Z | [
"python",
"animation",
"matplotlib",
"arrow"
] |
Arrow animation in Python | 40,033,948 | <p>First of all, I am just starting to learn Python. I have been struggling during the last hours trying to update the arrow properties in order to change them during a plot animation.</p>
<p>After thoroughly looking for an answer, I have checked that it is possible to change a circle patch center by modifying the attribute 'center' such as <code>circle.center = new_coordinates</code>. However, I don't find the way to extrapolate this mechanism to an arrow patch...</p>
<p>The code so far is:</p>
<pre><code>import numpy as np, math, matplotlib.patches as patches
from matplotlib import pyplot as plt
from matplotlib import animation
# Create figure
fig = plt.figure()
ax = fig.gca()
# Axes labels and title are established
ax = fig.gca()
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_ylim(-2,2)
ax.set_xlim(-2,2)
plt.gca().set_aspect('equal', adjustable='box')
x = np.linspace(-1,1,20)
y = np.linspace(-1,1,20)
dx = np.zeros(len(x))
dy = np.zeros(len(y))
for i in range(len(x)):
dx[i] = math.sin(x[i])
dy[i] = math.cos(y[i])
patch = patches.Arrow(x[0], y[0], dx[0], dy[0] )
def init():
ax.add_patch(patch)
return patch,
def animate(t):
patch.update(x[t], y[t], dx[t], dy[t]) # ERROR
return patch,
anim = animation.FuncAnimation(fig, animate,
init_func=init,
interval=20,
blit=False)
plt.show()
</code></pre>
<p>After trying several options, I thought that the function update could somehow take me closer to the solution. However, I get the error:</p>
<pre><code>TypeError: update() takes 2 positional arguments but 5 were given
</code></pre>
<p>If I just add one more patch per step by defining the animate function as shown below, I get the result shown in the image attached.</p>
<pre><code>def animate(t):
patch = plt.Arrow(x[t], y[t], dx[t], dy[t] )
ax.add_patch(patch)
return patch,
</code></pre>
<p><a href="https://i.stack.imgur.com/fE2B1.png" rel="nofollow">Wrong animation</a></p>
<p>I have tried to add a patch.delete statement and create a new patch as update mechanism but that results in an empty animation...</p>
<p>I would be really grateful if anyone could bring some fresh air to this issue :)</p>
<p>Thanks in advance!</p>
| 4 | 2016-10-14T02:25:45Z | 40,034,308 | <p>Add <code>ax.clear()</code> before <code>ax.add_patch(patch)</code> but will remove all elements from plot.</p>
<pre><code>def animate(t):
ax.clear()
patch = plt.Arrow(x[t], y[t], dx[t], dy[t] )
ax.add_patch(patch)
return patch,
</code></pre>
<hr>
<p><strong>EDIT:</strong> removing one patch</p>
<ul>
<li><p>using <code>ax.patches.pop(index)</code>. </p>
<p>In your example is only one patch so you can use <code>index=0</code></p>
<pre><code>def animate(t):
ax.patches.pop(0)
patch = plt.Arrow(x[t], y[t], dx[t], dy[t] )
ax.add_patch(patch)
return patch,
</code></pre></li>
<li><p>using <code>ax.patches.remove(object)</code></p>
<p>It needs <code>global</code> to get/set external <code>patch</code> with <code>Arrow</code></p>
<pre><code>def animate(t):
global patch
ax.patches.remove(patch)
patch = plt.Arrow(x[t], y[t], dx[t], dy[t] )
ax.add_patch(patch)
return patch,
</code></pre></li>
</ul>
<hr>
<p><strong>BTW:</strong> to get list of properties which you can use with <code>update()</code></p>
<pre><code>print( patch.properties().keys() )
dict_keys(['aa', 'clip_path', 'patch_transform', 'edgecolor', 'path', 'verts', 'rasterized', 'linestyle', 'transform', 'picker', 'capstyle', 'children', 'antialiased', 'sketch_params', 'contains', 'snap', 'extents', 'figure', 'gid', 'zorder', 'transformed_clip_path_and_affine', 'clip_on', 'data_transform', 'alpha', 'hatch', 'axes', 'lw', 'path_effects', 'visible', 'label', 'ls', 'linewidth', 'agg_filter', 'ec', 'facecolor', 'fc', 'window_extent', 'animated', 'url', 'clip_box', 'joinstyle', 'fill'])
</code></pre>
<p>so you can use <code>update</code> to change color - `facecolor</p>
<pre><code>def animate(t):
global patch
t %= 20 # get only 0-19 to loop animation and get color t/20 as 0.0-1.0
ax.patches.remove(patch)
patch = patches.Arrow(x[t], y[t], dx[t], dy[t])
patch.update({'facecolor': (t/20,t/20,t/20,1.0)})
ax.add_patch(patch)
return patch,
</code></pre>
| 2 | 2016-10-14T03:08:27Z | [
"python",
"animation",
"matplotlib",
"arrow"
] |
D&D dice roll python | 40,033,971 | <p>Trying to roll dice like in dungeons and dragon but display each roll. I dont quite know what im doing wrong and appreciate all the help.</p>
<pre><code>from random import randint
def d(y): #basic die roll
return randint(1, y)
def die(x, y): #multiple die roll 2d20 could roll 13 and 7 being 20
for [x*d(y)]:
print (sum(int(y)))
print (die(3, 20))
</code></pre>
<p>ok so i took the advice and changed it but still recieving an error on my return line</p>
<pre><code>#
#trying to roll dice like in dungeons and dragon but display each roll
from random import randint
def d(sides):
return randint(1, sides)
def roll(n, sides):
return tuple(d(sides) for _ in range(n))
def dice(n, sides):
print (roll(n, sides))
return sum(dice)
print(dice(3,20))
</code></pre>
| 0 | 2016-10-14T02:27:28Z | 40,034,181 | <p>You can't just multiple the result of a single call to <code>d()</code>, you need to make <code>n</code> different calls to the <code>d()</code>:</p>
<pre><code>from random import randint
def d(sides):
return randint(1, sides)
def roll(n, sides):
return tuple(d(sides) for _ in range(n))
dice = roll(3, 20)
print(dice, sum(dice))
# (20, 18, 1) 39
</code></pre>
| 1 | 2016-10-14T02:55:08Z | [
"python",
"python-3.x",
"dice"
] |
python and ipython seem to treat unicode characters differently | 40,033,979 | <p>I'm running python 2.7.12 from anaconda on windows 10. Included in the distro is ipython 5.1.0. I wrote a program to print certain columns of queried rows in a mysql database. The columns contain strings in unicode. When the program is run in python, an exception is thrown when a unicode character in one of the strings is first seen. The same program in ipython works, displaying all characters appropriately.</p>
<p>I've distilled the issue into a separate little program as follows:</p>
<pre><code>name = u'O\u2019Connor'
try:
print name
except:
print "exception 1 thrown"
try:
print u"{}".format(name)
except:
print "exception 2 thrown"
try:
print u"%s" % name
except:
print 'exception 3 thrown'
</code></pre>
<p>When run using python, exceptions are thrown everytime. When run in ipython, all three print statements work. Obviously, there is a difference between the two versions in the way unicode is handled. What is the difference and what should I do so that my program will handle being run in either environment?</p>
| 0 | 2016-10-14T02:28:31Z | 40,034,136 | <p>Looks like ipython is using a sane default output encoding (probably UTF-8 or UTF-16), while plain Python is using <code>cp437</code>, a limited one-byte-per-character ASCII superset that can't represent the whole Unicode range.</p>
<p>If you can control the command prompt, you can run <code>chcp 65001</code> before launching Python to make it use the "code page" for UTF-8 (which Python should pick up on). You might want to make this <a href="http://superuser.com/q/269818/556135">the default for command prompts in general to avoid future problems</a>.</p>
| 0 | 2016-10-14T02:47:47Z | [
"python",
"unicode",
"ipython",
"anaconda"
] |
Confusion on async file upload in python | 40,034,010 | <p>So I want to implement async file upload for a website. It uses python and javascript for frontend. After googling, there are a few great posts on them. However, the posts use different methods and I don't understand which one is the right one.</p>
<p>Method 1:
Use ajax post to the backend. </p>
<p>Comment: does it make a difference? I thought async has to be in the backend not the front? So when the backend is writing files to disk, it will still be single threaded.</p>
<p>Method 2:
Use celery or asyncio to upload file in python.</p>
<p>Method 3:
use background thread to upload file in python.</p>
<p>Any advice would be thankful.</p>
| 0 | 2016-10-14T02:33:12Z | 40,034,220 | <p>Asynchronous behavior applies to either side independently. Either side can take advantage of the capability to take care of several tasks as they become ready rather than blocking on a single task and doing nothing in the meantime. For example, servers do things asynchronously (or at least they should) while clients usually don't need to (though there can be benefits if they do and modern programming practices encourage that they do).</p>
| 1 | 2016-10-14T02:58:52Z | [
"python",
"ajax",
"asynchronous"
] |
Subsets and Splits