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
list |
---|---|---|---|---|---|---|---|---|---|
Tkinter Tix Checklist Hlist Header Configuration Options
| 39,441,438 |
<p>I'm hoping a tcl/tk expert can help answer this super-niche question regarding a <strong>Tix CheckList Hlist Header</strong>. All I want to do is change the background color from an ugly gray to white.</p>
<p>I find it very difficult to even know what options (<code>cnf={}</code> or <code>**kw</code>) I can use for ANYTHING in tix. I have discovered that I can do <code>self.checklist.hlist.config().keys()</code> which returns:</p>
<pre><code>['background', 'bd', 'bg', 'borderwidth', 'browsecmd', 'columns', 'command',
'cursor', 'dragcmd', 'drawbranch', 'dropcmd', 'fg', 'font', 'foreground',
'gap', 'header', 'height', 'highlightbackground', 'highlightcolor',
'highlightthickness', 'indent', 'indicator', 'indicatorcmd', 'itemtype',
'padx', 'pady', 'relief', 'selectbackground', 'selectborderwidth',
'selectforeground', 'selectmode', 'separator', 'sizecmd', 'takefocus',
'wideselection', 'width', 'xscrollcommand', 'yscrollcommand']
</code></pre>
<p>I don't know how to do this for the <strong>actual header object</strong> to see what options are available.</p>
<p>This is what it looks like:</p>
<p><a href="http://i.stack.imgur.com/1oxeu.png" rel="nofollow"><img src="http://i.stack.imgur.com/1oxeu.png" alt="Tix CheckList Hlist Header"></a></p>
<p>Here's the code that creates it:</p>
<pre><code>import tkinter as tk
from tkinter import tix
class whatever(tk.Frame):
def __init__(self, parent):
super(whatever, self).__init__(parent)
self.parent = parent
self.checklist = tix.CheckList(self.parent, browsecmd=self.selectItem,
options='hlist.columns 1', highlightthickness=1,
highlightcolor='#B7D9ED')
self.checklist.grid(sticky='ew', padx=20)
self.checklist.hlist.config(bg='white', bd=0, selectmode='none', selectbackground='white',
selectforeground='black', drawbranch=True, pady=5, header=True)
self.checklist.hlist.header_create(0, itemtype=tix.TEXT, text='My Heading Text',
relief='flat')
self.checklist.hlist.add("CL1", text="checklist1")
self.checklist.hlist.add("CL1.Item1", text="subitem1")
self.checklist.setstatus("CL1", "on")
self.checklist.setstatus("CL1.Item1", "off")
def selectItem(self, item):
print(item)
root = tix.Tk()
whatever(root)
root.mainloop()
</code></pre>
<p><strong>Additional info</strong>:</p>
<p>By the way, I'm mainly using this site to figure out what methods are available for <code>hlist</code> - <a href="http://epydoc.sourceforge.net/stdlib/Tix.HList-class.html" rel="nofollow">http://epydoc.sourceforge.net/stdlib/Tix.HList-class.html</a></p>
<p>This example was helpful too: <a href="https://svn.python.org/projects/stackless/trunk/Demo/tix/samples/SHList2.py" rel="nofollow">https://svn.python.org/projects/stackless/trunk/Demo/tix/samples/SHList2.py</a></p>
<p><strong>What Have I Tried...</strong></p>
<p>Lots of things for hours on-end. I think this should be in:</p>
<pre><code>self.checklist.hlist.header_configure(0, background='white')
</code></pre>
<p>but I've tried: <code>background</code>, <code>selectbackground</code>, <code>bg</code>, <code>color</code> ... and more. They all end with the same <code>_tkinter.TclError: unknown option "-NAMEHERE"</code>message.</p>
| 0 |
2016-09-11T22:56:16Z
| 39,445,503 |
<p>Simply, add <code>headerbackground</code> parameter to <code>header_create()</code> method:</p>
<pre><code>...
self.checklist.hlist.header_create(0, itemtype=tix.TEXT, text='My Heading Text',
headerbackground="red", relief='flat')
...
</code></pre>
| 1 |
2016-09-12T07:43:15Z
|
[
"python",
"tkinter",
"checklistbox",
"hlist",
"tix"
] |
Need Help Using python-quickbooks library and Quickbooks Accounting API
| 39,441,467 |
<p>I'm trying to implement the Quickbooks API for Python, to generate invoices based on transactions, and send them to my quickbooks account. I'm using <a href="https://github.com/sidecars/python-quickbooks" rel="nofollow">this</a> python library for accessing the API, which is currently in version 0.5.1 and is available on PyPI. I'm having trouble connecting my application to Quickbooks Online.</p>
<p>I have created a developer account on Quickbooks, and have access to my app token, consumer key, and consumer secret. The guide on the library's github page, confuses me because, under "Connecting your application to Quickbooks Online", steps 1 and 2 seem related but somewhat independent of each other; mainly because of the re-initialization of the client variable. </p>
<p>Am I supposed to have multiple Quickbook objects named client, but re-initializing it throughout my code? </p>
<p>My code looks like this: </p>
<pre><code>def create_invoice():
consumer_key = 'MY-CONSUMER-KEY'
consumer_secret = 'MY-CONSUMER-SECRET'
client = QuickBooks(
sandbox=True,
consumer_key=consumer_key,
consumer_secret=consumer_secret,
callback_url='https://sandbox-quickbooks.api.intuit.com',
)
authorize_url = client.get_authorize_url()
request_token = client.request_token
request_token_secret = client.request_token_secret
client = QuickBooks(
sandbox=True,
consumer_key=consumer_key,
consumer_secret=consumer_secret
)
client.authorize_url = authorize_url
client.request_token = request_token
client.request_token_secret = request_token_secret
client.set_up_service()
client.get_access_tokens(request.vars.oauth_verifier)
realm_id = request.vars.realmId
access_token = client.access_token
access_token_secret = client.access_token_secret
client = QuickBooks(
sandbox=True,
consumer_key=consumer_key,
consumer_secret=consumer_secret,
access_token=access_token,
access_token_secret=access_token_secret,
company_id=realm_id
)
invoice = Invoice()
line = SalesItemLine()
line.LineNum = 1
line.Description = "description"
line.Amount = 100
line.SalesItemLineDetail = SalesItemLineDetail()
item = Item.all(max_results=1, qb=client)[0]
line.SalesItemLineDetail.ItemRef = item.to_ref()
invoice.Line.append(line)
customer = Customer.all(max_results=1, qb=client)[0]
invoice.CustomerRef = customer.to_ref()
invoice.CustomerMemo = CustomerMemo()
invoice.CustomerMemo.value = "Customer Memo"
invoice.save(qb=client)
</code></pre>
<p>With this code I get the error: </p>
<pre><code>KeyError: 'Decoder failed to handle oauth_token with data as returned by provider. A different decoder may be needed. Provider returned: oauth_problem=parameter_absent&oauth_parameters_absent=oauth_verifier'
</code></pre>
<p>Because I'm getting the error something has to be wrong, but I'm confused where to go now.</p>
| 0 |
2016-09-11T23:00:43Z
| 39,461,234 |
<p>I found the answer to my problem. After reading this <a href="http://stackoverflow.com/questions/16078366/reuse-oauth1-authorization-tokens-with-rauth">thread</a>, where they had the same error, I got a better sense of what the library was doing; mainly the flow that was going on behind the scenes. I ultimately found it was the callback url that I had supplied was wrong. Choose a callback url that points back to where you are running above code. I also chose to store most of my variables in a database so I can easily access them for future use. My code now looks like this:</p>
<pre><code>def create_invoice():
consumer_key = 'MY-CONSUMER-KEY'
consumer_secret = 'MY-CONSUMER-SECRET'
rows = db(db.quickbooks_info).select()
p = [dict(realm_id=r.realm_id, access_token=r.access_token, access_token_secret=r.access_token_secret, consumer_key=r.consumer_key,
consumer_secret=r.consumer_secret, authorize_url=r.authorize_url, request_token=r.request_token, request_token_secret=r.request_token_secret)
for r in rows]
if len(p) == 0:
client = QuickBooks(
sandbox=True,
consumer_key=consumer_key,
consumer_secret=consumer_secret,
callback_url='http://127.0.0.1:8800/SNotes/default/create_invoice'
)
authorize_url = client.get_authorize_url()
request_token = client.request_token
request_token_secret = client.request_token_secret
db.quickbooks_info.update_or_insert((db.quickbooks_info.consumer_key == consumer_key),
consumer_key=consumer_key,
consumer_secret=consumer_secret,
authorize_url=authorize_url,
request_token=request_token,
request_token_secret=request_token_secret
)
else:
if p[0]['access_token'] == None and p[0]['access_token_secret'] == None and p[0]['realm_id'] == None:
client = QuickBooks(
sandbox=True,
consumer_key=p[0]['consumer_key'],
consumer_secret=p[0]['consumer_secret']
)
client.authorize_url = p[0]['authorize_url']
client.request_token = p[0]['request_token']
client.request_token_secret = p[0]['request_token_secret']
client.set_up_service()
client.get_access_tokens(request.get_vars['oauth_verifier'])
realm_id = request.vars.realmId
access_token = client.access_token
access_token_secret = client.access_token_secret
db.quickbooks_info.update_or_insert((db.quickbooks_info.consumer_key == p[0]['consumer_key']),
access_token=access_token,
access_token_secret=access_token_secret,
realm_id=realm_id
)
else:
client = QuickBooks(
sandbox=True,
consumer_key=p[0]['consumer_key'],
consumer_secret=p[0]['consumer_secret'],
access_token=p[0]['access_token'],
access_token_secret=p[0]['access_token_secret'],
company_id=p[0]['realm_id']
)
invoice = Invoice()
line = SalesItemLine()
line.LineNum = 1
line.Description = "test"
line.Amount = 6969
line.SalesItemLineDetail = SalesItemLineDetail()
item = Item.all(max_results=1, qb=client)[0]
line.SalesItemLineDetail.ItemRef = item.to_ref()
invoice.Line.append(line)
customer = Customer.all(max_results=1, qb=client)[0]
invoice.CustomerRef = customer.to_ref()
invoice.CustomerMemo = CustomerMemo()
invoice.CustomerMemo.value = "Customer Memo"
invoice.save(qb=client)
</code></pre>
| 0 |
2016-09-13T02:08:13Z
|
[
"python",
"web2py",
"quickbooks-online"
] |
pandas: groupby and aggregate without losing the column which was grouped
| 39,441,484 |
<p>I have a pandas dataframe as below. For each Id I can have multiple Names and Sub-ids.</p>
<pre><code>Id NAME SUB_ID
276956 A 5933
276956 B 5934
276956 C 5935
287266 D 1589
</code></pre>
<p>I want to condense the dataframe such that there is only one row for each id and all the names and sub_ids under each id appear as a singular set on that row</p>
<pre><code>Id NAME SUB_ID
276956 set(A,B,C) set(5933,5934,5935)
287266 set(D) set(1589)
</code></pre>
<p>I tried to groupby id and then aggregate over all the other columns </p>
<pre><code>df.groupby('Id').agg(lambda x: set(x))
</code></pre>
<p>But in doing so the resulting dataframe does not have the Id column. When you do groupby the id is returned as the first value of the tuple but I guess when you aggregate that is lost. Is there a way to get the dataframe that I am looking for. That is to groupby and aggregate without losing the column which was grouped.</p>
| 3 |
2016-09-11T23:03:57Z
| 39,441,498 |
<p>The groupby column becomes the index. You can simply reset the index to get it back:</p>
<pre><code>In [4]: df.groupby('Id').agg(lambda x: set(x)).reset_index()
Out[4]:
Id NAME SUB_ID
0 276956 {A, C, B} {5933, 5934, 5935}
1 287266 {D} {1589}
</code></pre>
| 5 |
2016-09-11T23:07:08Z
|
[
"python",
"pandas",
"dataframe",
"group-by"
] |
pandas: groupby and aggregate without losing the column which was grouped
| 39,441,484 |
<p>I have a pandas dataframe as below. For each Id I can have multiple Names and Sub-ids.</p>
<pre><code>Id NAME SUB_ID
276956 A 5933
276956 B 5934
276956 C 5935
287266 D 1589
</code></pre>
<p>I want to condense the dataframe such that there is only one row for each id and all the names and sub_ids under each id appear as a singular set on that row</p>
<pre><code>Id NAME SUB_ID
276956 set(A,B,C) set(5933,5934,5935)
287266 set(D) set(1589)
</code></pre>
<p>I tried to groupby id and then aggregate over all the other columns </p>
<pre><code>df.groupby('Id').agg(lambda x: set(x))
</code></pre>
<p>But in doing so the resulting dataframe does not have the Id column. When you do groupby the id is returned as the first value of the tuple but I guess when you aggregate that is lost. Is there a way to get the dataframe that I am looking for. That is to groupby and aggregate without losing the column which was grouped.</p>
| 3 |
2016-09-11T23:03:57Z
| 39,442,599 |
<p>If you don't want the groupby as an index, there is an argument for it to avoid further reset:</p>
<pre><code>df.groupby('Id', as_index=False).agg(lambda x: set(x))
</code></pre>
| 1 |
2016-09-12T02:23:13Z
|
[
"python",
"pandas",
"dataframe",
"group-by"
] |
python linklist pointer and size
| 39,441,511 |
<p>I am a rookie python programmer. I see the leetcode's definition of a linked list below. I got 2 questions for this concept, any help would be appreciated. Thanks in advance</p>
<pre><code># Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
</code></pre>
<p>Q1 Just wonder what is the type of the "self.next", I know in C++, it should be a pointer that represents the address of the next node. But python does not have that type, so I am confused what type "next" is.</p>
<p>Q2 Some tell me next is just a name. If that is the case, I run the code below, </p>
<pre><code>head =ListNode(1)
print sys.getsizeof(head)
head.next = ListNode(2)
print sys.getsizeof(head)
</code></pre>
<p>first the head.next is 'None', and then it is assigned to another ListNode type,
but I get the same size of head before and after this change, which I think the size of head should be larger since one of its member (next) is changed from None type to ListNode type. I am just confused about this, thank you so much!</p>
<p>PS. In my understanding, if I keep adding new nodes to the linklist, the head will be larger and larger since there are more and more 'nested' member 'next', just point out where I get wrong, thanks.</p>
| 0 |
2016-09-11T23:09:33Z
| 39,441,618 |
<p>Question 1:</p>
<p>Python variables are dynamically typed. (i.e. a variable could hold an int, and then hold a list, and then any other arbitrary object, etc).</p>
<p>In your case, <code>Head.next</code> starts by referencing, <code>None</code> a <code>NoneType</code> object.</p>
<p>After you assign it a different value (<code>ListNode(2)</code>), the <code>Head.next</code> now references the newly created <code>ListNode</code> object.</p>
<p>Question 2:</p>
<p>Why doesn't the size change.
I'm not an expert on how python's <code>sys.getsizeof</code> works, but from what I can gather, is that List.next in both cases is a reference variable (i.e. a variable that references some other object). The size doesn't change because <code>sys.getsizeof</code> finds the size of the object's variables. Where <code>Head.next</code> is just a reference to some other object in both cases.</p>
<p>See, <a href="http://stackoverflow.com/questions/449560/how-do-i-determine-the-size-of-an-object-in-python">How do I determine the size of an object in Python?</a>, for more complete answers on how <code>sys.getsizeof</code> works.</p>
| 0 |
2016-09-11T23:26:54Z
|
[
"python",
"c++",
"class",
"pointers",
"linked-list"
] |
python linklist pointer and size
| 39,441,511 |
<p>I am a rookie python programmer. I see the leetcode's definition of a linked list below. I got 2 questions for this concept, any help would be appreciated. Thanks in advance</p>
<pre><code># Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
</code></pre>
<p>Q1 Just wonder what is the type of the "self.next", I know in C++, it should be a pointer that represents the address of the next node. But python does not have that type, so I am confused what type "next" is.</p>
<p>Q2 Some tell me next is just a name. If that is the case, I run the code below, </p>
<pre><code>head =ListNode(1)
print sys.getsizeof(head)
head.next = ListNode(2)
print sys.getsizeof(head)
</code></pre>
<p>first the head.next is 'None', and then it is assigned to another ListNode type,
but I get the same size of head before and after this change, which I think the size of head should be larger since one of its member (next) is changed from None type to ListNode type. I am just confused about this, thank you so much!</p>
<p>PS. In my understanding, if I keep adding new nodes to the linklist, the head will be larger and larger since there are more and more 'nested' member 'next', just point out where I get wrong, thanks.</p>
| 0 |
2016-09-11T23:09:33Z
| 39,441,620 |
<p>My interpretation of a linked list. </p>
<pre><code>class LinkedList(object):
class Node(object):
def __init__(self, val=None, next=None, previous=None):
self.val = val
self.next = next
self.last = previous
def __init__(self):
self.length = 0
self.start = None
self.end = None
def append(self, value):
self.length += 1
if not self.start:
self.start = self.Node(value)
else:
if not self.end:
self.end = self.Node(value)
self.end.previous = self.start
self.end.next = self.start
self.start.next = self.end
else:
end = self.Node(value)
self.end.next = end
end.previous = self.end
self.end = end
self.end.next = self.start
def prepend(self, value):
self.length += 1
if not self.start:
self.start = self.Node(value)
else:
n = self.Node(value, self.start, self.end)
self.start.previous = n
self.start = n
def __len__(self):
return self.length
def __iter__(self):
self.position = 0
return self
def next(self):
self.position += 1
if self.position-1 >= len(self):
raise StopIteration
if self.position-1 == 0:
return self.start
cnt = 0
n = self.start
while cnt<self.position-1:
n = n.next
cnt += 1
return n
def __getitem__(self, index):
if index == 0:
return self.start
if index == -1:
return self.end
cnt = 0
n = self.start
while cnt<index+1:
n = n.next
cnt += 1
return n.val
def __repr__(self):
return repr(tuple(x.val for x in self))
l = LinkedList()
l.append(4)
l.append(5)
l.append(3)
l.prepend(0)
print l
print l[1]
</code></pre>
| 0 |
2016-09-11T23:27:11Z
|
[
"python",
"c++",
"class",
"pointers",
"linked-list"
] |
How to draw rotated stripe patterns
| 39,441,563 |
<p>I want to draw stripe patterns given a rotated angle. I figured out how to draw vertical lines but not rotated. For example, given the image below with an input of 45 degrees I want to generate the second image.</p>
<p>Here's my code for generating the first image:
from <strong>future</strong> import division</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
stripe_width = 15
gap = 20
offset = 2
image_size = 250
canvas = np.zeros((image_size, image_size))
current_col = 0
while current_col < image_size:
if current_col + stripe_width + gap <= image_size-1:
canvas[:, current_col:current_col+stripe_width] = 1
current_col += stripe_width + gap
elif current_col + stripe_width <= image_size-1:
canvas[:, current_col:current_col+stripe_width] = 1
current_col = image_size
else:
canvas[:, current_col:] = 1
current_col = image_size
plt.imshow(canvas)
</code></pre>
<p>And here's the image output from my code:
<a href="http://i.stack.imgur.com/nJJ9m.png" rel="nofollow">Current Output</a></p>
<p>And here's what I want the rotated image to look like:
<a href="http://i.stack.imgur.com/inCNQ.png" rel="nofollow">Desired Output</a></p>
<p>Any suggestions?</p>
| -1 |
2016-09-11T23:18:17Z
| 39,442,913 |
<p>You need to have a rotate method with respect to some <code>center</code>. For example below is a sample method. You will have to modify it for your needs, but that should be sufficient to start your code</p>
<pre><code> def rotate_point(center, point, angle):
"""Rotate point around center by angle
Args:
center:
Center point (tuple, [x,y])
point:
Point to be rotated (tuple, [x,y])
angle:
Angle in radians to rotate by
Returns:
New coordinates for the point
"""
angle = math.radians(angle)
temp_point = point[0]-center[0] , point[1]-center[1]
temp_point = ( -temp_point[0]*math.cos(angle)+temp_point[1]*math.sin(angle) , temp_point[0]*math.sin(angle)-temp_point[1]*math.cos(angle))
temp_point = [temp_point[0]+center[0] , temp_point[1]+center[1]]
return temp_point
</code></pre>
| 0 |
2016-09-12T03:18:38Z
|
[
"python",
"numpy"
] |
Python 3.5 While loop not entering the If Statements
| 39,441,606 |
<p>My apologies in advance. I know this question has probably been asked on stack exchange before and I do see some relevant posts,but I'm having some issue interpreting the responses.</p>
<p>I've been asked to create a guessing program that uses 'bisection search' to guess the number that you've selected (in your mind).</p>
<p>I have a program that runs on Python 2 interpreters when I change input() to raw_input(). My program also runs on a python 3 interpreter (python tutor). However when I run the program from scipython, pycharm or command line I do not see the response I'm expecting. Instead of moving through the if statements under the while loop the program seems to loop through the top of the while statement over and over again. I'll paste my code any suggestions would be appreciated.</p>
<pre><code>low = 0
high = 100
flag = True
print("Please think of a number between 0 and 100!")
while flag:
ans = (high + low) // 2
print("Is your secret number " + str(ans))
question = input(
"Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ")
if question == 'l':
low = ans
elif question == 'h':
high = ans
elif question == 'c':
flag = False
print("Game over. Your secret number was: " + str(ans))
else:
print('invalid response, please choose again.')
</code></pre>
<p>EDIT:
This is the output to console. There is no failure but as you can see the program is not entering the if conditionals. I entered the response to each conditional and it just returns the same guess. I assume that I'm not entering the if statements because I do not get a change to the answer or if I hit an incorrect character, I do not get to the else: print.</p>
<pre><code>Is your secret number 50
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
Is your secret number 50
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. h
Is your secret number 50
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. c
Is your secret number 50
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.
</code></pre>
<p>EDIT #2:
I just got it to work for some random unknown reason. scipython still won't run the code correctly, but the grading program marked me correct. So frustrating! </p>
| 1 |
2016-09-11T23:25:12Z
| 39,441,822 |
<p>Ok I figured it out after my code graded correctly. I was using the wrong console in scipython IDE to evaluate my code D'Oh</p>
<p>Anyways the code is a good example of taking an input() inside a while loop and using if/elsif/else to meet conditions.</p>
<p>Just remeber that in python 2 you'll want to use raw_input() instead of input() as the method changes from python 2 to 3</p>
| 1 |
2016-09-12T00:05:28Z
|
[
"python",
"python-3.x",
"bisection"
] |
Getting the date of the first day of the week
| 39,441,639 |
<p>I had a record in a table which contains a date field which will always be the date of the Sunday of a given week.</p>
<p>I would like to query the table so that the records that are returned are in the same week as the week in the date field of the records.</p>
<p>How could I use python's <code>datetime</code> library to achieve this? Thanks.</p>
| -3 |
2016-09-11T23:30:27Z
| 39,448,093 |
<p>To get the beginning date of the week:</p>
<pre><code>datetime.today() - timedelta(days=datetime.today().isoweekday() % 7)
</code></pre>
<p>I use this with a filter to get the Sunday date of a record.</p>
| 0 |
2016-09-12T10:19:08Z
|
[
"python",
"datetime"
] |
Methods to search and replace values in nested lists
| 39,441,646 |
<p>I'd like to search and replace values in a list of of list. I've cobbled together answers to:</p>
<ol>
<li><a href="http://stackoverflow.com/a/952952/2694260">Flatten a nested list</a></li>
<li><a href="http://stackoverflow.com/a/1540069/2694260">Search for and replace a value</a></li>
<li><a href="http://stackoverflow.com/a/6615011/2694260">Regroup the flat list into a list of lists</a></li>
</ol>
<p>My current code works however I feel that it's more convoluted then it needs to be. Is there a more elegant way of doing this?</p>
<pre><code># Create test data- a list of lists which each contain 2 items
numbers = list(range(10))
list_of_lists = [numbers[i:i+2] for i in range(0, len(numbers), 2)]
# Flatten the list of lists
flat_list = [item for sublist in list_of_lists for item in sublist]
# Search for and replace values
modified_list = [-1 if e > 5 else e for e in flat_list]
# Regroup into a list of lists
regrouped_list_of_lists = [modified_list[i:i+2] for i in range(0, len(modified_list), 2)]
</code></pre>
| 0 |
2016-09-11T23:32:22Z
| 39,441,668 |
<p>You're already using list comprehensions, just combine them:</p>
<pre><code>replaced_list_of_lists = [
[-1 if e > 5 else e for e in inner_list]
for inner_list in list_of_lists
]
</code></pre>
| 1 |
2016-09-11T23:36:41Z
|
[
"python"
] |
Methods to search and replace values in nested lists
| 39,441,646 |
<p>I'd like to search and replace values in a list of of list. I've cobbled together answers to:</p>
<ol>
<li><a href="http://stackoverflow.com/a/952952/2694260">Flatten a nested list</a></li>
<li><a href="http://stackoverflow.com/a/1540069/2694260">Search for and replace a value</a></li>
<li><a href="http://stackoverflow.com/a/6615011/2694260">Regroup the flat list into a list of lists</a></li>
</ol>
<p>My current code works however I feel that it's more convoluted then it needs to be. Is there a more elegant way of doing this?</p>
<pre><code># Create test data- a list of lists which each contain 2 items
numbers = list(range(10))
list_of_lists = [numbers[i:i+2] for i in range(0, len(numbers), 2)]
# Flatten the list of lists
flat_list = [item for sublist in list_of_lists for item in sublist]
# Search for and replace values
modified_list = [-1 if e > 5 else e for e in flat_list]
# Regroup into a list of lists
regrouped_list_of_lists = [modified_list[i:i+2] for i in range(0, len(modified_list), 2)]
</code></pre>
| 0 |
2016-09-11T23:32:22Z
| 39,441,670 |
<p>Make the replacements in the sublists in a <em>nested list comprehension</em> without having to flatten and regroup:</p>
<pre><code>numbers = list(range(10))
list_of_lists = [numbers[i:i+2] for i in range(0, len(numbers), 2)]
# here
list_of_lists = [[-1 if e > 5 else e for e in sublist] for sublist in list_of_lists]
</code></pre>
| 2 |
2016-09-11T23:37:08Z
|
[
"python"
] |
How to create tuples from a single list with alpha-numeric chacters?
| 39,441,730 |
<p>I have the following list with 2 elements:</p>
<pre><code>['AGCTT 6 6 35 25 10', 'AGGGT 7 7 28 29 2']
</code></pre>
<p>I need to make a list or zip file such that each alphabet corresponds to its number further in the list. For example in list[0] the list/zip should read</p>
<pre><code>{"A":"6", "G":"6", "C":"35","T":"25","T":"10"}
</code></pre>
<p>Can I make a list of such lists/zips that stores the corresponding vales for list[0], list[1],...list[n]?</p>
<p>Note: The alphabets can only be A,G,C or T, and the numbers can take anyvalue</p>
<p>Edit 1: Previously, I thought I could use a dictionary. But several members pointed out that this cannot be done. So I just want to make a list or zip or anything else recommended to pair the Alphabet element to its corresponding number. </p>
| 2 |
2016-09-11T23:46:30Z
| 39,441,768 |
<p>This code would work, assuming the elements in the list are correctly formed.
This means the number of letters and numbers must match!</p>
<p>And it will overwrite the value if the key already exists.</p>
<pre><code>list = ['AGCTT 6 6 35 25 10', 'AGGGT 7 7 28 29 2']
dictionary = {}
for line in list:
split_line = line.split()
letters = split_line[0]
iterator = 1
for letter in letters:
dictionary[letter] = split_line[iterator]
iterator += 1
print dictionary
</code></pre>
<p>This modified one will check if the key exists and add it to a list with that key:</p>
<pre><code>list = ['AGCTT 6 6 35 25 10', 'AGGGT 7 7 28 29 2']
dictionary = {}
for line in list:
split_line = line.split()
letters = split_line[0]
iterator = 1
for letter in letters:
if letter in dictionary.keys():
dictionary[letter].append(split_line[iterator])
else:
dictionary[letter] = [split_line[iterator]]
iterator += 1
print dictionary
</code></pre>
| -1 |
2016-09-11T23:54:41Z
|
[
"python",
"list",
"dictionary",
"zip",
"tuples"
] |
How to create tuples from a single list with alpha-numeric chacters?
| 39,441,730 |
<p>I have the following list with 2 elements:</p>
<pre><code>['AGCTT 6 6 35 25 10', 'AGGGT 7 7 28 29 2']
</code></pre>
<p>I need to make a list or zip file such that each alphabet corresponds to its number further in the list. For example in list[0] the list/zip should read</p>
<pre><code>{"A":"6", "G":"6", "C":"35","T":"25","T":"10"}
</code></pre>
<p>Can I make a list of such lists/zips that stores the corresponding vales for list[0], list[1],...list[n]?</p>
<p>Note: The alphabets can only be A,G,C or T, and the numbers can take anyvalue</p>
<p>Edit 1: Previously, I thought I could use a dictionary. But several members pointed out that this cannot be done. So I just want to make a list or zip or anything else recommended to pair the Alphabet element to its corresponding number. </p>
| 2 |
2016-09-11T23:46:30Z
| 39,441,797 |
<p>Use tuples splitting once to get the pairs, then split the second element of each pair, <em>zip</em> together:</p>
<pre><code>l =['AGCTT 6 6 35 25 10', 'AGGGT 7 7 28 29 2']
pairs = [zip(a,b.split()) for a,b in (sub.split(None,1) for sub in l]
</code></pre>
<p>Which would give you:</p>
<pre><code>[[('A', '6'), ('G', '6'), ('C', '35'), ('T', '25'), ('T', '10')], [('A', '7'), ('G', '7'), ('G', '28'), ('G', '29'), ('T', '2')]]
</code></pre>
<p>Of using a for loop with <em>list.append:</em></p>
<pre><code>l = ['AGCTT 6 6 35 25 10', 'AGGGT 7 7 28 29 2']
out = []
for a,b in (sub.split(None,1) for sub in l ):
out.append(zip(a,b))
</code></pre>
<p>If you want to convert any letter to <code>Z</code> where the digit is < 10, you just need another loop where we check the digit in each pairing:</p>
<pre><code>pairs = [[("Z", i ) if int(i) < 10 else (c, i) for c,i in zip(a, b.split())]
for a,b in (sub.split(None, 1) for sub in l)]
print(pairs)
</code></pre>
<p>Which would give you:</p>
<pre><code>[[('Z', '6'), ('Z', '6'), ('C', '35'), ('T', '25'), ('T', '10')], [('Z', '7'), ('Z', '7'), ('G', '28'), ('G', '29'), ('Z', '2')]]
</code></pre>
<p>To break it into a regular loop:</p>
<pre><code>pairs = []
for a, b in (sub.split(None, 1) for sub in l):
pairs.append([("Z", i) if int(i) < 10 else (c, i) for c, i in zip(a, b.split())])
print(pairs)
</code></pre>
<p><code>[("Z", i) if int(i) < 10 else (c, i) for c, i in zip(a, b.split())]</code> sets the letter to <code>Z</code> if the corresponding digit <code>i</code> is <code>< 10</code> or else we just leave the letter as is.</p>
<p>if you want to get back to the original pairs after you just need to <a href="https://en.wikipedia.org/wiki/Transpose" rel="nofollow">transpose</a> with <em>zip</em>:</p>
<pre><code>In [13]: l = ['AGCTT 6 6 35 25 10', 'AGGGT 7 7 28 29 2']
In [14]: pairs = [[("Z", i) if int(i) < 10 else (c, i) for c, i in zip(a, b.split())] for a, b in
....: (sub.split(None, 1) for sub in l)]
In [15]: pairs
Out[15]:
[[('Z', '6'), ('Z', '6'), ('C', '35'), ('T', '25'), ('T', '10')],
[('Z', '7'), ('Z', '7'), ('G', '28'), ('G', '29'), ('Z', '2')]]
In [16]: unzipped = [["".join(a), " ".join(b)] for a, b in (zip(*tup) for tup in pairs)]
In [17]: unzipped
Out[17]: [['ZZCTT', '6 6 35 25 10'], ['ZZGGZ', '7 7 28 29 2']]
</code></pre>
<p><code>zip(*...)</code> will give you the original elements back into a tuple of their own, we then just need to join the strings back together. If you wanted to get back to the total original state you could just join again:</p>
<pre><code>In[18][ " ".join(["".join(a), " ".join(b)]) for a, b in (zip(*tup) for tup in pairs) ]
Out[19]: ['ZZCTT 6 6 35 25 10', 'ZZGGZ 7 7 28 29 2']
</code></pre>
| 3 |
2016-09-11T23:59:07Z
|
[
"python",
"list",
"dictionary",
"zip",
"tuples"
] |
How to create tuples from a single list with alpha-numeric chacters?
| 39,441,730 |
<p>I have the following list with 2 elements:</p>
<pre><code>['AGCTT 6 6 35 25 10', 'AGGGT 7 7 28 29 2']
</code></pre>
<p>I need to make a list or zip file such that each alphabet corresponds to its number further in the list. For example in list[0] the list/zip should read</p>
<pre><code>{"A":"6", "G":"6", "C":"35","T":"25","T":"10"}
</code></pre>
<p>Can I make a list of such lists/zips that stores the corresponding vales for list[0], list[1],...list[n]?</p>
<p>Note: The alphabets can only be A,G,C or T, and the numbers can take anyvalue</p>
<p>Edit 1: Previously, I thought I could use a dictionary. But several members pointed out that this cannot be done. So I just want to make a list or zip or anything else recommended to pair the Alphabet element to its corresponding number. </p>
| 2 |
2016-09-11T23:46:30Z
| 39,441,824 |
<p>If you consider using tuples to pair the items, then this works: </p>
<pre><code>>>> from pprint import pprint
>>> lst = ['AGCTT 6 6 35 25 10', 'AGGGT 7 7 28 29 2']
>>> new_lst = [list(zip(sub[0], sub[1:])) for sub in [i.split() for i in lst]]
>>> pprint(new_lst)
[[('A', '6'), ('G', '6'), ('C', '35'), ('T', '25'), ('T', '10')],
[('A', '7'), ('G', '7'), ('G', '28'), ('G', '29'), ('T', '2')]]
</code></pre>
<ol>
<li><p><code>[i.split() for i in lst]</code>: An initial split on the string.</p></li>
<li><p><code>zip(sub[0], sub[1:]))</code>: Zip lists of alphabets and list of numbers</p></li>
</ol>
| 1 |
2016-09-12T00:05:56Z
|
[
"python",
"list",
"dictionary",
"zip",
"tuples"
] |
How to create tuples from a single list with alpha-numeric chacters?
| 39,441,730 |
<p>I have the following list with 2 elements:</p>
<pre><code>['AGCTT 6 6 35 25 10', 'AGGGT 7 7 28 29 2']
</code></pre>
<p>I need to make a list or zip file such that each alphabet corresponds to its number further in the list. For example in list[0] the list/zip should read</p>
<pre><code>{"A":"6", "G":"6", "C":"35","T":"25","T":"10"}
</code></pre>
<p>Can I make a list of such lists/zips that stores the corresponding vales for list[0], list[1],...list[n]?</p>
<p>Note: The alphabets can only be A,G,C or T, and the numbers can take anyvalue</p>
<p>Edit 1: Previously, I thought I could use a dictionary. But several members pointed out that this cannot be done. So I just want to make a list or zip or anything else recommended to pair the Alphabet element to its corresponding number. </p>
| 2 |
2016-09-11T23:46:30Z
| 39,444,830 |
<p>Iterate through list > iterate through items (alpha numeric) of the list and construct list of characters and numbers > and then construct list of tuple.</p>
<pre><code>alphanum = ['AGCTT 6 6 35 25 10', 'AGGGT 7 7 28 29 2']
list_of_tuple = []
for s in alphanum:
ints = []
chars = []
for i in s.split():
if i.isdigit():
ints.append(i)
else:
chars.append(i)
new_tuple = []
for (n, item) in enumerate(list(chars[0])):
new_tuple.append((item, ints[n]))
list_of_tuple.append(new_tuple)
print list_of_tuple
</code></pre>
| 0 |
2016-09-12T06:56:48Z
|
[
"python",
"list",
"dictionary",
"zip",
"tuples"
] |
Postgresql/Python compressing text column with a lot of redundant rows
| 39,441,734 |
<p>Note:</p>
<ul>
<li>We're using Amazon RDS, so we're very limited on the number of PostgreSQL extensions we can use.</li>
<li>I've said PostgreSQL on RDS , because 1) we must use AWS, 2) we want the safest solution on data integrity with lowest time spent on maintenance. (so if an other service is better suited with these requirements, we're open to suggestion)</li>
<li>we have several terabyte of said data, so space efficiency is important (but we can easily shard based on the source)</li>
</ul>
<p>We would like to store "logs" in a table with the following minimal set of fields (more maybe added for optimization purpose):</p>
<ul>
<li>source</li>
<li>time</li>
<li>level</li>
<li>message</li>
</ul>
<p>The message column has the following specificity
* 99% of the time very short (< 64 chars, but for the exceptions they can be quite long > 1024 chars)
* some of the well identified message can take up to 10% of the number of messages
* a lot of "nearly" duplicated messages (i.e like <code>this system hs been up and running for X seconds</code>)<br>
* a long tail of "unique" messages
* taking the messages of a typical day and running them through gzip easily divided the size by 15</p>
<p>Right now i'm thinking of two possible solution</p>
<h2>Compression algorithm accepting dictionary of user defined "tokens"</h2>
<p>The idea we have would be to have some kind of compression algorithm that can use a user provided "dictionnary" based on our identified list of "repeated text" and storing the result. as our "app" is the only one to write and read, we would be able to decompress "on the fly" </p>
<ul>
<li><strong>Pro</strong>: will permit certainly to have a pretty good compression ratio</li>
<li><strong>cons</strong>: I don't know where to search (LZ77 ? but i don't see how)</li>
</ul>
<h2>Dictionnary table for "exactly" matching predefined messages</h2>
<ul>
<li>LOGS_TABLE</li>
<li>source</li>
<li>time</li>
<li>level</li>
<li>dictionnary_id</li>
<li>message (nullable)</li>
</ul>
<p>_</p>
<ul>
<li>DICTIONNARY_TABLE</li>
<li>dictionnary_id</li>
<li>message</li>
</ul>
<p>_</p>
<ul>
<li><strong>Pro</strong>: I perfectly see how to implement it, and it's easy to "update"</li>
<li><strong>cons</strong>: Does not cover the "near" match </li>
</ul>
<p>Is there an already "state of the art" solution for this kind of problem ?</p>
| 1 |
2016-09-11T23:46:59Z
| 39,539,195 |
<p>I finally went with the dictionnary table idea</p>
<p>for the dictionnary_id I actually used a <code>murmurhash 64 bits</code> (and named the id <code>hash_message</code> so that I can precompute it on the python side first, and as it is a non-crytographic, it's pretty to call, for python there's a pure C implementation of it <code>mmh3</code> module).</p>
<p>I preloaded the dictionnary table with the 500k most common (and duplicated) logs out of the 507 millions messages I got from a "typical day" of logs.
Then I loaded the data doing the following <code>INSERT</code> request:</p>
<pre><code> INSERT INTO my_logs (
service_id,
creation_date,
level,
hash_message,
message
)
SELECT
%(hash_robot)s,
%(creation_date)s,
%(hash_message)s,
NULLIF (
%(message)s,
min(message)
)
FROM dictionnary
WHERE hash_message = %(hash_message)s;
</code></pre>
<p>by doing so, the insert automatically if the <code>message</code> is already existing, and only insert the actual text in my log table if it's not present in the dictionnary.</p>
<p>With I got an average of only 3 bytes used by the <code>message</code> column of my log table !! which mean that most of the time the message table is null, and though adding more logs in my dictionnary would not be worth it (and that switching from a <code>bigint</code> for my service_id to a <code>int</code> would actually be a better idea)</p>
| 0 |
2016-09-16T19:53:54Z
|
[
"python",
"algorithm",
"postgresql",
"compression"
] |
I am unable to get my code to count and reset to zero
| 39,441,863 |
<p>I am having an issue with creating code that will count when a pattern is not matched and reset back to 0 once that pattern has a match using regular expression. I will list a an example of the file and try to attempt to demonstrate what I am looking to do. No matter how many matches are in the file I receive a -1. I am also not sure how the numbers should be formatted in the text file. </p>
<p>regEx56 "locates all numbers that have 56 in it regardless of location) 256 526 065.
regEx57 "The same as 56 but uses 57 instead"</p>
<pre><code>p3text file. python count: 56 57
107 -1 -1
328 -2 -2
156 0 -3
725 -1 0
</code></pre>
<p>Here is my code:</p>
<pre><code>import re
my_p3text = open("p3text.txt", "r")
p3data = my_p3text.read()
regEx56 = str(re.findall(r'\b[0-4]*(?:5[0-4]?6|6[0-4]?5)[0-4]*\b',p3data))
regEx57 =str(r'\b[0-4]*(?:5[0-4]?7|7[0-4]?5)[0-4]*\b',p3data)
for line in my_p3text:
match=regEx56.search(line)
count = 0
print (match)
else:
count = -1
print (count)
</code></pre>
| -2 |
2016-09-12T00:13:34Z
| 39,442,831 |
<p>First of all:</p>
<pre><code>for line in my_p3text:
match=regEx56.search(line)
count = 0
print (match)
else:
count = -1
</code></pre>
<p>means that when there are no more lines, it will print -1, which is always. Put an if-else statement inside the for loop.</p>
<p>Also, right now your numbers can only start with 0-4, 5, 6 or 7; with a possible 0-4 between 6-7 and 5 (and vice versa). It also ends in a similar fashion to the way it starts.</p>
<p>If this is what you want, then it's fine, otherwise try...</p>
<pre><code>(\d*((5\d*?[67])|([67]\d*?5))\d*)
</code></pre>
| 0 |
2016-09-12T03:04:28Z
|
[
"python",
"regex"
] |
former form fields no longer found by mechanize python script
| 39,441,880 |
<p>Let me start by apologizing for my utter newbness. I was asked by a friend a couple years ago if I could write a program to automatically grab substitute teaching openings. It wasn't an area I knew anything about, but a couple tutorials allowed me to bang something out despite ignorance about html (and more than a little about Python for that matter). Script worked great since then but this year their site seems to have been redone and broke things, pushing it far beyond my understanding.</p>
<p>My previous code that worked:</p>
<pre><code># Create a Browser instance
b = mechanize.Browser()
# Load the page
b.open(loginURL)
# Select the form
b.select_form(nr=0)
# Fill out the form
b['id'] = 'XXXXXXXXXX' # Note: I edited out my friend's login info here for privacy
b['pin'] = 'XXXX'
b.submit();
</code></pre>
<p>There is still only one form but the controls are now of type "hidden" and are not the ones I directly need any longer. I can see the old fields in the html when I examine it with developer mode and the names are the same but I can't figure out (tried some things that didn't work) how I would access them now. Here is the html:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="loginform" name="loginform" method="post" action="https://www.aesoponline.com/login.asp?x=x&amp;&amp;pswd=&amp;sso=">
<input type="hidden" name="location" value="">
<input type="hidden" name="qstring" value="">
<input type="hidden" name="absr_ID" value="">
<input type="hidden" name="foil" value="">
<div style="margin: auto; text-align:center;">
<div id="loginContainer" style="text-align: left;">
<div id="loginContent">
<div id="Div1" style="position:relative; left:65px;" class="hide-me-for-rebranding">
<a href="http://www.frontlinetechnologies.com">
<img src="images/frontlinelogo.png" border="0">
</a>
</div>
<div id="loginLoginBox" style="position:relative;">
<div id="loginAesopLogo" style="padding-bottom:0px;" class="hide-me-for-rebranding"></div>
<!--endloginAesopLogo-->
<div id="loginLoginFields" style="margin-top:0px;">
<br>
<table>
<tbody>
<tr height="25px">
<td width="30px"><span class="corrLoginFormText">ID:</span>
</td>
<td>
<input type="text" class="loginFormText" maxlength="80" id="txtLoginID" name="id" value="">
</td>
</tr>
<tr height="25px">
<td width="30px"><span class="corrLoginFormText">Pin:</span>
</td>
<td>
<input type="password" class="loginFormText" maxlength="20" id="txtPassword" name="pin">
</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr height="30px">
<td width="75px" valign="top">
<a class="textButton" id="loginLink" name="loginLink" href="#"><span style="white-space:nowrap;">Login</span></a>
<input type="hidden" id="submitLogin" name="submitLogin" value="1">
</td>
<td>
<div id="loginhelp" style="float:right;">
<img src="images/icon.pinreminder.png" alt="pin" width="10" height="15" align="top"><a href="forgot_pin.asp">Pin Reminder</a>
<br>
<img src="images/icon.loginproblems.png" alt="login" width="11" height="17" align="top"> <a href="http://help.frontlinek12.com/Employee/Docs/ClientServicesHelpGuide-LoginProblems.pdf">Login Problems</a>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!--endloginLoginFields-->
<div id="errorLabel" style="position: absolute; top: 170px; left:5px;margin:0px;"><span class="assistanceText"></span>
</div>
</div>
<!--endloginLoginBox-->
<div id="loginContentText">
<span class="loginContentHeader">Welcome To Absence Management</span>
<br>
<span class="loginContentText">
You are about to enter Frontline Absence Management!<br> Please enter your ID and PIN to login to your account, or click the button below to learn more about Frontline's growing impact on education.</span>
<br>
<a class="textButton" href="http://www.frontlinek12.com/Products/Aesop.html"><span>Learn More</span></a>
</div>
<!--endloginContentText-->
</div>
<!--endLoginContent-->
<div id="loginFooterShading" class="hide-me-for-rebranding">
<div id="loginFooterLeft"></div>
<div id="loginFooterRight"></div>
</div>
<!--endloginFooterShading-->
<div id="loginFooter" style="text-align:center;width:725px;">
<a href="http://www.frontlinetechnologies.com/Privacy_Policy.html" style="color: rgb(153, 0, 0) ; font-size:9px;" target="_blank">Privacy Policy</a>
<br>© Frontline Technologies Group LLC &lt;
<parm1>&gt;
<br>All rights reserved. Protected under US Patents 6,334,133, 6,675,151, 7,430,519, 7,945,468 and 8,140,366 with additional patents pending.
</parm1>
</div>
<!--endloginReflections-->
</div>
<!--endLoginContainer-->
</div>
<!--end margin div -->
<!-- MODAL DIALOG -->
<div id="basicModalContent" style="display:none">
<span class="assistanceText"></span>
</div>
</form></code></pre>
</div>
</div>
</p>
<p>Any assistance would be greatly appreciated. Thank you very much.</p>
| 0 |
2016-09-12T00:15:32Z
| 39,441,959 |
<p>Try something like this if that html code is exactly what is on that page. When you put b.select_form(nr=0) there is the possibility that for some reason the first form is not what you are selecting. By looking for the form name in the b.select_form() you can ensure you find the correct form. Test it out and see if it works out. </p>
<pre><code>import mechanize
b = mechanize.Browser()
b.open(loginURL)
#since the actual form is named loginform just select it
b.select_form("loginform")
b['id'] name of login input field
b['pin']
b.submit()
</code></pre>
| 0 |
2016-09-12T00:30:34Z
|
[
"python",
"html",
"forms",
"mechanize",
"hidden"
] |
Run same loop twice, but getting different results
| 39,441,896 |
<p>I cannot figure this out, but say I have a depth-3 array of strings called "text".</p>
<p>How can it be that in the following code:</p>
<pre><code>print "FIRST"
for gate in text[1:]:
print "GATE"
for text in gate:
print "TEXT"
for entry in text:
print "ENTRY"
print what
print "SECOND"
for gate in text[1:]:
print "GATE"
for text in gate:
print "TEXT"
for entry in text:
print "ENTRY"
print what
</code></pre>
<p>I get different output for each loop.</p>
<p>"First"</p>
<pre class="lang-none prettyprint-override"><code>FIRST
GATE
TEXT
ENTRY
×
ENTRY
×××רת ××"×£
ENTRY
××× ×××ר ×ש×× ×××××ת, ×××¢××× ×× ××× ××¤× ×©×ת, ×ש ××× ×¨×ת ×¤× ×× ××× ×ת××× × ××ש××× ×ס×××ת××, ×× ×× ××××ת ×¢× ×× × ×שר ס××××ת×× ××ר××ת ×¤× ××, ×× ×××× ××ש×ת ×××××ת ×¢× ×שר ×ת××קת ××ר×× ××× ×¢× ×××©× ×¢×©×¨ ×¤× ××, ×¢× ×× ×ש ××× ×שר ××¢× ×× ××ש×× × ××××¨× ×¢××× ××××× ×¢× ××רת×. ××ש ××× ×שר ××× ××ש×ת ××¢× ×× ××××רת ×פתר×× ×ש×× ×¡×××, ××× ××× ×¤×ª×¨×× ××ש×× ×פשר ××××× ××¤× ××××§×ת××× ×ת×צ××ת×××.
TEXT
ENTRY
××.
</code></pre>
<p>"Second"</p>
<pre class="lang-none prettyprint-override"><code>SECOND
GATE
TEXT
ENTRY
×
TEXT
ENTRY
ת
TEXT
ENTRY
×
TEXT
ENTRY
×
TEXT
ENTRY
</code></pre>
<p>Each Loop is coded exactly the same and yet I get different output. How is this possible?</p>
| 1 |
2016-09-12T00:18:52Z
| 39,441,910 |
<p><code>text</code> has been modified. Before the SECOND loop, <code>text</code> has its value taken from the last iteration of <code>for text in gate: ...</code></p>
<p>You should consider renaming the inner loop variable to something different.</p>
| 6 |
2016-09-12T00:22:02Z
|
[
"python"
] |
Run same loop twice, but getting different results
| 39,441,896 |
<p>I cannot figure this out, but say I have a depth-3 array of strings called "text".</p>
<p>How can it be that in the following code:</p>
<pre><code>print "FIRST"
for gate in text[1:]:
print "GATE"
for text in gate:
print "TEXT"
for entry in text:
print "ENTRY"
print what
print "SECOND"
for gate in text[1:]:
print "GATE"
for text in gate:
print "TEXT"
for entry in text:
print "ENTRY"
print what
</code></pre>
<p>I get different output for each loop.</p>
<p>"First"</p>
<pre class="lang-none prettyprint-override"><code>FIRST
GATE
TEXT
ENTRY
×
ENTRY
×××רת ××"×£
ENTRY
××× ×××ר ×ש×× ×××××ת, ×××¢××× ×× ××× ××¤× ×©×ת, ×ש ××× ×¨×ת ×¤× ×× ××× ×ת××× × ××ש××× ×ס×××ת××, ×× ×× ××××ת ×¢× ×× × ×שר ס××××ת×× ××ר××ת ×¤× ××, ×× ×××× ××ש×ת ×××××ת ×¢× ×שר ×ת××קת ××ר×× ××× ×¢× ×××©× ×¢×©×¨ ×¤× ××, ×¢× ×× ×ש ××× ×שר ××¢× ×× ××ש×× × ××××¨× ×¢××× ××××× ×¢× ××רת×. ××ש ××× ×שר ××× ××ש×ת ××¢× ×× ××××רת ×פתר×× ×ש×× ×¡×××, ××× ××× ×¤×ª×¨×× ××ש×× ×פשר ××××× ××¤× ××××§×ת××× ×ת×צ××ת×××.
TEXT
ENTRY
××.
</code></pre>
<p>"Second"</p>
<pre class="lang-none prettyprint-override"><code>SECOND
GATE
TEXT
ENTRY
×
TEXT
ENTRY
ת
TEXT
ENTRY
×
TEXT
ENTRY
×
TEXT
ENTRY
</code></pre>
<p>Each Loop is coded exactly the same and yet I get different output. How is this possible?</p>
| 1 |
2016-09-12T00:18:52Z
| 39,441,913 |
<p><code>for</code> loops "leak" variables. You might expect <code>gate</code>, <code>text</code>, and <code>entry</code> to be scoped to their respective loops, but they're actually global. So, at the end of this loop</p>
<pre><code>for text in gate:
</code></pre>
<p>The value of <code>text</code> has been altered, which affects the next loop.</p>
<p>Here's a more minimal example:</p>
<pre><code>x = 'abc'
for x in x:
print x,
# output: "a b c"
for x in x:
print x,
# output: "c"
</code></pre>
<p>(If being able to run the same code twice and get the same result is the kind of thing that you find valuable, Python might not be the right choice of language for you. There are plenty of <a href="https://en.wikipedia.org/wiki/Purely_functional_programming">lovely</a> languages that do have this property.)</p>
| 7 |
2016-09-12T00:22:21Z
|
[
"python"
] |
Reindexing a multiindex in pandas dataframe
| 39,441,925 |
<p>I'm trying to reindex a 2-level multiindex pandas dataframe. Data struct looks like this:</p>
<pre><code>In [1]: df.head(5)
Out [1]: arrivals departs
station datetime
S1 2014-03-03 07:45:00 1 1
2014-03-03 09:00:00 2 1
2014-03-03 11:45:00 1 1
2014-03-04 08:45:00 1 1
2014-03-04 09:45:00 2 1
</code></pre>
<p>I want to fill <code>datetime</code> gaps with 15 minute intervals, but when I call</p>
<pre><code>In [2]: df.reindex(pd.date_range(start='2014-03-03 07:45:00',
end='2014-03-04 07:45:00', freq='15min'), level=1)
</code></pre>
<p>I get the exact same dataframe. I expected something like the following</p>
<pre><code>Out [2]: arrivals departs
station datetime
S1 2014-03-03 07:45:00 1 1 <-- original row
2014-03-03 08:00:00 0 0 <-- filled in row
2014-03-03 08:15:00 0 0 <-- filled in
2014-03-03 08:30:00 0 0 <-- filled in
2014-03-03 08:45:00 0 0 <-- filled in
2014-03-03 09:00:00 2 1 <-- original
etc...
</code></pre>
<p>Any ideas?</p>
| 1 |
2016-09-12T00:24:10Z
| 39,442,551 |
<p>Turn it back into a simple datetimeindex and fill the gaps:</p>
<pre><code>df = (df.unstack(level=0)
.reindex(pd.date_range(start='2014-03-03 07:45:00',
end='2014-03-04 07:45:00', freq='15min')))
df = df.fillna(0) # for the data, 0 is the desired value
df.stack('station').swaplevel(0,1).sort_index()
</code></pre>
| 1 |
2016-09-12T02:14:22Z
|
[
"python",
"pandas",
"multi-index"
] |
How to get x,y position of contours in Python OpenCV
| 39,441,935 |
<p>I'm trying to get x and y positions of contours from the following image, but I messed up.
<a href="http://i.stack.imgur.com/ctBI9.png" rel="nofollow">the image</a></p>
<p>I just need to find x and y positions of contours or center of the contours.</p>
<p>The results will be something like the following as I manually look up their positions from GIMP.</p>
<p>290, 210
982, 190
570, 478 </p>
<p>I believe it can be done with cv2.findContours method, but I'm really out of ideas right now.</p>
<p>-Offtopic-</p>
<p>I will use these values in setting cursor position usingwin32api.SetCursorPos((xposition,yposition))</p>
<p>Thanks</p>
| -2 |
2016-09-12T00:26:08Z
| 39,458,083 |
<p>Indeed, you can do that with <code>findContours</code>. Since you have your contours there are several options:</p>
<ol>
<li>Calculate enclosing rectangle and take e.g. the center point.</li>
<li>Calculate moments and take the centroid </li>
<li>Fit minimum enclosing circle and take the center</li>
<li>and so on...</li>
</ol>
<p><a href="http://docs.opencv.org/trunk/dd/d49/tutorial_py_contour_features.html" rel="nofollow">Here</a> are some examples of what you can do with your contours, including the options above. </p>
| 0 |
2016-09-12T20:11:38Z
|
[
"python",
"opencv"
] |
If statements with undefined variable
| 39,442,055 |
<p>I'm not sure what I'm doing wrong I tried to define "if the answer was <code>'Y'</code> Then <code>premium_membership=true</code>" but I keep getting this error. The beginning is as far as I get when I run the code and the second is my code.</p>
<pre><code>What is your name? John Smith
How many books are you purchasing today? 5
Are you apart of our membership program? Enter Y for yes or N for No. N
Would you like to join our membership program for $4.95? Enter Y for yes or N for no. N
Thank you for your interest, and thanks for shopping with us!
John Smith
The customer is purchasing 5.0 books
Traceback (most recent call last):
File , line 41, in <module>
if premium_member==True:
NameError: name 'premium_member' is not defined
>>>
</code></pre>
<hr>
<pre><code>#ask what customer's name is
customer_name=input("What is your name?")
#ask customer how many books they are purchasing
#define answer as float so you can multiply by price later
books_purchased=float(input("How many books are you purchasing today?"))
#ask customer if they are a member
membership=input("Are you apart of our membership program? Enter Y for yes or N for No.")
#determine if and print if member or not
if membership =='Y':
premium_member=True
else:
join=input("Would you like to join our membership program for $4.95? Enter Y for yes or N for no.")
#define join
if join =='Y':
print("Thank you for joining our Membership Program!")
else:
print("Thank you for your interest, and thanks for shopping with us!")
#print name
print("\n",customer_name)
#print number of books purchased
print("The customer is purchasing", books_purchased, "books")
#determine if they customer is premium
if premium_member==True:
print("Premium Member")
else:
print("Regular Member")
#determine if customer gets any free books
if premium_member==True:
if book_purchased>9:
print("Congratulations you get two books for free!")
total_books=book_purchased+2
else:
if book_purchased >6 and book_purchased<=9:
print("Congratulations you get one book for free!")
total_books=books_purchased+1
else:
total_books=books_purchased
else:
if books_purchased>12:
print("Congratulations you get two books for free!")
total_books=book_purchased+2
else:
if books_purchased >8 and books_purchased <=12:
print("Congratulations you get one book for free!")
total_books=book_purchased+1
else:
total_books=books_purchased
</code></pre>
| 0 |
2016-09-12T00:47:56Z
| 39,442,079 |
<p>In this section of code</p>
<pre><code>if membership =='Y':
premium_member=True
else:
join=input("Would you like to join our membership program for $4.95? Enter Y for yes or N for no.")
</code></pre>
<p>you're assigning <code>premium_member=True</code> in the case that <code>membership</code> is equal to <code>'Y'</code> but in the case that it's not (the <code>else</code> branch) you aren't assigning a value at all, meaning that the variable will be undefined. You should add the line <code>premium_member=False</code> to the <code>else</code> branch.</p>
<pre><code>if membership =='Y':
premium_member=True
else:
premium_member=False
join=input("Would you like to join our membership program for $4.95? Enter Y for yes or N for no.")
</code></pre>
| 4 |
2016-09-12T00:53:13Z
|
[
"python",
"python-3.x"
] |
Scraping several pages with BeautifulSoup
| 39,442,058 |
<p>I'd like to scrape through several pages of a website using Python and BeautifulSoup4. The pages differ by only a single number in their URL, so I could actually make a declaration like this:</p>
<pre><code>theurl = "beginningofurl/" + str(counter) + "/endofurl.html"
</code></pre>
<p>The link I've been testing with is this:</p>
<p>And my python script is this: <a href="http://www.worldofquotes.com/topic/Art/1/index.html" rel="nofollow">http://www.worldofquotes.com/topic/Art/1/index.html</a></p>
<pre><code>import urllib
import urllib.request
from bs4 import BeautifulSoup
def category_crawler():
''' This function will crawl through an entire category, regardless how many pages it consists of. '''
pager = 1
while pager < 11:
theurl = "http://www.worldofquotes.com/topic/Nature/"+str(pager)+"/index.html"
thepage = urllib.request.urlopen(theurl)
soup = BeautifulSoup(thepage, "html.parser")
for link in soup.findAll('blockquote'):
sanitized = link.find('p').text.strip()
spantext = link.find('a')
writer = spantext.find('span').text
print(sanitized)
print(writer)
print('---------------------------------------------------------')
pager += 1
category_crawler()
</code></pre>
<p>So the question is: how to change the hardcoded number in the while loop into a solution that makes the script automatically recognize that it passed the last page, and then it quits automatically?</p>
| 1 |
2016-09-12T00:48:21Z
| 39,442,266 |
<p>Try with <code>requests</code> (avoiding redirections) and check if you get new quotes.</p>
<pre><code>import requests
from bs4 import BeautifulSoup
def category_crawler():
''' This function will crawl through an entire category, regardless how many pages it consists of. '''
pager = 1
while pager < 11:
theurl = "http://www.worldofquotes.com/topic/Art/"+str(pager)+"/index.html"
thepage = requests.get(theurl, allow_redirects=False).text
soup = BeautifulSoup(thepage, "html.parser")
for link in soup.find_all('blockquote'):
sanitized = link.find('p').text.strip()
spantext = link.find('a')
writer = spantext.find('span').text
if not sanitized:
break
print(sanitized)
print(writer)
print('---------------------------------------------------------')
pager += 1
category_crawler()
</code></pre>
| 0 |
2016-09-12T01:27:10Z
|
[
"python",
"beautifulsoup"
] |
Scraping several pages with BeautifulSoup
| 39,442,058 |
<p>I'd like to scrape through several pages of a website using Python and BeautifulSoup4. The pages differ by only a single number in their URL, so I could actually make a declaration like this:</p>
<pre><code>theurl = "beginningofurl/" + str(counter) + "/endofurl.html"
</code></pre>
<p>The link I've been testing with is this:</p>
<p>And my python script is this: <a href="http://www.worldofquotes.com/topic/Art/1/index.html" rel="nofollow">http://www.worldofquotes.com/topic/Art/1/index.html</a></p>
<pre><code>import urllib
import urllib.request
from bs4 import BeautifulSoup
def category_crawler():
''' This function will crawl through an entire category, regardless how many pages it consists of. '''
pager = 1
while pager < 11:
theurl = "http://www.worldofquotes.com/topic/Nature/"+str(pager)+"/index.html"
thepage = urllib.request.urlopen(theurl)
soup = BeautifulSoup(thepage, "html.parser")
for link in soup.findAll('blockquote'):
sanitized = link.find('p').text.strip()
spantext = link.find('a')
writer = spantext.find('span').text
print(sanitized)
print(writer)
print('---------------------------------------------------------')
pager += 1
category_crawler()
</code></pre>
<p>So the question is: how to change the hardcoded number in the while loop into a solution that makes the script automatically recognize that it passed the last page, and then it quits automatically?</p>
| 1 |
2016-09-12T00:48:21Z
| 39,442,352 |
<p>Here is my attempt. </p>
<p>Minor issue: put a <code>try-except</code> block in the code in case the redirection leads you somewhere that doesn't exist. </p>
<p>Now, the main issue: how to avoid parsing stuff you already parsed. Keep a record of urls that you have parsed. Then detect if the <em>actual</em> url from the page <code>urllib</code> is reading from (using the <code>geturl()</code> method from from <code>thepage</code>) has already been read. Worked on my Mac OSX machine. </p>
<p>Note: there are 10 pages in total according to what I see from the website and this method does not require prior knowledge about the page's HTML- it works in general.</p>
<pre><code>import urllib
import urllib.request
from bs4 import BeautifulSoup
def category_crawler():
''' This function will crawl through an entire category, regardless how many pages it consists of. '''
urlarchive = [];
pager = 1
while True:
theurl = "http://www.worldofquotes.com/topic/Nature/"+str(pager)+"/index.html"
thepage = None;
try:
thepage = urllib.request.urlopen(theurl)
if thepage.geturl() in urlarchive:
break;
else:
urlarchive.append(thepage.geturl());
print(pager);
except:
break;
soup = BeautifulSoup(thepage, "html.parser")
for link in soup.findAll('blockquote'):
sanitized = link.find('p').text.strip()
spantext = link.find('a')
writer = spantext.find('span').text
print(sanitized)
print(writer)
print('---------------------------------------------------------')
pager += 1
category_crawler()
</code></pre>
| 0 |
2016-09-12T01:38:06Z
|
[
"python",
"beautifulsoup"
] |
Scraping several pages with BeautifulSoup
| 39,442,058 |
<p>I'd like to scrape through several pages of a website using Python and BeautifulSoup4. The pages differ by only a single number in their URL, so I could actually make a declaration like this:</p>
<pre><code>theurl = "beginningofurl/" + str(counter) + "/endofurl.html"
</code></pre>
<p>The link I've been testing with is this:</p>
<p>And my python script is this: <a href="http://www.worldofquotes.com/topic/Art/1/index.html" rel="nofollow">http://www.worldofquotes.com/topic/Art/1/index.html</a></p>
<pre><code>import urllib
import urllib.request
from bs4 import BeautifulSoup
def category_crawler():
''' This function will crawl through an entire category, regardless how many pages it consists of. '''
pager = 1
while pager < 11:
theurl = "http://www.worldofquotes.com/topic/Nature/"+str(pager)+"/index.html"
thepage = urllib.request.urlopen(theurl)
soup = BeautifulSoup(thepage, "html.parser")
for link in soup.findAll('blockquote'):
sanitized = link.find('p').text.strip()
spantext = link.find('a')
writer = spantext.find('span').text
print(sanitized)
print(writer)
print('---------------------------------------------------------')
pager += 1
category_crawler()
</code></pre>
<p>So the question is: how to change the hardcoded number in the while loop into a solution that makes the script automatically recognize that it passed the last page, and then it quits automatically?</p>
| 1 |
2016-09-12T00:48:21Z
| 39,442,359 |
<p>The idea is to <em>have an endless loop and break it once you don't have the "arrow right" element on the page</em> which would mean you are on the last page, simple and quite logical:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
page = 1
url = "http://www.worldofquotes.com/topic/Nature/{page}/index.html"
with requests.Session() as session:
while True:
response = session.get(url.format(page=page))
soup = BeautifulSoup(response.content, "html.parser")
# TODO: parse the page and collect the results
if soup.find(class_="icon-arrow-right") is None:
break # last page
page += 1
</code></pre>
<p>Note that we are <a class='doc-link' href="http://stackoverflow.com/documentation/python/1792/web-scraping-with-python/8152/maintaining-web-scraping-session-with-requests#t=201609120141377732173">maintaining the web-scraping session with <code>requests</code> here</a>.</p>
| 0 |
2016-09-12T01:39:05Z
|
[
"python",
"beautifulsoup"
] |
Merging with more than one level overlap not allowed
| 39,442,064 |
<p>So, I'm using pandas and essentially trying to calculate a normalized weight. For each day in my dataframe, I want the 'SECTOR' weight grouped by 'CAP', but they won't sum up to 1, so I want to normalize them as well. I thought I could accomplish this by dividing two groupbys, but I'm getting an error on my code that I don't quite understand. The code can run if I eliminate the 'CAP' in the second groupby.</p>
<p>Can anyone explain this to me?</p>
<pre><code>df.groupby(['EFFECTIVE DATE','CAP','SECTOR'])['INDEX WEIGHT'].sum() / df.groupby(['EFFECTIVE DATE','CAP'])['INDEX WEIGHT'].sum()
NotImplementedError: merging with more than one level overlap on a multi-index is not implemented
</code></pre>
<p>Anybody know what I need to change? As always thank you!!!</p>
| 2 |
2016-09-12T00:50:07Z
| 39,447,470 |
<p><strong><em>Option 1</em></strong><br>
Very close to what you had</p>
<pre><code>cols = ['EFFECTIVE DATE', 'CAP', 'SECTOR', 'INDEX WEIGHT']
sector_sum = df.groupby(cols[:3])[cols[-1]].sum()
cap_sum = df.groupby(cols[:2])[cols[-1]].transform(pd.Series.sum).values
sector_sum / cap_sum
</code></pre>
<p><strong><em>Option 2</em></strong><br>
Use a single <code>transform</code></p>
<pre><code>cols = ['EFFECTIVE DATE', 'CAP', 'SECTOR', 'INDEX WEIGHT']
sumto = lambda x: x / x.sum()
df.groupby(cols[:3])[cols[-1]].sum().groupby(level=cols[:2]).transform(sumto)
</code></pre>
<p>If you consider the <code>df</code></p>
<pre><code>df = pd.DataFrame([
[0, 'Large', 'A', .1, 'a'],
[0, 'Large', 'B', .2, 'b'],
[0, 'Large', 'C', .1, 'c'],
[0, 'Large', 'D', .3, 'd'],
[0, 'Large', 'E', .1, 'e'],
[0, 'Large', 'F', .4, 'f'],
[0, 'Large', 'G', .1, 'g'],
[0, 'Small', 'A', .2, 'h'],
[0, 'Small', 'B', .3, 'i'],
[0, 'Small', 'C', .4, 'j'],
[0, 'Small', 'D', .5, 'k'],
[0, 'Small', 'E', .1, 'l'],
[0, 'Small', 'F', .2, 'm'],
[0, 'Small', 'G', .1, 'n'],
[1, 'Large', 'A', .1, 'a'],
[1, 'Large', 'B', .2, 'b'],
[1, 'Large', 'C', .1, 'c'],
[1, 'Large', 'D', .3, 'd'],
[1, 'Large', 'E', .1, 'e'],
[1, 'Large', 'F', .4, 'f'],
[1, 'Large', 'G', .1, 'g'],
[1, 'Small', 'A', .2, 'h'],
[1, 'Small', 'B', .3, 'i'],
[1, 'Small', 'C', .4, 'j'],
[1, 'Small', 'D', .5, 'k'],
[1, 'Small', 'E', .1, 'l'],
[1, 'Small', 'F', .2, 'm'],
[1, 'Small', 'G', .1, 'n'],
], columns=['EFFECTIVE DATE', 'CAP', 'SECTOR', 'INDEX WEIGHT', 'ID'])
</code></pre>
<p>Both options produce</p>
<pre><code>EFFECTIVE DATE CAP SECTOR
0 Large A 0.076923
B 0.153846
C 0.076923
D 0.230769
E 0.076923
F 0.307692
G 0.076923
Small A 0.111111
B 0.166667
C 0.222222
D 0.277778
E 0.055556
F 0.111111
G 0.055556
1 Large A 0.076923
B 0.153846
C 0.076923
D 0.230769
E 0.076923
F 0.307692
G 0.076923
Small A 0.111111
B 0.166667
C 0.222222
D 0.277778
E 0.055556
F 0.111111
G 0.055556
Name: INDEX WEIGHT, dtype: float64
</code></pre>
<p>If you assign one of the options to <code>df1</code> then sum the sub-groups</p>
<pre><code>df1.groupby(level=['EFFECTIVE DATE', 'CAP']).sum()
EFFECTIVE DATE CAP
0 Large 1.0
Small 1.0
1 Large 1.0
Small 1.0
Name: INDEX WEIGHT, dtype: float64
</code></pre>
<hr>
<h3>Timing</h3>
<p><a href="http://i.stack.imgur.com/W67TF.png" rel="nofollow"><img src="http://i.stack.imgur.com/W67TF.png" alt="enter image description here"></a></p>
| 2 |
2016-09-12T09:42:34Z
|
[
"python",
"pandas"
] |
Confused by results from simple calculation
| 39,442,102 |
<p>I am not sure why the below code is not working. I am running this in python 3.5.2 and the problem appears to be in the calculation portion of the code. It returns no errors but gives huge values that shouldn't be the average of the 5 inputs.</p>
<pre><code>#inputs
year1 = input("Enter wins for year 1: ")
year2 = input("Enter wins for year 2: ")
year3 = input("Enter wins for year 3: ")
year4 = input("Enter wins for year 4: ")
year5 = input("Enter wins for year 5: ")
#calculation
averageWin = int(year1 + year2 + year3 + year4 + year5) / 5
#output
print ("Average wins are", averageWin)
</code></pre>
| -2 |
2016-09-12T00:58:03Z
| 39,442,111 |
<p>you need to cast the input values to integer individually</p>
<pre><code>averageWin = (int(year1) + int(year2) + int(year3) + int(year4) + int(year5)) / 5
</code></pre>
<p>What you did before was concatenating the strings:</p>
<pre><code>int('100' + '100') => int('100100') => 100100
</code></pre>
| 1 |
2016-09-12T01:00:09Z
|
[
"python",
"python-3.x",
"average"
] |
Confused by results from simple calculation
| 39,442,102 |
<p>I am not sure why the below code is not working. I am running this in python 3.5.2 and the problem appears to be in the calculation portion of the code. It returns no errors but gives huge values that shouldn't be the average of the 5 inputs.</p>
<pre><code>#inputs
year1 = input("Enter wins for year 1: ")
year2 = input("Enter wins for year 2: ")
year3 = input("Enter wins for year 3: ")
year4 = input("Enter wins for year 4: ")
year5 = input("Enter wins for year 5: ")
#calculation
averageWin = int(year1 + year2 + year3 + year4 + year5) / 5
#output
print ("Average wins are", averageWin)
</code></pre>
| -2 |
2016-09-12T00:58:03Z
| 39,442,125 |
<p>You are concatenating strings, and then turning that into an integer. You have to turn each individual string into an integer before adding them.</p>
<pre><code>>>> a = '3'
>>> b = '5'
>>> c = '4'
>>> x = a+b+c
>>> int(x)
354
>>> x
'354'
>>> int(a)+int(b)+int(c)
12
</code></pre>
<p>Also, instead of naming individual variables, use a <code>list</code>.</p>
<pre><code>>>> result = [int(input('Enter wins for year %d: ' % i)) for i in range(1,6)]
Enter wins for year 1: 3
Enter wins for year 2: 4
Enter wins for year 3: 3
Enter wins for year 4: 5
Enter wins for year 5: 5
>>> sum(result)/len(result)
4.0
</code></pre>
| 0 |
2016-09-12T01:02:15Z
|
[
"python",
"python-3.x",
"average"
] |
Confused by results from simple calculation
| 39,442,102 |
<p>I am not sure why the below code is not working. I am running this in python 3.5.2 and the problem appears to be in the calculation portion of the code. It returns no errors but gives huge values that shouldn't be the average of the 5 inputs.</p>
<pre><code>#inputs
year1 = input("Enter wins for year 1: ")
year2 = input("Enter wins for year 2: ")
year3 = input("Enter wins for year 3: ")
year4 = input("Enter wins for year 4: ")
year5 = input("Enter wins for year 5: ")
#calculation
averageWin = int(year1 + year2 + year3 + year4 + year5) / 5
#output
print ("Average wins are", averageWin)
</code></pre>
| -2 |
2016-09-12T00:58:03Z
| 39,442,127 |
<h2>By default, <code>input()</code> returns a string. You are adding the strings and then converting the result into an <code>int.</code></h2>
<p>Assume we have the inputs <code>1, 2, 3, 4, 5</code> as our variables. Your code does <code>'1'+ '2' + '3' + '4' + '5'</code> instead of <code>1 + 2 + 3 + 4 + 5</code>. Your result is <code>'12345'</code> instead of <code>15</code>. So you are dividing 12345 by 5 instead of 15. To fix this, put <code>int()</code> around each of your <code>input()</code> calls, to convert those answers into numbers. </p>
| 0 |
2016-09-12T01:02:28Z
|
[
"python",
"python-3.x",
"average"
] |
Confused by results from simple calculation
| 39,442,102 |
<p>I am not sure why the below code is not working. I am running this in python 3.5.2 and the problem appears to be in the calculation portion of the code. It returns no errors but gives huge values that shouldn't be the average of the 5 inputs.</p>
<pre><code>#inputs
year1 = input("Enter wins for year 1: ")
year2 = input("Enter wins for year 2: ")
year3 = input("Enter wins for year 3: ")
year4 = input("Enter wins for year 4: ")
year5 = input("Enter wins for year 5: ")
#calculation
averageWin = int(year1 + year2 + year3 + year4 + year5) / 5
#output
print ("Average wins are", averageWin)
</code></pre>
| -2 |
2016-09-12T00:58:03Z
| 39,442,193 |
<p>Try this.</p>
<pre><code> year = 0
for i in range(5):
ann = "{:,.0f}".format(i+1)
year=year+input("Enter wins for year "+ann+": ")
print year/5.
</code></pre>
<p>Shorter and works.</p>
| 0 |
2016-09-12T01:12:27Z
|
[
"python",
"python-3.x",
"average"
] |
itertools.groupby function seems inconsistent
| 39,442,128 |
<p>I'm having trouble understanding exactly what it is that this function does because of I guess, the programming magic around its use?</p>
<p>It seems to me like it returns a list of keys (unique letters in a string) paired with iterators, that reference a list of the number of each of those letters in the original string, but sometimes it seems like this is not the case.</p>
<p>For example:</p>
<pre><code>import itertools
x = list(itertools.groupby("AAABBB"))
print x
</code></pre>
<p>which prints:</p>
<pre><code>[('A', <itertools._grouper object at 0x101a0b050),
('B', <itertools._grouper object at 0x101a0b090)]
</code></pre>
<p>This seems correct, we have our unique keys paired with iterators. But when I run:</p>
<pre><code>print list(x[0][1])
</code></pre>
<p>I get:</p>
<pre><code>[]
</code></pre>
<p>and when I run</p>
<pre><code>for k, g in x:
print k + ' - ' + g
</code></pre>
<p>I get:</p>
<pre><code>B - <itertools._grouper object at 0x1007eedd5>
</code></pre>
<p>It ignores the first element. This seems counter-intuitive, because if I just change the syntax a little bit:</p>
<pre><code>[list(g) for k, g in itertools.groupby("AAABBB")]
</code></pre>
<p>I get:</p>
<pre><code>[["A", "A", "A"], ["B", "B", "B"]]
</code></pre>
<p>which is right, and aligns with what I think this function should be doing.</p>
<p>However, if I once again change the syntax just a bit:</p>
<pre><code>[list(thing) for thing in [g for k, g in itertools.groupby(string)]]
</code></pre>
<p>I get back:</p>
<pre><code>[[], ['B']]
</code></pre>
<p>These two list comprehensions should be directly equivalent, but they return different results.</p>
<p>What is going on? Insight would be extremely appreciated.</p>
| 2 |
2016-09-12T01:02:38Z
| 39,442,145 |
<p>To get the answers you expect, convert the returned iterators to a list.</p>
<p><a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow"><em>Groupby</em></a> consumes an input iterator lazily (that means that it reads data only as needed). To find a new group, it needs to read up to next non-equal element (the first member of the next group). If you <em>list</em> the subgroup iterator, it will advance the input to the end of the current group.</p>
<p>In general, if you advance to the next group, then the previously returned subgroup iterator won't have an data and will appear empty. So, if you need the data in the subgroup iterator, you need to <em>list</em> it <strong>before</strong> advancing to the next group.</p>
<p>The reason for this behavior is that iterators are all about looking a one piece of data at a time and not keeping anything unnecessary in memory.</p>
<p>Here's some code that make all the operations visible:</p>
<pre><code>from itertools import groupby
def supply():
'Make the lazy input visible'
for c in 'aaaaabbbcdddddddeeee':
print('supplying %r' % c)
yield c
print("\nCase where we don't consume the sub-iterator")
for k, g in groupby(supply()):
print('Got group for %r' % k)
print("\nCase where we do consume the sub-iterator before advancing")
for k, g in groupby(supply()):
print('Got group for %r' % k)
print(list(g))
</code></pre>
<p>In the example "that is driving you crazy", the <em>list</em> operation is being applied too late (in the outer list comprehension). The solution is to move the <em>list</em> step to the inner comprehension:</p>
<pre><code>>>> import itertools
>>> [list(g) for k, g in itertools.groupby('aaaaabbbb')]
>>> [['a', 'a', 'a', 'a', 'a'], ['b', 'b', 'b', 'b']]
</code></pre>
<p>If you don't really care about conserving memory, then running <code>grouped = [list(g) for k, g in itertools.groupby(data)]</code> is a perfectly reasonable way to go. Then you can lookup data in any of the sublists whenever you want and not be subject to rules about when the iterator is consumed. In general, list of lists are easier to work with than iterators. Hope this helps :-)</p>
| 4 |
2016-09-12T01:06:07Z
|
[
"python",
"group-by",
"list-comprehension",
"itertools"
] |
itertools.groupby function seems inconsistent
| 39,442,128 |
<p>I'm having trouble understanding exactly what it is that this function does because of I guess, the programming magic around its use?</p>
<p>It seems to me like it returns a list of keys (unique letters in a string) paired with iterators, that reference a list of the number of each of those letters in the original string, but sometimes it seems like this is not the case.</p>
<p>For example:</p>
<pre><code>import itertools
x = list(itertools.groupby("AAABBB"))
print x
</code></pre>
<p>which prints:</p>
<pre><code>[('A', <itertools._grouper object at 0x101a0b050),
('B', <itertools._grouper object at 0x101a0b090)]
</code></pre>
<p>This seems correct, we have our unique keys paired with iterators. But when I run:</p>
<pre><code>print list(x[0][1])
</code></pre>
<p>I get:</p>
<pre><code>[]
</code></pre>
<p>and when I run</p>
<pre><code>for k, g in x:
print k + ' - ' + g
</code></pre>
<p>I get:</p>
<pre><code>B - <itertools._grouper object at 0x1007eedd5>
</code></pre>
<p>It ignores the first element. This seems counter-intuitive, because if I just change the syntax a little bit:</p>
<pre><code>[list(g) for k, g in itertools.groupby("AAABBB")]
</code></pre>
<p>I get:</p>
<pre><code>[["A", "A", "A"], ["B", "B", "B"]]
</code></pre>
<p>which is right, and aligns with what I think this function should be doing.</p>
<p>However, if I once again change the syntax just a bit:</p>
<pre><code>[list(thing) for thing in [g for k, g in itertools.groupby(string)]]
</code></pre>
<p>I get back:</p>
<pre><code>[[], ['B']]
</code></pre>
<p>These two list comprehensions should be directly equivalent, but they return different results.</p>
<p>What is going on? Insight would be extremely appreciated.</p>
| 2 |
2016-09-12T01:02:38Z
| 39,442,179 |
<p>The docs already explain why your listcomps aren't equivalent:</p>
<blockquote>
<p>The returned group is itself an iterator that shares the underlying iterable with groupby(). Because the source is shared, when the groupby() object is advanced, the previous group is no longer visible. So, if that data is needed later, it should be stored as a list</p>
</blockquote>
<p>Your</p>
<pre><code>[list(g) for k, g in itertools.groupby("AAABBB")]
</code></pre>
<p><em>does</em> use each group before <code>groupby()</code> advances, so it works.</p>
<p>Your</p>
<pre><code>[list(thing) for thing in [g for k, g in itertools.groupby(string)]]
</code></pre>
<p>doesn't use any group until after all groups have been generated. Not at all the same, and for the reason the quoted docs explained.</p>
| 6 |
2016-09-12T01:11:21Z
|
[
"python",
"group-by",
"list-comprehension",
"itertools"
] |
Calling methods from classes
| 39,442,181 |
<p>I'm writing some classes:</p>
<pre><code>bean_version = "1.0"
from random import randint
console = []
print "Running Bean v%s" % bean_version
#Math Function
class math(object):
def __init__(self, op1 = 0, op2 = 0):
self.op1 = op1
self.op2 = op2
def add(self):
return self.op1 + self.op2
def sub(self):
return self.op1 - self.op2
def mul(self):
return self.op1 * self.op2
def div(self):
return self.op1 / self.op2
</code></pre>
<p>What I realized I could do is:</p>
<pre><code>math.add(math(3,5))
==>8
</code></pre>
<p>What I'm wondering is, is there any way to be able to do:</p>
<pre><code>math.add(3,5)
</code></pre>
<p>Python 2.7.10</p>
| -1 |
2016-09-12T01:11:35Z
| 39,442,219 |
<p>Yes, of course. The problem currently is that you are defining your class such that the operands must be passed to the <em>constructor</em>, not the operators. Try this:</p>
<pre><code>class math(object):
def add(self, op1=0, op2=0):
return op1 + op2
def sub(self, op1=0, op2=0):
return op1 - op2
def mul(self, op1=0, op2=0):
return op1 * op2
def div(self, op1=0, op2=0):
return op1 / op2
m = math()
m.add(2, 3)
</code></pre>
<p>Given that none of the methods use <code>self</code>, they should actually be static methods. See <a href="https://docs.python.org/2/library/functions.html#staticmethod" rel="nofollow">https://docs.python.org/2/library/functions.html#staticmethod</a></p>
| 0 |
2016-09-12T01:15:43Z
|
[
"python",
"python-2.7"
] |
Calling methods from classes
| 39,442,181 |
<p>I'm writing some classes:</p>
<pre><code>bean_version = "1.0"
from random import randint
console = []
print "Running Bean v%s" % bean_version
#Math Function
class math(object):
def __init__(self, op1 = 0, op2 = 0):
self.op1 = op1
self.op2 = op2
def add(self):
return self.op1 + self.op2
def sub(self):
return self.op1 - self.op2
def mul(self):
return self.op1 * self.op2
def div(self):
return self.op1 / self.op2
</code></pre>
<p>What I realized I could do is:</p>
<pre><code>math.add(math(3,5))
==>8
</code></pre>
<p>What I'm wondering is, is there any way to be able to do:</p>
<pre><code>math.add(3,5)
</code></pre>
<p>Python 2.7.10</p>
| -1 |
2016-09-12T01:11:35Z
| 39,442,242 |
<p>That is possible. In this case you use the class just as a way to logically group your operators (add, sub, mul, div) and you don't really need to initialize the operands in the class instance itself. This calls for the <a href="https://docs.python.org/2/library/functions.html#staticmethod" rel="nofollow"><code>staticmethods</code></a> decorator, and the code looks like the one below.
You can also see it in action here: <a href="https://eval.in/639864" rel="nofollow">https://eval.in/639864</a></p>
<pre><code>bean_version = "1.0"
from random import randint
console = []
print "Running Bean v%s" % bean_version
#Math Function
class math(object):
def __init__(self):
pass
@staticmethod
def add(op1, op2):
return op1 + op2
@staticmethod
def sub(op1, op2):
return op1 - op2
@staticmethod
def mul(op1, op2):
return op1 * op2
@staticmethod
def div(op1, op2):
return op1 / op2
print math.add(3,5)
print math.sub(3,5)
print math.mul(3,5)
print math.div(3,5)
</code></pre>
| 1 |
2016-09-12T01:19:30Z
|
[
"python",
"python-2.7"
] |
Update dictionary keys to be in ascending order?
| 39,442,207 |
<p>I have a dictionary:</p>
<pre><code>A = {'cat': {0: {'variable_1': 'xxx', 'variable_2': 'yyy'},
1: {'variable_1': 'ttt', 'variable_2': 'kkk'}},
'dog': {0: {'variable_1': 'xxx', 'variable_2': 'ppp'},
1: {'variable_1': 'qqq', 'variable_2': 'www'}},
'fox': {0: {'variable_1': 'xxx', 'variable_2': 'zzz'},
1: {'variable_1': 'yyy', 'variable_2': 'uuu'},
3: {'variable_1': 'ccc', 'variable_2': 'jjj'}}}
</code></pre>
<p>I want to make the second level key automated ascend
like this:</p>
<pre><code>{'cat': {0: {'variable_1': 'xxx', 'variable_2': 'yyy'},
1: {'variable_1': 'ttt', 'variable_2': 'kkk'}},
'dog': {2: {'variable_1': 'xxx', 'variable_2': 'ppp'},
3: {'variable_1': 'qqq', 'variable_2': 'www'}},
'fox': {4: {'variable_1': 'xxx', 'variable_2': 'zzz'},
5: {'variable_1': 'yyy', 'variable_2': 'uuu'},
6: {'variable_1': 'ccc', 'variable_2': 'jjj'}}}
</code></pre>
| 2 |
2016-09-12T01:13:47Z
| 39,442,531 |
<p>As martineau mentioned, If you want to keep a data set sorted, you'll want to use a collection/data type that preserves order. For a record like this, you can use tuples or namedtuples. These will allow you to keep data sorted, and having them in a list allows them compatibility with built in functions that allow to you insert future data into an sorted set.</p>
| 0 |
2016-09-12T02:11:26Z
|
[
"python",
"dictionary",
"key",
"value",
"auto-update"
] |
Update dictionary keys to be in ascending order?
| 39,442,207 |
<p>I have a dictionary:</p>
<pre><code>A = {'cat': {0: {'variable_1': 'xxx', 'variable_2': 'yyy'},
1: {'variable_1': 'ttt', 'variable_2': 'kkk'}},
'dog': {0: {'variable_1': 'xxx', 'variable_2': 'ppp'},
1: {'variable_1': 'qqq', 'variable_2': 'www'}},
'fox': {0: {'variable_1': 'xxx', 'variable_2': 'zzz'},
1: {'variable_1': 'yyy', 'variable_2': 'uuu'},
3: {'variable_1': 'ccc', 'variable_2': 'jjj'}}}
</code></pre>
<p>I want to make the second level key automated ascend
like this:</p>
<pre><code>{'cat': {0: {'variable_1': 'xxx', 'variable_2': 'yyy'},
1: {'variable_1': 'ttt', 'variable_2': 'kkk'}},
'dog': {2: {'variable_1': 'xxx', 'variable_2': 'ppp'},
3: {'variable_1': 'qqq', 'variable_2': 'www'}},
'fox': {4: {'variable_1': 'xxx', 'variable_2': 'zzz'},
5: {'variable_1': 'yyy', 'variable_2': 'uuu'},
6: {'variable_1': 'ccc', 'variable_2': 'jjj'}}}
</code></pre>
| 2 |
2016-09-12T01:13:47Z
| 39,442,646 |
<p>Regular dictionaries are unordered, so you will need to use <a href="https://docs.python.org/3/library/collections.html#collections.OrderedDict" rel="nofollow"><em>OrderedDict</em></a>.</p>
<p>A global <em>counter</em> variable can keep track of the total number of entries.</p>
<p>The <a href="https://docs.python.org/3/library/functions.html#sorted" rel="nofollow"><em>sorted</em></a> function will take a list of key/value tuples and sort them according to the key.</p>
<pre><code>>>> from collections import OrderedDict
>>> A = {'cat': {0: {'variable_1': 'xxx', 'variable_2': 'yyy'},
1: {'variable_1': 'ttt', 'variable_2': 'kkk'}},
'dog': {0: {'variable_1': 'xxx', 'variable_2': 'ppp'},
1: {'variable_1': 'qqq', 'variable_2': 'www'}},
'fox': {0: {'variable_1': 'xxx', 'variable_2': 'zzz'},
1: {'variable_1': 'yyy', 'variable_2': 'uuu'},
3: {'variable_1': 'ccc', 'variable_2': 'jjj'}}}
>>> OA = OrderedDict()
>>> count = 0
>>> for animal, info in sorted(A.items()):
OA[animal] = OrderedDict()
for i, variables in sorted(info.items()):
OA[animal][count] = variables
count += 1
>>> OA
OrderedDict([
('cat', OrderedDict([(0, {'variable_2': 'yyy', 'variable_1': 'xxx'}),
(1, {'variable_2': 'kkk', 'variable_1': 'ttt'})])),
('dog', OrderedDict([(2, {'variable_2': 'ppp', 'variable_1': 'xxx'}),
(3, {'variable_2': 'www', 'variable_1': 'qqq'})])),
('fox', OrderedDict([(4, {'variable_2': 'zzz', 'variable_1': 'xxx'}),
(5, {'variable_2': 'uuu', 'variable_1': 'yyy'}),
(6, {'variable_2': 'jjj', 'variable_1': 'ccc'})]))
])
</code></pre>
<p>If needed you can sort the innermost variables and stored them in an OrderedDict as well.</p>
| 1 |
2016-09-12T02:30:26Z
|
[
"python",
"dictionary",
"key",
"value",
"auto-update"
] |
Update dictionary keys to be in ascending order?
| 39,442,207 |
<p>I have a dictionary:</p>
<pre><code>A = {'cat': {0: {'variable_1': 'xxx', 'variable_2': 'yyy'},
1: {'variable_1': 'ttt', 'variable_2': 'kkk'}},
'dog': {0: {'variable_1': 'xxx', 'variable_2': 'ppp'},
1: {'variable_1': 'qqq', 'variable_2': 'www'}},
'fox': {0: {'variable_1': 'xxx', 'variable_2': 'zzz'},
1: {'variable_1': 'yyy', 'variable_2': 'uuu'},
3: {'variable_1': 'ccc', 'variable_2': 'jjj'}}}
</code></pre>
<p>I want to make the second level key automated ascend
like this:</p>
<pre><code>{'cat': {0: {'variable_1': 'xxx', 'variable_2': 'yyy'},
1: {'variable_1': 'ttt', 'variable_2': 'kkk'}},
'dog': {2: {'variable_1': 'xxx', 'variable_2': 'ppp'},
3: {'variable_1': 'qqq', 'variable_2': 'www'}},
'fox': {4: {'variable_1': 'xxx', 'variable_2': 'zzz'},
5: {'variable_1': 'yyy', 'variable_2': 'uuu'},
6: {'variable_1': 'ccc', 'variable_2': 'jjj'}}}
</code></pre>
| 2 |
2016-09-12T01:13:47Z
| 39,442,813 |
<p>if u don't need to keep the orderï¼u can copy the dict to other dict. A global variable can keep the second level key.</p>
<pre><code># coding=utf-8
A={'cat':{0:{'variable_1':'xxx','variable_2':'yyy'},1:{'variable_1':'ttt','variable_2':'kkk'}},
'dog':{0:{'variable_1':'xxx','variable_2':'ppp'},1:{'variable_1':'qqq','variable_2':'www'}},
'fox':{0:{'variable_1':'xxx','variable_2':'zzz'},1:{'variable_1':'yyy','variable_2':'uuu'},3:{'variable_1':'ccc','variable_2':'jjj'}}}
B = dict()
index = 0
for key in A:
animal = A[key]
B[key] = dict()
for i in animal:
B[key][index] = animal[i]
index += 1
print(B)
</code></pre>
<p>output:</p>
<pre><code>{
'dog': {
0: {'variable_1': 'xxx', 'variable_2': 'ppp'},
1: {'variable_1': 'qqq', 'variable_2': 'www'}
},
'fox': {
2: {'variable_1': 'xxx', 'variable_2': 'zzz'},
3: {'variable_1': 'yyy', 'variable_2': 'uuu'},
4: {'variable_1': 'ccc', 'variable_2': 'jjj'}
},
'cat': {
5: {'variable_1': 'xxx', 'variable_2': 'yyy'},
6: {'variable_1': 'ttt', 'variable_2': 'kkk'}
}
}
</code></pre>
| 0 |
2016-09-12T03:00:39Z
|
[
"python",
"dictionary",
"key",
"value",
"auto-update"
] |
Why won't functions run in parallel?
| 39,442,239 |
<p>I've been reading up and trying to implement multithreading into my program, but no matter how I do it, it will not run my functions in parallel. I'm using sensors for a raspberry pi 3, trying to have them print out statuses in parallel rather than wait for one to finish and then move to the next function.</p>
<p>What happens now is that it waits for those 20 seconds before the program checks the seconds sensor and prints out that status message. I have no idea why!</p>
<p>Code:</p>
<pre><code>import RPi.GPIO as GPIO
import time
from multiprocessing import Process
''' Define pins and setup the sensors '''
def runInParallel(*fns):
proc = []
for fn in fns:
p = Process(target=fn)
p.start()
proc.append(p)
for p in proc:
p.join()
def sensor1():
#Sleep timer long so I can check that I can see prints from 2nd sensor while this thread is sleeping
time.sleep(20)
#Get status from sensor---
if status == 1:
print "Ouch!"
else:
print "Good!"
def sensor2():
time.sleep(0.2)
#Get status from 2nd sensor---
if status == 1:
print "Ouch2!"
else:
print "Good2!"
runInParallel(sensor1, sensor2)
</code></pre>
| 2 |
2016-09-12T01:19:02Z
| 39,442,494 |
<p>I don't know why your example isn't working, but I tried this:</p>
<pre><code> import time
from threading import Thread
''' Define pins and setup the sensors '''
status = 0
def runInParallel(*fns):
proc = []
for fn in fns:
p = Thread(target=fn)
proc.append(p)
for p in proc:
p.start()
def sensor1():
#Sleep timer long so I can check that I can see prints from 2nd sensor while this thread is sleeping
time.sleep(.2)
#Get status from sensor---
if status == 1:
print("Ouch!")
else:
print("Good!")
def sensor2():
time.sleep(0.2)
#Get status from 2nd sensor---
if status == 1:
print("Ouch2!")
else:
print("Good2!")
runInParallel(sensor1, sensor2)
</code></pre>
<p>and it outputted <code>good2</code> and <code>good</code> almost simultaneously. If you really need the outputs to be exact then try to debug you example, but if closer than you can notice with the naked eye is OK then I think that the threading module will work well enough.</p>
<h2>EDIT:</h2>
<p>Ok I think that you problem is that you think that the <code>Process.join()</code> counts the waits in the function. <code>Process.join()</code> only makes sure that the functions <em>start</em> at the same time. If you have a wait in one function, then <code>runInParallel</code> won't care about that.</p>
| 1 |
2016-09-12T02:05:32Z
|
[
"python",
"linux",
"raspberry-pi",
"gpio"
] |
issue with nested try else statement
| 39,442,247 |
<p>I am a beginner programmer and am writing a program that converts letter grades to GPA, or GPA to letter grades as entered by the user. I reference two functions to do the conversions in other programs. I am using the try statement to start by assuming it is a letter grade to convert to GPA, and that doesn't work i try the function to convert from GPA to letter grade.</p>
<p>My program works, the only problem is that my else statement always executes, even if I enter something that is not a letter grade or GPA. I am guessing it is something easy that I am not seeing.</p>
<pre><code>#Convert a letter grade to GPA, or GPA to letter grade
from grade_points_to_letter import gpa_converter
from letter_grade_to_grade_point import letter_converter
grade = input('Enter a letter grade or GPA to convert: ')
while grade != '':
try:
grade = grade.upper()
conversion = letter_converter(grade)
try:
conversion = gpa_converter(float(grade))
except:
print('You did not enter a valid letter grade or GPA')
except:
pass
else:
print('Your converted grade is:', conversion)
grade = input('Enter a letter grade or GPA to convert: ')
</code></pre>
| 0 |
2016-09-12T01:21:50Z
| 39,442,277 |
<p>You can use an else statement with try catch. However, checkout how the docs recommends using try catch else. Catch should take an error. You should figure out what kind of error you want to catch. </p>
<p><a href="https://docs.python.org/3/tutorial/errors.html" rel="nofollow">https://docs.python.org/3/tutorial/errors.html</a></p>
<p>Another thing you can do is use a debugger to see what you're getting in each block. Just put the following code in the block you want to check out:</p>
<p>import pdb; pdb.set_trace()</p>
| 0 |
2016-09-12T01:28:28Z
|
[
"python"
] |
issue with nested try else statement
| 39,442,247 |
<p>I am a beginner programmer and am writing a program that converts letter grades to GPA, or GPA to letter grades as entered by the user. I reference two functions to do the conversions in other programs. I am using the try statement to start by assuming it is a letter grade to convert to GPA, and that doesn't work i try the function to convert from GPA to letter grade.</p>
<p>My program works, the only problem is that my else statement always executes, even if I enter something that is not a letter grade or GPA. I am guessing it is something easy that I am not seeing.</p>
<pre><code>#Convert a letter grade to GPA, or GPA to letter grade
from grade_points_to_letter import gpa_converter
from letter_grade_to_grade_point import letter_converter
grade = input('Enter a letter grade or GPA to convert: ')
while grade != '':
try:
grade = grade.upper()
conversion = letter_converter(grade)
try:
conversion = gpa_converter(float(grade))
except:
print('You did not enter a valid letter grade or GPA')
except:
pass
else:
print('Your converted grade is:', conversion)
grade = input('Enter a letter grade or GPA to convert: ')
</code></pre>
| 0 |
2016-09-12T01:21:50Z
| 39,442,361 |
<p>Your inner <code>try-except</code> will swallow any exceptions, which means that even if <code>gpa_converter</code> raises an exception, the outermost <code>try</code> suite will still be 'successful' and thus the <code>else</code> clause will execute. </p>
<p>There are several ways to fix this, but the way that involves the least amount of refactoring would probably be to re-raise the exception in the innermost <code>except</code> clause.</p>
<pre><code>while grade != '':
try:
grade = grade.upper()
conversion = letter_converter(grade)
try:
conversion = gpa_converter(float(grade))
except:
print('You did not enter a valid letter grade or GPA')
raise
except:
pass
else:
print('Your converted grade is:', conversion)
grade = input('Enter a letter grade or GPA to convert: ')
</code></pre>
<p>Edit: Okay, based off your comments, what you're actually going for is something like this:</p>
<pre><code>while grade != '':
grade = grade.upper()
try:
conversion = letter_converter(grade)
except Exception:
try:
conversion = gpa_converter(float(grade))
except Exception:
print('You did not enter a valid letter grade or GPA')
else:
print('Your converted grade is:', conversion)
else:
print('Your converted grade is:', conversion)
grade = input('Enter a letter grade or GPA to convert: ')
</code></pre>
| 0 |
2016-09-12T01:39:52Z
|
[
"python"
] |
issue with nested try else statement
| 39,442,247 |
<p>I am a beginner programmer and am writing a program that converts letter grades to GPA, or GPA to letter grades as entered by the user. I reference two functions to do the conversions in other programs. I am using the try statement to start by assuming it is a letter grade to convert to GPA, and that doesn't work i try the function to convert from GPA to letter grade.</p>
<p>My program works, the only problem is that my else statement always executes, even if I enter something that is not a letter grade or GPA. I am guessing it is something easy that I am not seeing.</p>
<pre><code>#Convert a letter grade to GPA, or GPA to letter grade
from grade_points_to_letter import gpa_converter
from letter_grade_to_grade_point import letter_converter
grade = input('Enter a letter grade or GPA to convert: ')
while grade != '':
try:
grade = grade.upper()
conversion = letter_converter(grade)
try:
conversion = gpa_converter(float(grade))
except:
print('You did not enter a valid letter grade or GPA')
except:
pass
else:
print('Your converted grade is:', conversion)
grade = input('Enter a letter grade or GPA to convert: ')
</code></pre>
| 0 |
2016-09-12T01:21:50Z
| 39,442,444 |
<p>If you're trying to catch exceptions raised by functions on invalid inputs, probably you would like to rewrite the code to something like this:</p>
<pre><code>while grade != '':
try:
grade = grade.upper()
conversion = letter_converter(grade)
except:
try:
conversion = gpa_converter(float(grade))
except:
print('You did not enter a valid letter grade or GPA')
conversion = None
if conversion:
print('Your converted grade is:', conversion)
</code></pre>
<p>Also it is recommended to specify expected exceptions,
for example:</p>
<pre><code>except(TypeError, ValueError):
pass
</code></pre>
<p>so you won't miss bugs, that you may be not aware of.</p>
| 0 |
2016-09-12T01:57:40Z
|
[
"python"
] |
What is wrong with the following quadratic equation code?
| 39,442,260 |
<p>I am trying to make a program that converts standard form quadratic equations to factored form using the quadratic formula, but I'm getting an error on the part where I begin to do math. It seems like it has a problem with the floats I am using, but I do not know why, nor do I know how to fix it.</p>
<p>This is the error I get:</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "C:\Users\Josef\Documents\Python\standardFactored.py", line 25, in <module>
rightS = b^2-4*a*c
TypeError: unsupported operand type(s) for ^: 'float' and 'float'
</code></pre>
<hr>
<p>Here's the code:</p>
<pre><code>print("This program will convert standard form quadratic equations to "
"factored form. ax^2+bx+c --> a(x+ )(x+ )")
while True:
try:
a = float(raw_input("a = "))
break
except:
print("that is not a valid number")
while True:
try:
b = float(raw_input("b = "))
break
except:
print("that is not a valid number")
while True:
try:
c = float(raw_input("c = "))
break
except:
print("that is not a valid number")
rightS = b^2-4*a*c
try:
math.sqrt(rightS)
except:
("There is no factored for for this equation")
quit()
</code></pre>
| 1 |
2016-09-12T01:26:06Z
| 39,442,284 |
<p>The <code>^</code> operator probably doesn't do what you expect. It's a binary XOR, or e<strong>X</strong>clusive <strong>OR</strong> operator. The XOR operator doesn't work with floating point numbers, thus producing the error. The error basically says it can't do the operation on two floats. With exponents, use a double asterisk. See the Python operators <a href="https://www.tutorialspoint.com//python/python_basic_operators.htm" rel="nofollow">here</a>.</p>
<p>Example, a to the power b is:</p>
<pre><code>a ** b
</code></pre>
<p>In your case, it would be:</p>
<pre><code>rightS = b ** 2 - 4 * a * c
</code></pre>
| 2 |
2016-09-12T01:29:34Z
|
[
"python",
"variables",
"math",
"floating-point",
"quadratic"
] |
How do I stop Appium/Python script hanging when connecting to app?
| 39,442,270 |
<p>I have an Appium script (written in Python) which freezes when connecting the web driver.</p>
<p>It is at the following line of code:</p>
<pre><code>self.driver = webdriver.Remote(self.webdriver_url,
desired_capabilities=self.desired_capabilities)
</code></pre>
<p>I am using the following url:
<a href="http://0.0.0.0:4723/wd/hub" rel="nofollow">http://0.0.0.0:4723/wd/hub</a></p>
<p>I am trying to connect to an iOS app (with version 9.3). The app has a login screen which comes up first, but bypasses that if the app has already been logged into. When I run the script against the app without it being logged in, the script runs fine. However, if the app has already signed in then the script hangs upon connecting with the above line of code.</p>
<p>Also, if I run the script from a clean installation of the app, my script works fine until it has logged in. Then it gets stuck waiting. </p>
<p>What can I do at this point? Surely, Appium should be able to handle this scenario. </p>
| 1 |
2016-09-12T01:27:26Z
| 39,443,224 |
<p>I think you should deal with it , not Appium.You should design the test cases run independently,i mean test case 002 should not depend on test case 001.You will need clean installation for each testcase.</p>
<p>Eg: u want to test order test case (005),you should repeat the actions from test case login (001).It will keep you less pain in the future when something change.</p>
| 0 |
2016-09-12T04:06:41Z
|
[
"python",
"ios",
"appium"
] |
Django, Querysets. How to perform search on 400mb sql query set faster?
| 39,442,274 |
<p>I Have a problem. I'm working with a 400mb postgres database. I have to perform searches with a lot of different filters. It takes me around a minute to load the page. </p>
<p>example from views.py, the task is to search all the possible combinations of word's letters. Like cat > act > atc etc. :</p>
<pre><code>def neighb():
count = 0
words = []
mylist = re.findall(r'\w', word)
combinations = (list(itertools.permutations(mylist)))
result = ''
for comb in combinations:
for letters in comb:
result += letters
if data.filter(form_v=result).exists():
count += 1
words.append(result)
result = ''
return count, words
</code></pre>
<p>So, is there some way to make it faster?</p>
| 0 |
2016-09-12T01:28:01Z
| 39,443,260 |
<p>There few things you are not doing optimally.</p>
<p><strong>First:</strong> don't join strings like this</p>
<pre><code>for letters in comb:
result += letters
</code></pre>
<p>do this</p>
<pre><code>result = ''.join(comb)
</code></pre>
<p><strong>Second:</strong> you should always try to do as less db queries as possible. In your case you will do it for every combination. Why not just get filter by all combinations and then get all words that actually in db. This way you will do only one db query.</p>
<pre><code>def neighb(data, word):
mylist = re.findall(r'\w', word)
combinations = [''.join(c) for c in itertools.permutations(mylist)]
words = list(data.filter(form_v__in=combinations).values_list('form_v', flat=True))
return len(words), words
</code></pre>
| 1 |
2016-09-12T04:12:20Z
|
[
"python",
"django",
"postgresql"
] |
How to rewrite the following zip code in nested for and if loops?
| 39,442,294 |
<p>List l has the following elements</p>
<pre><code>l = ['AGCTT 6 6 35 25 10', 'AGGGT 7 7 28 29 2']
</code></pre>
<p>List l was split into pairs using tuples, such that every alphabet corresponded as A:6, G:6, C:35 ..etc
If a value for less than 10, then the alphabets were converted to Z.
The following is the code:</p>
<pre><code>pairs = []
for a, b in (sub.split(None, 1) for sub in l):
pairs.append([("Z", i) if int(i) < 10 else (c, i) for c, i in zip(a,b.split())])
print(pairs)
</code></pre>
<p>How can one code the same thing using nested for and if loops? (I need to do this exercise to help understand coding in Python better) </p>
<p>Here is my attempt:</p>
<pre><code>pairs =[]
for a, b in (sub.split(None, 1) #What is sub.split(None,1)
for sub in l:
if int(i) < 10:
pairs.append("Z",i)
else:
pairs.append(c,i)
print pairs
</code></pre>
<p>Note 1: If someone could help me frame the question better- specific to the questions, please do suggest changes</p>
<p>The above question and code (credits: P. Cunningham) can be found <a href="http://stackoverflow.com/a/39441797/6820344">here</a></p>
| 2 |
2016-09-12T01:31:02Z
| 39,442,548 |
<p>To reverse engineer the code, usually working on the python console is the best way to proceed. So, I would start taking the different statements apart one by one and see what each does. Now, there will probably be many different ways to explain/rewrite that code, so mine will be one that hopefully will help you understand the process.</p>
<p>Your code is good, but there is one problem and one discrepancy to the final desired output.</p>
<ol>
<li>The problem is at the first loop: you should swap the <code>for a, b</code> with the <code>for sub in l</code> line, because this should give you an error about <code>sub</code> not being defined or so.</li>
<li>The discrepancy is that <code>pairs</code> is a list of lists, and instead you are trying to append a tuple. I say "try" because the statement is invalid and should be written as <code>pairs.append(("Z",i))</code> for example. But still misses the subtle <code>list</code> which is defined in the original code. In fact there you have a <code>pairs.append([])</code>, and the full logic inside creates what is called a <code>list comprehension</code>. </li>
</ol>
<p>Nevertheless, very good work from your part.</p>
<p>The final "new code" looks like below and you can see it in action at: <a href="https://eval.in/639908" rel="nofollow">https://eval.in/639908</a></p>
<pre><code>l = ['AGCTT 6 6 35 25 10', 'AGGGT 7 7 28 29 2']
pairs = []
# for each element in the list
for sub in l:
# we will create a new empty list
new_list = []
# split 'sub' into the string and the numbers parts
a, b = sub.split(None, 1)
# further, split the numbers into a list
numbers = b.split()
# now using positional index, we will...
for x in range(len(a)):
# ... create a new tuple taking one character from string
# 'a' and one number from list 'numbers'
new_tuple = ( a[x], numbers[x] )
# if the value is less than 10, then...
if int(numbers[x]) < 10:
# ... let's just put "Z"
new_tuple = ("Z", numbers[x])
# append this to the temporary list
new_list.append(new_tuple)
# once the sequence is complete, add it to the main list
pairs.append(new_list)
# When it's all done, print the list
print pairs
</code></pre>
| 1 |
2016-09-12T02:14:13Z
|
[
"python",
"if-statement",
"for-loop"
] |
Select option from javascript span with python and selenium
| 39,442,316 |
<p>I'm trying to generate a bot to automatically make orders from walmart, but it seems like I just can't get selected the color and the quantity, since they are not really selectors and they have no id.
I'm working with python and selenium.</p>
<p>The item using for tests right now is this one:
<a href="https://www.walmart.com/ip/8-x10-Picture-Frames-Set-of-6/10404226" rel="nofollow">https://www.walmart.com/ip/8-x10-Picture-Frames-Set-of-6/10404226</a></p>
<p>About the quantity I think I was able to select the list with:</p>
<pre><code>quantity = walmart.find_element_by_css_selector("span.product-quantity-dropdown-wrapper")
</code></pre>
<p>but after that I just can't select the quantity.</p>
| -2 |
2016-09-12T01:33:34Z
| 39,442,449 |
<p>As far as <code>quantity</code> goes, you can operate <em>the actual <code>select</code> element</em> (via the <a href="http://selenium-python.readthedocs.io/api.html#selenium.webdriver.support.select.Select" rel="nofollow"><code>Select</code> class</a>) which is not visually detected, but is actually visible. As for the color, you can <em>dynamically construct an XPath expression</em> to locate the color "by name". </p>
<p>Complete working implementation (selects white color and quantity = 2):</p>
<pre><code>import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
driver = webdriver.Chrome("/usr/local/bin/chromedriver")
driver.maximize_window()
driver.get("https://www.walmart.com/ip/8-x10-Picture-Frames-Set-of-6/10404226")
color = "White"
quantity = 2
wait = WebDriverWait(driver, 10)
# select color
color_selector = wait.until(EC.visibility_of_element_located((By.XPATH, "//span[@class = 'variant-swatch' and @title='{color}']/..".format(color=color))))
color_selector.click()
# harcode delay - see if you can avoid it
time.sleep(0.5)
# select quantity
quantity_selector = wait.until(EC.visibility_of_element_located((By.ID, "WMItemQtyDropDown")))
quantity_selector = Select(quantity_selector)
quantity_selector.select_by_value(str(quantity))
</code></pre>
<p>That said, make sure you are not violating any Terms of Use and staying on the legal side. Make sure to explore the <a href="https://developer.walmartlabs.com/" rel="nofollow">Walmart API</a> as well (see @MattDMo's comment).</p>
| 0 |
2016-09-12T01:58:51Z
|
[
"python",
"selenium"
] |
Training a neural network with two groups of spacial coordinates per observation?
| 39,442,327 |
<p>I'm trying to predict an output (regression) where multiple groups have spacial (x,y) coordinates. I've been using scikit-learn's neural network packages (MLPClassifier and MLPRegressor), which I know can be trained with spacial data by inputting a 1-D array per observation (ex. the MNIST dataset). </p>
<p>I'm trying to figure out the best way to tell the model that group 1 has this set of spacial coordinates AND group 2 has a different set of spacial coordinates, and that combination yielded a result. Would it make more sense to input a single array where a group 1 location is represented by 1 and group 2 location is represented by -1? Or to create an array for group 1 and group to and append them? Still pretty new to neural nets - hopefully this question makes sense.</p>
| 0 |
2016-09-12T01:34:52Z
| 39,446,832 |
<p>If I got this right, you are basically trying to implement classification variables into your input, and this is basically done by adding an input variable for each possible class (in your case "group 1" and "group 2") that holds binary values (1 if the sample belongs to the group, 0 if it doesn't). Wheather or not you would want to retain the actual coordinates depends on wheather you would like your network to process actual spatial data, or simply base it's output on the group that the sample belongs to. As I don't have much experience with the particular module you're using, I am unable to provide actual code, but I hope this helps.</p>
| 0 |
2016-09-12T09:09:17Z
|
[
"python",
"machine-learning",
"scikit-learn",
"neural-network",
"regression"
] |
WIN32COM saving/exporting multiple sheets as PDF
| 39,442,476 |
<p>I'd like to select multiple sheets (in a certain order) in a workbook and export them as a single PDF using win32com. I tried:</p>
<pre><code>wb_HC.Sheets(['sheetname1','sheetname2']).ExportAsFixedFormat(0, workdir+'\\'+run_date+'_MD_Summary.pdf')
</code></pre>
<p>But this does not work. I know that in VBA sheets can be called as an array of sheets:</p>
<pre><code>Array(sheets(1), sheets(2))
</code></pre>
<p>But I think this is not equivalent to list() in Python.</p>
| 0 |
2016-09-12T02:02:45Z
| 39,442,728 |
<p>Consider using Python's list <code>[]</code> method which could correspond to VBA's <code>Array()</code>. Apply it to the <code>Worksheets()</code> method passing either Sheet index number or Sheet name. Then in the <code>ExportAsFixedFormat</code> qualify the method with <code>xlApp.ActiveSheet</code>:</p>
<pre><code>import os
import win32com.client
workdir = "C:\\Path\\To\\Working\\Directory"
rundate = '2016-09-11'
try:
xlApp = win32com.client.Dispatch("Excel.Application")
wb = xlApp.Workbooks.Open(os.path.join(workdir, 'ExcelFile.xlsx'))
wb.Worksheets(["Sheet1", "Sheet2"]).Select()
xlTypePDF = 0
xlQualityStandard = 0
xlApp.ActiveSheet.ExportAsFixedFormat(xlTypePDF,
os.path.join(workdir, run_date+'_MD_Summary.pdf'),
xlQualityStandard, True, True)
except Exception as e:
print(e)
finally:
wb.Close(False)
xlApp.Quit
wb = None
xlApp = None
</code></pre>
<p>By the way, be sure to wrap your processing in <code>try/except/finally</code> blocks. Otherwise, any error you encounter will leave the Excel.exe running in background process. In this setup, the script always closes workbook and uninitializes the COM object regardless of error. The counterpart in VBA would be the <code>On Error Goto ...</code> handling (another best practice method).</p>
| 0 |
2016-09-12T02:46:05Z
|
[
"python",
"excel",
"win32com"
] |
logging - rewrite if size gets too big?
| 39,442,558 |
<p>I have a daemon and it logs its operations:</p>
<pre><code>LOG_FILE = '%s/%s.log' % (LOG_DIR, machine_name)
logging.basicConfig(filename=LOG_FILE,
level=logging.DEBUG,
format='%(asctime)s,%(msecs)05.1f '
'(%(funcName)s) %(message)s',
datefmt='%H:%M:%S')
</code></pre>
<p>After a while, the log size got really big and there was no space left on the device.</p>
<p>So I had to manually remove the logs and it was fine.</p>
<p>What's the best way to keep the log size not to go over certain limit?
Can it be done via logging module or do i need to write external script to just remove the logs every once in a while?</p>
| 3 |
2016-09-12T02:15:40Z
| 39,442,697 |
<p>You could use <a href="https://docs.python.org/3.5/library/logging.handlers.html#logging.handlers.RotatingFileHandler" rel="nofollow"><code>RotatingFileHandler</code></a> to do the log rotation for you. There's an example in <a href="https://docs.python.org/3.5/library/logging.handlers.html#logging.handlers.RotatingFileHandler" rel="nofollow">Logging Cookbook</a> at Python docs:</p>
<pre><code>import logging
import logging.handlers
LOG_FILENAME = 'logging_rotatingfile_example.out'
# Set up a specific logger with our desired output level
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
# Add the log message handler to the logger
handler = logging.handlers.RotatingFileHandler(
LOG_FILENAME, maxBytes=20, backupCount=5)
my_logger.addHandler(handler)
# Log some messages
for i in range(20):
my_logger.debug('i = %d' % i)
</code></pre>
| 3 |
2016-09-12T02:38:06Z
|
[
"python",
"logging"
] |
Error while installing OpenCV for Python 2.7 on OSX Yosemite - error: no matching function
| 39,442,642 |
<p>I was using this guide for installing OpenCV on my Mac: <a href="http://www.pyimagesearch.com/2015/06/15/install-opencv-3-0-and-python-2-7-on-osx/" rel="nofollow">http://www.pyimagesearch.com/2015/06/15/install-opencv-3-0-and-python-2-7-on-osx/</a></p>
<p>Everything worked until the last step:</p>
<pre><code>make install
</code></pre>
<p>When I got this error message:</p>
<pre><code>/Users/Nirzvi/opencv_contrib/modules/aruco/src/aruco.cpp:1629:12: error: no matching function for call to 'calibrateCamera'
return calibrateCamera(processedObjectPoints, processedImagePoints, imageSize, _cameraMatrix,
^~~~~~~~~~~~~~~
/Users/Nirzvi/opencv/modules/calib3d/include/opencv2/calib3d.hpp:844:21: note: candidate function not viable: requires at most 9
arguments, but 12 were provided
CV_EXPORTS_W double calibrateCamera( InputArrayOfArrays objectPoints,
</code></pre>
<p>The install process stopped immediately and, being a beginner programmer, I have no idea what to do next.</p>
| 0 |
2016-09-12T02:29:59Z
| 40,022,348 |
<p>If you're using <a href="http://www.pyimagesearch.com/2015/06/15/install-opencv-3-0-and-python-2-7-on-osx/" rel="nofollow">this guide</a>, make sure you remember to clone both opencv and opencv-contrib in your home folder rather than nesting them. It's easy to miss the instruction where it tells you to go back to <code>~/</code></p>
<p>As stated above, make sure you've downloaded matching versions of opencv and opencv-contrib from git.</p>
<p>Finally, make sure that your cmake command "OPENCV_EXTRA_MODULES_PATH" is pointing to the correct path for your corrected version of "opencv_contrib". If you just pull the correct version to the proper path, but don't update that value, it will keep trying to use the incorrect version of contrib.</p>
<p><strong>Note</strong>: The following is not recommended:
As an absolute last resort, you can always navigate to the cpp file it errored on (in your case: <code>/Users/Nirzvi/opencv_contrib/modules/aruco/src/aruco.cpp</code>), and comment out the "calibrateCamera" call and its surrounding function. You won't be able to make use of whatever that function was, but opencv has a ton of functions, if it's not one you need for your project, commenting out the function will at least get you further in your install process.</p>
| 1 |
2016-10-13T13:27:11Z
|
[
"python",
"osx",
"python-2.7",
"opencv",
"install"
] |
Calculate all possible combinations from differnt array in Python
| 39,442,702 |
<p>I have some group data like below a, b, c and so on. What I want to do is to calculate all possible combinations from the data. It's ok if the count of input data is always same. But in my case, I want to assume that the count of input data is from 0 to N, I mean a, b, c, d, e ...</p>
<p>I think I have to use recurrent loop. But I'm not sure to use recurrent loop to resolve this problem.</p>
<p><strong>Input</strong></p>
<pre><code>a = ["x", "y"]
b = ["q", "w", "c"]
c = ["i", "o", "p"]
...
</code></pre>
<p><strong>Ouput</strong></p>
<p>The expected output is all combinations with each value's all combinations.</p>
<pre><code>[{a:[], b:["q"], c:["i", "o"]}, {a:["x"], b:[], c:["o"]}, ...]
</code></pre>
| 1 |
2016-09-12T02:39:05Z
| 39,442,783 |
<p>If I am understanding what you're looking for, you can use <a href="https://docs.python.org/2.7/library/itertools.html#itertools.product" rel="nofollow"><em>itertools.product()</em></a> over the <a href="https://en.wikipedia.org/wiki/Power_set" rel="nofollow">powersets</a> of the inputs (there is a recipe for <a href="https://docs.python.org/2.7/library/itertools.html#recipes" rel="nofollow"><em>powerset()</em></a> in the docs). The <a href="https://docs.python.org/3/library/functions.html#map" rel="nofollow"><em>map()</em></a> function can be used to apply <em>powerset</em> to each of the inputs.</p>
<pre><code>from itertools import product, combinations, chain
from pprint import pprint
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
names = ['a', 'b', 'c']
a = ["x", "y"]
b = ["q", "w", "c"]
c = ["i", "o", "p"]
result = []
for values in product(*map(powerset, [a, b, c])):
result.append(dict(zip(names, values)))
pprint(result)
</code></pre>
<p><strong>Here is how it works:</strong></p>
<p>First, it builds the powersets:</p>
<pre><code>>>> list(powerset(["x", "y"]))
[(), ('x',), ('y',), ('x', 'y')]
>>>
>>> list(powerset(["x", "y"]))
[(), ('x',), ('y',), ('x', 'y')]
>>> list(powerset(["q", "w", "c"]))
[(), ('q',), ('w',), ('c',), ('q', 'w'), ('q', 'c'),
('w', 'c'), ('q', 'w', 'c')]
>>> list(powerset(["i", "o", "p"]))
[(), ('i',), ('o',), ('p',), ('i', 'o'), ('i', 'p'),
('o', 'p'), ('i', 'o', 'p')]
</code></pre>
<p>Next <a href="https://docs.python.org/2.7/library/itertools.html#itertools.product" rel="nofollow"><em>product()</em></a> pulls one element from each powerset:</p>
<pre><code>>>> for values in product(*map(powerset, [a, b, c])):
print(values)
((), (), ())
((), (), ('i',))
((), (), ('o',))
((), (), ('p',))
((), (), ('i', 'o'))
((), (), ('i', 'p'))
((), (), ('o', 'p'))
((), (), ('i', 'o', 'p'))
((), ('q',), ())
((), ('q',), ('i',))
((), ('q',), ('o',))
((), ('q',), ('p',))
((), ('q',), ('i', 'o'))
((), ('q',), ('i', 'p'))
((), ('q',), ('o', 'p'))
((), ('q',), ('i', 'o', 'p'))
</code></pre>
<p>Lastly, we <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow"><em>zip()</em></a> together the above results with the variable <em>names</em> to make a <a href="https://docs.python.org/3/library/functions.html#func-dict" rel="nofollow"><em>dict()</em></a>:</p>
<pre><code># What zip does
>>> list(zip(['a', 'b', 'c'], ((), ('q',), ('i', 'o', 'p'))))
[('a', ()), ('b', ('q',)), ('c', ('i', 'o', 'p'))]
# What dict does with the zip:
>>> dict(zip(['a', 'b', 'c'], ((), ('q',), ('i', 'o', 'p'))))
{'b': ('q',), 'c': ('i', 'o', 'p'), 'a': ()}
</code></pre>
| 5 |
2016-09-12T02:54:53Z
|
[
"python",
"combinations"
] |
Running Python Script with lynx command in Terminal
| 39,442,746 |
<p>I just installed emacs and python on my Mac and I'm trying to learn how to run my Python Scripts through my terminal and I'm getting an error message
"sh: lynx: command not found". From what I have researched it sounds like i need to install lynx on my mac but I do not know how to get it installed so if that is the issue how do I install lynx on a macbook? I will include screenshots of the issues I'm having. Thanks very much!
<a href="http://i.stack.imgur.com/TDamC.png" rel="nofollow">python script</a><a href="http://i.stack.imgur.com/789AB.png" rel="nofollow">Terminal</a></p>
| 0 |
2016-09-12T02:49:05Z
| 39,442,772 |
<p>You should already have Python on your mac. My Macbook Air came with python 2.x on El Capitan OSX. When you open up the Terminal and type in "python" without any quotations does the python interpreter come up? From the look of your image, there is something wrong inside the file you are trying to run with python. </p>
<p>As far as I know, Lynx is a Web Browser, are you trying to do something with Lynx inside that python file? If you happen to have brew on your mac you can try brew install lynx to install lynx onto the mac.</p>
<p>From the script, I think you are trying to get the source code from the link you are trying to open with lynx. Try this method instead if that is what you are doing.</p>
<p>Code:</p>
<pre><code>from urllib.request import urlopen
html = urlopen("http://www.careercast.com/jobs-rated/2016-ranking-200-jobs")
with open("lang.txt",'w') as output:
output.write(html.read())
</code></pre>
<p>You can use <a href="https://pip.pypa.io/en/stable/installing/" rel="nofollow">pip</a> to install urllib.request. If you do not have pip, it is very helpful when installing python packages, or you can use easy_install. Run this in the terminal if you already have pip installed. Otherwise follow <a href="https://pip.pypa.io/en/stable/installing/" rel="nofollow">this to install it</a>.</p>
<pre><code>pip install urllib.request
</code></pre>
| 0 |
2016-09-12T02:52:47Z
|
[
"python",
"emacs",
"terminal",
"lynx"
] |
Running Python Script with lynx command in Terminal
| 39,442,746 |
<p>I just installed emacs and python on my Mac and I'm trying to learn how to run my Python Scripts through my terminal and I'm getting an error message
"sh: lynx: command not found". From what I have researched it sounds like i need to install lynx on my mac but I do not know how to get it installed so if that is the issue how do I install lynx on a macbook? I will include screenshots of the issues I'm having. Thanks very much!
<a href="http://i.stack.imgur.com/TDamC.png" rel="nofollow">python script</a><a href="http://i.stack.imgur.com/789AB.png" rel="nofollow">Terminal</a></p>
| 0 |
2016-09-12T02:49:05Z
| 39,443,191 |
<p>You might see the above error if Lynx package is not installed on your server. Follow the below steps to install lynx on your Linux Server</p>
<p>Login to your Linux Server via SSH as root. Run <code>yum install lynx</code> to install lynx package</p>
| 0 |
2016-09-12T04:01:27Z
|
[
"python",
"emacs",
"terminal",
"lynx"
] |
How to block a number from texting me in python via Twilio
| 39,442,833 |
<p>I've been trying to find a way to block numbers that have texted my Twilio once, so that I don't get charged after the first time because they will be blocked. I've checked around and seen that rejecting calls is possible, but I have yet to find anything that 'rejects' incoming sms's.</p>
| 0 |
2016-09-12T03:04:46Z
| 39,443,759 |
<p>According to the <a href="https://support.twilio.com/hc/en-us/articles/223181648-Is-there-a-way-to-block-incoming-SMS-on-my-Twilio-phone-number-" rel="nofollow">Twilio documentation</a> it is not possible to block SMS to a Twilio number selectively. </p>
<p>You are only able to toggle on/off SMS for an entire account or number.</p>
| 1 |
2016-09-12T05:19:57Z
|
[
"python",
"python-2.7",
"twilio",
"twilio-api"
] |
Can a process update a shared queue while threads consume the queue?
| 39,442,945 |
<p>I'm trying to create a multithreaded hash cracker/bruteforcer in Python and I'm encountering an issue when having a thread generate all possible word combinations and put them on a queue while having 10 other threads hash the queue. The issue is that the 10 hashing threads hog execution time from the 1 thread generator, bottlenecking it. So my question is this: Is it possible to have a process update a queue that can be used by other threads concurrently in Python?</p>
| 0 |
2016-09-12T03:24:59Z
| 39,464,290 |
<p>The <a href="https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Queue" rel="nofollow">multiprocessing.Queue</a> object is process and thread safe.</p>
<p>I'd let the main loop of your solution populate the Queue while multiple processes hash its content.</p>
<p>As you work seems to be CPU bound, I'd avoid threads. </p>
| 0 |
2016-09-13T07:21:12Z
|
[
"python",
"multithreading",
"concurrency",
"multiprocessing"
] |
Scipy sparse matrix as DataFrame column
| 39,442,979 |
<p>I'm developing tooling based on pandas DataFrame objects. I would like to keep scipy sparse matrices around as column of a DataFrame without converting it row-wise to a list / numpy array of dtype('O').</p>
<p>The snippet below doesn't work as pandas treats the matrix as a scalar, and suggests to add an index. When providing a pd.RangeIndex over the row indices in the matrix, the matrix gets repeated for every row in the dataframe (as pandas thinks it is a scalar).</p>
<pre><code>ma = scipy.sparse.rand(10, 100, 0.1, 'csr', dtype=np.float64)
df = pd.DataFrame(dict(X=ma))
</code></pre>
<p>This does work:</p>
<pre><code>df = pd.DataFrame(dict(X=list(ma)))
</code></pre>
<p>However, this cuts up the matrix row-wise into CSR matrices each of 1 row. Which I would then need to vstack everytime I'd want to work on the original matrix.</p>
<p>Any pointers? I tried wrapping the CSR matrix into a pd.Series object, pretending it has dtype('O'), but I run into a lot of assumptions on the underlying data being numpy arrays and such.</p>
| 1 |
2016-09-12T03:30:48Z
| 39,443,506 |
<p>There is a sparse dataframe or dataseries feature. It is still experimental. I've answered a few SO questions about converting back and forth between that and <code>scipy</code> sparse matrices.</p>
<p>From the sidebar:</p>
<p><a href="http://stackoverflow.com/questions/34181494/populate-a-pandas-sparsedataframe-from-a-scipy-sparse-coo-matrix">Populate a Pandas SparseDataFrame from a SciPy Sparse Coo Matrix</a></p>
<p>Without such a specialized pandas structure I don't see how a sparse matrix could be added to a pandas frame. The internal structure of a sparse matrix is too different. For a start it is not a subclass of numpy array.</p>
<p>A <code>csr</code> matrix is an object with data contained in 3 arrays, <code>ma.data</code> and <code>ma.indices</code> are 1d arrays with one value for each non-zero element of the array. <code>ma.indptr</code> has a value for each row of the matrix.</p>
<p><code>list(ma)</code> is meaningless. <code>ma.toarray()</code> produces a 2d array with the same data, and will all those zeros filled in as well.</p>
<p>Other sparse matrix formats store their data in other structures - 3 equal length arrays for <code>coo</code>, two lists of lists for <code>lil</code>, and a dictionary of <code>dok</code>.</p>
| 0 |
2016-09-12T04:49:59Z
|
[
"python",
"pandas",
"dataframe",
"scipy",
"sparse-matrix"
] |
Need Haar Casscade xml for open mouth
| 39,442,984 |
<p>I need to detect an open mouth using Opencv Haar cascade. </p>
<p>I find Haar Casscade for mouth, but it detects mouth in general. I need to distinguish between a close mouth and an open mouth. </p>
| 0 |
2016-09-12T03:31:13Z
| 39,457,236 |
<p>I have a few steps to build my own haar cascade classifier quickly:</p>
<ol>
<li>I always think about sources for my training samples </li>
</ol>
<p>Try to extract positive samples showing different open mouths from free sources like <a href="https://www.flickr.com/search/?text=open%20mouth%20smile" rel="nofollow">flickr</a> or <a href="http://www.face-rec.org/databases/" rel="nofollow">face databases</a>. Extract ~30-50 positive samples. Edit them using gimp to get only the open mouths not the hole faces. Then extract non mouths and closed mouthes (~100 samples).
This is enough to build a weak classifier (more later)</p>
<ol start="2">
<li>Clone this <a href="https://github.com/mrnugget/opencv-haar-classifier-training" rel="nofollow">Github Repo</a> and follow the instructions of the README.md.<br>
Adjust the params -h -w in step 5 & 7 (the size of your sample images) and decrease numStages, numPos, numNeg (used per stage so should be really small)</li>
</ol>
<p>Now you've build your own weak classifier for open mouths but it will detect too much or sometimes closed mouths as well, so you need more training samples. But this time you can use your weak classifier to create them. </p>
<ol start="3">
<li>I wrote a really simple sample extractor in python. Clone <a href="https://github.com/fabianbormann/Classifier-Sample-Extractor" rel="nofollow">this Github repo</a> and replace the <code>cascade.xml</code> with yours. Add a large set of photos or faces (maybe <a href="http://cswww.essex.ac.uk/mv/allfaces/index.html" rel="nofollow">faces94 by Dr Libor Spacek</a>) to the <code>data</code> folder. And start the extraction using <code>python sample_extractor.py</code>. It will read the files in the data folder randomly and show you white bounding boxes where the classifier found a "open mouth". If you <em>left click</em> the boxes they will become green and the rect will be cropped and added to the <code>positives</code> folder. A <em>right click</em> will add the box to the <code>negative</code> folder. A click with the center <code>mouse button</code> will load the next random data image. Now you can create you training samples really fast. I trained a classifier for various cell types or mitosis detection and it turns out (my personal experience), that ~1000 positive and ~2000 samples would be a good choice. </li>
</ol>
| 1 |
2016-09-12T19:16:53Z
|
[
"python",
"opencv",
"detection",
"haar-classifier"
] |
create polymial in powers of (x-1) from given coefficients in python
| 39,443,005 |
<p>I have the following coefficient matrix.</p>
<pre><code>import numpy as np
coeffMatrix = np.array([[ 1. , 1.46599761, 0. , 0.25228421],
[ 2.71828183, 2.22285026, 0.75685264, 1.69107137],
[ 7.3890561 , 8.80976965, 5.83006675, -1.94335558],
[ 20.08553692, 0. , 0. , 0. ]])
</code></pre>
<p>I can then create a polynomials <code>s0</code> as follows:</p>
<pre><code>s0 = np.poly1d(coeffMatrix[0][::-1])
print (s0)
</code></pre>
<p>It prints out the following output:</p>
<pre><code> 3
0.2523 x + 1.466 x + 1
</code></pre>
<p>I now want to create <code>s1</code> using <code>coeffMatrix[1][::-1]</code> as the coefficients but I want <code>s1</code> to be in powers of (x-1). </p>
<p>How can I do this?</p>
<p>On a side note. I don't know how to copy paste jupyter notebook input output straight into stackoverflow.</p>
| 1 |
2016-09-12T03:33:43Z
| 39,465,758 |
<p>Use <code>variable</code> parameter. I used <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.poly1d.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.poly1d.html</a></p>
<p>(I prefer to look on <code>np.array</code> as matrix and not as list of arrays)</p>
<pre><code>s1 = np.poly1d(coeffMatrix[1, ::-1], variable='(x-1)')
print(s1)
</code></pre>
| 1 |
2016-09-13T08:45:06Z
|
[
"python",
"numpy",
"scipy",
"polynomials"
] |
Python TypeError: not enough arguments for format string in case of string %s
| 39,443,037 |
<pre><code>wrapper = """<html>
<head>
</head>
<body>
<table style="height: 100px;" width="500">
<tbody>
<tr>
<td rowspan="3"><a id="imgrec1" href="http://www.w3.org"><img src="%s" alt="Smiley face" width="50" height="100" /><br /><br /></a></td>
<td>%s</td>
</tr>
<tr>
<td>%s</td>
</tr>
<tr>
<td>%s</td>
</tr>
<tr>
<tr>
<td rowspan="3"><a id="imgrec1" href="http://www.w3.org"><img src="%s" alt="Smiley face" width="50" height="100" /><br /><br /></a></td>
<td>%s</td>
</tr>
<tr>
<td>%s</td>
</tr>
<tr>
<td>%s</td>
</tr>
<tr>
</tbody>
</table>
</body>
</html>"""
str=""
for i in reclist[:2]:
str=str + "I[\"" + i + "\"]," + "T[\"" + i + "\"]," +"R[\"" + i + "\"]," +"P[\"" + i + "\"],"
str = str[:-1]
print str
whole = wrapper % (str)
Output: I["M1"],T["M1"],R["M1"],P["M1"],I["M2"],T["M2"],R["M2"],P["M2"]
whole = wrapper % (str)
TypeError: not enough arguments for format string
</code></pre>
<p>As <code>wrapper</code> has exactly 8 %s and <code>str</code> has also 8 tuples, but still showing error <code>TypeError: not enough arguments for format string.</code></p>
<p>But instead of str, if I use </p>
<pre><code> whole = wrapper %
(I["M1"],T["M1"],R["M1"],P["M1"],I["M2"],T["M2"],R["M2"],P["M2"])
</code></pre>
<p>then it is working fine.</p>
<p>I refer <a href="http://stackoverflow.com/questions/24252358/typeerror-not-enough-arguments-for-format-string-when-using-s">stackoverflow</a> <a href="http://stackoverflow.com/questions/11146190/python-typeerror-not-enough-arguments-for-format-string">stackoverflow</a> for this problem, but it did not help.</p>
| 3 |
2016-09-12T03:39:56Z
| 39,443,372 |
<p>I suppose you get an error because you pass a string as a single argument when formatting a string.
You can create a list initially:</p>
<pre><code>str = []
for i in reclist[:2]:
str += [I[i], T[i] etc.]
</code></pre>
<p>and then use:</p>
<pre><code>whole = wrapper % tuple(str)
</code></pre>
<p>so that every item in a list will be passed as a separate argument.</p>
| 0 |
2016-09-12T04:28:59Z
|
[
"python",
"html",
"string",
"typeerror"
] |
3 level dictionary to dataframe in Python
| 39,443,135 |
<p>I have a 3 level dictionary, which I need to convert to a dataframe in Python.
I am fairly new to python and tried to run a loop in loop to write the file in a dataframe but doesn't give me the required output.</p>
<p>The current dictionary format:
<a href="http://i.stack.imgur.com/UZmbj.png" rel="nofollow">enter image description here</a></p>
<p>Required dataframe:
<a href="http://i.stack.imgur.com/swGxe.png" rel="nofollow">enter image description here</a></p>
<p>Any help will be really appreciated!</p>
<p>Dictionary:</p>
<pre><code>{
"60354": [
{
"http://www.aaaaaaaaaaaaaaaaaaaa.com": [
{
"Garden fresh": "Best frozen peas",
"Soooo flavorful!": "I typically"
}
],
"http://www.bbbbbbbbbbbbbbbbbbbbbbbb.com": [
{
"good food": "a very good product",
"Taste is fresh": "Very good frozen peas"
}
]
}
],
"66019": [
{
"http://www.cccccccccccccccccccccccccccccc.com": [
{
"YUM!": "Tastes really good",
"Very good": "Glad to have tried them"
}
],
"http://www.ddddddddddddddddddddddddddddddddd.com": [
{
"Amazing!": "I used orange juice",
"Awesome": "Definitely will try other flavors"
}
]
}
]
}
</code></pre>
| -2 |
2016-09-12T03:53:51Z
| 39,445,705 |
<pre><code>def order_from_chaos(data):
result = []
ids = [id_ for id_ in data]
id_content = [data[id_][0] for id_ in data]
links_in_id_content = [dictionary.keys() for dictionary in id_content]
for i in range(len(ids)):
id_ = ids[i]
links = links_in_id_content[i]
descriptions = [id_content[i][key][0] for key in links_in_id_content[i]]
content = zip(links, descriptions)
for elem in list(content):
link = elem[0]
description_list = elem[1].items()
for description in description_list:
formatted_data = id_, link, description[0], description[1]
result.append(formatted_data)
return result
data = {
"60354": [
{
"http://www.aaaaaaaaaaaaaaaaaaaa.com": [
{
"Garden fresh": "Best frozen peas",
"Soooo flavorful!": "I typically"
}
],
"http://www.bbbbbbbbbbbbbbbbbbbbbbbb.com": [
{
"good food": "a very good product",
"Taste is fresh": "Very good frozen peas"
}
]
}
],
"66019": [
{
"http://www.cccccccccccccccccccccccccccccc.com": [
{
"YUM!": "Tastes really good",
"Very good": "Glad to have tried them"
}
],
"http://www.ddddddddddddddddddddddddddddddddd.com": [
{
"Amazing!": "I used orange juice",
"Awesome": "Definitely will try other flavors"
}
]
}
]
}
result = order_from_chaos(data)
[print(res) for res in result]
</code></pre>
<p>will give you</p>
<pre><code>('60354', 'http://www.bbbbbbbbbbbbbbbbbbbbbbbb.com', 'Taste is fresh', 'Very good frozen peas')
('60354', 'http://www.bbbbbbbbbbbbbbbbbbbbbbbb.com', 'good food', 'a very good product')
('60354', 'http://www.aaaaaaaaaaaaaaaaaaaa.com', 'Soooo flavorful!', 'I typically')
('60354', 'http://www.aaaaaaaaaaaaaaaaaaaa.com', 'Garden fresh', 'Best frozen peas')
('66019', 'http://www.cccccccccccccccccccccccccccccc.com', 'Very good', 'Glad to have tried them')
('66019', 'http://www.cccccccccccccccccccccccccccccc.com', 'YUM!', 'Tastes really good')
('66019', 'http://www.ddddddddddddddddddddddddddddddddd.com', 'Awesome', 'Definitely will try other flavors')
('66019', 'http://www.ddddddddddddddddddddddddddddddddd.com', 'Amazing!', 'I used orange juice')
Process finished with exit code 0
</code></pre>
<p>not so cool structure at all.
but anyway messy way to proceed it</p>
| 0 |
2016-09-12T07:56:15Z
|
[
"python",
"json",
"pandas",
"dictionary"
] |
can't get <p>'s text when useing python scrapy a website
| 39,443,136 |
<p>Here is the website's source html code:</p>
<pre><code> <p class="fc-gray">
hello
<span class="">2010-10</span>
<em class="shuxian">|</em>
4.2
</p>
</code></pre>
<p>I want to get the value 4.2.
The following is my code (carInfoDiv is a xpath element selector): </p>
<pre><code> miles = carInfoDiv.xpath("p[contains(@class,'fc-gray')]/text()").extract()[0]
</code></pre>
<p>in this way, I got the string 'hello', I have also tried string(.), but got all string in <code><p></code>, not the result I wanted. Please show me how to get only 4.2 in this situation.</p>
| 0 |
2016-09-12T03:53:58Z
| 39,444,197 |
<p>I don't know xpath very much. but regular expression may help you</p>
<p>this is not so elegant, but will work for you</p>
<pre><code>>>> import re
>>> html = """
<p class="fc-gray">
hello
<span class="">2010-10</span>
<em class="shuxian">|</em>
4.2
</p>
"""
>>> search = re.search('em>[\n\s]*(?P<result>[\d.]+).*', html, flags=re.DOTALL)
>>> if search:
... print(search.group('result'))
...
4.2
</code></pre>
| 0 |
2016-09-12T06:04:57Z
|
[
"python",
"scrapy"
] |
can't get <p>'s text when useing python scrapy a website
| 39,443,136 |
<p>Here is the website's source html code:</p>
<pre><code> <p class="fc-gray">
hello
<span class="">2010-10</span>
<em class="shuxian">|</em>
4.2
</p>
</code></pre>
<p>I want to get the value 4.2.
The following is my code (carInfoDiv is a xpath element selector): </p>
<pre><code> miles = carInfoDiv.xpath("p[contains(@class,'fc-gray')]/text()").extract()[0]
</code></pre>
<p>in this way, I got the string 'hello', I have also tried string(.), but got all string in <code><p></code>, not the result I wanted. Please show me how to get only 4.2 in this situation.</p>
| 0 |
2016-09-12T03:53:58Z
| 39,445,677 |
<p>You are after the last text child of the <code><P></code> element, so you can add a <code>[last()]</code> predicate to your XPath expression:</p>
<pre><code>>>> import scrapy
>>> s = scrapy.Selector(text=""" <p class="fc-gray">
... hello
... <span class="">2010-10</span>
... <em class="shuxian">|</em>
... 4.2
... </p>""")
>>> s.xpath('.//p[@class="fc-gray"]/text()[last()]')
[<Selector xpath='.//p[@class="fc-gray"]/text()[last()]' data='\n 4.2 \n '>]
>>> s.xpath('.//p[@class="fc-gray"]/text()[last()]').extract_first()
'\n 4.2 \n '
>>> s.xpath('.//p[@class="fc-gray"]/text()[last()]').extract_first().strip()
'4.2'
>>>> # alternative using XPath's normalize-space() to do the whitespace stripping
>>> s.xpath('normalize-space(.//p[@class="fc-gray"]/text()[last()])').extract_first()
'4.2'
</code></pre>
| 0 |
2016-09-12T07:54:25Z
|
[
"python",
"scrapy"
] |
How to read this file on Python 3.4.4?
| 39,443,156 |
<pre><code>readme = open (r'c:\users\user\desktop\br.txt','r',encoding = 'utf-8')
print (readme.read)
</code></pre>
<p>I have been trying to open a file, but this script isn't working, it says </p>
<blockquote>
<p>built-in method read of _io.TextIOWrapper object at 0x00000000036A83A8</p>
</blockquote>
| -4 |
2016-09-12T03:56:55Z
| 39,443,237 |
<p>you want to call <code>readme.read()</code> method to read file.</p>
<pre><code>readme = open (r'c:\users\user\desktop\br.txt','r',encoding = 'utf-8')
readme.read()
</code></pre>
<p>if you want to read file line by line you can use.</p>
<pre><code>readme.readlines()
</code></pre>
| 2 |
2016-09-12T04:08:33Z
|
[
"python"
] |
python I want to set_index dateFrame with datetime
| 39,443,206 |
<pre><code>poorList = [datetime.date(2016, 5, 2),
datetime.date(2016, 8, 26),
datetime.date(2016, 6, 9),
datetime.date(2016, 3, 4)]
dateForm.set_index(poorList)
</code></pre>
<p>then it was Errorï¼</p>
<blockquote>
<p>File "pandas\index.pyx", line 137, in pandas.index.IndexEngine.get_loc
(pandas\index.c:4066)
File "pandas\index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas\index.c:3930)
File "pandas\hashtable.pyx", line 675, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12408)
File "pandas\hashtable.pyx", line 683, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12359)
KeyError: datetime.date(2016, 5, 2)</p>
</blockquote>
<p>Please tell me how to do it ?</p>
| 3 |
2016-09-12T04:04:04Z
| 39,443,311 |
<p>DataFrame.set_index() expects a column name or list of columns as an argument, so you should do:</p>
<pre><code>dateForm['date'] = poorList
dateForm.set_index('date', inplace=True)
</code></pre>
| 2 |
2016-09-12T04:20:00Z
|
[
"python",
"list",
"date",
"pandas",
"datetimeindex"
] |
python I want to set_index dateFrame with datetime
| 39,443,206 |
<pre><code>poorList = [datetime.date(2016, 5, 2),
datetime.date(2016, 8, 26),
datetime.date(2016, 6, 9),
datetime.date(2016, 3, 4)]
dateForm.set_index(poorList)
</code></pre>
<p>then it was Errorï¼</p>
<blockquote>
<p>File "pandas\index.pyx", line 137, in pandas.index.IndexEngine.get_loc
(pandas\index.c:4066)
File "pandas\index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas\index.c:3930)
File "pandas\hashtable.pyx", line 675, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12408)
File "pandas\hashtable.pyx", line 683, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12359)
KeyError: datetime.date(2016, 5, 2)</p>
</blockquote>
<p>Please tell me how to do it ?</p>
| 3 |
2016-09-12T04:04:04Z
| 39,444,208 |
<p>To generate an index with time stamps, you can use either the <code>DatetimeIndex</code> or Index constructor and pass in a list of datetime objects:</p>
<pre><code>dateForm.set_index(pd.DatetimeIndex(poorList), inplace=True) # Even pd.Index() works
</code></pre>
<p>Another way of doing would be to convert the list into an array as <code>set_index</code> accepts it's key as arrays and specify it's dtype accordingly.</p>
<pre><code>dateForm.set_index(np.array(poorList, dtype='datetime64'), inplace=True)
</code></pre>
| 1 |
2016-09-12T06:06:21Z
|
[
"python",
"list",
"date",
"pandas",
"datetimeindex"
] |
python I want to set_index dateFrame with datetime
| 39,443,206 |
<pre><code>poorList = [datetime.date(2016, 5, 2),
datetime.date(2016, 8, 26),
datetime.date(2016, 6, 9),
datetime.date(2016, 3, 4)]
dateForm.set_index(poorList)
</code></pre>
<p>then it was Errorï¼</p>
<blockquote>
<p>File "pandas\index.pyx", line 137, in pandas.index.IndexEngine.get_loc
(pandas\index.c:4066)
File "pandas\index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas\index.c:3930)
File "pandas\hashtable.pyx", line 675, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12408)
File "pandas\hashtable.pyx", line 683, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12359)
KeyError: datetime.date(2016, 5, 2)</p>
</blockquote>
<p>Please tell me how to do it ?</p>
| 3 |
2016-09-12T04:04:04Z
| 39,444,255 |
<p>Another solutions is assign list converted <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.html" rel="nofollow"><code>DatetimeIndex</code></a>:</p>
<pre><code>poorList = [datetime.date(2016, 5, 2),
datetime.date(2016, 8, 26),
datetime.date(2016, 6, 9),
datetime.date(2016, 3, 4)]
dateForm.index = pd.DatetimeIndex(poorList)
print (dateForm.index)
DatetimeIndex(['2016-05-02', '2016-08-26', '2016-06-09', '2016-03-04'],
dtype='datetime64[ns]', freq=None)
</code></pre>
<p>Solution with sample:</p>
<pre><code>dateForm = pd.DataFrame({'A':[1,2,3,7],
'B':[4,5,6,8]})
print (dateForm)
A B
0 1 4
1 2 5
2 3 6
3 7 8
poorList = [datetime.date(2016, 5, 2),
datetime.date(2016, 8, 26),
datetime.date(2016, 6, 9),
datetime.date(2016, 3, 4)]
dateForm.index = pd.to_datetime(poorList)
print (dateForm)
A B
2016-05-02 1 4
2016-08-26 2 5
2016-06-09 3 6
2016-03-04 7 8
print (dateForm.index)
DatetimeIndex(['2016-05-02', '2016-08-26', '2016-06-09', '2016-03-04'],
dtype='datetime64[ns]', freq=None)
</code></pre>
| 1 |
2016-09-12T06:12:03Z
|
[
"python",
"list",
"date",
"pandas",
"datetimeindex"
] |
pip ssl certificate error OSX installing scrapy
| 39,443,240 |
<p>Getting an error from pip when installing scrapy on OS X El Capitan</p>
<pre><code> ~ pip install scrapy
Requirement already satisfied (use --upgrade to upgrade): scrapy in /usr/local/lib/python2.7/site-packages
Requirement already satisfied (use --upgrade to upgrade): six>=1.5.2 in /usr/local/lib/python2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): pyOpenSSL in /usr/local/lib/python2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): cssselect>=0.9 in /usr/local/lib/python2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): queuelib in /usr/local/lib/python2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): parsel>=0.9.3 in /usr/local/lib/python2.7/site-packages (from scrapy)
Requirement already satisfied (use --upgrade to upgrade): PyDispatcher>=2.0.5 in /usr/local/lib/python2.7/site-packages (from scrapy)
Collecting cffi>=1.4.1 (from cryptography>=1.3->pyOpenSSL->scrapy)
Could not fetch URL https://pypi.python.org/simple/cffi/: There was a problem confirming the ssl certificate: [Errno 2] No such file or directory - skipping
Could not find a version that satisfies the requirement cffi>=1.4.1 (from cryptography>=1.3->pyOpenSSL->scrapy) (from versions: )
No matching distribution found for cffi>=1.4.1 (from cryptography>=1.3->pyOpenSSL->scrapy)
</code></pre>
<p>Have tried to reinstall pip, python & homebrew
Scrubbed directories as well, but nothing working</p>
<p>Tried independently install cryptography, installing via brew â no dice</p>
| 0 |
2016-09-12T04:08:52Z
| 39,500,160 |
<p>The entire environment was broken.</p>
<p>I deleted the following folders out of ~/usr/lib/</p>
<ul>
<li>python2.7</li>
<li>python3.4</li>
<li>python3.5</li>
</ul>
<p>Then did the following</p>
<pre><code>brew uninstall python
brew update
brew upgrade
brew doctor
brew cleanup
brew install python
pip install scrapy
</code></pre>
<p>All works now!</p>
| 0 |
2016-09-14T21:48:38Z
|
[
"python",
"osx",
"ssl",
"https",
"pip"
] |
How can I populate a txt with results from a mechanized results?
| 39,443,370 |
<p>I am trying to populate a txt file with the response I get from a mechanized form. Here's the form code</p>
<pre><code>import mechanize
from bs4 import BeautifulSoup
br = mechanize.Browser()
br.open ('https://www.cpsbc.ca/physician_search')
first = raw_input('Enter first name: ')
last = raw_input('Enter last name: ')
br.select_form(nr=0)
br.form['filter[first_name]'] = first
br.form['filter[last_name]'] = last
response = br.submit()
content = response.read()
soup = BeautifulSoup(content, "html.parser")
for row in soup.find_all('tbody'):
print row
</code></pre>
<p>This spits out lines of html code depending on how many privileges the doc has in regards to locations, but the last line has their specialty of training. Please go ahead and test it with any physician from BC, Canada.</p>
<p>I have a txt file that is listed as such:</p>
<pre><code>lastname1, firstname1
lastname2, firstname2
lastname3, firstname3 middlename3
lastname4, firstname4 middlename4
</code></pre>
<p>I hope you get the idea. I would appreciate any help in automatizing the following steps:</p>
<p>go through txt with names one by one and record the output text into a new txt file.</p>
<p>So far, I have this working to spit out the row (which is raw html), which I don't mind, but I can't get it to write into a txt file...</p>
<pre><code>import mechanize
from bs4 import BeautifulSoup
with open('/Users/s/Downloads/hope.txt', 'w') as file_out:
with open('/Users/s/Downloads/names.txt', 'r') as file_in:
for line in file_in:
a = line
delim = ", "
i1 = a.find(delim)
br = mechanize.Browser()
br.open('https://www.cpsbc.ca/physician_search')
br.select_form(nr=0)
br.form['filter[first_name]'] = a[i1+2:]
br.form['filter[last_name]'] = a[:i1]
response = br.submit()
content = response.read()
soup = BeautifulSoup(content, "html.parser")
for row in soup.find_all('tbody'):
print row
</code></pre>
| 0 |
2016-09-12T04:28:54Z
| 39,443,648 |
<p>This should not be too complicated. Assuming your file with all the names you want to query upon is called "names.txt" and the output file you want to create is called "output.txt", the code should look something like:</p>
<pre><code>with open('output.txt', 'w') as file_out:
with open('names.txt', 'r') as file_in:
for line in file_in:
<your parsing logic goes here>
file_out.write(new_record)
</code></pre>
<p>This assumes your parsing logic generates some sort of "record" to be written on file as a string.</p>
<p>If you get more advanced, you can also look into the <code>csv</code> module to import/export data in CSV.</p>
<p>Also have a look at the <a href="https://docs.python.org/2/tutorial/inputoutput.html" rel="nofollow">Input and Output tutorial</a>.</p>
| 0 |
2016-09-12T05:07:27Z
|
[
"python",
"mechanize"
] |
Top 7 most common tags Taggit
| 39,443,376 |
<pre><code>def most_common(self):
return self.get_queryset().annotate(
num_times=models.Count(self.through.tag_relname())
).order_by('-num_times')
</code></pre>
<p>How would I edit this to only view the top 7 tags. This is a function from taggit and I would only like to see only 7. thanks. </p>
| 0 |
2016-09-12T04:30:11Z
| 39,444,097 |
<p>How about most_common()[:7]? docs.djangoproject.com/en/1.10/topics/db/queries/⦠â ozgur</p>
<p>This is the correct asnwer, thanks ozgur</p>
| 0 |
2016-09-12T05:54:59Z
|
[
"python",
"django",
"django-views"
] |
How to fix encoding issue when writing to csv file
| 39,443,394 |
<p>i have some encoding issuse when writing to csv file</p>
<p>how can i fix it</p>
<pre><code>import csv
a = [s.encode('utf-8') for s in a]
f3 = open('test.csv', 'at')
writer = csv.writer(f3,delimiter = ',', lineterminator='\n',quoting=csv.QUOTE_ALL)
writer.writerow(a)
</code></pre>
<p>Error </p>
<pre><code>Traceback (most recent call last):
File "test.py", line 6, in <module>
a = [s.encode('ascii') for s in a]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 1: ordinal not in range(128)
</code></pre>
<p>How to make program work and write it to csv file?</p>
| 0 |
2016-09-12T04:32:03Z
| 39,443,463 |
<p>I ran your code and it works without throwing any errors. Only thing is that your csv file contains byte encoded values. Values with a b' at the front. Is this what you were trying to accomplish? I am using python 3.5.2 .</p>
<p>In the event you do not want byte encoded data just remove the </p>
<pre><code>a = [s.encode('utf-8') for s in a]
</code></pre>
<p>And it should work. Here is the output of your data into the csv when I ran it on my machine. </p>
<p><a href="http://puu.sh/r8ksr/d778437622.png" rel="nofollow">http://puu.sh/r8ksr/d778437622.png</a></p>
| 0 |
2016-09-12T04:42:07Z
|
[
"python",
"csv",
"encoding"
] |
How to fix encoding issue when writing to csv file
| 39,443,394 |
<p>i have some encoding issuse when writing to csv file</p>
<p>how can i fix it</p>
<pre><code>import csv
a = [s.encode('utf-8') for s in a]
f3 = open('test.csv', 'at')
writer = csv.writer(f3,delimiter = ',', lineterminator='\n',quoting=csv.QUOTE_ALL)
writer.writerow(a)
</code></pre>
<p>Error </p>
<pre><code>Traceback (most recent call last):
File "test.py", line 6, in <module>
a = [s.encode('ascii') for s in a]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 1: ordinal not in range(128)
</code></pre>
<p>How to make program work and write it to csv file?</p>
| 0 |
2016-09-12T04:32:03Z
| 39,443,467 |
<pre><code># encoding=utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
</code></pre>
| 0 |
2016-09-12T04:42:21Z
|
[
"python",
"csv",
"encoding"
] |
TypeError: 'bool' object is not iterable, when reading a text file
| 39,443,473 |
<p>I'm busy with a Uni project where I need to read text files and ten populate a table with their information. It was working fine last week when I first coded it. Now however, when I try to run it, I get the TypeError: bool, it occurs in my for loop, when I read_ln from the text file, the code is :</p>
<pre><code>from sqlite3 import *
from webbrowser import *
#retrieve a text file
while inc != len(categories):
file_open = open(categories[inc]+'.txt','U')
#assign the category
category = categories[inc]
#run the loop to populate the table popularity
for each_ln in file_open:
#assign the variables.
tab_index = each_ln.find('\t')
PersonNumber = each_ln[0:tab_index]
value = each_ln[tab_index + 1:len(each_ln)]
#populate the database.
TH2_db.execute("INSERT INTO popularity VALUES (?,?,?)" \
, (PersonNumber, category, value))
#increment to move onto the next textfile
inc = inc + 1
</code></pre>
| -1 |
2016-09-12T04:43:06Z
| 39,443,564 |
<p>Your statements <code>from webbrowser import *</code> at the top of your module imports the <code>webbrowser.open</code> function (which opens a new browser window), shadowing the builtin <code>open</code> function (that opens files) which you were intending to call in your later code. <code>webbrowser.open</code> returns a Boolean value, rather than a file object, which is what the exception is about.</p>
<p>To fix this, change the import. Either use <code>import webbrowser</code> and qualify the places you use the module (e.g. <code>webbrowser.get()</code> or whatever you're using it for), or import just the specific names that you know you will need (e.g. <code>from webbrowser import get</code>).</p>
<p>Importing with a wildcard is not generally a good idea unless the module you're doing it on is specifically designed for it. This issue shows exactly why.</p>
| 0 |
2016-09-12T04:56:25Z
|
[
"python",
"boolean",
"text-files",
"typeerror"
] |
How to call a function correctly
| 39,443,478 |
<p>Here is the function which has four parameters. </p>
<pre><code>import urllib
import xlrd
from xlwt import Workbook
def getClose(q, i ,p, f):
inputQ=q;
inputI=str(i);
inputP=str(p);
inputF=f;
address='http://www.google.com/finance/getprices?q='+inputQ+'&i='+inputI+'&p='+inputP+'d&f='+inputF;
response = urllib.request.urlopen(address);
data = response.readlines();
newData = data[7:len(data)];
result=[];
amount =0;
for line in newData:
content =str((line.decode("utf-8", errors='ignore').split("\n")[0]));
result.insert(amount,content);
amount = amount +1;
#write the list of result into the excel file
writeBook= Workbook();
writeSheet= writeBook.add_sheet('Close Price');
for n in range(amount):
writeSheet.write(n,0,result[n]);
writeBook.save('close price.xls');
</code></pre>
<p>But now I want to get the parameter q from a excel,what should I do?
I know how to write it by using three parameters.</p>
<pre><code>import urllib
import xlrd
from xlwt import Workbook
def getClose(i ,p, f):
workbook = xlrd.open_workbook('test1.xlsx');
sheet=workbook.sheet_by_index(0);
num_rows = sheet.nrows -1;
inputI=str(i);
inputP=str(p);
inputF=f;
writeBook= Workbook();
writeSheet= writeBook.add_sheet('Close Price');
for i in range(0,num_rows+1):
inputS=sheet.cell_value(i,0);
address='http://www.google.com/finance/getprices?q='+inputS+'&i='+inputI+'&p='+inputP+'d&f='+inputF;
response = urllib.request.urlopen(address);
data = response.readlines();
newData = data[7:len(data)];
result=[];
amount =0;
for line in newData:
content =str((line.decode("utf-8", errors='ignore').split("\n")[0]));
result.insert(amount,content);
amount = amount +1;
for n in range(amount):
writeSheet.write(n,i,result[n]);
writeBook.save('close price.xls');
</code></pre>
<p>What should I do here? Really appreciate it.</p>
| -2 |
2016-09-12T04:43:35Z
| 39,443,584 |
<p>Doing too many things in a single function is not advisable. Looking at the function, there are three main operations:</p>
<ol>
<li>from a spreadsheet (test1.xlsx) get a query parameter (q) retrieve</li>
<li>and parse values from a webpage save the parsed results in a</li>
<li>spreadsheet (close price.xls)</li>
</ol>
<p>What I would suggest is to make a function <code>getClose</code> only for #2, and then use it inside a main loop that will read parameter <code>q</code> from <code>test1.xlsx</code> and write the results in <code>close price.xls</code>. Pseudo code like:</p>
<pre><code># THIS IS PSEUDO-CODE, not python...
open(input_spreadsheet)
open(output_spreadsheet)
for row in input_spreadsheet:
q = parse_row(row)
result = getClose(<adjust parameters after function rewrite>)
write_row(output_spreadsheet)
</code></pre>
| 0 |
2016-09-12T04:58:30Z
|
[
"python",
"python-3.x"
] |
Syntax error: unexpected EOF while parsing. Am I inputting incorrectly?
| 39,443,524 |
<p>While trying to solve <a href="http://www.usaco.org/index.php?page=viewproblem2&cpid=94" rel="nofollow" title="this">this</a> computer olympiad problem, I ran into this error:</p>
<pre><code>Traceback (most recent call last):
File "haybales.py", line 5, in <module>
s = input()
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
</code></pre>
<p>My current code looks like this:</p>
<pre><code>hay = []
s = input()
while s != 'END':
hay.append(s)
s = input()
for i in hay: #adds all integers in array
var = var + i
if var % hay[0] == 0:
average = var / hay[0] #finds average of all numbers in array
for bale in hay:
diff = bale - average
total += diff
#finds sum of all differences to find the final answer
print 'you need to move' + str(total) + 'piles of hay'
else:
print 'it\'s not possible to make them equal'
</code></pre>
<p>Are my inputs being read incorrectly?
How can I change my code to resolve the error?</p>
| 0 |
2016-09-12T04:51:59Z
| 39,444,580 |
<p>There are a number of problems with your code:</p>
<ul>
<li><p><strong>Indentation</strong>:
In Python indentation is very important. You can't ignore it, or your code will either fail to run or give unexpected results. This may be due to the way you pasted the code into stack overflow, which I admit can sometimes be troublesome, but it's best to mention it just in case.</p>
<pre><code>hay = []
s = input()
while s != 'END':
hay.append(s)
s = input()
for i in hay: #adds all integers in array
var = var + i
if var % hay[0] == 0:
average = var / hay[0] #finds average of all numbers in array
for bale in hay:
diff = bale - average
total += diff
#finds sum of all differences to find the final answer
print 'you need to move' + str(total) + 'piles of hay'
else:
print "it's not possible to make them equal"
</code></pre></li>
<li><p><strong>input</strong>:
You should convert your input to an integer to allow the calucation to function correctly. Ideally you would also validate the input, but that's another topic. Here, just change line 4:</p>
<pre><code>hay.append(int(s))
</code></pre></li>
<li><p><strong>Scope</strong>:
Visibility of variables is a little off in your code. On line 8 for example, you attempt to add a value to var. But each time you run through the loop var is a new variable and will cause an error. (var is not defined). This is also a problem for Total.</p>
<pre><code>hay = []
s = input()
while s != 'END':
hay.append(s)
s = input()
var = 0 ###ADD var HERE
for i in hay: #adds all integers in array
var = var + i
if var % hay[0] == 0:
average = var / hay[0] #finds average of all numbers in array
total = 0 ###ADD total HERE
for bale in hay:
diff = bale - average
total += diff
#finds sum of all differences to find the final answer
print 'you need to move' + str(total) + 'piles of hay'
else:
print "it's not possible to make them equal"
</code></pre></li>
<li><p><strong>Calculation</strong>:
Average is the sum of all values divided by the number of values.
hay[0] is the first value, not the number of values. To get the number of values entered you can use the len() function.</p>
<pre><code>hay = []
s = input()
while s != 'END':
hay.append(s)
s = input()
var = 0;
for i in hay: #adds all integers in array
var = var + i
if var % hay[0] == 0:
###CHANGE BELOW LINE TO USE len(hay)
average = var / len(hay) #finds average of all numbers in array
total = 0
for bale in hay:
diff = bale - average
total += diff
#finds sum of all differences to find the final answer
print 'you need to move' + str(total) + 'piles of hay'
else:
print "it's not possible to make them equal"
</code></pre></li>
<li><p><strong>print</strong>:
When you print remember to add a space before and after your concatenated (joined) string:</p>
<pre><code>print 'you need to move ' + str(total) + ' piles of hay'
</code></pre></li>
</ul>
<p>Otherwise there will be no space when you get your output.</p>
<p>I hope this helped.</p>
| 0 |
2016-09-12T06:39:16Z
|
[
"python"
] |
Syntax error: unexpected EOF while parsing. Am I inputting incorrectly?
| 39,443,524 |
<p>While trying to solve <a href="http://www.usaco.org/index.php?page=viewproblem2&cpid=94" rel="nofollow" title="this">this</a> computer olympiad problem, I ran into this error:</p>
<pre><code>Traceback (most recent call last):
File "haybales.py", line 5, in <module>
s = input()
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
</code></pre>
<p>My current code looks like this:</p>
<pre><code>hay = []
s = input()
while s != 'END':
hay.append(s)
s = input()
for i in hay: #adds all integers in array
var = var + i
if var % hay[0] == 0:
average = var / hay[0] #finds average of all numbers in array
for bale in hay:
diff = bale - average
total += diff
#finds sum of all differences to find the final answer
print 'you need to move' + str(total) + 'piles of hay'
else:
print 'it\'s not possible to make them equal'
</code></pre>
<p>Are my inputs being read incorrectly?
How can I change my code to resolve the error?</p>
| 0 |
2016-09-12T04:51:59Z
| 39,445,011 |
<p>In addition to the fixes suggeted by Andrew Hewitt, the error you see is caused by your use of <code>input</code> instead of <code>raw_input</code> in python2 (in python3 <code>raw_input</code> was renamed to <code>input</code> ). If you check the <a href="https://docs.python.org/2/library/functions.html#input" rel="nofollow">documentation</a> for <code>input</code> you'll see that it expects <strong>valid python code</strong> then tries to run it and returns what ever comes out of it.
<code>raw_input</code> will just put your input in a string and return it.</p>
<p>So just use <code>raw_input</code> and convert manually the string you get to the desired format.</p>
| 1 |
2016-09-12T07:09:00Z
|
[
"python"
] |
How to load this dataset into Pandas
| 39,443,549 |
<p><a href="http://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data" rel="nofollow">data</a></p>
<p>I tried reading the pandas.read_csv doc to see how I could use newlines to delimit each row as a separate sample. Which parameter should I use to do this?</p>
| 1 |
2016-09-12T04:54:42Z
| 39,443,776 |
<p>You can read it right in with <code>pd.read_csv</code>.</p>
<pre><code>df = pd.read_csv(r'http://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data', header=None)
</code></pre>
| 0 |
2016-09-12T05:21:52Z
|
[
"python",
"pandas"
] |
Receiving and empty list when trying to make a webscraper to parse websites for links
| 39,443,570 |
<p>I was reading <a href="http://docs.python-guide.org/en/latest/scenarios/scrape/" rel="nofollow">this</a> website and learning how to make a webscraper with <code>lxml</code> and `Requests. This is the webscraper code:</p>
<pre><code>from lxml import html
import requests
web_page = requests.get('http://econpy.pythonanywhere.com/ex/001.html')
tree = html.fromstring(web_page.content)
buyers = tree.xpath('//div[@title="buyer-name"]/text()')
prices = tree.xpath('//span[@class="item-price"]/text()')
print "These are the buyers: ", buyers
print "And these are the prices: ", prices
</code></pre>
<p>It works as intended, but when I try to scrape <a href="https://www.reddit.com/r/cringe/" rel="nofollow">https://www.reddit.com/r/cringe/</a> for all the links I'm simply getting <code>[]</code> as a result: </p>
<pre><code>#this code will scrape a Reddit page
from lxml import html
import requests
web_page = requests.get("https://www.reddit.com/r/cringe/")
tree = html.fromstring(web_page.content)
links = tree.xpath('//div[@class="data-url"]/text()')
print links
</code></pre>
<p>What's the problem with the xpath I'm using? I can't figure out what to put in the square brackets in the xpath</p>
| 1 |
2016-09-12T04:57:09Z
| 39,451,123 |
<p>First off, your xpath is wrong, there are no classes with <em>data-url</em>, it is an <em>attribute</em> so you would want <code>div[@data-url]</code> and to extract the attribute you would use <code>/@data-url</code>:</p>
<pre><code>from lxml import html
import requests
headers = {"User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.92 Safari/537.36"}
web_page = requests.get("https://www.reddit.com/r/cringe/", headers=headers)
tree = html.fromstring(web_page.content)
links = tree.xpath('//div[@data-url]/@data-url')
print links
</code></pre>
<p>Also you may see html like the following returned if you query too often or don't use a user-agent so respect what they recommend:</p>
<pre><code><p>we're sorry, but you appear to be a bot and we've seen too many requests
from you lately. we enforce a hard speed limit on requests that appear to come
from bots to prevent abuse.</p>
<p>if you are not a bot but are spoofing one via your browser's user agent
string: please change your user agent string to avoid seeing this message
again.</p>
<p>please wait 6 second(s) and try again.</p>
<p>as a reminder to developers, we recommend that clients make no
more than <a href="http://github.com/reddit/reddit/wiki/API">one
request every two seconds</a> to avoid seeing this message.</p>
</body>
</html>
</code></pre>
<p>If you plan on scraping a lot of reddit, you may want to look at <a href="https://praw.readthedocs.io/en/stable/" rel="nofollow">PRAW</a> and <a href="http://www.w3schools.com/xsl/xpath_syntax.asp" rel="nofollow">w3schools</a> has a nice introduction to <em>xpath</em> expressions.</p>
<p>To break it down:</p>
<pre><code>//div[@data-url]
</code></pre>
<p>searches the doc for <em>div's</em> that have an attribute <code>data-url</code> we don't care what the attribute value is, we just want the div. </p>
<p>That just finds the <em>div's</em>, if you removed the <em>/@data-url</em> you would end up with a list of elements like:</p>
<pre><code>[<Element div at 0x7fbb27a9a940>, <Element div at 0x7fbb27a9a8e8>,..
</code></pre>
<p><code>/@data-url</code> actually extracts the <em>attrbute value</em> i.e the <em>hrefs</em>.</p>
<p>Also you just wanted specific links, the <em>youtube</em> links you could filter using <em>contains</em>: </p>
<pre><code>'//div[contains(@data-url, "www.youtube.com")]/@data-url'
</code></pre>
<p><code>contains(@data-url, "www.youtube.com")</code> will check if the <em>data-url</em> attribute values contain <em>www.youtube.com</em> so the output will be a list of the <em>youtube</em> links.</p>
| 2 |
2016-09-12T13:09:49Z
|
[
"python",
"html",
"web-scraping",
"lxml"
] |
NameError: name 'form' is not defined (Python3)
| 39,443,624 |
<p>Basically the <code>main</code> method takes user input, checks it and calls the <code>first</code> method if the user doesn't enter <code>quit</code>.</p>
<p>The <code>first</code> method checks the first section of the input and calls one of the other methods depending on what the user enters. This is the point I get an error; when the <code>first</code> method calls the <code>form</code> method, for example, I get an <code>NameError: name 'form' is not defined</code> exception. I'm a little confused about this since I've defined each method and they're all spelt correctly, also when I call the <code>quit</code> method it works perfectly fine.</p>
<p>Main method: </p>
<pre><code>if __name__ == '__main__':
for line in sys.stdin:
s = line.strip()
if not s: break
if (str(s) == "quit"): quit()
elif (str(s) == "quit") == False:
a = s.split()
print(a)
if (len(a) is 2): first(a)
elif (len(a) is 3): first(a)
else: print("Invalid Input. Please Re-enter.")
</code></pre>
<p>First method:</p>
<pre><code>def first(a = list()):
word = a[0]
if word == "ls":
ls(a[1])
elif word == "format":
form(a[1])
elif word == "reconnect":
reconnect(a[1])
elif word == "mkfile":
mkfile(a[1])
elif word == "mkdir":
mkdir(a[1])
elif word == "append":
append(a[1], a[2])
elif word == "delfile":
delfile(a[1])
elif word == "deldir":
deldir(a[1])
else:
print("Invalid Prompt. Please Re-enter.")
</code></pre>
<p>Other methods (these are all called from the first method):</p>
<pre><code>def reconnect(one = ""):
print("Reconnect")
def ls(one = ""):
print("list")
def mkfile(one = ""):
print("make file")
def mkdir(one = ""):
print("make drive")
def append(one = "", two = ""):
print("append")
def form(one = ""):
print("format " + one)
def delfile(one = ""):
print("delete file")
def deldir(one = ""):
print("delete directory")
def quit():
print("quit")
sys.exit(0)
</code></pre>
| 0 |
2016-09-12T05:04:24Z
| 39,443,789 |
<p>It depends if you use python 2.7 or 3, but your code works with some minor changes.</p>
<pre><code>import sys
def reconnect(one=""):
print("Reconnect")
def ls(one=""):
print("list")
def mkfile(one=""):
print("make file")
def mkdir(one=""):
print("make drive")
def append(one="", two=""):
print("append")
def form(one=""):
print("format " + one)
def delfile(one=""):
print("delete file")
def deldir(one=""):
print("delete directory")
def quit():
print("quit")
sys.exit(0)
def first(a=list()):
word = a[0]
if word == "ls":
ls(a[1])
elif word == "format":
form(a[1])
elif word == "reconnect":
reconnect(a[1])
elif word == "mkfile":
mkfile(a[1])
elif word == "mkdir":
mkdir(a[1])
elif word == "append":
append(a[1], a[2])
elif word == "delfile":
delfile(a[1])
elif word == "deldir":
deldir(a[1])
else:
print("Invalid Prompt. Please Re-enter.")
line = raw_input("Some input please: ") # or `input("Some...` in python 3
print(line)
s = line.strip()
if (str(s) == "quit"):
quit()
elif (str(s) == "quit") == False:
a = s.split()
print(a)
if (len(a) is 2):
first(a)
elif (len(a) is 3):
first(a)
else:
print("Invalid Input. Please Re-enter.")
</code></pre>
<p>Test</p>
<pre><code> python pyprog.py
Some input please: ls text.txt
ls text.txt
['ls', 'text.txt']
list
</code></pre>
<p>You can also try it <a href="https://repl.it/D5Vy" rel="nofollow">online</a>.</p>
<p><a href="http://i.stack.imgur.com/Q2i3D.png" rel="nofollow"><img src="http://i.stack.imgur.com/Q2i3D.png" alt="enter image description here"></a></p>
| 0 |
2016-09-12T05:22:57Z
|
[
"python",
"error-handling"
] |
NameError: name 'form' is not defined (Python3)
| 39,443,624 |
<p>Basically the <code>main</code> method takes user input, checks it and calls the <code>first</code> method if the user doesn't enter <code>quit</code>.</p>
<p>The <code>first</code> method checks the first section of the input and calls one of the other methods depending on what the user enters. This is the point I get an error; when the <code>first</code> method calls the <code>form</code> method, for example, I get an <code>NameError: name 'form' is not defined</code> exception. I'm a little confused about this since I've defined each method and they're all spelt correctly, also when I call the <code>quit</code> method it works perfectly fine.</p>
<p>Main method: </p>
<pre><code>if __name__ == '__main__':
for line in sys.stdin:
s = line.strip()
if not s: break
if (str(s) == "quit"): quit()
elif (str(s) == "quit") == False:
a = s.split()
print(a)
if (len(a) is 2): first(a)
elif (len(a) is 3): first(a)
else: print("Invalid Input. Please Re-enter.")
</code></pre>
<p>First method:</p>
<pre><code>def first(a = list()):
word = a[0]
if word == "ls":
ls(a[1])
elif word == "format":
form(a[1])
elif word == "reconnect":
reconnect(a[1])
elif word == "mkfile":
mkfile(a[1])
elif word == "mkdir":
mkdir(a[1])
elif word == "append":
append(a[1], a[2])
elif word == "delfile":
delfile(a[1])
elif word == "deldir":
deldir(a[1])
else:
print("Invalid Prompt. Please Re-enter.")
</code></pre>
<p>Other methods (these are all called from the first method):</p>
<pre><code>def reconnect(one = ""):
print("Reconnect")
def ls(one = ""):
print("list")
def mkfile(one = ""):
print("make file")
def mkdir(one = ""):
print("make drive")
def append(one = "", two = ""):
print("append")
def form(one = ""):
print("format " + one)
def delfile(one = ""):
print("delete file")
def deldir(one = ""):
print("delete directory")
def quit():
print("quit")
sys.exit(0)
</code></pre>
| 0 |
2016-09-12T05:04:24Z
| 39,444,435 |
<p>this error is because of </p>
<pre><code> elif word == "format":
form(a[1])
</code></pre>
<p>python basically doesn't know what form is.</p>
<p>let me show you:</p>
<pre><code>gaf@$[09:21:56]~> python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> form()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'form' is not defined
>>>
</code></pre>
<p>there is two ways out</p>
<pre><code>>>> def form():
... pass
...
>>> form()
>>> form
<function form at 0x7f49d7f38a28>
>>>
</code></pre>
<p>or import it form some library using</p>
<pre><code>import
</code></pre>
<p>command</p>
<p>also order is matters too</p>
<pre><code>try:
form()
except NameError:
print('Oops name error raise above')
def form():
print('form foo is called')
try:
form()
except NameError:
print('Oops name error raise below')
</code></pre>
<p>will give you</p>
<pre><code>/home/gaf/dashboard/bin/python /home/gaf/PycharmProjects/dashboard/test.py
Oops name error raise above
form foo is called
Process finished with exit code 0
</code></pre>
<p>P.S.
take a look at pep8
your code is a mess %)
but no worries this what everybody does with first language</p>
| 1 |
2016-09-12T06:26:24Z
|
[
"python",
"error-handling"
] |
python 3 how to make .exe from .py
| 39,443,717 |
<p>Could someone please give me a step-by-step recipe for how, in September 2016, one makes in Windows 10 an exe from a python script? Nowhere can I find instructions on exactly what to do, although there is much written on the general subject. </p>
<p>Also, there are a number of .wav files that need to be incorporated into the final .exe. Exactly how do I do this?</p>
<p>Many thanks.</p>
| 0 |
2016-09-12T05:15:25Z
| 39,444,010 |
<p>You can use <a href="http://www.pyinstaller.org/" rel="nofollow">PyInstaller</a>.it have a option for pack everything to a one file exe.</p>
| 0 |
2016-09-12T05:46:47Z
|
[
"python"
] |
list comprehension and map without lambda on long string
| 39,443,809 |
<pre><code>$ python -m timeit -s'tes = "987kkv45kk321"*100' 'a = [list(i) for i in tes.split("kk")]'
10000 loops, best of 3: 79.4 usec per loop
$ python -m timeit -s'tes = "987kkv45kk321"*100' 'b = list(map(list, tes.split("kk")))'
10000 loops, best of 3: 66.9 usec per loop
$ python -m timeit -s'tes = "987kkv45kk321"*10' 'a = [list(i) for i in tes.split("kk")]'
100000 loops, best of 3: 8.34 usec per loop
$ python -m timeit -s'tes = "987kkv45kk321"*10' 'b = list(map(list, tes.split("kk")))'
100000 loops, best of 3: 7.38 usec per loop
$ python -m timeit -s'tes = "987kkv45kk321"' 'a = [list(i) for i in tes.split("kk")]'
1000000 loops, best of 3: 1.51 usec per loop
$ python -m timeit -s'tes = "987kkv45kk321"' 'b = list(map(list, tes.split("kk")))'
1000000 loops, best of 3: 1.63 usec per loop
</code></pre>
<p>I tried using timeit and wonder why creating list of lists from string.split() with list comprehension is faster for a shorter string but slower for longer string.</p>
| 1 |
2016-09-12T05:25:26Z
| 39,451,839 |
<p>This kind of timing is basically useless. </p>
<p>The time frames you are getting are in microseconds - and you are just creating tens of different one-character-long-elements list in each interaction. You get basically linear type, because the number of objects you create is proportional to your string lengths. There is hardly any surprise in this. </p>
| 0 |
2016-09-12T13:46:14Z
|
[
"python",
"python-3.x",
"built-in"
] |
list comprehension and map without lambda on long string
| 39,443,809 |
<pre><code>$ python -m timeit -s'tes = "987kkv45kk321"*100' 'a = [list(i) for i in tes.split("kk")]'
10000 loops, best of 3: 79.4 usec per loop
$ python -m timeit -s'tes = "987kkv45kk321"*100' 'b = list(map(list, tes.split("kk")))'
10000 loops, best of 3: 66.9 usec per loop
$ python -m timeit -s'tes = "987kkv45kk321"*10' 'a = [list(i) for i in tes.split("kk")]'
100000 loops, best of 3: 8.34 usec per loop
$ python -m timeit -s'tes = "987kkv45kk321"*10' 'b = list(map(list, tes.split("kk")))'
100000 loops, best of 3: 7.38 usec per loop
$ python -m timeit -s'tes = "987kkv45kk321"' 'a = [list(i) for i in tes.split("kk")]'
1000000 loops, best of 3: 1.51 usec per loop
$ python -m timeit -s'tes = "987kkv45kk321"' 'b = list(map(list, tes.split("kk")))'
1000000 loops, best of 3: 1.63 usec per loop
</code></pre>
<p>I tried using timeit and wonder why creating list of lists from string.split() with list comprehension is faster for a shorter string but slower for longer string.</p>
| 1 |
2016-09-12T05:25:26Z
| 39,461,331 |
<p>The fixed setup costs for <code>map</code> are higher than the setup costs for the listcomp solution. But the per-item costs for <code>map</code> are lower. So for short inputs, <code>map</code> is paying more in fixed setup costs than it saves on the per item costs (because there are so few items). When the number of items increases, the fixed setup costs for <code>map</code> don't change, but the savings per item is being reaped for more items, so <code>map</code> slowly pulls ahead.</p>
<p>Things that <code>map</code> saves on:</p>
<ol>
<li>Only looks up <code>list</code> once (the listcomp has to look it up in the builtin namespace every single loop, after checking the nested and global scopes first, because it can't guarantee <code>list</code> isn't overridden from loop to loop)</li>
<li>Executes no Python bytecode per item (because the mapping function is also C level), so the interpreter doesn't get involved at all, reducing the amount of hot C level code</li>
</ol>
<p><code>map</code> loses on the actual call to <code>map</code> (C built-in functions are fast to run, but comparatively slow to call, especially if they take variable length arguments), and the creation and cleanup of the <code>map</code> object (the listcomp closure is compiled up front). But as I noted above, neither of these is tied to the size of the inputs, so you make up for it rapidly if the mapping function is a C builtin.</p>
| 0 |
2016-09-13T02:20:00Z
|
[
"python",
"python-3.x",
"built-in"
] |
Self attribute not working pygame
| 39,443,815 |
<p>I am trying to create a simple object-oriented pong game. I have a <code>Player</code> object and one method (<code>create_paddle</code>). When I create an instance of <code>Player</code> and call the <code>create_paddle</code> method it gives me the following error:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\jerem\Documents\python_programs\pong.py", line 30, in <module>
player1.create_paddle(30, 180, 15, 120)
TypeError: create_paddle() missing 1 required positional argument: 'h'
</code></pre>
<p>Program:</p>
<pre><code>class Player:
def create_paddle(self, x, y, w, h):
pygame.draw.rect(surface, white, (x, y, w, h))
player1 = Player
player1.create_paddle(30, 180, 15, 120)
</code></pre>
<p>I have looked up the error and no other posts helped.
Any help is appreciated!
Thanks, JC</p>
| 0 |
2016-09-12T05:25:48Z
| 39,443,831 |
<p>You're missing parentheses when creating the object:</p>
<pre><code>player1 = Player()
</code></pre>
<p>Which means you're just assigning player1 to Player and trying to call your method like a static method....so self isn't getting passed for you.</p>
<pre><code>player1.create_paddle(player1, 30, 180, 15, 120)
</code></pre>
<p>That is what python does for you behind the scenes.</p>
| 4 |
2016-09-12T05:27:44Z
|
[
"python",
"python-3.x",
"oop",
"compiler-errors",
"pygame"
] |
Convert date to timestamp using lambda function while reading the file
| 39,443,887 |
<p>I am reading csv file which contains date in this format:</p>
<pre><code>date
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014
</code></pre>
<p>I can not use date like this in string format, which I need to convert into numeric timestamp.</p>
<p>So I wrote this code:</p>
<pre><code>Train = pd.read_csv("train.tsv", sep='\t')
Train['timestamp'] = pd.to_datetime(Train['date']).apply(lambda a: a.timestamp())
</code></pre>
<p>This give me:</p>
<blockquote>
<p>Train['timestamp'] = pd.to_datetime(Train['date']).apply(lambda a: a.timestamp())<br>
AttributeError: 'Timestamp' object has no attribute 'timestamp'</p>
</blockquote>
<p>Could you please correct me to get in timestamp in lambda?</p>
<p>Edit code :</p>
<pre><code>Train = pd.read_csv("data_scientist_assignment.tsv", sep='\t', parse_dates=['date'])
#print df.head()
# Train['timestamp'] = pd.to_datetime(Train['date']).apply(lambda a: a.timestamp())
Train['timestamp'] = Train.date.values.astype(np.int64)
x1=["timestamp", "hr_of_day"]
test=pd.read_csv("test.csv")
print(Train.columns)
print(test.columns)
model = LogisticRegression()
model.fit(Train[x1], Train["vals"])
print(model)
print model.score(Train[x1], Train["vals"])
</code></pre>
| 2 |
2016-09-12T05:33:41Z
| 39,443,907 |
<p>You need add parameter <code>parse_dates</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a> with column name converted to <code>datetime</code>:</p>
<pre><code>import pandas as pd
import io
temp=u"""date
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp), sep='\t', parse_dates=['date'])
print (df)
date
0 2014-01-05
1 2014-01-05
2 2014-01-05
3 2014-01-05
4 2014-01-05
5 2014-01-05
6 2014-01-05
7 2014-01-05
8 2014-01-05
print (df.dtypes)
date datetime64[ns]
dtype: object
</code></pre>
<p>Another solution is add numbers for order of column <code>date</code> - in sample it is first column, so add <code>0</code> (python counts from <code>0</code>):</p>
<pre><code>df = pd.read_csv(io.StringIO(temp), sep='\t', parse_dates=[0])
print (df)
date
0 2014-01-05
1 2014-01-05
2 2014-01-05
3 2014-01-05
4 2014-01-05
5 2014-01-05
6 2014-01-05
7 2014-01-05
8 2014-01-05
print (df.dtypes)
date datetime64[ns]
dtype: object
</code></pre>
<hr>
<p>Then need convert column to <code>numpy array</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.values.html" rel="nofollow"><code>values</code></a> and cast to <code>int</code>:</p>
<pre><code>#unix time in ns
df.date = df.date.values.astype(np.int64)
print (df)
date
0 1388880000000000000
1 1388880000000000000
2 1388880000000000000
3 1388880000000000000
4 1388880000000000000
5 1388880000000000000
6 1388880000000000000
7 1388880000000000000
8 1388880000000000000
#unix time in us
df.date = df.date.values.astype(np.int64) // 1000
print (df)
date
0 1388880000000000
1 1388880000000000
2 1388880000000000
3 1388880000000000
4 1388880000000000
5 1388880000000000
6 1388880000000000
7 1388880000000000
8 1388880000000000
</code></pre>
<pre><code>#unix time in ms
df.date = df.date.values.astype(np.int64) // 1000000
#df.date = pd.to_datetime(df.date, unit='ms')
print (df)
date
0 1388880000000
1 1388880000000
2 1388880000000
3 1388880000000
4 1388880000000
5 1388880000000
6 1388880000000
7 1388880000000
8 1388880000000
#unix time in s
df.date = df.date.values.astype(np.int64) // 1000000000
print (df)
date
0 1388880000
1 1388880000
2 1388880000
3 1388880000
4 1388880000
5 1388880000
6 1388880000
7 1388880000
8 1388880000
</code></pre>
| 1 |
2016-09-12T05:35:49Z
|
[
"python",
"csv",
"pandas",
"lambda",
"timestamp"
] |
Convert date to timestamp using lambda function while reading the file
| 39,443,887 |
<p>I am reading csv file which contains date in this format:</p>
<pre><code>date
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014
01/05/2014
</code></pre>
<p>I can not use date like this in string format, which I need to convert into numeric timestamp.</p>
<p>So I wrote this code:</p>
<pre><code>Train = pd.read_csv("train.tsv", sep='\t')
Train['timestamp'] = pd.to_datetime(Train['date']).apply(lambda a: a.timestamp())
</code></pre>
<p>This give me:</p>
<blockquote>
<p>Train['timestamp'] = pd.to_datetime(Train['date']).apply(lambda a: a.timestamp())<br>
AttributeError: 'Timestamp' object has no attribute 'timestamp'</p>
</blockquote>
<p>Could you please correct me to get in timestamp in lambda?</p>
<p>Edit code :</p>
<pre><code>Train = pd.read_csv("data_scientist_assignment.tsv", sep='\t', parse_dates=['date'])
#print df.head()
# Train['timestamp'] = pd.to_datetime(Train['date']).apply(lambda a: a.timestamp())
Train['timestamp'] = Train.date.values.astype(np.int64)
x1=["timestamp", "hr_of_day"]
test=pd.read_csv("test.csv")
print(Train.columns)
print(test.columns)
model = LogisticRegression()
model.fit(Train[x1], Train["vals"])
print(model)
print model.score(Train[x1], Train["vals"])
</code></pre>
| 2 |
2016-09-12T05:33:41Z
| 39,443,968 |
<p>Another short way to go about this is to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow">to_datetime()</a>:</p>
<pre><code>In [209]: df['date']
Out[209]:
0 01/05/2014
1 01/05/2014
2 01/05/2014
3 01/05/2014
4 01/05/2014
5 01/05/2014
6 01/05/2014
7 01/05/2014
8 01/05/2014
Name: date, dtype: object
In [210]: df['date'] = pd.to_datetime(df['date'])
In [211]: df['date']
Out[211]:
0 2014-01-05
1 2014-01-05
2 2014-01-05
3 2014-01-05
4 2014-01-05
5 2014-01-05
6 2014-01-05
7 2014-01-05
8 2014-01-05
Name: date, dtype: datetime64[ns]
</code></pre>
<p>Also, you can get seconds like this:</p>
<pre><code>In [232]: df['date'].astype(pd.np.int64) // 10**9
Out[232]:
0 1388880000
1 1388880000
2 1388880000
3 1388880000
4 1388880000
5 1388880000
6 1388880000
7 1388880000
8 1388880000
Name: date, dtype: int64
</code></pre>
| 1 |
2016-09-12T05:42:24Z
|
[
"python",
"csv",
"pandas",
"lambda",
"timestamp"
] |
Using loop(Efficient Looping technique): To extract certain url's out of my string in Python
| 39,443,911 |
<p>The following lines of code gives me the source code to a specific playlist and stores all url's in a variable "newlink". I wish to write a loop that can go through this string of url's and store the ones that say '/watch?v=' into an array in Python so that array[0] would give me the first link, array[1] the second and so on. What would be the best way of doing this?</p>
<pre><code>import re
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
import requests
#Asks which playlist you want downloaded
print ('Which playlist do you want to download?')
playlist = input()
#Access my youtube playlists page
driver = webdriver.Chrome(executable_path='E:\chromedriver\chromedriver.exe')
driver.get("https://www.youtube.com/user/randomuser/playlists?sort=dd&view=1&shelf_id=0")
#Access the 'classic' playlist
if playlist == 'classic':
driver.find_element_by_xpath('//a[contains(text(), "classic")]').click()
newurl = driver.current_url
requrl = requests.get(newurl)
requrlcont = requrl.content
soup = BeautifulSoup(requrlcont, "html.parser")
for link in soup.find_all('a'):
newlink = link.get('href'))
</code></pre>
| 0 |
2016-09-12T05:36:08Z
| 39,444,084 |
<p>This code is tested with a playlist that actually created the array. </p>
<pre><code>import re
from selenium import webdriver
from bs4 import BeautifulSoup
import requests
#Asks which playlist you want downloaded
print ('Which playlist do you want to download?')
playlist = raw_input()
#Access my youtube playlists page
driver = webdriver.Chrome(executable_path='/usr/lib/chromium-browser/chromedriver')
driver.get("https://www.youtube.com/user/randomuser/playlists?sort=dd&view=1&shelf_id=0")
#Access the 'Favorites' playlist
if playlist == 'Favorites':
driver.find_element_by_xpath('//a[contains(text(), "Favorites")]').click()
newurl = driver.current_url
requrl = requests.get(newurl)
requrlcont = requrl.content
links = []
soup = BeautifulSoup(requrlcont, "html.parser")
for link in soup.find_all('a'):
#print("link " + str(link))
if re.match("/watch\?v=", link.get('href')):
links.append(link.get('href'))
print links
</code></pre>
<p>Output</p>
<pre><code>python pyprog.py
Which playlist do you want to download?
Favorites
[u'/watch?v=fG9_AYzehJw&list=FLRMDL-xDn7xqDznwaQbUH6g', u'/watch?v=fG9_AYzehJw&list=FLRMDL-xDn7xqDznwaQbUH6g', u'/watch?v=fG9_AYzehJw&index=1&list=FLRMDL-xDn7xqDznwaQbUH6g', u'/watch?v=fG9_AYzehJw&index=1&list=FLRMDL-xDn7xqDznwaQbUH6g', u'/watch?v=MKfDwChOoHI&index=2&list=FLRMDL-xDn7xqDznwaQbUH6g', u'/watch?v=MKfDwChOoHI&index=2&list=FLRMDL-xDn7xqDznwaQbUH6g', u'/watch?v=JQTXawaAKNA&index=3&list=FLRMDL-xDn7xqDznwaQbUH6g', u'/watch?v=JQTXawaAKNA&index=3&list=FLRMDL-xDn7xqDznwaQbUH6g', u'/watch?v=dG8wsae-6tU&index=4&list=FLRMDL-xDn7xqDznwaQbUH6g', u'/watch?v=dG8wsae-6tU&index=4&list=FLRMDL-xDn7xqDznwaQbUH6g', u'/watch?v=9mcZdDCOeuE&index=5&list=FLRMDL-xDn7xqDznwaQbUH6g', u'/watch?v=9mcZdDCOeuE&index=5&list=FLRMDL-xDn7xqDznwaQbUH6g', u'/watch?v=lh0ZB9OD_fg&index=6&list=FLRMDL-xDn7xqDznwaQbUH6g', u'/watch?v=lh0ZB9OD_fg&index=6&list=FLRMDL-xDn7xqDznwaQbUH6g', u'/watch?v=NfLmCPfx_gY&index=7&list=FLRMDL-xDn7xqDznwaQbUH6g', u'/watch?v=NfLmCPfx_gY&index=7&list=FLRMDL-xDn7xqDznwaQbUH6g', u'/watch?v=FoQzWb_f1oA&index=8&list=FLRMDL-xDn7xqDznwaQbUH6g', u'/watch?v=FoQzWb_f1oA&index=8&list=FLRMDL-xDn7xqDznwaQbUH6g', u'/watch?v=l8rJ1WML60Y&index=9&list=FLRMDL-xDn7xqDznwaQbUH6g', u'/watch?v=l8rJ1WML60Y&index=9&list=FLRMDL-xDn7xqDznwaQbUH6g', u'/watch?v=9rCug1ANQdE&index=10&list=FLRMDL-xDn7xqDznwaQbUH6g', u'/watch?v=9rCug1ANQdE&index=10&list=FLRMDL-xDn7xqDznwaQbUH6g']
</code></pre>
| 0 |
2016-09-12T05:53:44Z
|
[
"python"
] |
I am trying to delete a node from chef server using PyChef but i am getting a error given below
| 39,444,153 |
<p>I am trying to delete a node on chef server using PyChef but getting an error given below. And here is my script:</p>
<pre><code>import json
import requests
import chef
import base64
from chef import Node
from chef import auth
from chef.rsa import Key
from chef.api import ChefAPI
from chef import api
import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()
key = open('/root/chef-repo/.chef/gs-validator.pem', "r").read()
key =Key(key)
hashed_body = auth.sha1_base64('')
#print hashed_body
from datetime import datetime
timestamp = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
#print timestamp
headers={}
req=auth.canonical_request('GET','here-is-my url-of server',hashed_body,timestamp,'here-is-client-name')
sig =auth. _ruby_b64encode(key.private_encrypt(req))
#print sig
for i, line in enumerate(sig):
headers['x-ops-authorization-%s'%(i+1)] = line
#print headers
#print "--------------",headers.get('x-ops-authorization-%s'%(4),False)
X1= headers.get('x-ops-authorization-%s'%(1),False)
X2 = headers.get('x-ops-authorization-%s'%(2),False)
X3 = headers.get('x-ops-authorization-%s'%(3),False)
X4 = headers.get('x-ops-authorization-%s'%(4),False)
X5 = headers.get('x-ops-authorization-%s'%(5),False)
headers = {'Method':'GET','X-Ops-Content-Hash':hashed_body,'content- type':'application/json','accept':'application/json','X-Ops-Timestamp':timestamp,'X-Ops-UserId':'gs-validator','X-Ops-Authorization-1':X1,'X-Ops-Authorization-2':X2,'X-Ops-Authorization-3':X3,'X-Ops-Authorization-4':X4,'X-Ops-Authorization-5':X5}
with chef.ChefAPI(url, '/root/chef-repo/.chef/gs-validator.pem', 'gs- validator',headers = headers,ssl_verify = False):
node = Node('node-name')
print node.delete()
</code></pre>
<p>Error:</p>
<pre><code>Traceback (most recent call last):
File "delchef.py", line 55, in <module>
print node.delete()
File "/usr/local/lib/python2.7/dist-packages/chef/base.py", line 117, in delete
api.api_request('DELETE', self.url)
File "/usr/local/lib/python2.7/dist-packages/chef/api.py", line 217, in api_request
response = self.request(method, path, headers, data)
File "/usr/local/lib/python2.7/dist-packages/chef/api.py", line 207, in request
raise ChefServerError.from_error(response.reason, code=response.status_code)
chef.exceptions.ChefServerNotFoundError: Object Not Found
</code></pre>
<p>And when i print instead of node.delete():<br>
node.attributes</p>
<pre><code>it gives me this output:
chef.node.NodeAttributes object at 0x7fb2c11e7390
</code></pre>
<p>Thank you in advance.. Please suggest me the possible solution for this error. </p>
| 0 |
2016-09-12T06:01:16Z
| 39,445,444 |
<p>PyChef already does all the authentication headers for you, why are you duplicating things? For the specific question, a 404 means the node you are trying to delete doesn't exist. You can see what nodes exist on the server with <code>Node.list()</code>.</p>
| 0 |
2016-09-12T07:39:15Z
|
[
"python",
"chef",
"pychef"
] |
python create nested directory based on two lists
| 39,444,360 |
<p>Good morning,</p>
<p>This might be easy but I´m just starting with python. For learning:
Is there are 'cleaner' way creating a nested dict based on two lists than this:</p>
<pre><code>person = ['mama.a','mama.b', 'mama.c',
'mama.d', 'papa.a', 'papa.b']
kind = ['a', 'b', 'c', 'd']
combined = {}
# GOAL:
# {'mama': {'a': [], 'c': [], 'b': [], 'd': []}, 'papa': {'a': [], 'c': [], 'b': [], 'd': []}}
for human in [i.split('.')[0] for i in person]:
combined[human] = {}
for attrib in kind:
combined[human][attrib] = []
</code></pre>
| 2 |
2016-09-12T06:19:55Z
| 39,444,446 |
<pre><code>{p.split('.')[0]: {k: [] for k in kind} for p in person}
</code></pre>
| 3 |
2016-09-12T06:27:04Z
|
[
"python",
"list"
] |
python create nested directory based on two lists
| 39,444,360 |
<p>Good morning,</p>
<p>This might be easy but I´m just starting with python. For learning:
Is there are 'cleaner' way creating a nested dict based on two lists than this:</p>
<pre><code>person = ['mama.a','mama.b', 'mama.c',
'mama.d', 'papa.a', 'papa.b']
kind = ['a', 'b', 'c', 'd']
combined = {}
# GOAL:
# {'mama': {'a': [], 'c': [], 'b': [], 'd': []}, 'papa': {'a': [], 'c': [], 'b': [], 'd': []}}
for human in [i.split('.')[0] for i in person]:
combined[human] = {}
for attrib in kind:
combined[human][attrib] = []
</code></pre>
| 2 |
2016-09-12T06:19:55Z
| 39,444,485 |
<p>What about making a <code>set</code> of the names. To ensure you only try to add each one to <code>dict</code> once.</p>
<pre><code>combined = {}
for n in set(p.split('.')[0] for p in person):
combined[n] = {k:[] for k in kind}
</code></pre>
<p>This could probably be made into a monster one-liner nested <code>dict</code> comprehension. Although I dont think it would be as easy to read.</p>
<p>or you could split the <code>set</code> out onto another line. It then becomes</p>
<pre><code>pset = set(p.split('.')[0] for p in person)
pdict = {p: {k: [] for k in kind} for p in pset}
</code></pre>
<p>Where the second line is the same as @Faiz Haldes answer.</p>
| 0 |
2016-09-12T06:30:38Z
|
[
"python",
"list"
] |
python create nested directory based on two lists
| 39,444,360 |
<p>Good morning,</p>
<p>This might be easy but I´m just starting with python. For learning:
Is there are 'cleaner' way creating a nested dict based on two lists than this:</p>
<pre><code>person = ['mama.a','mama.b', 'mama.c',
'mama.d', 'papa.a', 'papa.b']
kind = ['a', 'b', 'c', 'd']
combined = {}
# GOAL:
# {'mama': {'a': [], 'c': [], 'b': [], 'd': []}, 'papa': {'a': [], 'c': [], 'b': [], 'd': []}}
for human in [i.split('.')[0] for i in person]:
combined[human] = {}
for attrib in kind:
combined[human][attrib] = []
</code></pre>
| 2 |
2016-09-12T06:19:55Z
| 39,444,619 |
<pre><code>combined = {x.split('.')[0]:{i:[] for i in kind} for x in person} #if you require no check as to whether mama or papa contain a, b, c, or d
print combined
neutral = {i.split('.')[0]:[n.split('.')[1] for n in person if n.split('.')[0] == i.split('.')[0]] for i in person} #if you require a check
combined = {k:{v:[] for v in neutral[k]} for k in neutral}
print combined
</code></pre>
| 0 |
2016-09-12T06:41:59Z
|
[
"python",
"list"
] |
How to make Table sort of thing which is in line?
| 39,444,472 |
<p>I want to find out the way to keep my table all proper and lined up but when the size of the variable changes, the borders change aswell. Take a look at my code.I need a solution to keep my table straight.</p>
<pre><code>generation = int(input('how many generations do you need?'))
population_calf = int(input('how many calf are there?'))
population_old_cow = int(input('how many old_cow are there?'))
population_cows = int(input('how many cows are there?'))
birth_rate = 1
survival_rate_calf = 0.75
survival_rate_old_cow = 0.25
survival_rate_cows = 0.75
NUMBER = 0
print(' || POPULATION calf | POPULATION cows | POPULATION old_cow ||')
for i in range(generation):
print('GENERATION', NUMBER, ' '' |',' ', int(population_calf), ' ', int(population_cows), ' ', int(population_old_cow),' ||')
population_old_cow = population_cows * survival_rate_cows + population_old_cow * survival_rate_old_cow
population_calf = population_cows * survival_rate_cows * birth_rate
population_cows = population_calf * survival_rate_calf
print(int(population_calf), int(population_cows), int(population_old_cow))
NUMBER = NUMBER + 1
</code></pre>
<p>Here is a picture of what it prints out:
<a href="http://i.stack.imgur.com/WLMD9.png" rel="nofollow">Pic of what it prints out</a></p>
<p>THANKS IN ADVANCE GUYS:) IF YOU NEED MORE DETAIL, ASK ME I WILL REPLY CHEERS</p>
| 2 |
2016-09-12T06:29:53Z
| 39,444,774 |
<p>You can use <a href="https://pypi.python.org/pypi/terminaltables" rel="nofollow">terminaltables</a> or <a href="https://pypi.python.org/pypi/texttable/0.8.4" rel="nofollow">texttable</a>.</p>
| 0 |
2016-09-12T06:52:48Z
|
[
"python",
"python-3.x"
] |
How to make Table sort of thing which is in line?
| 39,444,472 |
<p>I want to find out the way to keep my table all proper and lined up but when the size of the variable changes, the borders change aswell. Take a look at my code.I need a solution to keep my table straight.</p>
<pre><code>generation = int(input('how many generations do you need?'))
population_calf = int(input('how many calf are there?'))
population_old_cow = int(input('how many old_cow are there?'))
population_cows = int(input('how many cows are there?'))
birth_rate = 1
survival_rate_calf = 0.75
survival_rate_old_cow = 0.25
survival_rate_cows = 0.75
NUMBER = 0
print(' || POPULATION calf | POPULATION cows | POPULATION old_cow ||')
for i in range(generation):
print('GENERATION', NUMBER, ' '' |',' ', int(population_calf), ' ', int(population_cows), ' ', int(population_old_cow),' ||')
population_old_cow = population_cows * survival_rate_cows + population_old_cow * survival_rate_old_cow
population_calf = population_cows * survival_rate_cows * birth_rate
population_cows = population_calf * survival_rate_calf
print(int(population_calf), int(population_cows), int(population_old_cow))
NUMBER = NUMBER + 1
</code></pre>
<p>Here is a picture of what it prints out:
<a href="http://i.stack.imgur.com/WLMD9.png" rel="nofollow">Pic of what it prints out</a></p>
<p>THANKS IN ADVANCE GUYS:) IF YOU NEED MORE DETAIL, ASK ME I WILL REPLY CHEERS</p>
| 2 |
2016-09-12T06:29:53Z
| 39,444,979 |
<p>You can use formatting in <code>print()</code>:</p>
<pre><code>fmt = '%-15s || %15s | %15s | %18s ||'
print(fmt % ('', 'POPULATION calf', 'POPULATION cows', 'POPULATION old_cow'))
for i in range(generation):
print(fmt % ('GENERATION %d'%i, int(population_calf), int(population_cows), int(population_old_cow)), end='')
population_old_cow = population_cows * survival_rate_cows + population_old_cow * survival_rate_old_cow
population_calf = population_cows * survival_rate_cows * birth_rate
population_cows = population_calf * survival_rate_calf
print('', int(population_calf), int(population_cows), int(population_old_cow))
</code></pre>
| 0 |
2016-09-12T07:06:48Z
|
[
"python",
"python-3.x"
] |
how to use my drive api downloaded file as an attachment on my app engine application
| 39,444,477 |
<p>I used the drive api to download a pdf file, and I want to use that file as an attachment using the app engine mail api (python). I have tried the following code below, the file downloaded and the email was sent but in the email there is no attachment at all. Please help me out</p>
<pre><code>class ManageGoogleDriveAPI(webapp2.RequestHandler):
def get(self):
credentials = AppAssertionCredentials('https://www.googleapis.com/auth/drive')
http_auth = credentials.authorize(Http())
# Create a communication between my app and google api endpoint
DRIVE = build('drive', 'v3', http=http_auth)
file_id = '18mHxcum4n_-hxDBvmyEZaWTkirPuaWXptYAJG3PWGvU'
request = DRIVE.files().export_media(fileId=file_id, mimeType='application/pdf')
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
logging.info("Download %d%%." % int(status.progress() * 100))
filename = 'hello.pdf'
mail.send_mail(sender='app_name@appspot.gserviceaccount.com'.format(
app_identity.get_application_id()),
to="johndoe@gmail.com",
subject=subject,
body=body,
attachments=[(filename, fh.read())])
logging.info('COMPLETED!!')
self.response.write('PROCESS COMPLETED!!, You can close this window now. Thank you!')
</code></pre>
| 0 |
2016-09-12T06:30:04Z
| 39,463,490 |
<p>I finally figured what happened...</p>
<p>Instead of:</p>
<pre><code>attachments=[(filename, fh.read())])
</code></pre>
<p>Do this:</p>
<pre><code>attachments=[(filename, fh.getvalue())])
</code></pre>
| 0 |
2016-09-13T06:27:46Z
|
[
"python",
"google-app-engine",
"google-drive-sdk"
] |
Set handler for GPIO state change using python signal module
| 39,444,591 |
<p>I want to detect change in <code>gpio</code> input of raspberry pi and set handler using signal module of python. I am new to signal module and I can't understand how to use it. I am using this code now:</p>
<pre><code>import RPi.GPIO as GPIO
import time
from datetime import datetime
import picamera
i=0
j=0
camera= picamera.PiCamera()
camera.resolution = (640, 480)
# handle the button event
def buttonEventHandler (pin):
global j
j+=1
#camera.close()
print "handling button event"
print("pressed",str(datetime.now()))
time.sleep(4)
camera.capture( 'clicked%02d.jpg' %j )
#camera.close()
def main():
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(2,GPIO.IN,pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(2,GPIO.FALLING)
GPIO.add_event_callback(2,buttonEventHandler)
# RPIO.add_interrupt_callback(2,buttonEventHandler,falling,RPIO.PUD_UP,False,None)
while True:
global i
print "Hello world! {0}".format(i)
i=i+1
time.sleep(5)
# if(GPIO.input(2)==GPIO.LOW):
# GPIO.cleanup()
if __name__=="__main__":
main()
</code></pre>
| 1 |
2016-09-12T06:39:52Z
| 39,491,922 |
<p>I just changed code in a different manner tough you are free to implement same using SIGNAL module.You can start new thread and poll or register call back event their, by using following code and write whatever your functional logic in it's run() method.</p>
<pre><code>import threading
import RPi.GPIO as GPIO
import time
import time
from datetime import datetime
import picamera
i=0
j=0
camera= picamera.PiCamera()
camera.resolution = (640, 480)
PIN = 2
class GPIOThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
while True:
if GPIO.input(PIN) == False: # adjust this statement as per your pin status i.e HIGH/LOW
global j
j+=1
#camera.close()
print "handling button event"
print("pressed",str(datetime.now()))
time.sleep(4)
camera.capture( 'clicked%02d.jpg' %j )
def main():
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(PIN,GPIO.IN,pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(PIN,GPIO.FALLING)
gpio_thread = GPIOThread()
gpio_thread.start()
while True:
global i
print "Hello world! {0}".format(i)
i=i+1
time.sleep(5)
if __name__=="__main__":
main()
</code></pre>
<p>The above code will iterate until PIN input goes high, so once PIN goes high the condition in while loop inside run method breaks and picture is captured.</p>
<p>So, in order to call above thread do this.</p>
<pre><code>gpio_thread = GPIOThread()
gpio_thread.start()
</code></pre>
<p>this will call the thread constructor <strong>init</strong> and will initialize the variable inside constructor if any, and execute the run method.</p>
<p>You can also call join() method , to wait until thread completes it's execution.</p>
<pre><code>gpio_thread.join()
</code></pre>
<p>This always works for me, so Cheers!!</p>
| 0 |
2016-09-14T13:35:23Z
|
[
"python",
"raspberry-pi",
"interrupt",
"gpio",
"django-signals"
] |
Using PBKDF2 SHA512 data in other languages
| 39,444,627 |
<p>I'm using pbkdf2_sha512 as the hashing algorithm in a Flask web app.</p>
<p>I don't want to lose my user data in my database. Can I use same hashing algorithm in the future if I want to change the backend programming language to any other language (like node.js, PHP, Ruby, etc)?</p>
<p>Will the same password hashing work for other programming languages?</p>
| 1 |
2016-09-12T06:42:16Z
| 39,444,678 |
<p><a href="https://en.wikipedia.org/wiki/PBKDF2" rel="nofollow">PBKDF2</a> is a <em>standard</em>; in this case configured to use SHA256 as the hashing function. You'll find implementations for the standard in most programming languages. It is not unique to Flask or Python.</p>
<p>So yes, you can calculate the hash from any other language and test against the stored hash.</p>
<p>Example implementations in other languages:</p>
<ul>
<li>node.js: <a href="https://nodejs.org/api/crypto.html#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback" rel="nofollow"><code>crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)</code></a></li>
<li>PHP: <a href="http://php.net/hash-pbkdf2" rel="nofollow"><code>string hash_pbkdf2 ( string $algo , string $password , string $salt , int $iterations [, int $length = 0 [, bool $raw_output = false ]] )</code></a></li>
<li>Ruby: <a href="http://www.ruby-doc.org/stdlib-1.9.3/libdoc/openssl/rdoc/OpenSSL/PKCS5.html#method-c-pbkdf2_hmac_sha1" rel="nofollow"><code>pbkdf2_hmac(pass, salt, iter, keylen, digest)</code></a></li>
</ul>
| 0 |
2016-09-12T06:46:34Z
|
[
"python",
"postgresql",
"flask",
"pbkdf2"
] |
Add data labels to Seaborn factor plot
| 39,444,665 |
<p>I would like to add data labels to factor plots generated by Seaborn. Here is an example: </p>
<pre><code>import pandas as pd
from pandas import Series, DataFrame
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
titanic_df = pd.read_csv('train.csv')
sns.factorplot('Sex',data=titanic_df,kind='count')
</code></pre>
<p><a href="http://i.stack.imgur.com/pVziQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/pVziQ.png" alt="This image is created"></a></p>
<p>How can I add the 'count' values to the top of each bar on the graph?</p>
| 0 |
2016-09-12T06:45:18Z
| 39,448,291 |
<p>You could do it this way:</p>
<pre><code>import math
# Set plotting style
sns.set_style('whitegrid')
# Rounding the integer to the next hundredth value plus an offset of 100
def roundup(x):
return 100 + int(math.ceil(x / 100.0)) * 100
df = pd.read_csv('train.csv')
sns.factorplot('Sex', data=df, kind='count', alpha=0.7, size=4, aspect=1)
# Get current axis on current figure
ax = plt.gca()
# ylim max value to be set
y_max = df['Sex'].value_counts().max()
ax.set_ylim([0, roundup(y_max)])
# Iterate through the list of axes' patches
for p in ax.patches:
ax.text(p.get_x() + p.get_width()/2., p.get_height(), '%d' % int(p.get_height()),
fontsize=12, color='red', ha='center', va='bottom')
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/tEPd9.png" rel="nofollow"><img src="http://i.stack.imgur.com/tEPd9.png" alt="Image"></a></p>
| 2 |
2016-09-12T10:29:58Z
|
[
"python",
"matplotlib",
"seaborn"
] |
os.walk works with non-escaped backslash?
| 39,444,763 |
<p>Just found a bug in a bit of code I was writing that wasn't actually bugging?</p>
<pre><code>for folderName, subfolders, filenames in os.walk('C:\FOLDER'):
print('The current folder is ' + folderName)
for subfolder in subfolders:
print('SUBFOLDER OF ' + folderName + ': ' + subfolder)
for filename in filenames:
print('FILE INSIDE ' + folderName + ': '+ filename)
</code></pre>
<p>and</p>
<pre><code>for folderName, subfolders, filenames in os.walk('C:\\FOLDER'):
print('The current folder is ' + folderName)
for subfolder in subfolders:
print('SUBFOLDER OF ' + folderName + ': ' + subfolder)
for filename in filenames:
print('FILE INSIDE ' + folderName + ': '+ filename)
</code></pre>
<p>both work in shell and the full code runs fine? Shouldn't that first one be stuffing up because it is feeding it 'C:OLDER'?</p>
| 0 |
2016-09-12T06:51:52Z
| 39,444,782 |
<p>Python ignores unrecognised escape sequences and leaves the original backslash and letter in place.</p>
<p><code>\F</code> is not a valid escape sequence, so your string contains a literal <code>\</code> backslash followed by a literal <code>F</code>:</p>
<pre><code>>>> 'C:\FOLDER'
'C:\\FOLDER'
</code></pre>
| 5 |
2016-09-12T06:53:26Z
|
[
"python",
"python-3.x"
] |
How to set the column width to be the whole QTableWidget width?
| 39,444,808 |
<p>I have an object of type QTableWidget. It contains only one column.
How do I set the column width to be the whole QTableWidget width?</p>
<p><img src="http://i.stack.imgur.com/7Yq3o.png" alt="Graphical representation"></p>
<p>Also: is there a way to delete the header of the column?</p>
| 0 |
2016-09-12T06:55:11Z
| 39,451,105 |
<p>Try to use the following (assuming your table widget is called <code>tableWidget</code>)...</p>
<pre><code>tableWidget.horizontalHeader().setStretchLastSection(True)
</code></pre>
| 0 |
2016-09-12T13:09:15Z
|
[
"python",
"pyqt",
"width",
"pyqt5",
"qtablewidget"
] |
Using logistic regression to predict the parameter value
| 39,444,955 |
<p>I have written vary basic sklearn code using logistic regression to predict the value. </p>
<p>Training data looks like - </p>
<p><a href="https://gist.github.com/anonymous/563591e0395e8d988277d3ce63d7438f" rel="nofollow">https://gist.github.com/anonymous/563591e0395e8d988277d3ce63d7438f</a></p>
<pre><code>date hr_of_day vals
01/05/2014 9 929
01/05/2014 10 942
01/05/2014 11 968
01/05/2014 12 856
01/05/2014 13 835
01/05/2014 14 885
01/05/2014 15 945
01/05/2014 16 924
01/05/2014 17 914
01/05/2014 18 744
01/05/2014 19 377
01/05/2014 20 219
01/05/2014 21 106
</code></pre>
<p>and I have selected first 8 items from training data to just validate the classifier which is </p>
<p>I want to predict the value of <code>vals</code>, in testing data, I have put it as <code>0</code>. Is that correct?</p>
<pre><code>date hr_of_day vals
2014-05-01 0 0
2014-05-01 1 0
2014-05-01 2 0
2014-05-01 3 0
2014-05-01 4 0
2014-05-01 5 0
2014-05-01 6 0
2014-05-01 7 0
</code></pre>
<p>My model code, works fine. But my result looks trange. I was expecting value of <code>vals</code> in result. Rather then that, I am getting large matrix with all element value as <code>0.00030676</code>.</p>
<p>I appreciate if someone can give details or help me to play better with this result.</p>
<pre><code>import pandas as pd
from sklearn import datasets
from sklearn import metrics
from sklearn.linear_model import LogisticRegression
from datetime import datetime, date, timedelta
Train = pd.read_csv("data_scientist_assignment.tsv", sep='\t', parse_dates=['date'])
Train['timestamp'] = Train.date.values.astype(pd.np.int64)
x1=["timestamp", "hr_of_day"]
test=pd.read_csv("test.tsv", sep='\t', parse_dates=['date'])
test['timestamp'] = test.date.values.astype(pd.np.int64)
print(Train.columns)
print(test.columns)
model = LogisticRegression()
model.fit(Train[x1], Train["vals"])
print(model)
print model.score(Train[x1], Train["vals"])
print model.predict_proba(test[x1])
</code></pre>
<p>results looks like this:</p>
<pre><code>In [92]: print(model)
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1,
penalty='l2', random_state=None, solver='liblinear', tol=0.0001,
verbose=0, warm_start=False)
In [93]: print model.score(Train[x1], Train["vals"])
0.00520833333333
In [94]:
In [94]: print model.predict_proba(test[x1])
[[ 0.00030676 0.00030676 0.00030676 ..., 0.00030889 0.00030885
0.00030902]
[ 0.00030676 0.00030676 0.00030676 ..., 0.00030889 0.00030885
0.00030902]
[ 0.00030676 0.00030676 0.00030676 ..., 0.00030889 0.00030885
0.00030902]
...,
[ 0.00030676 0.00030676 0.00030676 ..., 0.00030889 0.00030885
0.00030902]
[ 0.00030676 0.00030676 0.00030676 ..., 0.00030889 0.00030885
0.00030902]
[ 0.00030676 0.00030676 0.00030676 ..., 0.00030889 0.00030885
0.00030902]]
</code></pre>
| 0 |
2016-09-12T07:05:21Z
| 39,447,049 |
<ol>
<li>You are using <strong><em>predict_proba()</em></strong> which gives class probabilities, instead of that you should use <strong><em>predict()</em></strong> function.</li>
<li>You are using a <strong><em>wrong model</em></strong>. The target variable in your data has <strong>continuous data</strong>, therefore you will have to use <strong>linear regression</strong>.
<strong>Logistic Regression</strong> actually works as a <strong>classifier</strong> and classification tasks require discrete data(as in fixed number of labels).</li>
</ol>
| 3 |
2016-09-12T09:20:44Z
|
[
"python",
"machine-learning",
"scikit-learn",
"classification",
"logistic-regression"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.