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 |
|---|---|---|---|---|---|---|---|---|---|
Can Dask provide a speedup for 1D arrays?
| 39,344,258
|
<p>When working on 2D data, I see a slight speed-up on 2D arrays, but even on large 1D arrays that advantage disappears.</p>
<p>E.g., in 2D:</p>
<pre><code>In [48]: x = np.random.random((3000, 2000))
In [49]: X = da.from_array(x, chunks=(500,500))
In [50]: %timeit (np.cumsum(x - x**2, axis=0))
10 loops, best of 3: 131 ms per loop
In [51]: %timeit (da.cumsum(X - X**2, axis=0)).compute()
10 loops, best of 3: 89.3 ms per loop
</code></pre>
<p>But in 1D:</p>
<pre><code>In [52]: x = np.random.random(10e5)
In [53]: X = da.from_array(x, chunks=(2000,))
In [54]: %timeit (np.cumsum(x - x**2, axis=0))
100 loops, best of 3: 8.28 ms per loop
In [55]: %timeit (da.cumsum(X - X**2, axis=0)).compute()
1 loop, best of 3: 304 ms per loop
</code></pre>
<p>Can Dask provide a speedup for 1D arrays and, if so, what would an ideal chunk size be?</p>
| 1
|
2016-09-06T08:33:27Z
| 39,348,023
|
<p>Your FLOP/Byte ratio is still too low. The CPU isn't the bottleneck, your memory hierarchy is. </p>
<p>Additionally, chunksizes of (2000,) are just too small for Dask.array to be meaningful. Recall that dask introduces an overhead of a few hundred microseconds per task, so each task you do should be significantly longer than this. This explains the 300ms duration you're seeing.</p>
<pre><code>In [11]: 10e5 / 2000 # number of tasks
Out[11]: 500.0
</code></pre>
<p>But even if you do go for larger chunksizes you don't get any speedup on this computation:</p>
<pre><code>In [15]: x = np.random.random(1e8)
In [16]: X = da.from_array(x, chunks=1e6)
In [17]: %timeit np.cumsum(x - x**2, axis=0)
1 loop, best of 3: 632 ms per loop
In [18]: %timeit da.cumsum(X - X**2, axis=0).compute()
1 loop, best of 3: 759 ms per loop
</code></pre>
<p>However if you do something that requires more computation per byte then you enter the regime where parallel processing can actually help. For example arcsinh is actually quite costly to compute:</p>
<pre><code>In [20]: %timeit np.arcsinh(x).sum()
1 loop, best of 3: 3.32 s per loop
In [21]: %timeit da.arcsinh(X).sum().compute()
1 loop, best of 3: 724 ms per loop
</code></pre>
| 3
|
2016-09-06T11:30:56Z
|
[
"python",
"dask"
] |
Cycling through a list of IP addresses
| 39,344,401
|
<p>I have the below code, which will go and look in the .txt file for the IP address and then go to the device and return the commands, it will then print to the file requested and everything works.</p>
<p>What i cant get it to do is loop through a series of IP addresses and return the commands for different devices. I get an error of the script timing out when i add in more than one IP to the .txt list, this is proven by adding the same address twice so i know the addresses are good due to when only a single address is in the file it works seemlessly.</p>
<p>I am seeking a way to loop through 10 IP addresses and run the same commands when all is said and done.</p>
<pre><code>from __future__ import print_function
from netmiko import ConnectHandler
import sys
import time
import select
import paramiko
import re
fd = open(r'C:\Users\NewdayTest.txt','w')
old_stdout = sys.stdout
sys.stdout = fd
platform = 'cisco_ios'
username = 'Username'
password = 'Password'
ip_add_file = open(r'C:\Users\\IPAddressList.txt','r')
for host in ip_add_file:
device = ConnectHandler(device_type=platform, ip=host, username=username, password=password)
output = device.send_command('terminal length 0')
output = device.send_command('enable')
print('##############################################################\n')
print('...................CISCO COMMAND SHOW RUN OUTPUT......................\n')
output = device.send_command('sh run')
print(output)
print('##############################################################\n')
print('...................CISCO COMMAND SHOW IP INT BR OUTPUT......................\n')
output = device.send_command('sh ip int br')
print(output)
print('##############################################################\n')
fd.close()
</code></pre>
<p>For clarity the answer given below is perfect for what i have asked so the start of the code will look like this:</p>
<pre><code>from __future__ import print_function
from netmiko import ConnectHandler
import sys
import time
import select
import paramiko
import re
fd = open(r'C:\Users\NewdayTest.txt','w')
old_stdout = sys.stdout
sys.stdout = fd
platform = 'cisco_ios'
username = 'Username'
password = 'Password'
ip_add_file = open(r'C:\Users\\IPAddressList.txt','r')
for host in ip_add_file:
host = host.strip()
device = ConnectHandler(device_type=platform, ip=host, username=username, password=password)
output = device.send_command('terminal length 0')
</code></pre>
<p>And so on for what ever commands need to be run.</p>
| -1
|
2016-09-06T08:40:21Z
| 39,344,709
|
<p>My guess is that your <code>ConnectHandler</code> does not appreciate that there is a newline character at the end of your <code>host</code> string.</p>
<p>Try this:</p>
<pre><code>for host in ip_add_file:
host = host.strip()
...
</code></pre>
| 1
|
2016-09-06T08:54:42Z
|
[
"python",
"python-3.x",
"cisco"
] |
for loop stuck and not interating (Python 3)
| 39,344,596
|
<p>I'm currently working on a small script that aims to find taxicab numbers. There is only one small problem, the for loop doesn't increment the variable x and is stuck looping forever. I'll paste the relevant part of the code below:</p>
<pre><code>n = int(10)
counter = int(0)
m = int(m)
x = int(1)
y = int(n**(1/3))
cheatsheet = []
while counter in range(0,m):
for x in range(1,y):
if x**3 + y**3 < n:
print('less than')
print(x,y,n)
continue
elif x**3 + y**3 > n:
print('greater than')
y -= 1
continue
elif x > y:
if n in cheatsheet:
print('counting')
counter = counter+1
#checking if n occurs in the list, if so it will add 1 to the counter so that the program will know when to stop
n = n + 1
y = int(n**(1/3))
x = 1
print('break1')
#resetting values and bumping n so that it will continue the quest to find 'em all
break
else:
if x and y == 1:
#this is an error correction for low n values, i mean really low it might be redundant by now
n = n + 1
y = int(n**(1/3))
x = 1
print('break2')
break
cheatsheet.append((n,x,y))
print(cheatsheet)
</code></pre>
<p>This yields the following result in a terminal window:
<a href="http://i.imgur.com/Luq8vL8.png" rel="nofollow">image</a></p>
<p>Note that I killed the process by myself, the program did not.
As you can tell, the script just loops around and prints 'less than' and the values for x,y,n.</p>
<p>Help is greatly appreciated!</p>
<p>EDIT: the variable m is given by the user, but not included in this bit of code.</p>
| 0
|
2016-09-06T08:49:19Z
| 39,345,745
|
<p>This has a number of issues wrong with it I'm not willing to post functional code but I will point some of the issues out. </p>
<p>For starters:</p>
<pre><code>n = int(10)
</code></pre>
<p>isn't required, not an error but redundant. Use <code>n = 10</code> with the same effect. </p>
<p>Then:</p>
<pre><code>while counter in range(0,m):
</code></pre>
<p>will always evaluate to <code>True</code>. <code>m</code> is *never modified so the membership test always succeeds, maybe you need to re-evaluate your looping.</p>
<pre><code>for x in range(1,y):
</code></pre>
<p>This will assign <code>x</code> the value <code>1</code> all the time. <code>y</code> evaluates to <code>2</code> by your arithmetic (int rounds floats to the floor, i.e <code>int(2.9) -> 2</code>) so either use <code>math.ceil</code> or add one to your <code>y</code>.</p>
<p>Appart from that you re-assign variable names all the time inside your loops, that's confusing and might lead to unexpected behavior.</p>
| 2
|
2016-09-06T09:43:04Z
|
[
"python",
"python-3.x",
"for-loop",
"increment"
] |
Django Rest Framework API by accept multiple input and output multiple data
| 39,344,630
|
<p>I am two months with Django and API Rest Framework.
I am developing an API to accept (userid and week_number), and output with (week_number and status).</p>
<p>This is my model:</p>
<pre><code>class Timesheet(models.Model):
userid = models.ForeignKey(User)
week_number = models.CharField(max_length=2)
status = models.CharField(max_length=255)
</code></pre>
<p>This is my complete data example:</p>
<pre><code> [
{
"id": 1,
"userid": 1,
"week_number": "32",
"status": "completed"
},
{
"id": 2,
"userid": 1,
"week_number": "33",
"status": "approved"
},
{
"id": 3,
"userid": 1,
"week_number": "34",
"status": "incomplete"
}
]
</code></pre>
<p>API I want is like this:</p>
<pre><code>ACCEPT: userid=1
ACCEPT: week_number=33
ACCEPT: week_number=34
OUTPUT: week_number=33,status="approved"
OUTPUT: week_number=34,status="incomplete"
</code></pre>
<p>Note: I do not want data about <code>week_number=32</code></p>
<p>I not sure how to code for this kind of API. Hope someone can help.</p>
| 0
|
2016-09-06T08:50:40Z
| 39,346,533
|
<p>This would be the general route to getting what you want. </p>
<p>in models.py</p>
<pre><code>class Timesheet(models.Model):
userid = models.ForeignKey(User)
week_number = models.CharField(max_length=2)
status = models.CharField(max_length=255)
</code></pre>
<p>in serializer.py:</p>
<pre><code>class TimesheetSerializer(serializers.ModelSerializer):
class Meta:
model = Timesheet
// specify the fields that you want API to return below
fields = ('week_number', 'status')
</code></pre>
<p>in views.py:</p>
<pre><code>from rest_framework import generics
class TimesheetListView(generics.ListAPIView):
serializer_class = TimesheetSerializer
def get_queryset(self):
//get user and week_number from GET request
user = self.request.GET['user']
week_number = self.request.GET['week']
//filter and return the first result where user=user and week=week
return Timesheet.objects.filter(user=user, week_number=week_number)
</code></pre>
<p>in urls.py:</p>
<pre><code>url(r'^api/timesheet$', views.TimesheetListView.as_view(), name='timesheet'),
</code></pre>
<p>you can then access this endpoint with e.g.: </p>
<p><a href="http://127.0.0.1:8000/api/timesheet?user=123&week=33&format=api" rel="nofollow">http://127.0.0.1:8000/api/timesheet?user=123&week=33&format=api</a></p>
<p>It's good practice to disable Browsable API in production. it can be done by the following code in settings.py(this way you won't have to use &format=api in your call above):</p>
<pre><code>REST_FRAMEWORK = {
other settings ...
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
other settings ...
}
</code></pre>
<p>and in development mode you can do in settings.py:</p>
<pre><code> 'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
)
</code></pre>
<p>I didn't get the time to test this but this is the general guidelines of achieving what you want. Do add the required exception-handling to this as well.
you should go through the Django DRF tutorial though if you haven't already: <a href="http://www.django-rest-framework.org/tutorial/quickstart/" rel="nofollow">http://www.django-rest-framework.org/tutorial/quickstart/</a></p>
| 0
|
2016-09-06T10:18:37Z
|
[
"python",
"django",
"django-rest-framework"
] |
Python IndexError: string index out of range
| 39,344,633
|
<p>Can someone help me why is it saying: "IndexError: string index out of range"
When I add the "letterCount += 1" to the first else it makes this error, without it is working.</p>
<p>The goal is to count "bob"s in s.</p>
<p>Thanks!</p>
<pre><code>s = 'oobobodobooobobobobabobbobbobobbobbobhbxbobbk'
vowelCount = 0
letterCount = 0
pointer = s
for pointer in s:
print(pointer)
if pointer == 'b':
print (str(letterCount) + '. betű B' )
if (s[letterCount+1] + s[letterCount+2]) == str('ob') :
vowelCount += 1
letterCount += 1
print( str(vowelCount) + '. BOB megtalálva')
else:
print('Nem OB jön utána')
letterCount += 1
else:
print(str(letterCount) + '. betű nem B')
letterCount += 1
print ("Number of times bob occurs is: " + str(vowelCount))
</code></pre>
| 0
|
2016-09-06T08:51:06Z
| 39,344,759
|
<p>You need to check the string s length with something like:</p>
<pre><code>letterCount+2 <= len(s)
</code></pre>
<p>i.e.</p>
<pre><code>s = 'oobobodobooobobobobabobbobbobobbobbobhbxbobbk'
vowelCount = 0
letterCount = 0
pointer = s
for pointer in s:
print(pointer)
if pointer == 'b':
print (str(letterCount) + '. betű B' )
if (letterCount+2 <= len(s) and (s[letterCount+1] + s[letterCount+2]) == str('ob')) :
vowelCount += 1
letterCount += 1
print( str(vowelCount) + '. BOB megtalálva')
else:
print('Nem OB jön utána')
letterCount += 1
else:
print(str(letterCount) + '. betű nem B')
letterCount += 1
print ("Number of times bob occurs is: " + str(vowelCount))
</code></pre>
| 0
|
2016-09-06T08:56:43Z
|
[
"python"
] |
Python IndexError: string index out of range
| 39,344,633
|
<p>Can someone help me why is it saying: "IndexError: string index out of range"
When I add the "letterCount += 1" to the first else it makes this error, without it is working.</p>
<p>The goal is to count "bob"s in s.</p>
<p>Thanks!</p>
<pre><code>s = 'oobobodobooobobobobabobbobbobobbobbobhbxbobbk'
vowelCount = 0
letterCount = 0
pointer = s
for pointer in s:
print(pointer)
if pointer == 'b':
print (str(letterCount) + '. betű B' )
if (s[letterCount+1] + s[letterCount+2]) == str('ob') :
vowelCount += 1
letterCount += 1
print( str(vowelCount) + '. BOB megtalálva')
else:
print('Nem OB jön utána')
letterCount += 1
else:
print(str(letterCount) + '. betű nem B')
letterCount += 1
print ("Number of times bob occurs is: " + str(vowelCount))
</code></pre>
| 0
|
2016-09-06T08:51:06Z
| 39,345,747
|
<p>I hope the following code will work for you.</p>
<pre><code>s = 'oobobodobooobobobobabobbobbobobbobbobhbxbobbk'
vowelCount = 0
letterCount = 0
pointer = s
print len(s)
for pointer in s:
if pointer == 'b':
if (len(s) != letterCount+1 and len(s) != letterCount+2):
if (s[letterCount+1] + s[letterCount+2]) == str('ob'):
vowelCount += 1
letterCount += 1
print(str(vowelCount) + '. BOB')
else:
letterCount += 1
else:
letterCount += 1
print ("Number of times bob occurs is: " + str(vowelCount))
</code></pre>
<p>In this statement, i'm checking with letter count with the len of the string. it will match at the end of the string only.</p>
<p>or you can use the enumerator to check the len of the word in a string</p>
<p><pre>
for i, _ in enumerate(s): #i here is the index, equal to "i in
range(len(s))"</p>
<code>if s[i:i+3] == 'bob': #Check the current char + the next three chars.
bob += 1
print('Number of times bob occurs is: ' + str(bob))
</code></pre>
| 0
|
2016-09-06T09:43:06Z
|
[
"python"
] |
Python IndexError: string index out of range
| 39,344,633
|
<p>Can someone help me why is it saying: "IndexError: string index out of range"
When I add the "letterCount += 1" to the first else it makes this error, without it is working.</p>
<p>The goal is to count "bob"s in s.</p>
<p>Thanks!</p>
<pre><code>s = 'oobobodobooobobobobabobbobbobobbobbobhbxbobbk'
vowelCount = 0
letterCount = 0
pointer = s
for pointer in s:
print(pointer)
if pointer == 'b':
print (str(letterCount) + '. betű B' )
if (s[letterCount+1] + s[letterCount+2]) == str('ob') :
vowelCount += 1
letterCount += 1
print( str(vowelCount) + '. BOB megtalálva')
else:
print('Nem OB jön utána')
letterCount += 1
else:
print(str(letterCount) + '. betű nem B')
letterCount += 1
print ("Number of times bob occurs is: " + str(vowelCount))
</code></pre>
| 0
|
2016-09-06T08:51:06Z
| 39,347,253
|
<pre><code>The final solution.
s = 'obbobbbocbobbogboobm'
vowelCount = 0
letterCount = 0
pointer = s
for pointer in s:
print(pointer)
if pointer == 'b':
print (str(letterCount) + '. betű B' )
if (len(s)-2 > letterCount):
print('van utána két betű')
if (s[letterCount+1] + s[letterCount+2]) == str('ob') :
vowelCount += 1
letterCount += 1
print( str(vowelCount) + '. BOB megtalálva')
else:
print('Nem OB jön utána')
letterCount += 1
else:
print('nincs utána két betű')
break
else:
print(str(letterCount) + '. betű nem B')
letterCount += 1
print ("Number of times bob occurs is: " + str(vowelCount))
</code></pre>
| 0
|
2016-09-06T10:53:02Z
|
[
"python"
] |
Open URLs on chrome
| 39,344,725
|
<p>I have a .csv file that contains a column of urls (40-50 urls), I want to read the csv file and open all those urls on chrome? Is there a way to accomplish this in python? I'm using the following piece of code to read the csv file.</p>
<pre><code>exampleFile = open('MyFile.csv')
exampleReader = csv.reader(exampleFile)
exampleData = list(exampleReader)
final = []
for item in exampleData:
final.append(item[0])
for item in final:
???
</code></pre>
| 0
|
2016-09-06T08:55:23Z
| 39,344,819
|
<p>You can use selenium with Chrome web driver
<a href="https://sites.google.com/a/chromium.org/chromedriver/getting-started" rel="nofollow">https://sites.google.com/a/chromium.org/chromedriver/getting-started</a></p>
| 0
|
2016-09-06T08:59:36Z
|
[
"python"
] |
Open URLs on chrome
| 39,344,725
|
<p>I have a .csv file that contains a column of urls (40-50 urls), I want to read the csv file and open all those urls on chrome? Is there a way to accomplish this in python? I'm using the following piece of code to read the csv file.</p>
<pre><code>exampleFile = open('MyFile.csv')
exampleReader = csv.reader(exampleFile)
exampleData = list(exampleReader)
final = []
for item in exampleData:
final.append(item[0])
for item in final:
???
</code></pre>
| 0
|
2016-09-06T08:55:23Z
| 39,344,821
|
<p>You can use selenium. First install selenium by <code>pip install selenium</code>. The following code open <a href="http://www.python.org" rel="nofollow">http://www.python.org</a> in mozilla firefox.You can change driver to chrome driver in selenium to open links in chrome. For chrome you can see <a href="http://stackoverflow.com/questions/13724778/how-to-run-selenium-webdriver-test-cases-in-chrome">How to run Selenium WebDriver test cases in Chrome?</a></p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://www.python.org")
</code></pre>
| 0
|
2016-09-06T08:59:45Z
|
[
"python"
] |
Open URLs on chrome
| 39,344,725
|
<p>I have a .csv file that contains a column of urls (40-50 urls), I want to read the csv file and open all those urls on chrome? Is there a way to accomplish this in python? I'm using the following piece of code to read the csv file.</p>
<pre><code>exampleFile = open('MyFile.csv')
exampleReader = csv.reader(exampleFile)
exampleData = list(exampleReader)
final = []
for item in exampleData:
final.append(item[0])
for item in final:
???
</code></pre>
| 0
|
2016-09-06T08:55:23Z
| 39,345,030
|
<p>You can use <a href="http://www.seleniumhq.org/" rel="nofollow"><code>selenium</code></a> web driver to load each URL in chrome.</p>
<p>Reading the csv file can be improved like this:</p>
<pre><code>from selenium import webdriver
driver = webdriver.Chrome()
with open('MyFile.csv') as example_file:
example_reader = csv.reader(example_file)
for row in example_reader:
driver.get(row[0])
# do whatever...
driver.close()
</code></pre>
| 1
|
2016-09-06T09:10:44Z
|
[
"python"
] |
Open URLs on chrome
| 39,344,725
|
<p>I have a .csv file that contains a column of urls (40-50 urls), I want to read the csv file and open all those urls on chrome? Is there a way to accomplish this in python? I'm using the following piece of code to read the csv file.</p>
<pre><code>exampleFile = open('MyFile.csv')
exampleReader = csv.reader(exampleFile)
exampleData = list(exampleReader)
final = []
for item in exampleData:
final.append(item[0])
for item in final:
???
</code></pre>
| 0
|
2016-09-06T08:55:23Z
| 39,345,081
|
<p>Assuming your posted snippet is alright and <code>final</code> contains valid urls you could do something like this:</p>
<pre><code>import webbrowser
exampleFile = open('MyFile.csv')
exampleReader = csv.reader(exampleFile)
exampleData = list(exampleReader)
final = []
for item in exampleData:
final.append(item[0])
for url in final:
webbrowser.open_new_tab(url)
</code></pre>
<p>For more information take a look to the <a href="https://docs.python.org/3/library/webbrowser.html" rel="nofollow">Convenient Web-browser controller</a></p>
| 1
|
2016-09-06T09:12:48Z
|
[
"python"
] |
Open URLs on chrome
| 39,344,725
|
<p>I have a .csv file that contains a column of urls (40-50 urls), I want to read the csv file and open all those urls on chrome? Is there a way to accomplish this in python? I'm using the following piece of code to read the csv file.</p>
<pre><code>exampleFile = open('MyFile.csv')
exampleReader = csv.reader(exampleFile)
exampleData = list(exampleReader)
final = []
for item in exampleData:
final.append(item[0])
for item in final:
???
</code></pre>
| 0
|
2016-09-06T08:55:23Z
| 39,346,276
|
<p>Used this in the end to make it work the way I wanted to. Plus I did not have to install any external modules! Thanks a lot for all your answers, they helped me build the final one!</p>
<pre><code>import webbrowser
import csv
path = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s"
exampleFile = open('MyFile.csv')
exampleReader = csv.reader(exampleFile)
exampleData = list(exampleReader)
for item in exampleData:
webbrowser.get(path).open(item[0])
</code></pre>
| 1
|
2016-09-06T10:06:37Z
|
[
"python"
] |
Python Tkinter 2 classes
| 39,344,919
|
<p>I have 2 classes, i create the instance of each class like this </p>
<pre><code>if __name__ == '__main__':
root = Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.focus_set() # <-- move focus to this widget
root.geometry("%dx%d+0+0" % (w, h))
root.title("Circus ticketing system")
UI_Class = GUI(root)
Program_Class = Program()
root.mainloop()
</code></pre>
<p>i set variables in GUI like this:</p>
<pre><code>self.tenAmShowBtn = Button(self.fMain,text='10am Show',command=Program_Class.tenAmShow)
self.tenAmShowBtn.grid(column=0,row=2)
</code></pre>
<p>and to access variables in (ex)GUI from Program i do like this: </p>
<pre><code>UI_Class.tenAmShowBtn.config(bg='#00f0ff')
</code></pre>
<p>but i keep getting errors like <code>NameError: name 'UI_Class' is not defined</code>
and <code>NameError: name 'Program_Class' is not defined</code>
and <code>AttributeError: 'GUI' object has no attribute 'tenAmShowBtn'</code>i don't understand how the hell do i do this, the Program class continuosly has to access the GUI and edit variables and widgets, but i can't access variables, keep getting error after error, it woks great when i put everything in 1 class, i just CAN'T get this to work with 2 separete classes.</p>
<p>I put the whole code because i cannot explain in just bits of code, i aplogise.</p>
<pre><code>try:
# for Python2
from Tkinter import *
except ImportError:
# for Python3
from tkinter import *
from random import randint
#from user import Program
class GUI:
def __init__(self, parent):
self.seats_being_bought1 = IntVar()#Light-Blue buttons number for textvariable
self.seats_being_bought1.set(0)
self.seats_being_bought2 = IntVar()#Light-Blue buttons number for textvariable
self.seats_being_bought2.set(0)
self.seats_being_bought3 = IntVar()#Light-Blue buttons number for textvariable
self.seats_being_bought3.set(0)
self.available_seats1 = IntVar() #Non-red buttons
self.available_seats1.set("0")
self.available_seats2 = IntVar() #Non-red buttons
self.available_seats2.set(0)
self.available_seats3 = IntVar() #Non-red buttons
self.available_seats3.set(0)
self.pricePerTicket1 = IntVar()
self.pricePerTicket1.set(5)
self.pricePerTicket2 = IntVar()#<> Ticket/Seat Price Variables
self.pricePerTicket2.set(5)
self.pricePerTicket3 = IntVar()
self.pricePerTicket3.set(12)
self.totalPrice1 = IntVar()
self.totalPrice1.set(0)
self.totalPrice2 = IntVar()#total price variables
self.totalPrice2.set(0)
self.totalPrice3 = IntVar()
self.totalPrice3.set(0)
self.totalTicketsSold = IntVar()#Total seats sold
self.totalTicketsSold.set(0)
self.totalIncome = IntVar()#Total income
self.totalIncome.set(0)
self.white = '#ffffff' #save time
self.currentShow = StringVar()#currrent show
self.instructions_text = 'Select the show you desire, then click one of the seats to the right and click the buy button'
self.button_list1={} #all seats(Buttons)as matrix/object
self.button_list2={}
self.button_list3={}
self.total_seats1 = StringVar()
self.total_seats2 = StringVar()
self.total_seats3 = StringVar()
self.total_seats1.set('/250')
self.total_seats2.set('/150')
self.total_seats3.set('/150')
self.selected_button_list1=[] #Light-Blue buttons
self.selected_button_list2=[] #Light-Blue buttons
self.selected_button_list3=[] #Light-Blue buttons
self.previousTransactionButtonList1 = []#List of Seats in the last transaction
self.previousTransactionButtonList2 = []
self.previousTransactionButtonList3 = []
self.automatic_seat_selection_no = IntVar()#automatic seat selection number
self.automatic_seat_selection_no.set(0)
self.f1 = Frame(parent) #Frame for Seats/Buttons
self.seatTitle = Label(self.f1,bg=self.white,textvariable=self.currentShow).grid(row=0,column=0,columnspan=11,sticky=E+W)
self.f1.grid(column=2,row=0)
self.f2 = Frame(parent) #Frame for Seats/Buttons
self.seatTitle = Label(self.f2,bg=self.white,textvariable=self.currentShow).grid(row=0,column=0,columnspan=11,sticky=E+W)
self.f2.grid(column=2,row=0)
self.f3 = Frame(parent) #Frame for Seats/Buttons
self.seatTitle = Label(self.f3,bg=self.white,textvariable=self.currentShow).grid(row=0,column=0,columnspan=11,sticky=E+W)
self.f3.grid(column=2,row=0)
self.f2.grid_remove() #Hide other 2 frames
self.f3.grid_remove() #Hide other 2 frames
#self.create_UI(parent)
#START WITH 10AM SHOW
#self.currentShow.set('10Am Show')
#self.tenAmShowBtn.config(bg='#00f0ff')
Program.tenAmShow(Program)
Program.displaySeats(10)#10 refers to 10am show
#CREATING OTHER SEATS BUT THEIR FRAMES ARE HIDDEN
Program.displaySeats(3)
Program.displaySeats(8)
def create_UI(self,parent):
self.fMain = Frame(parent)#Frame for rest of program
fLegend = Frame(self.fMain)#Frame for Legend
legendLabel = Label(fLegend,text='Legend').grid(column=0,row=0,columnspan=3,sticky=E+W)
legendRed = Label(fLegend,text='seat123',fg='#ff0000',bg='#ff0000').grid(column=0,row=1,sticky=E+W)
legendRed1 = Label(fLegend,text=' =').grid(column=1,row=1)
legendRed2 = Label(fLegend,text='Taken Seat').grid(column=2,row=1)
legendLightRed = Label(fLegend,text='seat123',fg='#f99999',bg='#f99999').grid(column=0,row=2,sticky=E+W)
legendLightRed1 = Label(fLegend,text=' =').grid(column=1,row=2)
legendLightRed2 = Label(fLegend,text='Bought Seat').grid(column=2,row=2)
legendLightBlue = Label(fLegend,text='seat123',fg='#00f0ff',bg='#00f0ff').grid(column=0,row=3,sticky=E+W)
legendLightBlue1 = Label(fLegend,text=' =').grid(column=1,row=3)
legendLightBlue2 = Label(fLegend,text='Selected Seat').grid(column=2,row=3)
fLegend.grid(column=0,row=0,columnspan=3)
#end Legend frame
self.instructions = Label(self.fMain, text=self.instructions_text).grid(column=0,row=1,columnspan=3)
#Show Selection gui
self.tenAmShowBtn = Button(self.fMain,text='10am Show',command=Program_Class.tenAmShow)
self.tenAmShowBtn.grid(column=0,row=2)
self.threePmShowBtn = Button(self.fMain,text='3pm Show',command=Program_Class.threePmShow)
self.threePmShowBtn.grid(column=1,row=2)
self.eightPmShowBtn = Button(self.fMain,text='8Pm Show',command=Program_Class.eightPmShow)
self.eightPmShowBtn.grid(column=2,row=2)
#Purchase details and commands gui
self.seat_amountLabel = Label(self.fMain, text='Amount of seats Available').grid(column=0, row=3)
self.seat_amountEntry = Label(self.fMain, textvariable=self.available_seats1,bg="#444444",fg='#ffffff',anchor=E)
self.seat_amountEntry.grid(column=1,row=3,sticky=E+W)
self.seat_amountTotal = Label(self.fMain,textvariable=self.total_seats1 ,bg='#444444',fg='#ffffff',anchor=W)
self.seat_amountTotal.grid(column=2,row=3,sticky=E+W)
self.seatsBeingBoughtLabel = Label(self.fMain,text='Amount of seats being purchased').grid(column=0,row=4)
self.seatsBeingBoughtVal = Label(self.fMain, textvariable=self.seats_being_bought1,bg="#444444",fg='#ffffff')
self.seatsBeingBoughtVal.grid(column=1,row=4,columnspan=2,sticky=E+W)
#price per ticket
self.pricePerTicketLabel = Label(self.fMain,text='Cost per Ticket/Seat in $').grid(column=0,row=5)
self.pricePerTicketVal = Label(self.fMain,textvariable=self.pricePerTicket1,bg='#ffffff',fg='#444444')
self.pricePerTicketVal.grid(column=1,row=5,columnspan=2,sticky=E+W)
#total price
self.totalPriceLabel = Label(self.fMain,text='Total Price in $').grid(column=0,row=6)
self.totalPriceVal = Label(self.fMain,textvariable=self.totalPrice1,bg='#ffffff',fg='#444444')
self.totalPriceVal.grid(column=1,row=6,columnspan=2,sticky=E+W)
#Automatically select seats
self.auto_seat_selection_label = Label(self.fMain,text='Amount of seats to buy:').grid(column=0,row=7)
self.auto_seat_selection_entry = Entry(self.fMain, textvariable=self.automatic_seat_selection_no).grid(column=1,row=7,columnspan=2,sticky=E+W)
#cancel and purchase button
self.resetBtn = Button(self.fMain,text="Cancel/Reset",bg='#ff0000',command=Program_Class.CancelTransaction).grid(column=0,row=8,columnspan=1,sticky=E+W)
self.buyTicketsBtn = Button(self.fMain,text="Buy ticket",bg='#00f0ff',command=Program_Class.click_function).grid(column=1,row=8,columnspan=2,sticky=E+W)
#totals
self.totalTicketsSoldLabel = Label(self.fMain,text='Total tickets sold:').grid(column=0,row=9)
self.totalTicketsSoldVal = Label(self.fMain,textvariable=self.totalTicketsSold).grid(column=1,row=9,columnspan=2)
self.totalIncomeLabel = Label(self.fMain,text='Total Income for the Day in $:').grid(column=0,row=10)
self.totalIncomeVal = Label(self.fMain,textvariable=self.totalIncome).grid(column=1,row=10,columnspan=2)
self.fMain.grid(column=1,row=0,sticky=N)
class Program:
def __init__(self):
print('test')
def click_function(self): #Buy Button click
show = self.currentShow.get()
action = 0
inputed_seat = self.automatic_seat_selection_no.get()
#for automatic seat selection
if(inputed_seat != 0):
if(show == '10Am Show'):
button_list = self.button_list1
available_seats = self.available_seats1.get()
elif(show == '3Pm Show'):
button_list = self.button_list2
available_seats = self.available_seats2.get()
else:
button_list = self.button_list3
available_seats = self.available_seats3.get()
counter_var = 1
seat = 1
while counter_var <= inputed_seat:#i use while loop instead of for loop so i can continue/extend the loop if i find a taken/red seat
if(inputed_seat > available_seats):
print('Not enough seats available')
break
else:
if seat in button_list:
if(button_list[seat]['bg'] != '#f99999' and button_list[seat]['bg'] != '#00f0ff'):
self.SeatClick(seat)
else:
counter_var -= 1
else:#seat is taken/red
if(available_seats == 0):
print('Not enough seats available')
break
else:
counter_var -= 1
counter_var += 1
seat += 1
self.automatic_seat_selection_no.set(0)
self.click_function()
else:#for manual seat selection
if(show == '10Am Show'):
action = len(self.selected_button_list1)
elif(show == '3Pm Show'):
action = len(self.selected_button_list2)
else:
action = len(self.selected_button_list3)
if(action != 0):
if(show == '10Am Show'):
del self.previousTransactionButtonList1[:]#Clear last transaction
for i in range(len(self.selected_button_list1)):
self.button_list1[self.selected_button_list1[i]].config(bg='#f99999')
self.available_seats1.set(self.available_seats1.get() - 1)
#save to previous transactions
self.previousTransactionButtonList1.append(self.button_list1[self.selected_button_list1[i]])
self.selected_button_list1 = []
self.seats_being_bought1.set(0)
self.totalPrice1.set(0)
elif(show == '3Pm Show'):
del self.previousTransactionButtonList2[:]#Clear last transaction
for i in range(len(self.selected_button_list2)):
self.button_list2[self.selected_button_list2[i]].config(bg='#f99999')
self.available_seats2.set(self.available_seats2.get() - 1)
#save to previous transactions
self.previousTransactionButtonList2.append(self.button_list2[self.selected_button_list2[i]])
self.selected_button_list2 = []
self.seats_being_bought2.set(0)
self.totalPrice2.set(0)
else:
del self.previousTransactionButtonList3[:]#Clear last transaction
for i in range(len(self.selected_button_list3)):
self.button_list3[self.selected_button_list3[i]].config(bg='#f99999')
self.available_seats3.set(self.available_seats3.get() - 1)
#save to previous transactions
self.previousTransactionButtonList3.append(self.button_list3[self.selected_button_list3[i]])
self.selected_button_list3 = []
self.seats_being_bought3.set(0)
self.totalPrice3.set(0)
#get total seats sold INITIAL ONLY, SPECIFIC FUNCTION AT END OF PROGRAM
self.resetVal()
else:
print('No Seats Selected!')
def CancelTransaction(self):
show = self.currentShow.get()
if(show == '10Am Show' and len(self.previousTransactionButtonList1) >= 1):
for x in range(len(self.previousTransactionButtonList1)):
self.previousTransactionButtonList1[x].config(bg='SystemButtonFace')#make button return to available color
self.available_seats1.set(self.available_seats1.get() + 1)#Adjust available seat counter
self.totalTicketsSold.set(self.totalTicketsSold.get() - 1)
self.resetVal()
del self.previousTransactionButtonList1[:]#delete/clear previous transaction
elif(show == '3Pm Show' and len(self.previousTransactionButtonList2) >= 1):
for x in range(len(self.previousTransactionButtonList2)):
self.previousTransactionButtonList2[x].config(bg='SystemButtonFace')
self.available_seats2.set(self.available_seats2.get() + 1)#Adjust available seat counter
self.totalTicketsSold.set(self.totalTicketsSold.get() - 1)
self.resetVal()
del self.previousTransactionButtonList2[:]#delete/clear previous transaction
elif(show == '8Pm Show' and len(self.previousTransactionButtonList3) >= 1):
for x in range(len(self.previousTransactionButtonList3)):
self.previousTransactionButtonList3[x].config(bg='SystemButtonFace')
self.available_seats3.set(self.available_seats3.get() + 1)#Adjust available seat counter
self.totalTicketsSold.set(self.totalTicketsSold.get() - 1)
self.resetVal()
del self.previousTransactionButtonList3[:]#delete/clear previous transaction
else:
print('no previous transaction found')
def seatCounter(self,taken,show): #to count available seats
if(show == 1):
self.available_seats1.set(self.available_seats1.get() - taken)
elif(show == 2):
self.available_seats2.set(self.available_seats2.get() - taken)
else:
self.available_seats3.set(self.available_seats3.get() - taken)
#just to initially update the variables
def resetVal(self):
ticketSold1 = 250 - self.available_seats1.get()
ticketSold2 = 150 - self.available_seats2.get()
ticketSold3 = 150 - self.available_seats3.get()
self.totalTicketsSold.set(ticketSold1 + ticketSold2 + ticketSold3)
self.totalIncome.set((ticketSold1 * 5) + (ticketSold2 * 5) + (ticketSold3 * 12))
#CLICK ON SEAT/BUTTON
def SeatClick(self,seat_no):
show = self.currentShow.get()
action = 0
if(show == '10Am Show'):
action = self.button_list1[seat_no]['bg']
elif(show == '3Pm Show'):
action = self.button_list2[seat_no]['bg']
elif(show == '8Pm Show'):
action = self.button_list3[seat_no]['bg']
else:
return False
if(action == '#f99999'):
print('already bought')
else:
if(show == '10Am Show'):
if(seat_no in self.selected_button_list1):#IF Seat/Button already selected, then remove .after(1000, self.update_clock)
self.button_list1[seat_no].config(bg='SystemButtonFace')
self.selected_button_list1.remove(seat_no)
self.seats_being_bought1.set(str(len(self.selected_button_list1)))
self.totalPrice1.set(self.pricePerTicket1.get() * len(self.selected_button_list1))
else:
self.button_list1[seat_no].config(bg='#00f0ff')#IF Seat/Button not selected then toggle it
self.selected_button_list1.append(seat_no)
self.seats_being_bought1.set(str(len(self.selected_button_list1)))
self.totalPrice1.set(self.pricePerTicket1.get() * len(self.selected_button_list1))
elif(show == '3Pm Show'):
if(seat_no in self.selected_button_list2):
self.button_list2[seat_no].config(bg='SystemButtonFace')#IF Seat/Button already selected, then remove
self.selected_button_list2.remove(seat_no)
self.seats_being_bought2.set(str(len(self.selected_button_list2)))
self.totalPrice2.set(self.pricePerTicket2.get() * len(self.selected_button_list2))
else:
self.button_list2[seat_no].config(bg='#00f0ff')#IF Seat/Button not selected then toggle it
self.selected_button_list2.append(seat_no)
self.seats_being_bought2.set(len(self.selected_button_list2))
self.totalPrice2.set(self.pricePerTicket2.get() * len(self.selected_button_list2))
else:
if(seat_no in self.selected_button_list3):
self.button_list3[seat_no].config(bg='SystemButtonFace')#IF Seat/Button already selected, then remove
self.selected_button_list3.remove(seat_no)
self.seats_being_bought3.set(str(len(self.selected_button_list3)))
self.totalPrice3.set(self.pricePerTicket3.get() * len(self.selected_button_list3))
else:
self.button_list3[seat_no].config(bg='#00f0ff')#IF Seat/Button not selected then toggle it 613553
self.selected_button_list3.append(seat_no)
self.seats_being_bought3.set(len(self.selected_button_list3))
self.totalPrice3.set(self.pricePerTicket3.get() * len(self.selected_button_list3))
# SHOW SELECTION
def tenAmShow(self):
UI_Class.tenAmShowBtn.config(bg='#00f0ff')
self.threePmShowBtn.config(bg=self.white)
self.eightPmShowBtn.config(bg=self.white)
self.currentShow.set('10Am Show')
self.seat_amountEntry.config(textvariable = self.available_seats1)
self.seatsBeingBoughtVal.config(textvariable=self.seats_being_bought1)
self.pricePerTicketVal.config(textvariable=self.pricePerTicket1)
self.totalPriceVal.config(textvariable=self.totalPrice1)
self.seat_amountTotal.config(textvariable=self.total_seats1)
self.f1.grid()
self.f2.grid_remove()
self.f3.grid_remove()
def threePmShow(self):
self.threePmShowBtn.config(bg='#00f0ff')
self.tenAmShowBtn.config(bg=self.white)
self.eightPmShowBtn.config(bg=self.white)
self.currentShow.set('3Pm Show')
self.seat_amountEntry.config(textvariable = self.available_seats2)
self.seatsBeingBoughtVal.config(textvariable=self.seats_being_bought2)
self.pricePerTicketVal.config(textvariable=self.pricePerTicket2)
self.totalPriceVal.config(textvariable=self.totalPrice2)
self.seat_amountTotal.config(textvariable=self.total_seats2)
self.f1.grid_remove()
self.f2.grid()
self.f3.grid_remove()
def eightPmShow(self):
self.eightPmShowBtn.config(bg='#00f0ff')
self.tenAmShowBtn.config(bg=self.white)
self.threePmShowBtn.config(bg=self.white)
self.currentShow.set('8Pm Show')
self.seat_amountEntry.config(textvariable = self.available_seats3)
self.seatsBeingBoughtVal.config(textvariable= self.seats_being_bought3)
self.pricePerTicketVal.config(textvariable=self.pricePerTicket3)
self.totalPriceVal.config(textvariable=self.totalPrice3)
self.seat_amountTotal.config(textvariable=self.total_seats3)
self.f1.grid_remove()
self.f2.grid_remove()
self.f3.grid()
#BUTTON/SEAT CREATION AND DISPLAY
def createSeats(self,num_of_seats,frame_pointer):
col = num_of_seats / 10
if(frame_pointer == 1):
seat_counter1 = 1
for x in range(int(col)):
X = x + 10
for y in range(1, 11):
taken_seats = randint(1,3)
if(taken_seats == 3):
b1 = Button(
self.f1, text='Seat%d' % seat_counter1,
name='seat%d' % seat_counter1, bg='#ff0000'
)
b1.grid(row=X, column=y)
seat_counter1 += 1
self.seatCounter(1, 1)
else:
b1 = Button(
self.f1, text='Seat%d' % seat_counter1,
name='seat%d' % seat_counter1,command= lambda j = seat_counter1: self.SeatClick(j)
)
b1.grid(row=X, column=y)
self.button_list1[seat_counter1] = b1
seat_counter1 += 1
elif(frame_pointer == 2):
seat_counter2 = 1
for x in range(int(col)):
X = x + 10
for y in range(1, 11):
taken_seats = randint(1,3)
if(taken_seats == 3):
b2 = Button(
self.f2, text='Seat%d' % seat_counter2,
name='seat%d' % seat_counter2, bg='#ff0000'
)
b2.grid(row=X, column=y)
seat_counter2 += 1
self.seatCounter(1, 2)
else:
b2 = Button(
self.f2, text='Seat%d' % seat_counter2,
name='seat%d' % seat_counter2,command= lambda j = seat_counter2: self.SeatClick(j)
)
b2.grid(row=X, column=y)
self.button_list2[seat_counter2] = b2
seat_counter2 += 1
else:
seat_counter3 = 1
for x in range(int(col)):
X = x + 10
for y in range(1, 11):
taken_seats = randint(1,3)
if(taken_seats == 3):
b3 = Button(
self.f3, text='Seat%d' % seat_counter3,
name='seat%d' % seat_counter3, bg='#ff0000'
)
b3.grid(row=X, column=y)
seat_counter3 += 1
self.seatCounter(1, 3)
else:
b3 = Button(
self.f3, text='Seat%d' % seat_counter3,
name='seat%d' % seat_counter3,command= lambda j = seat_counter3: self.SeatClick(j)
)
b3.grid(row=X, column=y)
self.button_list3[seat_counter3] = b3
seat_counter3 += 1
def displaySeats(self,show):
if(show == 10):
self.available_seats1.set(250)
self.createSeats(250, 1)
elif(show == 3):
self.available_seats2.set(150)
self.createSeats(150, 2)
else:
self.available_seats3.set(150)
self.createSeats(150, 3)
self.resetVal()
if __name__ == '__main__':
root = Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
#root.overrideredirect(1) #removes menubar
root.focus_set() # <-- move focus to this widget
root.geometry("%dx%d+0+0" % (w, h))
root.title("Circus ticketing system")
UI_Class = GUI(root)
Program_Class = Program()
root.mainloop()
</code></pre>
| 0
|
2016-09-06T09:05:02Z
| 39,345,133
|
<p>the <code>Program_Class</code> object is instantiated after the <code>UI_Class</code> object and the latter doesn't reference the prior. Try passing <code>Program_Class</code> to the <code>GUI</code> constructor:</p>
<pre><code>Program_Class = Program()
UI_Class = GUI(root, Program_Class)
</code></pre>
<p>where:</p>
<pre><code>class GUI:
def __init__(self, parent, program):
self.program = program
</code></pre>
<p>then you should be able to reference <code>self.program</code>.</p>
| 1
|
2016-09-06T09:15:05Z
|
[
"python",
"tkinter"
] |
What are valid gstreamer song names?
| 39,344,951
|
<p>I'm trying to understand what song names can I use in my gstreamer python based audioplayer. Can't find any docs about it. For example song with name <code>test%.mp3</code> produce the error:</p>
<pre><code>Error: [<GError at 0x7f8a8c001620>, 'gstgiosrc.c(324): gst_gio_src_get_stream (): /GstPlayBin:playbin0/GstGioSrc:source:\nCould not open location file:///home/austinnikov/work/daemon_player/program_root/test%.mp3 for reading: Operation not supported'],
</code></pre>
<p>Songs without <code>%</code> are played. And of cause I have <code>test%.mp3</code> on the hard drive in that directory. </p>
| 0
|
2016-09-06T09:06:39Z
| 39,346,264
|
<p>See the following SO answer:<a href="http://stackoverflow.com/questions/26092616/solvedgstreamer-uri-format-on-windows">[Solved]gstreamer uri format on windows</a><br>
specifically the <code>'file:' + urllib.pathname2url(filepath)</code> part.<br>
While this does not answer your more general question, it does permit you to play files which include certain characters like <code>%</code> </p>
| 1
|
2016-09-06T10:06:03Z
|
[
"python",
"gstreamer"
] |
What are valid gstreamer song names?
| 39,344,951
|
<p>I'm trying to understand what song names can I use in my gstreamer python based audioplayer. Can't find any docs about it. For example song with name <code>test%.mp3</code> produce the error:</p>
<pre><code>Error: [<GError at 0x7f8a8c001620>, 'gstgiosrc.c(324): gst_gio_src_get_stream (): /GstPlayBin:playbin0/GstGioSrc:source:\nCould not open location file:///home/austinnikov/work/daemon_player/program_root/test%.mp3 for reading: Operation not supported'],
</code></pre>
<p>Songs without <code>%</code> are played. And of cause I have <code>test%.mp3</code> on the hard drive in that directory. </p>
| 0
|
2016-09-06T09:06:39Z
| 39,347,832
|
<p>Rolf's answer is great, but I wanted to add that if your songs_names are in unicode as mine then <code>pathname2url</code> will fail with <code>KeyError</code>. So I did it in slightly another way, note also <a href="http://stackoverflow.com/questions/11687478/convert-a-filename-to-a-file-url">Convert a filename to a file:// URL</a>.
This function is a part of <code>Player</code> class. <code>Player</code> instance has <code>player</code> variable <code>self.player = gst.element_factory_make("playbin")</code>:</p>
<pre><code>def set_song(self, song_name):
song_name = song_name.encode('utf8')
path = urlparse.urljoin("file://", urllib.pathname2url(song_name))
path = path.decode('utf8')
self.player.set_property("uri", path))
</code></pre>
<p>And now I'm pretty happy cause my song names can be in unicode and contain any weird symbols.</p>
| 0
|
2016-09-06T11:21:18Z
|
[
"python",
"gstreamer"
] |
how to close chrome browser popup dialog using selenium webdriver and python
| 39,345,066
|
<p>I have a python code that uses selenium webdriver (along with chromedriver), to log into facebook and take a screenshot of the page.<br>
the script itself works as expected, however, after logging in, chrome browser shows a dialog regarding facebook notifications (<a href="http://screencast.com/t/dUtCXk41gvu" rel="nofollow">Chrome Popup</a>)</p>
<p>The dialog seems to be generated by the browser, not the page itself.<br>
i'm unable to identify and capture the element or use "switch to alert" method. </p>
<p>How can i interact with this dialog (either Allow, Dismiss or close it)? </p>
<p>Thanks!</p>
| 1
|
2016-09-06T09:12:12Z
| 39,386,207
|
<p>You can try with launching the chrome browser with disabled pop-ups (browser pop-ups). The following code snippet is in Java. It will be somewhat similar in python i believe.</p>
<pre><code>ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-popup-blocking");
options.addArguments("test-type");
ChromeDriver driver = new ChromeDriver(options);
</code></pre>
| 0
|
2016-09-08T08:34:13Z
|
[
"python",
"google-chrome",
"selenium-webdriver",
"selenium-chromedriver"
] |
Django passing from DropDownlist to View
| 39,345,085
|
<p>I am trying to get the value of the Drop-down Menu Selected. I have done the following and it is returning a 'null' value. </p>
<p>I think the problem is here: newupload = request.POST('nameProjects') but I'm not sure which on how to get it working. </p>
<p>upload.html </p>
<pre><code><form class="form" method="POST" action="upload">
<select id="ddProjects" name="nameProjects">
{% for project in projects %}
<option value="{{ project.id }}">{{ project.name }}</option>
{% endfor %}
</select>
</form>
</code></pre>
<p>views.py</p>
<pre><code>def upload_new(request):
newupload = Upload()
projects = Project.objects.all()
newupload.project = request.POST['nameProjects']
newupload.save()
return render(request, 'upload.html', {'projects':projects})
</code></pre>
| -1
|
2016-09-06T09:12:59Z
| 39,346,804
|
<p>In the views.py, you should use request.POST['nameProjects'] because request.POST will give a dictionary. If you want to store the project object in upload model, we need to give the project model instance variable or can give the id.</p>
<pre>
def upload_new(request):
newupload = Upload()
projects = Project.objects.all()
newupload.project_id = request.POST['nameProjects']
newupload.save()
return render(request, 'upload.html', {'projects':projects})
</pre>
| 0
|
2016-09-06T10:30:30Z
|
[
"python",
"django",
"django-forms",
"django-views"
] |
Python: Scipy.optimize Levenberg-marquardt method
| 39,345,139
|
<p>I have a question about how to use the Levenberg-Marquardt optimize method in Python </p>
<p>In the library SCIPY there are many methods of optimize --> <a href="http://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html</a></p>
<p>I prove two methods(Nelder-Mead y Basinhopping) and the both works well whit the follow sentence:</p>
<p>Nelder mead ---> res0_10 = optimize.minimize(f0_10, x0, method='Nelder-Mead', options={'disp': True, 'maxiter': 2000})</p>
<p>Basinhopping ---> res0_10 = optimize.basinhopping(f0_10, x0, niter=100, disp=True)</p>
<p>The problem emerge when I use the Levenberg-Marquardt(I copy only the part of error, because the program is long)</p>
<pre><code>def f0_10(x):
m, u, z, s = x
for i in range(alt_max):
if i==alt_min: suma=0
if i > alt_min:
suma = suma + (B(x, i)-b0_10(x, i))**2
return np.sqrt(suma/alt_max)
x0 = np.array([40., 0., 500., 50.])
res0_10 = root(f0_10, x0, jac=True, method='lm')
</code></pre>
<p>I only change the last sentence --> res0_10 = root..............</p>
<p>The program compile well, but when I ejecute the program:</p>
<p>Exception in Tkinter callback</p>
<p>Traceback (most recent call last):</p>
<p>File "C:\Users\Quini SB\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.7.4.3348.win-x86_64\lib\lib-tk\Tkinter.py", line 1536, in <strong>call</strong>
return self.func(*args)</p>
<p>File "C:\Users\Quini SB\Desktop\tfg\Steyn - levmar.py", line 384, in askopenfilename
res0_10 = root(f0_10, x0, jac=True, method='lm')</p>
<p>File "C:\Users\Quini SB\AppData\Local\Enthought\Canopy\User\lib\site-packages\scipy\optimize_root.py", line 188, in root
sol = _root_leastsq(fun, x0, args=args, jac=jac, **options)</p>
<p>File "C:\Users\Quini SB\AppData\Local\Enthought\Canopy\User\lib\site-packages\scipy\optimize_root.py", line 251, in _root_leastsq
factor=factor, diag=diag)</p>
<p>File "C:\Users\Quini SB\AppData\Local\Enthought\Canopy\User\lib\site-packages\scipy\optimize\minpack.py", line 377, in leastsq
shape, dtype = _check_func('leastsq', 'func', func, x0, args, n)</p>
<p>File "C:\Users\Quini SB\AppData\Local\Enthought\Canopy\User\lib\site-packages\scipy\optimize\minpack.py", line 26, in _check_func
res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))</p>
<p>File "C:\Users\Quini SB\AppData\Local\Enthought\Canopy\User\lib\site-packages\scipy\optimize\optimize.py", line 64, in <strong>call</strong>
self.jac = fg[1]</p>
<p>IndexError: invalid index to scalar variable.</p>
<hr>
<p>I dont know because happen this error. I am student and I need this for my last work on Degree but my teacher dont know python</p>
<p>Thanks</p>
| 0
|
2016-09-06T09:15:14Z
| 39,345,476
|
<p>From documentation:</p>
<pre><code>jac : bool or callable, optional
If jac is a Boolean and is True, fun is assumed to return the value
of Jacobian along with the objective function. If False, the
Jacobian will be estimated numerically. jac can also be a callable
returning the Jacobian of fun. In this case, it must accept the
same arguments as fun.
</code></pre>
<p>So, your function 'f0_10' needs to return two values, because you set <code>jac</code> to <code>True</code></p>
| 1
|
2016-09-06T09:30:27Z
|
[
"python",
"optimization",
"scipy",
"levenberg-marquardt"
] |
How to create python conda 64 bit environment in existing 32bit install?
| 39,345,313
|
<p>I have a 32 bit installation of the Anaconda Python distribution.
I know how to create environments for different python versions.
What I need is to have a 64 bit version of python.</p>
<p>Is it possible to create a conda env with the 64 bit version?</p>
<p>Or do I have to reinstall anaconda or install a different version of anaconda and then switch the values of the PATH when I need the different versions?</p>
<p>I looked and searched the documentation, and the <code>conda create -h</code> help page did not find any mention of this.</p>
| 0
|
2016-09-06T09:22:48Z
| 39,345,619
|
<p>As I understand, Anaconda installs into a self-contained directory (<code><pwd>/anaconda3</code>). Since 64-bit and 32-bit builds of Python can not be mixed or converted into each other (in terms of the compiled Python binaries and libraries in <code>site-packages</code> or other <code>PYTHONPATH</code> location), you have to go with a second (64-bit) Anaconda installation in another directory.</p>
<p>If you have 32-bit code that needs to call 64-bit code, you have to rely subprocesses and pipes (or other IPC mechanisms). You probably have to be careful about your environment variables, e.g. <code>PATH</code> and <code>PYTHONPATH</code> when doing so.</p>
| 0
|
2016-09-06T09:36:52Z
|
[
"python",
"anaconda",
"32bit-64bit",
"development-environment",
"conda"
] |
Unable to connect to Heroku postgre SQL database locally
| 39,345,324
|
<p>I am trying to connect to Heroku postgre SQL database locally like this,</p>
<pre><code>from flask import Flask
import sys
import psycopg2
import urlparse
urlparse.uses_netloc.append("postgres")
url = urlparse.urlparse("postgres://url")
conn = psycopg2.connect(
database=url.path[1:],
user=url.username,
password=url.password,
host=url.hostname,
port=url.port
)
</code></pre>
<p>But after a lengthy pause I get the following error, </p>
<pre><code>psycopg2.OperationalError: could not connect to server: Connection timed out
Is the server running on host "URL" (IP) and accepting
TCP/IP connections on port 5432?
</code></pre>
<p>How can I fix this error and connect to the database locally?</p>
| 0
|
2016-09-06T09:23:20Z
| 39,346,821
|
<p>Kinda tough for me to narrow down, but I was able to set something similar with these steps:</p>
<p>If you have a 'server.py' make sure to have this at the top of the file:</p>
<pre><code>from dotenv import load_dotenv, find_dotenv
import os
load_dotenv(find_dotenv())
db = pg.DB(
dbname=os.environ.get('DBNAME'),
host=os.environ.get('DBHOST'),
port=int(os.environ.get('DBPORT')),
user=os.environ.get('DBUSER'),
passwd=os.environ.get('DBPASSWORD')
)
</code></pre>
<p>Dump the following in a Procfile (spell Procfile exactly like that)</p>
<pre><code>web: gunicorn -b 0.0.0.0:$PORT -w 4 server:app
</code></pre>
<p>Lastly, you need a requirements.txt that lists all Python modules you have installed. You can do this with the command: pip freeze > requirements.txt</p>
<p>Hope that helps.</p>
| 0
|
2016-09-06T10:31:22Z
|
[
"python",
"postgresql",
"heroku"
] |
Can we send a request object or keyword argument to modelformset_factory in django 1.9
| 39,345,346
|
<p>I have the following view</p>
<pre><code>def application(request, uuid):
application = get_object_or_404(LoanApplication, uuid=uuid)
partners = FirmPartner.objects.filter(application=application)
PartnerFormset = modelformset_factory(FirmPartner, form=FirmPartnerForm, can_delete=True, extra=1)
if request.method == 'POST':
.........
..........
</code></pre>
<p>But i want to make some fields in FirmPartnerForm required dynamically inside <strong>init</strong> method of form by using some values from request or keyword argument that we passed in like <code>modelformset_factory(......application=application)</code> ?</p>
<p>So is it possible to send request object or any keyword argument to modelformset_factory ? as below</p>
<pre><code>modelformset_factory(FirmPartner, form=FirmPartnerForm, can_delete=True, extra=1, request=request, application=application) ?
</code></pre>
<p><strong><em>Edit</em></strong></p>
<p>Now i upgraded to django 1.9.9 and below is my code</p>
<pre><code>from .forms import FirmPartnerForm
PartnerFormset = modelformset_factory(FirmPartner, form=FirmPartnerForm, can_delete=True, extra=1,
form_kwargs={'request': request, 'application': application})
</code></pre>
<p><strong><em>forms.py</em></strong></p>
<pre><code>class FirmPartnerForm(forms.ModelForm):
class Meta:
model = FirmPartner
exclude = ['application']
def __init__(self, *args, **kwargs):
super(FirmPartnerForm, self).__init__(*args, **kwargs)
if kwargs.get('application', None):
application = kwargs.get('application
.....................
.....................
</code></pre>
<p><strong><em>Error Traceback</em></strong></p>
<pre><code> File "/Users/name/projects/project_name/applications/views.py", line 462, in application_management
form_kwargs={'request': request, 'application': application})
TypeError: modelformset_factory() got an unexpected keyword argument 'form_kwargs'
</code></pre>
<p>So after <code>Daniel</code> said form_kwargs has been added in 1.9, i have upgraded to 1.9.9 and still i was getting the above error ?</p>
| 0
|
2016-09-06T09:24:08Z
| 39,345,426
|
<p>The <a href="https://docs.djangoproject.com/en/1.10/topics/forms/formsets/#passing-custom-parameters-to-formset-forms" rel="nofollow"><code>form_kwargs</code></a> parameter is what you need.</p>
<pre><code>modelformset_factory(FirmPartner, form=FirmPartnerForm, can_delete=True, extra=1,
form_kwargs={'request': request, 'application': application})
</code></pre>
| 1
|
2016-09-06T09:28:38Z
|
[
"python",
"django",
"django-forms",
"modelform"
] |
How to render PDF using poppler in pyqt4 or wxpython?
| 39,345,395
|
<p>My goal is to create a pdf viewer that can select a text in the viewer.</p>
<p>is it possible?
i'm only experienced using wxpython for deleveloping gui application. I just heard poppler can support rendering pdf, but i did not found any snippet or example. please help.</p>
| 0
|
2016-09-06T09:26:48Z
| 39,351,066
|
<p>If you are looking for how to create a wxPython PDF viewer, I've found a couple of examples. The first one uses Poppler as you mentioned in conjunction with wxPython:</p>
<ul>
<li><a href="http://code.activestate.com/recipes/577195-wxpython-pdf-viewer-using-poppler/" rel="nofollow">http://code.activestate.com/recipes/577195-wxpython-pdf-viewer-using-poppler/</a></li>
</ul>
<p>It's a pretty old example, so I don't know how well it works now. The other one I found uses PyMuPDF and fitz and was published this year (2016):</p>
<ul>
<li><a href="http://code.activestate.com/recipes/580621-wxpython-pdf-viewer-using-pymupdf-binding-for-fitz/" rel="nofollow">http://code.activestate.com/recipes/580621-wxpython-pdf-viewer-using-pymupdf-binding-for-fitz/</a></li>
</ul>
<p>If you happen to be on Windows, wxPython comes with an ActiveX wrapper around Adobe's reader. You can read more about it here:</p>
<ul>
<li><a href="https://wxpython.org/Phoenix/docs/html/wx.lib.pdfviewer.viewer.pdfViewer.html" rel="nofollow">https://wxpython.org/Phoenix/docs/html/wx.lib.pdfviewer.viewer.pdfViewer.html</a></li>
</ul>
| 0
|
2016-09-06T14:06:14Z
|
[
"python",
"pdf",
"wxpython",
"poppler"
] |
Can pandas dataframe have dtype of list?
| 39,345,624
|
<p>I'm new to Pandas, I process a dataset, where one of the columns is string with pipe (<code>|</code>) separated values. Now I have a task to remove any text in this |-separated field that's not fulfilling certain criteria.</p>
<p>My naive approach is to iterate the dataframe row by row and explode the field into list and validate this way. Then write the modified row back to the original dataframe. See this metasample:</p>
<pre><code>for index, row in dataframe.iterrows():
fixed = [x[:29] for x in row['field'].split('|')]
dataframe.loc[index, 'field'] = "|".join(fixed)
</code></pre>
<p>Is there a better, and more importantly faster way to do this?</p>
| 1
|
2016-09-06T09:36:58Z
| 39,346,589
|
<p>IIUC you can use:</p>
<pre><code>dataframe = pd.DataFrame({'field':['aasd|bbuu|cccc|ddde|e','ffff|gggg|hhhh|i|j','cccc|u|k'],
'G':[4,5,6]})
print (dataframe)
G field
0 4 aasd|bbuu|cccc|ddde|e
1 5 ffff|gggg|hhhh|i|j
2 6 cccc|u|k
print (dataframe.field.str.split('|', expand=True)
.stack()
.str[:2] #change to 29
.groupby(level=0)
.apply('|'.join))
0 aa|bb|cc|dd|e
1 ff|gg|hh|i|j
2 cc|u|k
dtype: object
</code></pre>
<p>Another solution via list comprehension:</p>
<pre><code>dataframe['new'] = pd.Series([[x[:2] for x in y] for y in dataframe.field.str.split('|')],
index=dataframe.index)
.apply('|'.join)
print (dataframe)
G field new
0 4 aasd|bbuu|cccc|ddde|e aa|bb|cc|dd|e
1 5 ffff|gggg|hhhh|i|j ff|gg|hh|i|j
2 6 cccc|u|k cc|u|k
</code></pre>
<hr>
<pre><code>dataframe = pd.DataFrame({'field':['aasd|bbuu|cc|ddde|e','ffff|gggg|hhhh|i|j','cccc|u|k'],
'G':[4,5,6]})
print (dataframe)
G field
0 4 aasd|bbuu|cc|ddde|e
1 5 ffff|gggg|hhhh|i|j
2 6 cccc|u|k
</code></pre>
<p>If need filter all values with values longer as <code>2</code>:</p>
<pre><code>s = dataframe.field.str.split('|', expand=True).stack()
print (s)
0 0 aasd
1 bbuu
2 cc
3 ddde
4 e
1 0 ffff
1 gggg
2 hhhh
3 i
4 j
2 0 cccc
1 u
2 k
dtype: object
dataframe['new'] = s[s.str.len() < 3].groupby(level=0).apply('|'.join)
print (dataframe)
G field new
0 4 aasd|bbuu|cc|ddde|e cc|e
1 5 ffff|gggg|hhhh|i|j i|j
2 6 cccc|u|k u|k
</code></pre>
<p>Another solution:</p>
<pre><code>dataframe['new'] = pd.Series([[x for x in y if len(x) < 3] for y in dataframe.field.str.split('|')],
index=dataframe.index)
.apply('|'.join)
print (dataframe)
G field new
0 4 aasd|bbuu|cc|ddde|e cc|e
1 5 ffff|gggg|hhhh|i|j i|j
2 6 cccc|u|k u|k
</code></pre>
| 2
|
2016-09-06T10:20:50Z
|
[
"python",
"string",
"list",
"pandas",
"list-comprehension"
] |
find the misclassified data in a confusion matrix
| 39,345,647
|
<p>I use this function to evaluate my model</p>
<pre><code>def stratified_cv(X, y, clf_class, shuffle=True, n_folds=10, **kwargs):
X = X.as_matrix().astype(np.float)
y = y.as_matrix().astype(np.int)
y_pred = y.copy()
stratified_k_fold = cross_validation.StratifiedKFold(y, n_folds=n_folds, shuffle=shuffle)
y_pred = y.copy()
for ii, jj in stratified_k_fold:
X_train, X_test = X[ii], X[jj]
y_train,y_test = y[ii],y[jj]
clf = clf_class(**kwargs)
clf.fit(X_train,y_train)
y_pred[jj] = clf.predict(X_test)
return y_pred
</code></pre>
<p>And the confusion matrix is given for example</p>
<pre><code>pass_agg_conf_matrix = metrics.confusion_matrix(y, stratified_cv(X, y, linear_model.PassiveAggressiveClassifier))
</code></pre>
<p><a href="http://i.stack.imgur.com/zC8ZI.png" rel="nofollow"><img src="http://i.stack.imgur.com/zC8ZI.png" alt="enter image description here"></a></p>
<p>Now I wanted to identify entries that are misclassified</p>
| -3
|
2016-09-06T09:37:52Z
| 39,361,999
|
<p>You can find out the misclassified predictions from the confusion matrix itself. The top right box gives the number of predictions predicted to be 0 but are not zero. And the lower left box shows those predicted 1but are not one.
This above mentioned cells are known as true negative and false positive if the confusion matrix is built according to the correct convention. </p>
| 0
|
2016-09-07T05:45:27Z
|
[
"python",
"pandas",
"machine-learning",
"confusion-matrix"
] |
Mutlithreading python
| 39,345,656
|
<p>I am new to Python coding and new to stackoverflow as well need your guidance:</p>
<p>I am trying to create AMI of EC2 instances using python. I need to implement multi threading so that AMI creation can run in parallel. But below code is not working. It is creating single AMI at a time.</p>
<p>module1</p>
<pre><code>from Libpy import Libpy
import boto.ec2
import sys
if __name__=='__main__':
a = B()
Libpy().multithreading(ec2list1,a.create_amibkp(ec2listname,ec2list1))
</code></pre>
<p>module2</p>
<pre><code>import threading
import time
class Libpy:
def multithreading(l, function):
threads = []
for z,v in enumerate(l):
dummy = z
t = threading.Thread(target=function, args=(v,))
threads.append(t)
t.start()
</code></pre>
<ol>
<li>ec2listname - contains the list of instance names for whom AMI
creation should be done </li>
<li>ec2list1 - contains the list of instance ids for whom AMI creation should be done </li>
<li>create_amibkp - customized function which takes AMI for the filtered instances From module1, I am calling module2 to multithread the function but it is not working. It is creating AMI one at time.
4.B() - class will return ec2listname and ec2list1</li>
</ol>
| 1
|
2016-09-06T09:38:19Z
| 39,346,858
|
<p>I can't reproduce your example but I've created a dummy version:</p>
<pre><code>import sys
import threading
import time
import random
random.seed(1)
class Libpy:
def multithreading(self, lst, function):
threads = []
for v in lst:
t = threading.Thread(target=function, args=(v,))
t.start()
threads.append(t)
for t in threads:
t.join()
def ami_creation(v):
t = random.random() * 4
print("creating ami {0}, sleeping {1}".format(v, t))
time.sleep(t)
print("ami {0} created ok".format(v))
ec2list1 = ["ec2-small", "ec2-medium", "ec2-large"]
Libpy().multithreading(ec2list1, ami_creation)
print("All boxes have been created...")
</code></pre>
<p>In the above example the main thread would wait till all boxes are created</p>
| 1
|
2016-09-06T10:33:02Z
|
[
"python",
"amazon-web-services",
"ami"
] |
Control a python process form another python file
| 39,345,829
|
<p>first of all a short overview over my current goal:</p>
<p>I want to use a scheduler to execute a simple python program every second. This program reads some data and enter the results inside a database. Because the scheduled task will operate over several days on a raspberry pie the process should start in the background. Therefore I want to create a python file which can start, stop and get the current status from the background job. Furthermore it should be possible to exit and reenter the control file without stopping the background job.</p>
<p>Currently I tried apscheduler to execute the python file every second. The actual problem is, that I can't access the current python file, to control the status, from another external file. Overall I found no real solution how I can control a subprocess form an external file and after find the same subprocess again after restarting the controlling python file.</p>
<p>EDIT:</p>
<p>So overall as far I got it now I'm able to find the current process with his pid. With that im able to send send a terminatesignal to the current process. Inside my scheduled file I'm able to <a href="https://nattster.wordpress.com/2013/06/05/catch-kill-signal-in-python/" rel="nofollow">catch these signals</a> and shut down the program on a normal way.</p>
| 1
|
2016-09-06T09:47:04Z
| 39,346,000
|
<p>To control (start, restart, stop, schedule) the background process use <a href="https://docs.python.org/3/library/subprocess.html" rel="nofollow">subprocess</a>. Here is <a href="http://stackoverflow.com/questions/1191374/using-module-subprocess-with-timeout">example</a> of subrocess' popen with timeout.</p>
<p>To pass some data between the <code>scheduler</code> and the <code>background job</code> use one of <a href="https://docs.python.org/3/library/ipc.html" rel="nofollow">IPC</a> mechanisms, for example sockets.</p>
| 1
|
2016-09-06T09:54:35Z
|
[
"python",
"python-3.x",
"subprocess",
"scheduled-tasks"
] |
can't get pydot to find graphviz on windows 10
| 39,345,846
|
<p>I'm trying to run a Random Forest analysis on Python 2.7 and I get this error while trying to create the graph of the decision trees.
<a href="http://i.stack.imgur.com/sHsra.jpg" rel="nofollow">error</a></p>
<p>I've tried reinstalling pydot and graphviz in alternating orders and I've also tried adding dot.exe to my system variables path with the value as C:\Program Files(x86)\Graphviz2.38\bin\</p>
<p>I'm fairly new to coding so I'd appreciate if you can explain the steps in detail.</p>
<p>Thanks!</p>
| -1
|
2016-09-06T09:48:10Z
| 39,665,443
|
<p>When changing the <code>PATH</code> variable (or any other system variable for that matter), the applications using this variables must be restarted in order to see the new values. Alternatively, log out completely and log back in.</p>
<p>The application (in this case Python) should now be able to call the programs in <code>C:\Program Files(x86)\Graphviz2.38\bin\</code>. Hope this solves it!</p>
| 1
|
2016-09-23T16:23:59Z
|
[
"python",
"graphviz",
"random-forest",
"pydot"
] |
Django: Test an Abstract Model
| 39,345,893
|
<p>I have a simple abstract class and I want to write a unit test for this.
I am using Django 1.10 and the most <a href="https://stackoverflow.com/questions/4281670/django-best-way-to-unit-test-an-abstract-model">answers I have found</a> are out there for years and maybe are outdated.
I have tried the solution from <a href="https://www.kurup.org/blog/2014/07/21/django-test-models" rel="nofollow">Vinod Kurup</a>:</p>
<pre><code># tests/test_foo.py
from django.db import models
from django.test import TestCase
from ..models import MyAbstractModel
class MyTestModel(MyAbstractModel):
name = models.CharField(max_length=20)
class Meta:
app_label = 'myappname'
class AbstractTest(TestCase):
def test_my_test_model(self):
self.assertTrue(MyTestModel.objects.create(name='foo'))
</code></pre>
<p>Are there any simple modern approaches to test an abstract model that work with Django 1.10 like the one from Vinod Kurup?</p>
<p><strong>Edit:</strong></p>
<p>Code for my Abstract Model:</p>
<pre><code>class FlagsModel(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
reported = models.BooleanField(default=False)
deleted = models.BooleanField(default=False)
class Meta:
abstract = True
</code></pre>
<p>And this is my test file:</p>
<pre><code>from ..models import RecipeModel, FlagsModel
class FlagsTestModel(FlagsModel):
class Meta:
app_label = 'recipes'
class FlagsModelAbstractTest(TestCase):
def test_my_test_model(self):
self.assertTrue(FlagsTestModel.objects.create())
</code></pre>
<p>The error I get is:</p>
<pre><code>Traceback (most recent call last):
File "/home/arch/.environments/djanveg_dev/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation "recipes_flagstestmodel" does not exist
LINE 1: ...eported", "recipes_flagstestmodel"."deleted" FROM "recipes_f...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/arch/.environments/djanveg_dev/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/home/arch/.environments/djanveg_dev/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/arch/.environments/djanveg_dev/lib/python3.5/site-packages/django/core/management/commands/test.py", line 29, in run_from_argv
super(Command, self).run_from_argv(argv)
File "/home/arch/.environments/djanveg_dev/lib/python3.5/site-packages/django/core/management/base.py", line 305, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/arch/.environments/djanveg_dev/lib/python3.5/site-packages/django/core/management/base.py", line 356, in execute
output = self.handle(*args, **options)
File "/home/arch/.environments/djanveg_dev/lib/python3.5/site-packages/django/core/management/commands/test.py", line 72, in handle
failures = test_runner.run_tests(test_labels)
File "/home/arch/.environments/djanveg_dev/lib/python3.5/site-packages/django/test/runner.py", line 549, in run_tests
old_config = self.setup_databases()
File "/home/arch/.environments/djanveg_dev/lib/python3.5/site-packages/django/test/runner.py", line 499, in setup_databases
self.parallel, **kwargs
File "/home/arch/.environments/djanveg_dev/lib/python3.5/site-packages/django/test/runner.py", line 743, in setup_databases
serialize=connection.settings_dict.get("TEST", {}).get("SERIALIZE", True),
File "/home/arch/.environments/djanveg_dev/lib/python3.5/site-packages/django/db/backends/base/creation.py", line 78, in create_test_db
self.connection._test_serialized_contents = self.serialize_db_to_string()
File "/home/arch/.environments/djanveg_dev/lib/python3.5/site-packages/django/db/backends/base/creation.py", line 122, in serialize_db_to_string
serializers.serialize("json", get_objects(), indent=None, stream=out)
File "/home/arch/.environments/djanveg_dev/lib/python3.5/site-packages/django/core/serializers/__init__.py", line 129, in serialize
s.serialize(queryset, **options)
File "/home/arch/.environments/djanveg_dev/lib/python3.5/site-packages/django/core/serializers/base.py", line 79, in serialize
for count, obj in enumerate(queryset, start=1):
File "/home/arch/.environments/djanveg_dev/lib/python3.5/site-packages/django/db/backends/base/creation.py", line 118, in get_objects
for obj in queryset.iterator():
File "/home/arch/.environments/djanveg_dev/lib/python3.5/site-packages/django/db/models/query.py", line 54, in __iter__
results = compiler.execute_sql()
File "/home/arch/.environments/djanveg_dev/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 835, in execute_sql
cursor.execute(sql, params)
File "/home/arch/.environments/djanveg_dev/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/arch/.environments/djanveg_dev/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/arch/.environments/djanveg_dev/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/arch/.environments/djanveg_dev/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "recipes_flagstestmodel" does not exist
LINE 1: ...eported", "recipes_flagstestmodel"."deleted" FROM "recipes_f...
</code></pre>
| 1
|
2016-09-06T09:50:14Z
| 39,415,678
|
<p>The problem is that you haven't migrated that model to your database, and that's because you created the model inside the tests file, Django only checks for models inside the <code>models.py</code> file, so move the next code to the <code>models.py</code> file:</p>
<pre><code>class FlagsTestModel(FlagsModel):
class Meta:
app_label = 'recipes'
</code></pre>
<p>Then run <code>python manage.py makemigrations</code> and <code>python manage.py mgirate</code> to create the table inside your database and everything will work as expected.</p>
| 1
|
2016-09-09T16:09:48Z
|
[
"python",
"django",
"unit-testing",
"django-models",
"abstract-class"
] |
how to search new line character from a string in python
| 39,345,915
|
<p>I want to split string based on new line character and replace the new line with a '.' in python. I tried this code but I'm not getting it.</p>
<pre><code>import nltk
from nltk.tokenize.punkt import PunktSentenceTokenizer, PunktParameters, PunktLanguageVars
ex_sent="Conclusion & Future Work
In our project we have tried for implementing northbound SDN application for OpenFlow protocol evaluation. The client and the RYU application is being connected, via socket connection."
class CommaPoint(PunktLanguageVars):
sent_end_chars = (',','\n')
tokenizer = PunktSentenceTokenizer(lang_vars = CommaPoint())
sentences = sentence_splitter.tokenize(ex_sent)
print sentences
</code></pre>
| 1
|
2016-09-06T09:51:24Z
| 39,346,122
|
<p>The newline character is <code>\n</code>. So If you want to replace all new line characters in string with <code>.</code> you should use <code>replace()</code> method. In this case:</p>
<pre><code>your_string.replace('\n', '.')
</code></pre>
<p>A second approach is to <code>.split('\n')</code> by newline and then <code>'.'.join(your_string)</code>. You should checkout the <a href="https://docs.python.org/3/library/stdtypes.html" rel="nofollow">Python documentation.</a></p>
| 4
|
2016-09-06T09:59:43Z
|
[
"python",
"nltk"
] |
Python returns string is both str and unicode type
| 39,345,916
|
<p>We have a .NET app that can be customized by IronPython (version 2.7.5)</p>
<p>Here is the script code:</p>
<pre><code>stringToPlay = # get it from our .NET app interface toward python here. The method returns .NET string
Log.Write("isinstance(stringToPlay, unicode): ", str(isinstance(stringToPlay, unicode)))
Log.Write("isinstance(stringToPlay, str): ", str(isinstance(stringToPlay, str)))
</code></pre>
<p>Both log lines will return True ??</p>
<p>stringToPlay value is "ÐиÑилиÑа" .</p>
<p>How is this possible when str and unicode should be two separate classes both inheriting from basestring?</p>
<p>Thank you</p>
| 1
|
2016-09-06T09:51:26Z
| 39,346,195
|
<p>In IronPython, the <code>str</code> type and the <code>unicode</code> type are the same object. The .NET string type is unicode.</p>
| 3
|
2016-09-06T10:03:00Z
|
[
"python",
".net",
"unicode",
"ironpython"
] |
Python returns string is both str and unicode type
| 39,345,916
|
<p>We have a .NET app that can be customized by IronPython (version 2.7.5)</p>
<p>Here is the script code:</p>
<pre><code>stringToPlay = # get it from our .NET app interface toward python here. The method returns .NET string
Log.Write("isinstance(stringToPlay, unicode): ", str(isinstance(stringToPlay, unicode)))
Log.Write("isinstance(stringToPlay, str): ", str(isinstance(stringToPlay, str)))
</code></pre>
<p>Both log lines will return True ??</p>
<p>stringToPlay value is "ÐиÑилиÑа" .</p>
<p>How is this possible when str and unicode should be two separate classes both inheriting from basestring?</p>
<p>Thank you</p>
| 1
|
2016-09-06T09:51:26Z
| 39,346,199
|
<p>IronPython makes no difference between <code>str</code> and <code>unicode</code>, which can be very confusing if you are used to the CPython 2 semantics. In fact, <code>basestring</code> and <code>unicode</code> are both aliases for <code>str</code>.</p>
<pre><code>IronPython 2.7.4 (2.7.0.40) on .NET 4.0.30319.42000 (32-bit)
Type "help", "copyright", "credits" or "license" for more information.
>>> unicode
<type 'str'>
>>> basestring
<type 'str'>
</code></pre>
<p>Regarding strings, IronPython (2.X) behaves more like Python 3, with the slightly annoying fact that you can't distinguish between <code>unicode</code> and <code>str</code> if you want to decode / encode based on the type (and since it is still Python 2, there is also no <code>bytes</code>).</p>
| 5
|
2016-09-06T10:03:15Z
|
[
"python",
".net",
"unicode",
"ironpython"
] |
How does Python return multiple values from a function?
| 39,345,995
|
<p>I have written the following code:</p>
<pre><code>class FigureOut:
first_name = None
last_name = None
def setName(self, name):
fullname = name.split()
self.first_name = fullname[0]
self.last_name = fullname[1]
def getName(self):
return self.first_name, self.last_name
f = FigureOut()
f.setName("Allen Solly")
name = f.getName()
print (name)
</code></pre>
<p>I get the following <strong>Output:</strong></p>
<pre><code>('Allen', 'Solly')
</code></pre>
<p>Whenever multiple values are returned from a function in python, does it always convert the multiple values to a <strong>list of multiple values</strong> and then returns it from the function?</p>
<p><em>Is the whole process same as converting the multiple values to a <code>list</code> explicitly and then returning the list, for example in JAVA, as one can return only one object from a function in JAVA?</em></p>
| 1
|
2016-09-06T09:54:25Z
| 39,346,109
|
<p>Python will return a <code>tuple</code> in this case since the return specifies <em>comma separated values</em>. Multiple values can only be returned inside containers.</p>
<p>You can look at the byte code generated from a function returning values like yours by using <a href="https://docs.python.org/3/library/dis.html#dis.dis" rel="nofollow"><code>dis.dis</code></a>. For comma separated values, it looks like:</p>
<pre><code>def foo(a, b):
return a,b
import dis
dis.dis(foo)
2 0 LOAD_FAST 0 (a)
3 LOAD_FAST 1 (b)
6 BUILD_TUPLE 2
9 RETURN_VALUE
</code></pre>
<p>As you can see the values are first loaded on the stack and then a <a href="https://docs.python.org/3/library/dis.html#opcode-BUILD_TUPLE" rel="nofollow"><code>BUILD_TUPLE</code></a> (grabbing the previous <code>2</code> elements placed on the stack) is generated. Python knows to create tuple due to thhe commas being present.</p>
<p>You could alternatively specify another return type, for example a list, for this case a <a href="https://docs.python.org/3/library/dis.html#opcode-BUILD_LIST" rel="nofollow"><code>BUILD_LIST</code></a> is going to be issued following the same semantics as it's tuple equivalent:</p>
<pre><code>def foo(a, b):
return [a, b]
import dis
dis.dis(foo)
2 0 LOAD_FAST 0 (a)
3 LOAD_FAST 1 (b)
6 BUILD_LIST 2
9 RETURN_VALUE
</code></pre>
<p>To summarize, <em>one actual object is returned</em>, if that object is of a container type, it in essence can contain multiple values giving the impression of multiple results.</p>
| 3
|
2016-09-06T09:59:12Z
|
[
"python",
"function",
"python-3.x",
"return"
] |
How does Python return multiple values from a function?
| 39,345,995
|
<p>I have written the following code:</p>
<pre><code>class FigureOut:
first_name = None
last_name = None
def setName(self, name):
fullname = name.split()
self.first_name = fullname[0]
self.last_name = fullname[1]
def getName(self):
return self.first_name, self.last_name
f = FigureOut()
f.setName("Allen Solly")
name = f.getName()
print (name)
</code></pre>
<p>I get the following <strong>Output:</strong></p>
<pre><code>('Allen', 'Solly')
</code></pre>
<p>Whenever multiple values are returned from a function in python, does it always convert the multiple values to a <strong>list of multiple values</strong> and then returns it from the function?</p>
<p><em>Is the whole process same as converting the multiple values to a <code>list</code> explicitly and then returning the list, for example in JAVA, as one can return only one object from a function in JAVA?</em></p>
| 1
|
2016-09-06T09:54:25Z
| 39,346,120
|
<p>From <a href="https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch07s04.html" rel="nofollow">Phyton Cookbook v.30</a></p>
<pre><code>def myfun():
return 1, 2, 3
</code></pre>
<p></p>
<pre><code>a, b, c = myfun()
</code></pre>
<blockquote>
<p><strong>Although it looks like <code>myfun()</code> returns multiple values, a <code>tuple</code> is actually being created.</strong> It looks a bit peculiar, but itâs actually the comma that forms a tuple, not the parentheses</p>
</blockquote>
<p>So yes, what's going on in <a href="/questions/tagged/phyton" class="post-tag" title="show questions tagged 'phyton'" rel="tag">phyton</a> is an internal transformation from multiple comma separated values to a tuple and viceversa. </p>
<p>Though there's no equivalent in <a href="/questions/tagged/java" class="post-tag" title="show questions tagged 'java'" rel="tag">java</a> you can easily create this behaviour using <code>array</code>'s or some <code>Collection</code>s like <code>List</code>s:</p>
<pre><code>private static int[] sumAndRest(int x, int y) {
int[] toReturn = new int[2];
toReturn[0] = x + y;
toReturn[1] = x - y;
return toReturn;
}
</code></pre>
<p>Executed in this way:</p>
<pre><code>public static void main(String[] args) {
int[] results = sumAndRest(10, 5);
int sum = results[0];
int rest = results[1];
System.out.println("sum = " + sum + "\nrest = " + rest);
}
</code></pre>
<p>result:</p>
<pre><code>sum = 15
rest = 5
</code></pre>
| 3
|
2016-09-06T09:59:37Z
|
[
"python",
"function",
"python-3.x",
"return"
] |
How does Python return multiple values from a function?
| 39,345,995
|
<p>I have written the following code:</p>
<pre><code>class FigureOut:
first_name = None
last_name = None
def setName(self, name):
fullname = name.split()
self.first_name = fullname[0]
self.last_name = fullname[1]
def getName(self):
return self.first_name, self.last_name
f = FigureOut()
f.setName("Allen Solly")
name = f.getName()
print (name)
</code></pre>
<p>I get the following <strong>Output:</strong></p>
<pre><code>('Allen', 'Solly')
</code></pre>
<p>Whenever multiple values are returned from a function in python, does it always convert the multiple values to a <strong>list of multiple values</strong> and then returns it from the function?</p>
<p><em>Is the whole process same as converting the multiple values to a <code>list</code> explicitly and then returning the list, for example in JAVA, as one can return only one object from a function in JAVA?</em></p>
| 1
|
2016-09-06T09:54:25Z
| 39,346,131
|
<p>Python functions always return a unique value. The comma operator is the constructor of tuples so <code>self.first_name, self.last_name</code> evaluates to a tuple and that tuple is the actual value the function is returning.</p>
| 1
|
2016-09-06T10:00:03Z
|
[
"python",
"function",
"python-3.x",
"return"
] |
How does Python return multiple values from a function?
| 39,345,995
|
<p>I have written the following code:</p>
<pre><code>class FigureOut:
first_name = None
last_name = None
def setName(self, name):
fullname = name.split()
self.first_name = fullname[0]
self.last_name = fullname[1]
def getName(self):
return self.first_name, self.last_name
f = FigureOut()
f.setName("Allen Solly")
name = f.getName()
print (name)
</code></pre>
<p>I get the following <strong>Output:</strong></p>
<pre><code>('Allen', 'Solly')
</code></pre>
<p>Whenever multiple values are returned from a function in python, does it always convert the multiple values to a <strong>list of multiple values</strong> and then returns it from the function?</p>
<p><em>Is the whole process same as converting the multiple values to a <code>list</code> explicitly and then returning the list, for example in JAVA, as one can return only one object from a function in JAVA?</em></p>
| 1
|
2016-09-06T09:54:25Z
| 39,346,392
|
<blockquote>
<p>Whenever multiple values are returned from a function in python, does it always convert the multiple values to a <strong>list</strong> of multiple values and then returns it from the function??
<br/></p>
</blockquote>
<p>I'm just adding a name and print the result that returns from the function.
the type of result is '<strong>tuple</strong>'.</p>
<pre><code> class FigureOut:
first_name = None
last_name = None
def setName(self, name):
fullname = name.split()
self.first_name = fullname[0]
self.last_name = fullname[1]
self.special_name = fullname[2]
def getName(self):
return self.first_name, self.last_name, self.special_name
f = FigureOut()
f.setName("Allen Solly Jun")
name = f.getName()
print type(name)
</code></pre>
<p><br/></p>
<p>I don't know whether you have heard about '<strong>first class function</strong>'. Python is the language that has '<a href="https://en.wikipedia.org/wiki/First-class_function" rel="nofollow">first class function</a>' </p>
<p>I hope my answer could help you.
Happy coding.</p>
| 1
|
2016-09-06T10:12:24Z
|
[
"python",
"function",
"python-3.x",
"return"
] |
How does Python return multiple values from a function?
| 39,345,995
|
<p>I have written the following code:</p>
<pre><code>class FigureOut:
first_name = None
last_name = None
def setName(self, name):
fullname = name.split()
self.first_name = fullname[0]
self.last_name = fullname[1]
def getName(self):
return self.first_name, self.last_name
f = FigureOut()
f.setName("Allen Solly")
name = f.getName()
print (name)
</code></pre>
<p>I get the following <strong>Output:</strong></p>
<pre><code>('Allen', 'Solly')
</code></pre>
<p>Whenever multiple values are returned from a function in python, does it always convert the multiple values to a <strong>list of multiple values</strong> and then returns it from the function?</p>
<p><em>Is the whole process same as converting the multiple values to a <code>list</code> explicitly and then returning the list, for example in JAVA, as one can return only one object from a function in JAVA?</em></p>
| 1
|
2016-09-06T09:54:25Z
| 39,346,404
|
<p>Here It is actually returning <code>tuple</code>.</p>
<p>If you execute this code in Python 3: </p>
<pre><code>def get():
a = 3
b = 5
return a,b
number = get()
print(type(number))
print(number)
</code></pre>
<p><strong>Output :</strong> </p>
<pre><code><class 'tuple'>
(3, 5)
</code></pre>
<p>But if you change the code line <code>return [a,b]</code> instead of <code>return a,b</code> and execute : </p>
<pre><code>def get():
a = 3
b = 5
return [a,b]
number = get()
print(type(number))
print(number)
</code></pre>
<p><strong>Output :</strong></p>
<pre><code><class 'list'>
[3, 5]
</code></pre>
<p>It is only returning single object which contains multiple values. </p>
<p>There is another alternative to <code>return</code> statement for returning multiple values, use <code>yield</code>( to check in details see this <a href="http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python">What does the "yield" keyword do in Python?</a>)</p>
<p><strong>Sample Example :</strong></p>
<pre><code>def get():
for i in range(5):
yield i
number = get()
print(type(number))
print(number)
for i in number:
print(i)
</code></pre>
<p><strong>Output :</strong></p>
<pre><code><class 'generator'>
<generator object get at 0x7fbe5a1698b8>
0
1
2
3
4
</code></pre>
| 1
|
2016-09-06T10:13:05Z
|
[
"python",
"function",
"python-3.x",
"return"
] |
When run a c++ exe in a python code, don't change text file
| 39,346,051
|
<p>I have a c++ code that in this, i change strings in a text file.
this code run correctly. but when i run exe of this code in a python file, run correctly but don't change strings of text file.
what must i do?</p>
<p>part of my c++ for change text file:</p>
<pre><code>ofstream myfile;
myfile.open ("example.txt");
myfile << i << endl;
myfile.close();
</code></pre>
<p>and i run exe of this code in python with this part of code:</p>
<pre><code>os.system(mycppcode)
</code></pre>
| -1
|
2016-09-06T09:56:46Z
| 39,347,030
|
<p>The problem here is that your compiled cpp binary runs in a wrong directory (check your user directory for <code>example.txt</code>)</p>
<p>You need to specify full path to your executable in python script:</p>
<pre><code>os.system(os.getcwd() + '/test')
</code></pre>
| 1
|
2016-09-06T10:41:16Z
|
[
"python",
"c++",
"text",
"exe"
] |
I can't get a html page with requests
| 39,346,096
|
<p>I would like to get an html page and read the content. I use requests (python) and my code is very simple:</p>
<pre><code>import requests
url = "http://www.romatoday.it"
r = requests.get(url)
print r.text
</code></pre>
<p>when I try to do this procedure I get ever:
Connection aborted.', error(110, 'Connection timed out')
If I open the url in a browser all work well.</p>
<p>If I use requests with other url all is ok</p>
<p>I think is a "<a href="http://www.romatoday.it" rel="nofollow">http://www.romatoday.it</a>" particularity but I don't understand what is the problem. Can you help me please? </p>
| 0
|
2016-09-06T09:58:40Z
| 39,346,171
|
<p>Maybe the problem is that the comma here</p>
<pre><code>>> url = "http://www.romatoday,it"
</code></pre>
<p>should be a dot</p>
<pre><code>>> url = "http://www.romatoday.it"
</code></pre>
<p>I tried that and it worked for me </p>
| 0
|
2016-09-06T10:02:15Z
|
[
"python",
"timeout",
"python-requests",
"screen-scraping"
] |
I can't get a html page with requests
| 39,346,096
|
<p>I would like to get an html page and read the content. I use requests (python) and my code is very simple:</p>
<pre><code>import requests
url = "http://www.romatoday.it"
r = requests.get(url)
print r.text
</code></pre>
<p>when I try to do this procedure I get ever:
Connection aborted.', error(110, 'Connection timed out')
If I open the url in a browser all work well.</p>
<p>If I use requests with other url all is ok</p>
<p>I think is a "<a href="http://www.romatoday.it" rel="nofollow">http://www.romatoday.it</a>" particularity but I don't understand what is the problem. Can you help me please? </p>
| 0
|
2016-09-06T09:58:40Z
| 39,346,757
|
<p>Hmm..Have you tried other packages, not 'requests'?
the code blow is same result as your code.</p>
<pre><code>import urllib
url = "http://www.romatoday.it"
r = urllib.urlopen(url)
print r.read()
</code></pre>
<p><a href="http://i.stack.imgur.com/bVBJa.png" rel="nofollow">a picture that I captured after running your code.</a></p>
| -1
|
2016-09-06T10:28:05Z
|
[
"python",
"timeout",
"python-requests",
"screen-scraping"
] |
Analysis and spelling correction of SMS text using python
| 39,346,126
|
<p>For example, I have a sentence:</p>
<blockquote>
<p>hav bin reali happy since tlkin 2 u</p>
</blockquote>
<p>With a python script, I want to edit above line so that it becomes:</p>
<blockquote>
<p>have been really happy since talking to you[sic]</p>
</blockquote>
<p>How can I read each and every character and either replace or edit, or remove letter from words?
And can I/must I store the whole correct sentence in a different variable?</p>
| -3
|
2016-09-06T09:59:50Z
| 39,346,256
|
<pre><code>replacements = {
'hav': 'have',
'bin': 'been',
'reali': 'really',
'u': 'you',
'tlkin': 'talking',
'2': 'to'
}
sms = 'hav bin reali happy since tlkin 2 u'
original = ' '.join([replacements.get(w, w) for w in sms.split()])
print(original)
</code></pre>
| 0
|
2016-09-06T10:05:41Z
|
[
"python",
"text-analysis"
] |
Cannot run python script under powershell in spite of adding env Path as required
| 39,346,283
|
<p>I am a user of python under mac and need to work now on a windows system.
I have installed Python35 for windows in Powershell, the command <code>py --version</code> and <code>python --version</code> provides me "Python 3.5.2".</p>
<p>I want to run a python script in Powershell and have tried : <code>py file.py</code> <code>python file.py</code> <code>py .\file.py</code> <code>python .\file.py</code>
and have the following :</p>
<pre><code>python : File ".\file.py", line 1
Au caractère Ligne:1 : 1
+ python .\file.py
+ ~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: ( File ".\file.py", line 1:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
SyntaxError: Non-UTF-8 code starting with '\xff' in file .\file.py on line 1, but no encoding declared; see
http://python.org/dev/peps/pep-0263/ for details
</code></pre>
<p>As for <code>.\file.py</code> it opens me a black window that closes within 1 second.</p>
<p>Interestingly, when doing <code>python</code> or <code>py</code> it outputs the python idle but powershell is blocked and I cannot use it either in powershell.</p>
<p>Now, I already looked at </p>
<p><a href="http://stackoverflow.com/questions/12829680/cannot-run-python-script-file-using-windows-prompt">cannot run python script file using windows prompt</a></p>
<p><a href="http://stackoverflow.com/questions/29627895/cannot-run-python-script">Cannot run python script</a></p>
<p><a href="http://stackoverflow.com/questions/19505337/run-python-script-inside-powershell-script">Run python script inside powershell script</a></p>
<p>As well as I tried to add the Python Path in Powershell and manully in the "Advance system" interface of windows.</p>
<p>By the way my <code>file.py</code> contains a simple <code>print("hello")</code></p>
<p>What am I doing wrong?</p>
| 1
|
2016-09-06T10:06:54Z
| 39,346,608
|
<p>The problem is explained in the error message:</p>
<blockquote>
<p>SyntaxError: Non-UTF-8 code starting with '\xff' in file .\file.py on line 1, but no encoding declared;</p>
</blockquote>
<p>It means that Python reads the source file and gets confused. On the other hand, it has a <a href="https://en.wikipedia.org/wiki/Byte_order_mark" rel="nofollow">byte order mark</a> header, but on the other hand there isn't enough information about what kind of Unicode the file is about.</p>
<p>It's better be safe than sorry, so Python requires you to tell what to do instead of trying to guess what's the real encoding. In unicode, you see, there are caveats. For example, ½ is actually a <em>number</em> that has value of 0.5.</p>
<p>As for how to solve this, either save the file as non-unicode (ANSI) or start the source file with, say, header:</p>
<pre><code># -*- coding: utf-8 -*-
</code></pre>
| 1
|
2016-09-06T10:21:53Z
|
[
"python",
"windows",
"powershell"
] |
Loss of information using XBee
| 39,346,386
|
<p>I am trying to establish communications via serial port between a PC with Ubuntu 14.04LTS and my RoMeo Arduino Board (Atmega 328). The used serial interface are 2 Xbee modules, one at PC and the other at the board.</p>
<p>Firstly, I am trying to develop a simple program to send messages to the board and receive them back. The code I use for the Arduino board is the following:</p>
<pre><code>void loop(void)
{
char msg;
if (Serial.available()){
msg = Serial.read();
msg = Serial.print(msg);
}
}
</code></pre>
<p>When I send a unique character, the PC receives it back correctly. However, the problem I am facing is that for longer strings, the following characters are misspelled, as I obtain back strange hex numbers, as follows:</p>
<pre><code>>>> import serial
>>> ser = serial.Serial(port='/dev/ttyUSB0', baudrate=57600, timeout=0.1)
>>> ser.write('H')
>>> ser.read(1)
'H'
>>> ser.write('Hello')
>>> ser.read(5)
'H\x8b\xbd'
</code></pre>
<p>Thanks in advance.</p>
<p>EDIT: Seems like there is an overflow problem with the <a href="https://www.sparkfun.com/datasheets/Wireless/Zigbee/XBee-Manual.pdf" rel="nofollow">XBee modules</a>, but I can not figure it out completely: The problem is solved if I wait 0.01 seconds or more between sent characters, which is a huge amount of time. Namely, the code I use now for sending a word is:</p>
<pre><code>for letter in word:
serial.write(letter)
time.sleep(0.01)
</code></pre>
<p>However, this waiting time is only needed when sending data from the PC to the Arduino. When the communication goes the other way (Arduino sends data to PC), I do not need to sleep and bytes are correctly sent all together at 57600 bauds.</p>
| 1
|
2016-09-06T10:12:00Z
| 39,741,986
|
<p>The reason why the PC could not send more than 1 character to the Arduino board was that there was an XBee module configured with different port parameters than both the other module and the pyserial instance. In this case, the communication was established in Python with the following main parameters:</p>
<ul>
<li><p>Baud rate: 57600</p></li>
<li><p>Bytesize: 8</p></li>
<li><p>Parity: None</p></li>
<li><p>Stop bits: 1</p></li>
</ul>
<p>If one of this parameters is different in one of the XBee modules, the communication will be faulty (like this case) or even impossible.</p>
<p>To check the XBee configuration, the Digi XCTU application can be used: With the RF modules connected to the PC, open the program and read their configuration. Once opened, it has to be made sure that the 'Serial interfacing' options are equal to the previously listed.</p>
<p><a href="http://i.stack.imgur.com/tiU8E.png" rel="nofollow"><img src="http://i.stack.imgur.com/tiU8E.png" alt="XCTU interface with the Serial options opened"></a></p>
<p>At the image, it is shown the menu where these options can be changed. Note that the Stop bits and the Bytesize can not be configured. The first parameter was not adjustable until the XB24-ZB versions, and the last one <a href="http://www.digi.com/wiki/developer/index.php/Setting_Serial_Adapter_Baud_Rate" rel="nofollow">seems to not be possible to change</a>.</p>
<p>In the case of this question, <strong>the wrong parameter was the parity</strong>, as it was set to <em>space parity</em> in one of the modules, instead of <em>no parity</em>. Thus, the first byte was sent correctly, but after it the data was not coherent. After changing this parameter, the connection run OK.</p>
| 0
|
2016-09-28T08:29:07Z
|
[
"python",
"arduino",
"serial-port",
"pyserial",
"xbee"
] |
Regex pattern behaving differently in TCL compared with Perl & Python
| 39,346,524
|
<p>I am trying to extract a sub-string from a string using regular expressions. Below is the working code in <code>Python</code> (giving desired results)</p>
<p><strong>Python Solution</strong></p>
<pre><code>x = r'CAR_2_ABC_547_d'
>>> spattern = re.compile("CAR_.*?_(.*)")
>>> spattern.search(x).group(1)
'ABC_547_d'
>>>
</code></pre>
<p><strong>Perl Solution</strong> </p>
<pre><code>$ echo "CAR_2_ABC_547_d" | perl -pe's/CAR_.*?_(.*)/$1/'
ABC_547_d
</code></pre>
<p><strong>TCL Solution</strong> </p>
<p>However, when I try to utilize this approach in <code>Tcl</code>, it is giving me different results. Can someone please comment on this behavior</p>
<pre><code>% regexp -inline "CAR_.*?_(.*)" "CAR_2_ABC_547_d"
CAR_2_ {}
</code></pre>
| 2
|
2016-09-06T10:18:01Z
| 39,347,224
|
<blockquote>
<p>A branch has the same preference as the first quantified atom in it
which has a preference.</p>
</blockquote>
<p>So if you have <code>.*</code> as the first quantifier, the whole RE will be greedy,
and if you have <code>.*?</code> as the first quantifier, the whole RE will be non-greedy.</p>
<p>Since you have used the <code>.*?</code> in the first place itself, the further expression follow lazy mode only. </p>
<p>If you add end of line <code>$</code>, then it will match the whole. </p>
<pre><code>% regexp -inline "CAR_.*?_(.*)$" "CAR_2_ABC_547_d"
CAR_2_ABC_547_d ABC_547_d
</code></pre>
<p><strong>Reference :</strong> <a href="https://www.tcl.tk/man/tcl8.6/TclCmd/re_syntax.htm#M95" rel="nofollow">re_syntax</a></p>
| 4
|
2016-09-06T10:51:16Z
|
[
"python",
"perl",
"tcl",
"tclsh"
] |
Regex pattern behaving differently in TCL compared with Perl & Python
| 39,346,524
|
<p>I am trying to extract a sub-string from a string using regular expressions. Below is the working code in <code>Python</code> (giving desired results)</p>
<p><strong>Python Solution</strong></p>
<pre><code>x = r'CAR_2_ABC_547_d'
>>> spattern = re.compile("CAR_.*?_(.*)")
>>> spattern.search(x).group(1)
'ABC_547_d'
>>>
</code></pre>
<p><strong>Perl Solution</strong> </p>
<pre><code>$ echo "CAR_2_ABC_547_d" | perl -pe's/CAR_.*?_(.*)/$1/'
ABC_547_d
</code></pre>
<p><strong>TCL Solution</strong> </p>
<p>However, when I try to utilize this approach in <code>Tcl</code>, it is giving me different results. Can someone please comment on this behavior</p>
<pre><code>% regexp -inline "CAR_.*?_(.*)" "CAR_2_ABC_547_d"
CAR_2_ {}
</code></pre>
| 2
|
2016-09-06T10:18:01Z
| 39,354,872
|
<p>Another approach, instead of capturing the text that follows the prefix, is to just remove the prefix:</p>
<pre><code>% set result [regsub {^CAR_.*?_} "CAR_2_ABC_547_d" {}]
ABC_547_d
</code></pre>
| 1
|
2016-09-06T17:38:18Z
|
[
"python",
"perl",
"tcl",
"tclsh"
] |
Count cells of adjacent numpy regions
| 39,346,545
|
<p>I'm looking to solve the following problem. I have a numpy array which is labeled to regions from 1 to n. Let's say this is the array:</p>
<pre><code>x = np.array([[1, 1, 1, 4], [1, 1, 2, 4], [1, 2, 2, 4], [5, 5, 3, 4]], np.int32)
array([[1, 1, 1, 4],
[1, 1, 2, 4],
[1, 2, 2, 4],
[5, 5, 3, 4]])
</code></pre>
<p>A region are the combined cells in the numpy array with a unique value. So in this example x has 5 regions; region 1 which consists of 5 cells, region 2 which consists of 3 cells etc.
Now, I determine the adjacent regions of each region with the following lines of code:</p>
<pre><code>n = x.max()
tmp = np.zeros((n+1, n+1), bool)
# check the vertical adjacency
a, b = x[:-1, :], x[1:, :]
tmp[a[a!=b], b[a!=b]] = True
# check the horizontal adjacency
a, b = x[:, :-1], x[:, 1:]
tmp[a[a!=b], b[a!=b]] = True
# register adjacency in both directions (up, down) and (left,right)
result = (tmp | tmp.T)
result = result.astype(int)
np.column_stack(np.nonzero(result))
resultlist = [np.flatnonzero(row) for row in result[1:]]
</code></pre>
<p>Which gives me a list of each region with its adjacent regions:</p>
<pre><code>[array([2, 4, 5], dtype=int64),
array([1, 3, 4, 5], dtype=int64),
array([2, 4, 5], dtype=int64),
array([1, 2, 3], dtype=int64),
array([1, 2, 3], dtype=int64)]
</code></pre>
<p>Which works really well. However, I would like to count the amount of cells of each adjacent region and return this output. So, for region 2, in this example would mean a total of 7 adjacent regions (three 1s, two 4s, one 3 and one 5). Therefore:</p>
<ul>
<li>2 is surrounded for 43% by 1</li>
<li>2 is surround for 14 % by 5</li>
<li>2 is surrounded for 14% by 3</li>
<li>2 is surrounded for 29% by 4</li>
</ul>
<p>How could I best adjust the above code to include the amount of cells for each adjacent region?
Many thanks guys!</p>
| 3
|
2016-09-06T10:19:01Z
| 39,348,877
|
<p>Here is a vectorized solution using the <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package (note; it isn't vectorized over the regions, but it is vectorized over the pixels, which is the useful thing to do assuming n_pixels >> n_regions):</p>
<pre><code>neighbors = np.concatenate([x[:, :-1].flatten(), x[:, +1:].flatten(), x[+1:, :].flatten(), x[:-1, :].flatten()])
centers = np.concatenate([x[:, +1:].flatten(), x[:, :-1].flatten(), x[:-1, :].flatten(), x[+1:, :].flatten()])
valid = neighbors != centers
import numpy_indexed as npi
regions, neighbors_per_regions = npi.group_by(centers[valid], neighbors[valid])
for region, neighbors_per_region in zip(regions, neighbors_per_regions):
print(region)
unique_neighbors, neighbor_counts = npi.count(neighbors_per_region)
print(unique_neighbors, neighbor_counts / neighbor_counts.sum() * 100)
</code></pre>
<p>Or for a solution which is fully vectorized over both pixels and regions:</p>
<pre><code>(neighbors, centers), counts = npi.count((neighbors[valid], centers[valid]))
region_group = group_by(centers)
regions, neighbors_per_region = region_group.sum(counts)
fractions = counts / neighbors_per_region[region_group.inverse]
for q in zip(centers, neighbors, fractions): print(q)
</code></pre>
| 2
|
2016-09-06T12:17:54Z
|
[
"python",
"arrays",
"numpy"
] |
Python webdriver: get XPATH from innerHTML
| 39,346,549
|
<p>Is there a way to get the xpath of an webelement knowing only its innerHTML value?</p>
<p>Say I've got a 'Save' button, which is a button with text "Save". Say that the button can change its location on the page with subsequent updates to the system, therefore changing its xpath every time.</p>
<p>Here is an example bit from the page source:</p>
<pre><code><button ng-click="Model.Save()" ng-disabled="Model.SavingChecklist" href="javascript:void(0)" class="btn" translate="">
<span class="ng-scope">Save</span>
</button>
</code></pre>
<p>I want to search the page for the innerHTML value "Save" and return the xpath (of the second line).
Note that "Save" is not a link.</p>
<p>Is it possible?</p>
| 0
|
2016-09-06T10:19:05Z
| 39,346,896
|
<p>You can use following <code>XPath</code> to match any element with <code>innerHTML="Save"</code>:</p>
<pre><code>//*[text()="Save"]
</code></pre>
<p>or in your case:</p>
<pre><code>//button/span[text()="Save"]
</code></pre>
| 0
|
2016-09-06T10:34:42Z
|
[
"python",
"selenium",
"xpath"
] |
Russian character decoding in python
| 39,346,820
|
<p>This question only for python:</p>
<p>I have a city name in a string in Russian language and which is in Unicode form like,</p>
<blockquote>
<p><code>\u041C\u043E\u0441\u043A\u0432\u0430</code></p>
</blockquote>
<p>means </p>
<blockquote>
<p><code>ÐоÑква</code></p>
</blockquote>
<p>How to get original text instead of unicode characters?</p>
<p><strong>Note:</strong> Do not use any import module</p>
| 0
|
2016-09-06T10:31:18Z
| 39,346,971
|
<pre><code>>>> a=u"\u041C\u043E\u0441\u043A\u0432\u0430"
>>> print a
ÐоÑква
</code></pre>
<p>Your string is a unicode string because each character/code point with \u is only usable from a unicode string, you should prefix the string with u. Otherwise is a regular string and each \u counts as a regular ascii character:</p>
<pre><code>>>> len(a)
6
>>> b="\u041C\u043E\u0441\u043A\u0432\u0430"
>>> len(b)
36
</code></pre>
| 5
|
2016-09-06T10:38:33Z
|
[
"python"
] |
Russian character decoding in python
| 39,346,820
|
<p>This question only for python:</p>
<p>I have a city name in a string in Russian language and which is in Unicode form like,</p>
<blockquote>
<p><code>\u041C\u043E\u0441\u043A\u0432\u0430</code></p>
</blockquote>
<p>means </p>
<blockquote>
<p><code>ÐоÑква</code></p>
</blockquote>
<p>How to get original text instead of unicode characters?</p>
<p><strong>Note:</strong> Do not use any import module</p>
| 0
|
2016-09-06T10:31:18Z
| 39,347,688
|
<p>In addition to vz0 answer : Pay attention to script's encoding.</p>
<p>This <strong>file</strong> will works great :</p>
<pre class="lang-py prettyprint-override"><code># coding: utf-8
s = u"\u041C\u043E\u0441\u043A\u0432\u0430"
print(s)
</code></pre>
<p>But this one will lead to an UnicodeEncodeError :</p>
<pre class="lang-py prettyprint-override"><code># coding: ASCII
s = u"\u041C\u043E\u0441\u043A\u0432\u0430"
print(s)
</code></pre>
| 2
|
2016-09-06T11:14:07Z
|
[
"python"
] |
Error while comparing string after transforming from datetime
| 39,346,960
|
<p>I am converting datetime to string and then comparing it with string from stdout.read from a file. But the "==" comparision fails.</p>
<p>Below is my code:</p>
<pre><code>date_input = datetime.datetime.now()
dat = date_input.strftime("%Y-%m-%d %H:%M:%S.%f")
command = 'echo %s > /media/mmcblk0p1/testCard.txt' %dat
try:
stdin, stdout, stderr = self._sshclient.exec_command(command,timeout=10)
command = 'cat /media/mmcblk0p1/testCard.txt'
try:
stdin, stdout, stderr = self._sshclient.exec_command(command, timeout=10)
date_output = stdout.read().decode(encoding='UTF-8')
self.logger.debug("dat=%s date_output=%s ",dat,date_output)
if(date_output == dat): #FAILS
self.logger.debug("read from file successful")
else:
self.logger.debug("read from file unsucessful")
except:
self.logger.exception('%s %s error, readtimeout',
ip, self.__class__.__name__)
self.add_response("read error/timeout")
except :
self.logger.exception('%s %s error, writetimeout',
ip, self.__class__.__name__)
self.add_response("write error/timeout")
</code></pre>
<h2>Output</h2>
<pre><code>dat=2016-09-06 15:49:49.104030 date_output=2016-09-06 15:49:49.104030
read from file unsucessful
dat=2016-09-06 15:49:49.237551 date_output=2016-09-06 15:49:49.237551
read from file unsucessful
</code></pre>
<p>I am unable to figure out the comparision failure, it prints "read from file unsuccessful" Is it for the stdout.read() or datetime.</p>
<p>NOTE: There is no exception in this code, and the values are same if i use print method also.</p>
<p>Any solution is welcome</p>
| 2
|
2016-09-06T10:38:09Z
| 39,347,075
|
<pre><code>>>> a
'2016-09-06 15:49:49.104030'
>>> b
u'2016-09-06 15:49:49.104030'
>>> a == b
True
>>> b = b + "\n"
>>> a == b
False
</code></pre>
<p>There could be whitespace characters in one of your strings, remove them using .strip()</p>
| 1
|
2016-09-06T10:43:51Z
|
[
"python",
"datetime"
] |
Error while comparing string after transforming from datetime
| 39,346,960
|
<p>I am converting datetime to string and then comparing it with string from stdout.read from a file. But the "==" comparision fails.</p>
<p>Below is my code:</p>
<pre><code>date_input = datetime.datetime.now()
dat = date_input.strftime("%Y-%m-%d %H:%M:%S.%f")
command = 'echo %s > /media/mmcblk0p1/testCard.txt' %dat
try:
stdin, stdout, stderr = self._sshclient.exec_command(command,timeout=10)
command = 'cat /media/mmcblk0p1/testCard.txt'
try:
stdin, stdout, stderr = self._sshclient.exec_command(command, timeout=10)
date_output = stdout.read().decode(encoding='UTF-8')
self.logger.debug("dat=%s date_output=%s ",dat,date_output)
if(date_output == dat): #FAILS
self.logger.debug("read from file successful")
else:
self.logger.debug("read from file unsucessful")
except:
self.logger.exception('%s %s error, readtimeout',
ip, self.__class__.__name__)
self.add_response("read error/timeout")
except :
self.logger.exception('%s %s error, writetimeout',
ip, self.__class__.__name__)
self.add_response("write error/timeout")
</code></pre>
<h2>Output</h2>
<pre><code>dat=2016-09-06 15:49:49.104030 date_output=2016-09-06 15:49:49.104030
read from file unsucessful
dat=2016-09-06 15:49:49.237551 date_output=2016-09-06 15:49:49.237551
read from file unsucessful
</code></pre>
<p>I am unable to figure out the comparision failure, it prints "read from file unsuccessful" Is it for the stdout.read() or datetime.</p>
<p>NOTE: There is no exception in this code, and the values are same if i use print method also.</p>
<p>Any solution is welcome</p>
| 2
|
2016-09-06T10:38:09Z
| 39,347,082
|
<p>Have you tried using <code>.strip()</code> </p>
<p><a href="http://www.tutorialspoint.com/python/string_strip.htm" rel="nofollow">http://www.tutorialspoint.com/python/string_strip.htm</a></p>
<pre><code>Example:
if(date_output.strip() == dat.strip()):
</code></pre>
<p>If there are any whitespace characters on either end of the string (which i think there are) then .strip() takes them out and we can compare the strings without the whitespace characters.</p>
| 1
|
2016-09-06T10:44:10Z
|
[
"python",
"datetime"
] |
Error while comparing string after transforming from datetime
| 39,346,960
|
<p>I am converting datetime to string and then comparing it with string from stdout.read from a file. But the "==" comparision fails.</p>
<p>Below is my code:</p>
<pre><code>date_input = datetime.datetime.now()
dat = date_input.strftime("%Y-%m-%d %H:%M:%S.%f")
command = 'echo %s > /media/mmcblk0p1/testCard.txt' %dat
try:
stdin, stdout, stderr = self._sshclient.exec_command(command,timeout=10)
command = 'cat /media/mmcblk0p1/testCard.txt'
try:
stdin, stdout, stderr = self._sshclient.exec_command(command, timeout=10)
date_output = stdout.read().decode(encoding='UTF-8')
self.logger.debug("dat=%s date_output=%s ",dat,date_output)
if(date_output == dat): #FAILS
self.logger.debug("read from file successful")
else:
self.logger.debug("read from file unsucessful")
except:
self.logger.exception('%s %s error, readtimeout',
ip, self.__class__.__name__)
self.add_response("read error/timeout")
except :
self.logger.exception('%s %s error, writetimeout',
ip, self.__class__.__name__)
self.add_response("write error/timeout")
</code></pre>
<h2>Output</h2>
<pre><code>dat=2016-09-06 15:49:49.104030 date_output=2016-09-06 15:49:49.104030
read from file unsucessful
dat=2016-09-06 15:49:49.237551 date_output=2016-09-06 15:49:49.237551
read from file unsucessful
</code></pre>
<p>I am unable to figure out the comparision failure, it prints "read from file unsuccessful" Is it for the stdout.read() or datetime.</p>
<p>NOTE: There is no exception in this code, and the values are same if i use print method also.</p>
<p>Any solution is welcome</p>
| 2
|
2016-09-06T10:38:09Z
| 39,347,254
|
<p><a href="http://linux.die.net/man/1/echo" rel="nofollow"><code>echo</code></a> adds a new line character to the end of its output, therefore the date is written to <code>/media/mmcblk0p1/testCard.txt</code> with a trailing new line. Either strip it off when you read it back in, or use the <code>-n</code> option to <code>echo</code> to suppress the new line on output like this:</p>
<pre><code>command = 'echo -n %s > /media/mmcblk0p1/testCard.txt' %dat
</code></pre>
| 1
|
2016-09-06T10:53:06Z
|
[
"python",
"datetime"
] |
Setting MultiColumn as index has issues with index names
| 39,346,999
|
<p>Here is how I create my multi column table:</p>
<pre><code>whatFields = ['mean', 'mom_2', 'n']
groupbyFields = ['foo', 'bar']
topFields = ['desc']*len(groupbyFields)
topFields += ['price']*len(whatFields)
topFields += ['units']*len(whatFields)
bottomFields = groupbyFields + whatFields + whatFields
resultsDf = pd.DataFrame(columns=pd.MultiIndex.from_arrays([topFields, bottomFields]))
indexFields = [('desc', field) for field in groupbyFields]
resultsDf.set_index(indexFields, inplace=True)
</code></pre>
<p>Here's the empty result:</p>
<pre><code>Empty DataFrame
Columns: [(price, mean), (price, mom_2), (price, n), (units, mean), (units, mom_2), (units, n)]
Index: []
>>> resultsDf.index
Out[2]:
MultiIndex(levels=[[], []],
labels=[[], []],
names=[('desc', 'foo'), ('desc', 'bar')])
</code></pre>
<p>However, after filling up, it looks like this:</p>
<pre><code> price units
mean mom_2 n mean mom_2 n
(desc, foo) (desc, bar)
1500002071 4292 NaN NaN NaN NaN NaN NaN
4246 NaN NaN NaN NaN NaN NaN
342 NaN NaN NaN NaN NaN NaN
104 NaN NaN NaN NaN NaN NaN
4218 2.59 0 1 NaN NaN NaN
</code></pre>
<p>the problem is that index fields have these weird names in tuple form, while columns have "proper" names now in the multi column shape.</p>
<p>You might think this is because they're an index. No:</p>
<pre><code> (desc, foo) (desc, bar) price units
mean mom_2 n mean mom_2 n
0 1500002071 4292 NaN NaN NaN NaN NaN NaN
1 1500002071 4246 NaN NaN NaN NaN NaN NaN
2 1500002071 342 NaN NaN NaN NaN NaN NaN
3 1500002071 104 NaN NaN NaN NaN NaN NaN
4 1500002071 4218 2.59 0 1 NaN NaN NaN
</code></pre>
<p>Why is the index not following the columns in terms of multi layout? Ultimatively, I'd like to access the index simply via <code>foo</code> and <code>bar</code> (or real multi index, at least not this pseudo tuples).</p>
<p>How could I achieve that? Is there a better way to generate my empty df to begin with?</p>
| 0
|
2016-09-06T10:39:53Z
| 39,360,998
|
<p>Is this what you were looking for? I wasn't exactly sure how you wanted to main index set up. </p>
<p>Two ways:</p>
<pre><code>In [1]: import numpy as np
In [2]: import pandas as pd
i
In [3]: import itertools as it
In [4]: whatFields = ['mean', 'mom_2', 'n']
...: groupbyFields = ['foo', 'bar']
...: topFields= ['price', 'units']
...: descriptions = [11, 22, 33, 44]
...:
...: top_index = list(it.product(topFields, whatFields))
...:
...: main_index = list(it.product(descriptions, groupbyFields))
...: main_index
Out[4]:
[(11, 'foo'),
(11, 'bar'),
(22, 'foo'),
(22, 'bar'),
(33, 'foo'),
(33, 'bar'),
(44, 'foo'),
(44, 'bar')]
In [5]: top_index
Out[5]:
[('price', 'mean'),
('price', 'mom_2'),
('price', 'n'),
('units', 'mean'),
('units', 'mom_2'),
('units', 'n')]
In [6]: resultsDf = pd.DataFrame(index=pd.MultiIndex.from_tuples(main_index)
...: .set_names(['desc', 'something']),
...: columns=pd.MultiIndex.from_tuples(top_index),
...: data=np.random.rand(len(main_index), len(top_index))
...: ).sort_index()
In [7]: resultsDf
Out[7]:
price units
mean mom_2 n mean mom_2 n
desc something
11 bar 0.415331 0.153503 0.750690 0.505439 0.781057 0.102450
foo 0.444163 0.921779 0.587966 0.988859 0.747277 0.645065
22 bar 0.205548 0.835086 0.630778 0.936277 0.587607 0.644636
foo 0.907772 0.927121 0.457286 0.881467 0.091484 0.217839
33 bar 0.207454 0.670291 0.609697 0.024396 0.808362 0.738188
foo 0.838015 0.058354 0.804375 0.704137 0.760060 0.638933
44 bar 0.577411 0.085774 0.394033 0.798052 0.107777 0.852888
foo 0.528873 0.902225 0.098982 0.611146 0.122890 0.887364
</code></pre>
<p>Or:</p>
<pre><code>In [10]: resultsDf = pd.DataFrame(columns=pd.MultiIndex.from_tuples(top_index),
...: data=np.random.rand(len(main_index), len(top_index)) )
...:
...: resultsDf['desc'], resultsDf['something'] = zip(*main_index)
...:
...:
...: resultsDf = resultsDf.set_index(['desc', 'something']).sort_index()
...:
In [11]: resultsDf
Out[11]:
price units
mean mom_2 n mean mom_2 n
desc something
11 foo 0.205574 0.673159 0.772009 0.598809 0.070022 0.332420
bar 0.844376 0.602825 0.433186 0.420408 0.299380 0.354098
22 foo 0.341226 0.489068 0.784226 0.721386 0.866248 0.113838
bar 0.729578 0.209731 0.533399 0.993587 0.340383 0.895143
33 foo 0.629427 0.285344 0.634120 0.940294 0.378314 0.416081
bar 0.251746 0.022984 0.415058 0.322093 0.719954 0.251906
44 foo 0.247829 0.085609 0.680114 0.760157 0.493465 0.659629
bar 0.667425 0.749589 0.578318 0.190334 0.131337 0.090083
In [13]: resultsDf.loc[(22, "bar")]
Out[13]:
price mean 0.729578
mom_2 0.209731
n 0.533399
units mean 0.993587
mom_2 0.340383
n 0.895143
Name: (22, bar), dtype: float64
In [14]: resultsDf.loc[(22, "bar"), "units"]
Out[14]:
mean 0.993587
mom_2 0.340383
n 0.895143
Name: (22, bar), dtype: float64
</code></pre>
| 0
|
2016-09-07T04:00:21Z
|
[
"python",
"pandas"
] |
cannot use python intersection set with ROS point lists
| 39,347,119
|
<p>i try to find a intersection set of two position lists, in ROS</p>
<p>so i write a code in python, and i have two lists, such as :</p>
<pre><code>position1 = Point()
position1.x =1
position2 = Point()
position2.x=2
a = [copy.deepcopy(position1),copy.deepcopy(position2)]
b = [copy.deepcopy(position1)]
</code></pre>
<p>then, when i try to get intersection of those two list a and b</p>
<p>it return me an answer: set([])</p>
<p>that's ridiculous,</p>
<p>normally i should have an answer like: set(a).intersection(set(b)) = set([position1])</p>
<p>if anyone could help me to fix this problem?</p>
<p>it's great thankful for viewing this problem</p>
<p>and i appreciate for your watching and answering.</p>
<p>thanks in advance.</p>
<p>here is my testing code</p>
<pre><code>import rospy,copy
from geometry_msgs.msg import Point
class test():
def __init__(self):
position1 = Point()
position1.x =1
position2 = Point()
position2.x=2
a = [copy.deepcopy(position1),copy.deepcopy(position2)]
b = [copy.deepcopy(position1)]
print set(a).intersection(set(b))
print 'a', set(a),'\n'
print 'b', set(b)
if __name__=='__main__':
try:
rospy.loginfo ("initialization system")
test()
rospy.loginfo ("process done and quit")
except rospy.ROSInterruptException:
rospy.loginfo("robot twist node terminated.")
</code></pre>
<p>BTW,ROS Point type is posted here: <a href="http://docs.ros.org/jade/api/geometry_msgs/html/msg/Point.html" rel="nofollow">http://docs.ros.org/jade/api/geometry_msgs/html/msg/Point.html</a></p>
| 1
|
2016-09-06T10:45:59Z
| 39,347,710
|
<p>Well, it doesn't returns <code>set([])</code> but prints <code>set()</code> (nitpicking maybe but it's not the same thing).</p>
<p>Actually it's the expected behavior :</p>
<ul>
<li>a set keeps only unique elements</li>
<li>unique is defined by having the same hash </li>
<li>the default hash comes from <strong>hash</strong>() method</li>
<li><strong>hash</strong>() uses the id of the object</li>
<li>you deepcopy your objects so they have different ids</li>
<li>so they're different</li>
</ul>
<p>I don't know why you think you need deepcopy but if you put your points directly in lists, it will works as expected</p>
| 0
|
2016-09-06T11:15:31Z
|
[
"python",
"set",
"intersection",
"ros"
] |
cannot use python intersection set with ROS point lists
| 39,347,119
|
<p>i try to find a intersection set of two position lists, in ROS</p>
<p>so i write a code in python, and i have two lists, such as :</p>
<pre><code>position1 = Point()
position1.x =1
position2 = Point()
position2.x=2
a = [copy.deepcopy(position1),copy.deepcopy(position2)]
b = [copy.deepcopy(position1)]
</code></pre>
<p>then, when i try to get intersection of those two list a and b</p>
<p>it return me an answer: set([])</p>
<p>that's ridiculous,</p>
<p>normally i should have an answer like: set(a).intersection(set(b)) = set([position1])</p>
<p>if anyone could help me to fix this problem?</p>
<p>it's great thankful for viewing this problem</p>
<p>and i appreciate for your watching and answering.</p>
<p>thanks in advance.</p>
<p>here is my testing code</p>
<pre><code>import rospy,copy
from geometry_msgs.msg import Point
class test():
def __init__(self):
position1 = Point()
position1.x =1
position2 = Point()
position2.x=2
a = [copy.deepcopy(position1),copy.deepcopy(position2)]
b = [copy.deepcopy(position1)]
print set(a).intersection(set(b))
print 'a', set(a),'\n'
print 'b', set(b)
if __name__=='__main__':
try:
rospy.loginfo ("initialization system")
test()
rospy.loginfo ("process done and quit")
except rospy.ROSInterruptException:
rospy.loginfo("robot twist node terminated.")
</code></pre>
<p>BTW,ROS Point type is posted here: <a href="http://docs.ros.org/jade/api/geometry_msgs/html/msg/Point.html" rel="nofollow">http://docs.ros.org/jade/api/geometry_msgs/html/msg/Point.html</a></p>
| 1
|
2016-09-06T10:45:59Z
| 39,360,094
|
<p>@Ninja Puppy delete an answer, which i think it helpful as well, so i add it here. while, if this is forbidden or Ninja Puppy feel sick of this, i will delete this answer too. following is his answer</p>
<blockquote>
<p>Okay, going by your comment:</p>
<pre><code>a[0]==b[0] is true, because they are both position1, but hash(a[0]) and hash(b[0]) is different
</code></pre>
<p>One way is to create a new Point that supports a hash that's
meaningful for use in a set, eg:</p>
<pre><code>class NewPoint(Point):
def __hash__(self):
return hash(self.x) # maybe self.y as well?
</code></pre>
<p>Ideally your hash should include the same attributes that
<code>Point.__eq__</code> uses.</p>
<p>Then use NewPoint to construct your objects instead.</p>
</blockquote>
| 0
|
2016-09-07T01:45:34Z
|
[
"python",
"set",
"intersection",
"ros"
] |
Loop creates unwanted duplicate
| 39,347,180
|
<p>I am trying to pull in data from an input file and iterate over a symbol file to create output for an output file but my code is creating an unwanted duplicate in the output file. The input file is very big so I need to filter the input first before I reference it against the symbol (city/state) file to generate the output.</p>
<pre><code>i_file = ('InputFile.csv')
o_file = ('OutputFile.csv')
symbol_file = ('SymbolFile.csv')
City = 'Tampa'
State = 'FL'
with open(symbol_file, 'r') as symfile:
with open(i_file, 'r') as infile:
with open(o_file, 'w') as outfile:
reader = csv.reader(infile)
symbol = csv.reader(symfile)
writer = csv.writer(outfile, delimiter = ',')
for row in reader:
if (row[2] == city and row[3] == state):
for line in symbol:
if (row[4] == line[0]):
nline = ([str(city)] + [str(line[3])])
writer.writerow(nline)
symfile.seek(0)
</code></pre>
| -3
|
2016-09-06T10:49:17Z
| 39,349,497
|
<blockquote>
<p>I only want one line for every line in the input file IF there is a matching line in the symbol file. </p>
</blockquote>
<p>Try it like this then:</p>
<pre><code>i_file = 'InputFile.csv'
o_file = 'OutputFile.csv'
symbol_file = 'SymbolFile.csv'
city = 'Tampa'
state = 'FL'
# load the symbols from the symbol file and store them in a dictionary
symbols = {}
with open(symbol_file, 'r') as symfile:
for line in csv.reader(symfile):
# key is line[0] which is the thing we match against
# value is line[3] which appears to be the only thing of interest later
symbols[line[0]] = line[3]
# now read the other files
with open(i_file, 'r') as infile, open(o_file, 'w') as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile, delimiter = ',')
for row in reader:
# check if `row[4] in symbols`
# which essentially checks whether row[4] is equal to a line[0] in the symbols file
if row[2] == city and row[3] == state and row[4] in symbols:
# get the symbol
symbol = symbols[row[4]]
# write output
nline = [city, symbol]
writer.writerow(nline)
</code></pre>
| 0
|
2016-09-06T12:52:35Z
|
[
"python",
"python-3.x",
"loops"
] |
Find two most distant points in a set of points in 3D space
| 39,347,209
|
<p>I need to find the diameter of the points cloud (two points with maximum distance between them) in 3-dimensional space. As a temporary solution, right now I'm just iterating through all possible pairs and comparing the distance between them, which is a very slow, <code>O(n^2)</code> solution.</p>
<p>I believe it can be done in <code>O(n log n)</code>. It's a fairly easy task in 2D (just find the <strong>convex hull</strong> and then apply the <strong>rotating calipers</strong> algorithm), but in 3D I can't imagine how to use rotating calipers, since there is no way to order the points. </p>
<p>Is there any simple way to do it (or ready-to-use implementation in <code>python</code> or <code>C/C++</code>)? </p>
<p><strong>PS</strong>: There are similar questions on StackOverflow, but the answers that I found only refers to Rotating Calipers (or similar) algorithms, which works fine in 2D situation but not really clear how to implement in 3D (or higher dimensionals). </p>
| 3
|
2016-09-06T10:50:39Z
| 39,347,974
|
<p>While O(n log n) expected time algorithms exist in 3d, they seem tricky to implement (while staying competitive to brute-force O(n^2) algorithms).</p>
<p>An algorithm is described in <a href="http://dl.acm.org/citation.cfm?id=378662" rel="nofollow">Har-Peled 2001</a>. The authors provide a <a href="http://sarielhp.org/research/papers/00/diam.html" rel="nofollow">source code</a> than can optionally be used for optimal computation. I was not able to download the latest version, the "old" version could be enough for your purpose, or you might want to contact the authors for the code.</p>
<p>An alternative approach is presented in <a href="http://www.worldscientific.com/doi/abs/10.1142/S0218195902001006" rel="nofollow">Malandain & Boissonnat 2002</a> and the authors <a href="http://www-sop.inria.fr/members/Gregoire.Malandain/diameter/" rel="nofollow">provide code</a>. Altough this algorithm is presented as approximate in higher dimensions, it could fit your purpose. Note that their code provide an implementation of Har-Peled's method for exact computation that you might also check.</p>
<p>In any case, in a real-world usage you should always check that your algorithm remains competitive with respect to the naïve O(n^2) approach.</p>
| 2
|
2016-09-06T11:28:39Z
|
[
"python",
"c++",
"geometry",
"convex-hull"
] |
model.objects.create in views is not working in my django project?
| 39,347,283
|
<p>This is <code>models.py</code></p>
<pre><code>from django.db import models
class Iot(models.Model):
user = models.CharField(max_length="50")
email = models.EmailField()
</code></pre>
<p>This is my <code>views.py</code></p>
<pre><code>def Test(request):
if request.method == 'PUT':
user = request.data['user']
email = request.data['email']
try:
s = Iot.objects.create(user=user)
print s.user
s.email = email
s.save()
return Response('ok', status=status.HTTP_200_OK)
except:
return Response('error',status=status.HTTP_400_BAD_REQUEST)
</code></pre>
<p>I'm using django rest_framework. When i send data it does not store in database and returns:</p>
<blockquote>
<p>('error',status=status.HTTP_400_BAD_REQUEST)</p>
</blockquote>
| -2
|
2016-09-06T10:54:40Z
| 39,347,478
|
<p>Most likely that error happens because you try to create Iot without email, but it is required field.
You should do something like</p>
<pre><code>Iot.objects.create(user=user, email=email)
</code></pre>
<p>To make your code working in the way you choose(set attributes one by one and not at once) you need to get rid of create and do the following:</p>
<pre><code>s = Iot(user=user)
s.email = email
s.save()
</code></pre>
<p>there are two different ways to create the entity in the model with on request. Create calls save() method inside, so they are quite the same, but create more handy in this case.</p>
<p>Also normally you should avoid doing create() and then save(), since it will appears two queries to DB.</p>
<p>UPD: +1 to @Daniel's comment about exception</p>
| 0
|
2016-09-06T11:04:05Z
|
[
"python",
"django",
"django-rest-framework"
] |
How to use glob in python to search through a specific folder
| 39,347,383
|
<p>I am currently working on a small piece of code that I want to go through a user-inputted folder and rename all the files in there depending on certain criteria. </p>
<p>At the moment, the user enters the filename using this code:</p>
<pre><code>src = input("Please enter the folder path where the files are located")
</code></pre>
<p>Then, I use the glob module to rename the files if they meet certain criteria, e.g:</p>
<pre><code>for f in glob.glob("*reference*" + "*letter*"):
new_filename = "203 Reference Letter" + " " + name
os.rename(f,new_filename)
</code></pre>
<p>Now all this works perfectly if the .py script is located in the folder with all the files in it, however my question is as follows: How can I basically combine the 2 bits of code above? Basically, how do I make it so that the user inputs a filepath, and the glob module then takes that path and renames the files in that folder? </p>
<p>Any help is greatly appreciated! Thank!</p>
| 1
|
2016-09-06T10:59:26Z
| 39,347,583
|
<p>You can use <a href="https://docs.python.org/3/library/os.path.html#os.path.join" rel="nofollow">os.path.join</a> to join the user input to the desired pattern:</p>
<pre><code>import os.path
src = input('Please enter the folder path where the files are located: ')
if not os.path.isdir(src):
print('Invalid given path.')
exit(1)
path = os.path.join(src, '*reference*letter*')
for f in glob.glob(path):
new_filename = '203 Reference Letter {}'.format(name)
os.rename(f, new_filename)
</code></pre>
<p>I do not know what is the pattern used in <code>glob</code>, but basically you join the user input folder to any pattern.</p>
| 2
|
2016-09-06T11:08:18Z
|
[
"python",
"python-3.x",
"glob"
] |
Python 3: How to compare two big files fastest?
| 39,347,463
|
<p>In <strong>"Big_file.txt</strong>", I want to extract UIDs of <strong>"User A"</strong> which is not duplicated with UIDs in "<strong>Small_file.txt</strong>". I wrote the following code but it seems it will never stop running. So, how to speed up the process ? Thank you very much :)</p>
<pre><code>import json
uid_available = []
linesB = []
for line in open('E:/Small_file.txt'):
line = json.loads(line)
linesB.append(hash(line['uid']))
for line in open('E:/Big_file.txt'):
line = json.loads(line)
if hash(line['uid']) not in linesB and line['user'] == 'User A':
uid_available.append(line['uid'])
</code></pre>
<p>This is format of Big_file.txt (has 10 millions lines):</p>
<pre><code>{'uid': 111, 'user': 'User A'}
{'uid': 222, 'user': 'User A'}
{'uid': 333, 'user': 'User A'}
{'uid': 444, 'user': 'User B'}
{'uid': 555, 'user': 'User C'}
{'uid': 666, 'user': 'User C'}
</code></pre>
<p>This is format of Small_file.txt (has few millions lines):</p>
<pre><code>{'uid': 333, 'user': 'User A'}
{'uid': 444, 'user': 'User B'}
{'uid': 555, 'user': 'User C'}
</code></pre>
<p>The output I expect:</p>
<pre><code>111
222
</code></pre>
| 2
|
2016-09-06T11:03:17Z
| 39,347,574
|
<p>looking up an item in a list takes <code>O(n)</code> time. If you use a <code>dict</code> or a <code>set</code> you can improve it to <code>O(1)</code>.</p>
<p>shortest modification you can do is :</p>
<pre><code>linesB = []
for line in open('E:/Small_file.txt'):
line = json.loads(line)
linesB.append(hash(line['uid']))
linesB = set(linesB)
</code></pre>
<p>or to do it right </p>
<pre><code>linesB = set()
for line in open('E:/Small_file.txt'):
line = json.loads(line)
linesB.add(hash(line['uid']))
</code></pre>
| 3
|
2016-09-06T11:07:59Z
|
[
"python",
"json",
"hash",
"compare"
] |
Python 3.2 how to set correct and incorrect answer on questions inside 2 lists
| 39,347,623
|
<p>I am making 2 sets of question, first set (list1) is all yes and second (list2) is all no 10 questions each then I used random.choice to randomly pick a question from the 2 sets. I want to make an output of "correct" whenever random.choice picks a question from list 1 when the user answered "Y" same with list2 if the user answered "N". Here is my code:</p>
<pre><code>import random
Count = 0
list1 = ['1+1=2?','2+2=4?','3+3=6?','4+4=8?','5+5=10?','15+15=30?','16+16=32?','17+17=34?','18+18=36?','19+19=38?']
list2 = list2 = ['20+20=10?','6+6=2?','7+7=11?','8+8=32?','9+9=21?','10+10=0?','11+11=4?','12+12=12?','13+13=25?','14+14=13?']
list = list1 + list2
while(Count < 5):
print(random.choice(list))
Answer = input("Answer: ").upper()
Count = Count+1
if(list == list1):
if(Answer == "Y"):
print("Correct")
else:
print("Incorrect")
if(list == list2):
if(Answer == "N"):
print("Correct")
else:
print("Incorrect")
</code></pre>
<p>I cannot figure out how to output the correct and incorrect statement. Any help would be truly appreciated.</p>
| 0
|
2016-09-06T11:10:37Z
| 39,347,740
|
<p>First off, don't use python keywords and built-in type names as your variable names.</p>
<p>You can check the membership of random choice simply with <code>in</code> operator.</p>
<pre><code>import random
list1 = ['1+1=2?','2+2=4?','3+3=6?','4+4=8?','5+5=10?','15+15=30?','16+16=32?','17+17=34?','18+18=36?','19+19=38?']
list2 = ['20+20=10?','6+6=2?','7+7=11?','8+8=32?','9+9=21?','10+10=0?','11+11=4?','12+12=12?','13+13=25?','14+14=13?']
lst = list1 + list2
for _ in range(5):
value = random.choice(lst)
print(value)
Answer = input("Answer: ").upper()
if(Answer == "Y"):
if value in list1:
print("Correct")
else:
print("Incorrect")
elif(Answer == "N"):
if value in list2:
print("Correct")
else:
print("Incorrect")
else:
print("Enter Y or N")
</code></pre>
| 2
|
2016-09-06T11:17:05Z
|
[
"python",
"python-3.x"
] |
Python 3.2 how to set correct and incorrect answer on questions inside 2 lists
| 39,347,623
|
<p>I am making 2 sets of question, first set (list1) is all yes and second (list2) is all no 10 questions each then I used random.choice to randomly pick a question from the 2 sets. I want to make an output of "correct" whenever random.choice picks a question from list 1 when the user answered "Y" same with list2 if the user answered "N". Here is my code:</p>
<pre><code>import random
Count = 0
list1 = ['1+1=2?','2+2=4?','3+3=6?','4+4=8?','5+5=10?','15+15=30?','16+16=32?','17+17=34?','18+18=36?','19+19=38?']
list2 = list2 = ['20+20=10?','6+6=2?','7+7=11?','8+8=32?','9+9=21?','10+10=0?','11+11=4?','12+12=12?','13+13=25?','14+14=13?']
list = list1 + list2
while(Count < 5):
print(random.choice(list))
Answer = input("Answer: ").upper()
Count = Count+1
if(list == list1):
if(Answer == "Y"):
print("Correct")
else:
print("Incorrect")
if(list == list2):
if(Answer == "N"):
print("Correct")
else:
print("Incorrect")
</code></pre>
<p>I cannot figure out how to output the correct and incorrect statement. Any help would be truly appreciated.</p>
| 0
|
2016-09-06T11:10:37Z
| 39,347,980
|
<p>My solution is slightly different!
Save the equations in the list with the double == and after do in this way:</p>
<pre><code>import random
list1 = ['1+1==2','2+2==4','3+3==6','4+4==8','5+5==10','15+15==30','16+16==32','17+17==34','18+18==36','19+19==38']
list2 = ['20+20==10','6+6==2','7+7==11','8+8==32','9+9==21','10+10==0','11+11==4','12+12==12','13+13==25','14+14==13']
lst = list1 + list2
for _ in range(5):
value = random.choice(lst)
print(value)
Answer = input("Answer: ").upper()
state = eval(value)
if(Answer == "Y" and state is True) or (Answer == "N" and state is False):
print("Correct")
else:
print("Incorrect")
</code></pre>
<p>The eval function take in input one string containing the operation and solve it. In this case it's a logical operation so it will return you True or False.
Try the eval function on the Python shell if you don't know it.</p>
<p>In this way if you want you could use only one list.</p>
<p>In that case:</p>
<pre><code>import random
lst = ['1+1==2','2+2==4','3+2==6','4+3==8','5+5==10','15+8==30','16+16==32','17+22==34','18+30==36','19+19==38']
for _ in range(5):
value = random.choice(lst)
print(value)
Answer = input("Answer: ").upper()
state = eval(value)
if(Answer == "Y" and state is True) or (Answer == "N" and state is False):
print("Correct")
else:
print("Incorrect")
</code></pre>
| 0
|
2016-09-06T11:28:52Z
|
[
"python",
"python-3.x"
] |
Python 3.2 how to set correct and incorrect answer on questions inside 2 lists
| 39,347,623
|
<p>I am making 2 sets of question, first set (list1) is all yes and second (list2) is all no 10 questions each then I used random.choice to randomly pick a question from the 2 sets. I want to make an output of "correct" whenever random.choice picks a question from list 1 when the user answered "Y" same with list2 if the user answered "N". Here is my code:</p>
<pre><code>import random
Count = 0
list1 = ['1+1=2?','2+2=4?','3+3=6?','4+4=8?','5+5=10?','15+15=30?','16+16=32?','17+17=34?','18+18=36?','19+19=38?']
list2 = list2 = ['20+20=10?','6+6=2?','7+7=11?','8+8=32?','9+9=21?','10+10=0?','11+11=4?','12+12=12?','13+13=25?','14+14=13?']
list = list1 + list2
while(Count < 5):
print(random.choice(list))
Answer = input("Answer: ").upper()
Count = Count+1
if(list == list1):
if(Answer == "Y"):
print("Correct")
else:
print("Incorrect")
if(list == list2):
if(Answer == "N"):
print("Correct")
else:
print("Incorrect")
</code></pre>
<p>I cannot figure out how to output the correct and incorrect statement. Any help would be truly appreciated.</p>
| 0
|
2016-09-06T11:10:37Z
| 39,347,991
|
<p>A more pythonic way would be:</p>
<pre><code>list1 = ['1 + 1 = 2? ', '2 + 2 = 4? ', '3 + 3 = 6? ', '4 + 4 = 8? ',
'5 + 5 = 10? ', '15 + 15 = 30? ', '16 + 16 = 32? ', '17 + 17 = 34? ',
'18 + 18 = 36? ', '19 + 19 = 38? ']
list2 = ['20 + 20 = 10? ', '6 + 6 = 2? ', '7 + 7 = 11? ', '8 + 8 = 32? ',
'9 + 9 = 21? ', '10 + 10 = 0? ', '11 + 11 = 4? ', '12 + 12 = 12? ',
'13 + 13 = 25? ', '14 + 14 = 13? ']
for _ in range(5):
chosen_list = random.choice([list1, list2])
chosen_question = random.choice(chosen_list)
answer = raw_input(chosen_question).upper()
if chosen_question in list1 and answer == 'Y':
print('Correct')
elif chosen_question in list2 and answer == 'N':
print('Correct')
else:
print('Incorrect')
</code></pre>
| 0
|
2016-09-06T11:29:18Z
|
[
"python",
"python-3.x"
] |
Python 3.2 how to set correct and incorrect answer on questions inside 2 lists
| 39,347,623
|
<p>I am making 2 sets of question, first set (list1) is all yes and second (list2) is all no 10 questions each then I used random.choice to randomly pick a question from the 2 sets. I want to make an output of "correct" whenever random.choice picks a question from list 1 when the user answered "Y" same with list2 if the user answered "N". Here is my code:</p>
<pre><code>import random
Count = 0
list1 = ['1+1=2?','2+2=4?','3+3=6?','4+4=8?','5+5=10?','15+15=30?','16+16=32?','17+17=34?','18+18=36?','19+19=38?']
list2 = list2 = ['20+20=10?','6+6=2?','7+7=11?','8+8=32?','9+9=21?','10+10=0?','11+11=4?','12+12=12?','13+13=25?','14+14=13?']
list = list1 + list2
while(Count < 5):
print(random.choice(list))
Answer = input("Answer: ").upper()
Count = Count+1
if(list == list1):
if(Answer == "Y"):
print("Correct")
else:
print("Incorrect")
if(list == list2):
if(Answer == "N"):
print("Correct")
else:
print("Incorrect")
</code></pre>
<p>I cannot figure out how to output the correct and incorrect statement. Any help would be truly appreciated.</p>
| 0
|
2016-09-06T11:10:37Z
| 39,348,183
|
<p>Rather than searching the two lists for the chosen question it's simpler to randomly choose a list and then choose a question from that list. This approach will have the same probability of choosing a given question as your approach as long as both lists have the same length.</p>
<p>We can still combine the two lists into a single data structure; the code below combines them into a dictionary, with the answer as the key.</p>
<pre><code>from random import choice
questions = {
'Y': [
'1+1=2?', '2+2=4?', '3+3=6?', '4+4=8?', '5+5=10?', '15+15=30?',
'16+16=32?', '17+17=34?', '18+18=36?', '19+19=38?',
],
'N': [
'20+20=10?', '6+6=2?', '7+7=11?', '8+8=32?', '9+9=21?', '10+10=0?',
'11+11=4?', '12+12=12?', '13+13=25?', '14+14=13?',
],
}
for _ in range(5):
key = choice('YN')
print(choice(questions[key]))
answer = input("Answer: ").upper()
if answer == key:
print("Correct")
else:
print("Incorrect")
</code></pre>
<p><strong>typical output</strong></p>
<pre><code>14+14=13?
Answer: N
Correct
19+19=38?
Answer: n
Incorrect
11+11=4?
Answer: Y
Incorrect
3+3=6?
Answer: y
Correct
13+13=25?
Answer: n
Correct
</code></pre>
<p>We can make the code more compact by replacing the <code>if...else</code> block with this:</p>
<pre><code>print(("Incorrect", "Correct")[answer == key])
</code></pre>
<p>That works because <code>False</code> has a numeric value of 0 and <code>True</code> has a numeric value of 1.</p>
| 0
|
2016-09-06T11:40:27Z
|
[
"python",
"python-3.x"
] |
Add user scripts folder to Maya
| 39,347,681
|
<p>I tried all methods explained on several documentation pages.</p>
<p>I modified the <strong>userSetup.mel</strong> file and it adds the folder with this code:</p>
<pre><code>string $s = `getenv MAYA_SCRIPT_PATH` + ";C:/MyScripts";
putenv "MAYA_SCRIPT_PATH" $s;
</code></pre>
<p>It didn't work. I also tried to do a "rehash" after doing putenv.</p>
<p>I removed that userSetup.mel file and modified the <strong>maya.env</strong> file using this other variable (since if I do this to MAYA_SCRIPT_PATH it breaks maya because overrides everything it had)</p>
<pre><code>USER_SCRIPT_PATH = C:/MyScripts
</code></pre>
<p>Anything works when I do "import folder" on a python tab. Folder is inside MyScripts folder, and there's a init file for all of them. It's not a python error, this folder works under maya/scripts folder.</p>
<p>It's not very clear why USER_SCRIPT_PATH is not mentioned anywhere in the docs as an official variable, no information about why any of those works. The folder ends up on the environment variable using getenv on MEL, but code is not loaded.</p>
| 0
|
2016-09-06T11:13:47Z
| 39,348,889
|
<p>you can also add the path like:</p>
<pre><code>import sys
sys.path.append("C:/MyScripts")
import my_module
reload(my_module)
my_module.run()
</code></pre>
<p>if you want that maya start with this env, you need a batch file(with all custom env paths like arnold or houdini engine or your own plugins) or a wrapper(more for pipelines with different maya setting for different departments like maya-modeling or maya-fx). this are the default env paths...</p>
<pre><code>-MAYA_PLUG_IN_PATH
-MAYA_MODULE_PATH
-MAYA_SCRIPT_PATH
-USER_SCRIPT_PATH
-PYTHONPATH
-MAYA_SHELF_PATH
-XBMLANGPATH
</code></pre>
| 0
|
2016-09-06T12:18:27Z
|
[
"python",
"python-2.7",
"maya",
"mel"
] |
Add user scripts folder to Maya
| 39,347,681
|
<p>I tried all methods explained on several documentation pages.</p>
<p>I modified the <strong>userSetup.mel</strong> file and it adds the folder with this code:</p>
<pre><code>string $s = `getenv MAYA_SCRIPT_PATH` + ";C:/MyScripts";
putenv "MAYA_SCRIPT_PATH" $s;
</code></pre>
<p>It didn't work. I also tried to do a "rehash" after doing putenv.</p>
<p>I removed that userSetup.mel file and modified the <strong>maya.env</strong> file using this other variable (since if I do this to MAYA_SCRIPT_PATH it breaks maya because overrides everything it had)</p>
<pre><code>USER_SCRIPT_PATH = C:/MyScripts
</code></pre>
<p>Anything works when I do "import folder" on a python tab. Folder is inside MyScripts folder, and there's a init file for all of them. It's not a python error, this folder works under maya/scripts folder.</p>
<p>It's not very clear why USER_SCRIPT_PATH is not mentioned anywhere in the docs as an official variable, no information about why any of those works. The folder ends up on the environment variable using getenv on MEL, but code is not loaded.</p>
| 0
|
2016-09-06T11:13:47Z
| 39,351,499
|
<p>At the same place where you find userSetup.mel, you can create a userSetup.py and do whatever import at the beginning of maya or execute any script.</p>
| 0
|
2016-09-06T14:26:25Z
|
[
"python",
"python-2.7",
"maya",
"mel"
] |
Add user scripts folder to Maya
| 39,347,681
|
<p>I tried all methods explained on several documentation pages.</p>
<p>I modified the <strong>userSetup.mel</strong> file and it adds the folder with this code:</p>
<pre><code>string $s = `getenv MAYA_SCRIPT_PATH` + ";C:/MyScripts";
putenv "MAYA_SCRIPT_PATH" $s;
</code></pre>
<p>It didn't work. I also tried to do a "rehash" after doing putenv.</p>
<p>I removed that userSetup.mel file and modified the <strong>maya.env</strong> file using this other variable (since if I do this to MAYA_SCRIPT_PATH it breaks maya because overrides everything it had)</p>
<pre><code>USER_SCRIPT_PATH = C:/MyScripts
</code></pre>
<p>Anything works when I do "import folder" on a python tab. Folder is inside MyScripts folder, and there's a init file for all of them. It's not a python error, this folder works under maya/scripts folder.</p>
<p>It's not very clear why USER_SCRIPT_PATH is not mentioned anywhere in the docs as an official variable, no information about why any of those works. The folder ends up on the environment variable using getenv on MEL, but code is not loaded.</p>
| 0
|
2016-09-06T11:13:47Z
| 39,377,126
|
<p>You don't want to set the environment variable after Maya is up and running, which is what you're doing in the mel example. You want it configured before maya starts looking for actual scripts. In general most programs that use env vars read them at startup time and don't recognize changes made while the program is running -- thats why in Windows for example you need to restart your dos windows after changing an env var from the GUI.</p>
<p>Popular methods are:</p>
<ol>
<li>Launch from a .bat file which sets the var and then runs maya. This lets you run multiple mayas side by side with different settings if needed</li>
<li>Do it with maya.env; this puts all the info into one place</li>
<li>For python, do it in <code>userSetup.py</code>. @AriGold's example will work, although I prefer to use the <code>site</code> module and <code>site.addsitedir('path/to/someplace')</code> because you can use .pth files in your target directory to make it as complex as you need; see <a href="http://stackoverflow.com/questions/15208615/using-pth-files">this question</a> for more details about pth files.</li>
<li>use a <a href="http://theodox.github.io/2014/magical_modules" rel="nofollow">Maya module</a> which allows you to set not only script paths but all the other paths (bitmaps, plugins etc) in one go></li>
</ol>
| 0
|
2016-09-07T18:46:54Z
|
[
"python",
"python-2.7",
"maya",
"mel"
] |
Stuck: Can't work out the error - index error python 3.5
| 39,347,857
|
<p>Here is part of my code (the part that is raising the issues):</p>
<pre><code>with open('list.txt') as csvfile:
readCSV = csv.reader(csvfile, delimiter = ",")
GTINs = []
products = []
prices = []
for row in readCSV:
GTIN = int(row[0])
product = row[1]
price = float(row[2])
GTINs.append(GTIN)
products.append(product)
prices.append(price)
</code></pre>
<p>On this line:</p>
<pre><code>GTIN = int(row[0])
</code></pre>
<p>I keep getting the error "IndexError: list index out of range", I have no idea how to fix it. Here is the information I am trying to extract (.txt file): </p>
<pre><code>69696961,Milk,1.29
55555555,Bread,0.49
45632549,Milkshake,1.99
</code></pre>
<p>The error occurred when I made an alteration to the the program (took away two lines).</p>
<p>Any help would be well appreciated as I am well and truly stuck.</p>
| 1
|
2016-09-06T11:22:21Z
| 39,347,957
|
<p>It seems that you have an incorrect or black line in your csv. You can handle the index error with a try-except expression.</p>
<pre><code>try:
GTIN = int(row[0])
product = row[1]
price = float(row[2])
GTINs.append(GTIN)
products.append(product)
prices.append(price)
except IndexError:
# do something (like "pass" if you don't want that lines)
</code></pre>
<p>But if you are going to extract the columns you can use <code>itertools.zip_longest()</code></p>
<pre><code>from itertools import zip_longest
with open('list.txt') as csvfile:
readCSV = csv.reader(csvfile, delimiter = ",")
GTIN, product, price = zip_longest(*readCSV, fillvalue="")
</code></pre>
<p>Note: You can use anything else instead of an empty string for missed values. Or if you don't pass it to the function it will use the default value which is <code>None</code>.</p>
<p>As mentioned in comment if you want the items in their real type you can use following approach which is using a generator expression:</p>
<pre><code>from itertools import zip_longest
with open('list.txt') as csvfile:
readCSV = csv.reader(csvfile, delimiter = ",")
rows = ((int(a), b, float(c)) for a, b, c in csv.reader(csvfile))
GTIN, product, price = zip_longest(*rows, fillvalue="")
</code></pre>
| 0
|
2016-09-06T11:28:16Z
|
[
"python",
"python-3.x"
] |
Stuck: Can't work out the error - index error python 3.5
| 39,347,857
|
<p>Here is part of my code (the part that is raising the issues):</p>
<pre><code>with open('list.txt') as csvfile:
readCSV = csv.reader(csvfile, delimiter = ",")
GTINs = []
products = []
prices = []
for row in readCSV:
GTIN = int(row[0])
product = row[1]
price = float(row[2])
GTINs.append(GTIN)
products.append(product)
prices.append(price)
</code></pre>
<p>On this line:</p>
<pre><code>GTIN = int(row[0])
</code></pre>
<p>I keep getting the error "IndexError: list index out of range", I have no idea how to fix it. Here is the information I am trying to extract (.txt file): </p>
<pre><code>69696961,Milk,1.29
55555555,Bread,0.49
45632549,Milkshake,1.99
</code></pre>
<p>The error occurred when I made an alteration to the the program (took away two lines).</p>
<p>Any help would be well appreciated as I am well and truly stuck.</p>
| 1
|
2016-09-06T11:22:21Z
| 39,348,102
|
<p>What i see here is a txt file not CSV. Here is an easy solution :</p>
<pre><code>GTINs = []
products = []
prices = []
with open('stack.txt','r') as f:
for line in f:
sentence = line.split(',')
GTINs.append(sentence[0])
products.append(sentence[1])
prices.append(sentence[2])
print(GTINs)
print(products)
print(prices)
</code></pre>
<p>The output is :
['69696961', '55555555', '45632549']
['Milk', 'Bread', 'Milkshake']
['1.29\n', '0.49\n', '1.99']</p>
| 0
|
2016-09-06T11:36:14Z
|
[
"python",
"python-3.x"
] |
Stuck: Can't work out the error - index error python 3.5
| 39,347,857
|
<p>Here is part of my code (the part that is raising the issues):</p>
<pre><code>with open('list.txt') as csvfile:
readCSV = csv.reader(csvfile, delimiter = ",")
GTINs = []
products = []
prices = []
for row in readCSV:
GTIN = int(row[0])
product = row[1]
price = float(row[2])
GTINs.append(GTIN)
products.append(product)
prices.append(price)
</code></pre>
<p>On this line:</p>
<pre><code>GTIN = int(row[0])
</code></pre>
<p>I keep getting the error "IndexError: list index out of range", I have no idea how to fix it. Here is the information I am trying to extract (.txt file): </p>
<pre><code>69696961,Milk,1.29
55555555,Bread,0.49
45632549,Milkshake,1.99
</code></pre>
<p>The error occurred when I made an alteration to the the program (took away two lines).</p>
<p>Any help would be well appreciated as I am well and truly stuck.</p>
| 1
|
2016-09-06T11:22:21Z
| 39,348,394
|
<p>Try to remove empty lines from the list.txt file.</p>
| 0
|
2016-09-06T11:52:09Z
|
[
"python",
"python-3.x"
] |
How to import a module which opens a file in the same directory as the module?
| 39,347,933
|
<p>I am trying to call a function <code>is_english_word</code> in a module <code>dict.py</code> in package <code>dictionary</code>. Here is the hierarchy:</p>
<pre><code>DataCleaning
|___ text_cleaner.py
|___ dictionary
|___ dict.py
|___ list_of_english_words.txt
</code></pre>
<p>To clarify, I have <code>dict.py</code> and <code>list_of_english_words.txt</code> in one package called <code>dictionary</code>. </p>
<p>Here is the import statement written in <code>text_cleaner.py</code>:</p>
<p><code>import DataCleaning.dictionary.dict as dictionary</code></p>
<p>and, here is the code written in <code>dict.py</code>:</p>
<pre><code>import os
with open(os.path.join(os.path.dirname(os.path.realpath('__file__')), 'list_of_english_words.txt')) as word_file:
english_words = set(word.strip().lower() for word in word_file)
def is_english_word(word):
return word.lower() in english_words
</code></pre>
<p>But when I run the <code>text_cleaner.py</code> file, it shows an import error as it cannot find the <code>list_of_english_words.txt</code>:</p>
<pre><code>Traceback (most recent call last):
File "E:/Analytics Practice/Social Media Analytics/analyticsPlatform/DataCleaning/text_cleaner.py", line 1, in <module>
import DataCleaning.dictionary.dict as dictionary
File "E:\Analytics Practice\Social Media Analytics\analyticsPlatform\DataCleaning\dictionary\dict.py", line 3, in <module>
with open(os.path.join(os.path.dirname(os.path.realpath('__file__')), 'list_of_english_words.txt')) as word_file:
FileNotFoundError: [Errno 2] No such file or directory: 'E:\\Analytics Practice\\Social Media Analytics\\analyticsPlatform\\DataCleaning\\list_of_english_words.txt'
</code></pre>
<p>But when I run the <code>dict.py</code> code itself, it shows no error. I can clearly see that the <code>os.path.dirname(os.path.realpath('__file__'))</code> points to the directory of <code>text_cleaner.py</code> and not of <code>dict.py</code>. How do I make the import of my module <code>dict.py</code> independent of from where it is called?</p>
| 0
|
2016-09-06T11:26:40Z
| 39,348,179
|
<p>The issue is that you are passing the string <code>'__file__'</code> to <code>os.path.realpath</code> instead of the variable <code>__file__</code>.</p>
<p>Change:</p>
<pre><code>os.path.realpath('__file__')
</code></pre>
<p>To:</p>
<pre><code>os.path.realpath(__file__)
</code></pre>
| 2
|
2016-09-06T11:40:21Z
|
[
"python",
"python-os"
] |
unicodedata is not found
| 39,347,976
|
<p>I'm trying to install Twisted on a small board running a version of OpenWRT (chaos calmer). I'm running it step by step so I could track and install the missing packages on the device. Last error was:</p>
<pre><code>ImportError: No module named unicodedata
</code></pre>
<p>I have installed all the packages offered for python by the vendor, tried find and grep in my Desktop's /usr/lib/python2.7/ also tried</p>
<pre><code>python -v
</code></pre>
<p>on my desktop to find the module but haven't been able to locate it. Seems like it's an internal package.
How can I install unicodedata on the device?</p>
| 2
|
2016-09-06T11:28:41Z
| 39,348,500
|
<p>The file <code>unicodedata.so</code> is provided in the <code>python-codecs</code> package. A <a href="https://downloads.openwrt.org/chaos_calmer/15.05.1/x86/64/packages/packages/python-codecs_2.7.9-6_x86_64.ipk" rel="nofollow">x86_64 version</a> is available so presumably it's also available for other architectures.</p>
<p>You should be able to determine that with:</p>
<pre><code>$ opkg search '*/unicodedata.so'
</code></pre>
<p>or possibly</p>
<pre><code>$ opkg whatprovides '*/unicodedata.so'
</code></pre>
| 2
|
2016-09-06T11:57:55Z
|
[
"python",
"python-2.7",
"openwrt",
"twisted.internet"
] |
[Pyasn1]: raise error.PyAsn1Error('Component type error %r vs %r' % (t, value))
| 39,348,029
|
<p>I have only one choice and within that choice I want to pass the object of the class with only one field. </p>
<p>Here is my code snippet:-</p>
<pre><code>from pyasn1.type import univ, namedtype, tag, char, namedval, useful
from pyasn1.codec.ber import encoder
class MiepPullWtdr(univ.Sequence):
componentType = namedtype.NamedTypes(namedtype.NamedType('wtdrId', univ.Integer().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))))
class ChoiceData(univ.Choice):
componentType = namedtype.NamedTypes(namedtype.NamedType('miepPullWtdr', MiepPullWtdr().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))))
seqObj = MiepPullWtdr()
seqObj.setComponentByName('wtdrId', 6555)
choiceObj = ChoiceData()
choiceObj.setComponentByName('miepPullWtdr', seqObj)
</code></pre>
<p>When I run my script test.py, it throws this error:-</p>
<pre><code>Traceback (most recent call last):
File "test.py", line 18, in <module>
choiceObj.setComponentByName('miepPullWtdr', seqObj)
File "/data/aman/cdr/lib/pyasn1-0.1.7/pyasn1/type/univ.py", line 760, in setComponentByName verifyConstraints
File "/data/aman/cdr/lib/pyasn1-0.1.7/pyasn1/type/univ.py", line 979, in setComponentByPosition
self._verifyComponent(idx, value)
File "/data/aman/cdr/lib/pyasn1-0.1.7/pyasn1/type/univ.py", line 751, in _verifyComponent
raise error.PyAsn1Error('Component type error %r vs %r' % (t, value))
pyasn1.error.PyAsn1Error: Component type error MiepPullWtdr() vs MiepPullWtdr().setComponentByPosition(0, Integer(6555))
</code></pre>
<p>Any help? Thanks.</p>
| 0
|
2016-09-06T11:31:15Z
| 39,401,851
|
<p>There is an inconsistency in how <code>MiepPullWtdr</code> type is ASN.1 tagged in its stand-alone definition versus as a <code>ChoiceData</code> component. I am not sure what exactly your intention is, here is one of possibly many consistent versions:</p>
<pre><code>from pyasn1.type import univ, namedtype, tag
class MiepPullWtdr(univ.Sequence):
tagSet = univ.Sequence.tagSet.tagImplicitly(
tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0)
)
componentType = namedtype.NamedTypes(
namedtype.NamedType('wtdrId', univ.Integer().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0)))
)
class ChoiceData(univ.Choice):
componentType = namedtype.NamedTypes(
namedtype.NamedType('miepPullWtdr', MiepPullWtdr())
)
seqObj = MiepPullWtdr()
seqObj['wtdrId'] = 6555
choiceObj = ChoiceData()
choiceObj['miepPullWtdr'] = seqObj
print(choiceObj.prettyPrint())
</code></pre>
| 0
|
2016-09-08T23:59:41Z
|
[
"python",
"pyasn1"
] |
Why isn't my function returning anything?
| 39,348,273
|
<p>I am attempting to make a rudimentary chatbot using python and tkinter, and have ran into an issue. I have excluded tkinter code for simplicity. The entire code is visible at the bottom.</p>
<pre><code> def communicate():
sent.set(HUMAN_ENTRY.get())
bottalk(response)
AI_RESPONSE.set(response.get())
print (response.get())
print(AI_RESPONSE.get())
root.update()
def bottalk(response):
if sent == 'hello':
response = 'hello recieved'
else:
response = 'hello not recieved'
return response
AI_RESPONSE = 'hellgeto'
header.pack()
sent = StringVar()
response = StringVar()
AI_RESPONSE = StringVar()
</code></pre>
<p>An input is made into a entry box, and is sent to the communicate function, which sends the input to the bottalk function, which should set response to either "hello received" or "hello not received", and update a label on the GUI. However, when I do this, the label does not change, and the console outputs what seems to be two blank lines. <em>Why is my function not setting response to either "hello received" or "hello not received", and if it is, why is it not printing this or updating the GUI?</em></p>
<p><strong>Print(AI_RESPONSE) resulting in Py-Var2 was to show that 2 blank lines out outputted. My question does not concern that line.</strong></p>
<pre><code>from tkinter import *
import random
class App:
def __init__(self, master):
def close():
quit()
def communicate():
sent.set(HUMAN_ENTRY.get())
bottalk(response)
AI_RESPONSE.set(response.get())
print (response.get())
print(AI_RESPONSE.get())
print(AI_RESPONSE)
root.update()
def bottalk(response):
if sent == 'hello':
response = 'hello recieved'
else:
response = 'hello not recieved'
return response
AI_RESPONSE = 'hellgeto'
root.title=('GoBot')
frame = Frame(master)
frame.pack()
self.button = Button(frame,text='Send', command=communicate)
self.button.pack(side=LEFT)
self.button2 = Button(frame,text='Quit', command=close)
self.button2.pack(side=RIGHT)
header = Label(frame, text='GoBot', fg= 'blue', font = 'Times')
header.pack()
sent = StringVar()
response = StringVar()
AI_RESPONSE = StringVar()
HUMAN_ENTRY = Entry(master, bd = 5)
HUMAN_ENTRY.pack(side=RIGHT)
responselabel = Label(frame, textvariable=AI_RESPONSE, fg = 'purple', font = 'ComicSans', anchor ='s')
responselabel.pack()
root = Tk()
app = App(root)
root.mainloop()
</code></pre>
<p><a href="http://i.stack.imgur.com/GSOXj.png" rel="nofollow"><img src="http://i.stack.imgur.com/GSOXj.png" alt="The Console"></a></p>
| 0
|
2016-09-06T11:45:13Z
| 39,348,366
|
<p>Since response returned as value, it won't update the <code>response</code> variable inside <code>communicate</code> function. You need to update <code>response</code> with the value returned from the function:</p>
<pre><code>def communicate():
sent.set(HUMAN_ENTRY.get())
response = bottalk(response)
AI_RESPONSE.set(response.get())
print (response.get())
print(AI_RESPONSE.get())
root.update()
</code></pre>
| 3
|
2016-09-06T11:50:23Z
|
[
"python",
"tkinter"
] |
Why isn't my function returning anything?
| 39,348,273
|
<p>I am attempting to make a rudimentary chatbot using python and tkinter, and have ran into an issue. I have excluded tkinter code for simplicity. The entire code is visible at the bottom.</p>
<pre><code> def communicate():
sent.set(HUMAN_ENTRY.get())
bottalk(response)
AI_RESPONSE.set(response.get())
print (response.get())
print(AI_RESPONSE.get())
root.update()
def bottalk(response):
if sent == 'hello':
response = 'hello recieved'
else:
response = 'hello not recieved'
return response
AI_RESPONSE = 'hellgeto'
header.pack()
sent = StringVar()
response = StringVar()
AI_RESPONSE = StringVar()
</code></pre>
<p>An input is made into a entry box, and is sent to the communicate function, which sends the input to the bottalk function, which should set response to either "hello received" or "hello not received", and update a label on the GUI. However, when I do this, the label does not change, and the console outputs what seems to be two blank lines. <em>Why is my function not setting response to either "hello received" or "hello not received", and if it is, why is it not printing this or updating the GUI?</em></p>
<p><strong>Print(AI_RESPONSE) resulting in Py-Var2 was to show that 2 blank lines out outputted. My question does not concern that line.</strong></p>
<pre><code>from tkinter import *
import random
class App:
def __init__(self, master):
def close():
quit()
def communicate():
sent.set(HUMAN_ENTRY.get())
bottalk(response)
AI_RESPONSE.set(response.get())
print (response.get())
print(AI_RESPONSE.get())
print(AI_RESPONSE)
root.update()
def bottalk(response):
if sent == 'hello':
response = 'hello recieved'
else:
response = 'hello not recieved'
return response
AI_RESPONSE = 'hellgeto'
root.title=('GoBot')
frame = Frame(master)
frame.pack()
self.button = Button(frame,text='Send', command=communicate)
self.button.pack(side=LEFT)
self.button2 = Button(frame,text='Quit', command=close)
self.button2.pack(side=RIGHT)
header = Label(frame, text='GoBot', fg= 'blue', font = 'Times')
header.pack()
sent = StringVar()
response = StringVar()
AI_RESPONSE = StringVar()
HUMAN_ENTRY = Entry(master, bd = 5)
HUMAN_ENTRY.pack(side=RIGHT)
responselabel = Label(frame, textvariable=AI_RESPONSE, fg = 'purple', font = 'ComicSans', anchor ='s')
responselabel.pack()
root = Tk()
app = App(root)
root.mainloop()
</code></pre>
<p><a href="http://i.stack.imgur.com/GSOXj.png" rel="nofollow"><img src="http://i.stack.imgur.com/GSOXj.png" alt="The Console"></a></p>
| 0
|
2016-09-06T11:45:13Z
| 39,348,822
|
<p><code>response</code> is <code>StringVar</code> so you have to use <code>.set(text)</code> instead of <code>=</code> </p>
<pre><code>def bottalk(response):
if sent == 'hello':
response.set('hello recieved')
else:
response.set('hello not recieved')
</code></pre>
<p>And now you don't have to return value, and don't need to use <code>global</code>. And you see text in label and console.</p>
| 1
|
2016-09-06T12:14:55Z
|
[
"python",
"tkinter"
] |
Why isn't my function returning anything?
| 39,348,273
|
<p>I am attempting to make a rudimentary chatbot using python and tkinter, and have ran into an issue. I have excluded tkinter code for simplicity. The entire code is visible at the bottom.</p>
<pre><code> def communicate():
sent.set(HUMAN_ENTRY.get())
bottalk(response)
AI_RESPONSE.set(response.get())
print (response.get())
print(AI_RESPONSE.get())
root.update()
def bottalk(response):
if sent == 'hello':
response = 'hello recieved'
else:
response = 'hello not recieved'
return response
AI_RESPONSE = 'hellgeto'
header.pack()
sent = StringVar()
response = StringVar()
AI_RESPONSE = StringVar()
</code></pre>
<p>An input is made into a entry box, and is sent to the communicate function, which sends the input to the bottalk function, which should set response to either "hello received" or "hello not received", and update a label on the GUI. However, when I do this, the label does not change, and the console outputs what seems to be two blank lines. <em>Why is my function not setting response to either "hello received" or "hello not received", and if it is, why is it not printing this or updating the GUI?</em></p>
<p><strong>Print(AI_RESPONSE) resulting in Py-Var2 was to show that 2 blank lines out outputted. My question does not concern that line.</strong></p>
<pre><code>from tkinter import *
import random
class App:
def __init__(self, master):
def close():
quit()
def communicate():
sent.set(HUMAN_ENTRY.get())
bottalk(response)
AI_RESPONSE.set(response.get())
print (response.get())
print(AI_RESPONSE.get())
print(AI_RESPONSE)
root.update()
def bottalk(response):
if sent == 'hello':
response = 'hello recieved'
else:
response = 'hello not recieved'
return response
AI_RESPONSE = 'hellgeto'
root.title=('GoBot')
frame = Frame(master)
frame.pack()
self.button = Button(frame,text='Send', command=communicate)
self.button.pack(side=LEFT)
self.button2 = Button(frame,text='Quit', command=close)
self.button2.pack(side=RIGHT)
header = Label(frame, text='GoBot', fg= 'blue', font = 'Times')
header.pack()
sent = StringVar()
response = StringVar()
AI_RESPONSE = StringVar()
HUMAN_ENTRY = Entry(master, bd = 5)
HUMAN_ENTRY.pack(side=RIGHT)
responselabel = Label(frame, textvariable=AI_RESPONSE, fg = 'purple', font = 'ComicSans', anchor ='s')
responselabel.pack()
root = Tk()
app = App(root)
root.mainloop()
</code></pre>
<p><a href="http://i.stack.imgur.com/GSOXj.png" rel="nofollow"><img src="http://i.stack.imgur.com/GSOXj.png" alt="The Console"></a></p>
| 0
|
2016-09-06T11:45:13Z
| 39,348,902
|
<p>Ok from beginning, i think that you have few mistakes in your code:</p>
<pre><code>class App:
def __init__(self, master):
</code></pre>
<p>You dont have anything in constructor, maybe you should put below code there:</p>
<pre><code> AI_RESPONSE = 'hellgeto'
root.title=('GoBot')
frame = Frame(master)
frame.pack()
self.button = Button(frame,text='Send', command=communicate)
self.button.pack(side=LEFT)
self.button2 = Button(frame,text='Quit', command=close)
self.button2.pack(side=RIGHT)
header = Label(frame, text='GoBot', fg= 'blue', font = 'Times')
header.pack()
sent = StringVar()
response = StringVar()
AI_RESPONSE = StringVar()
HUMAN_ENTRY = Entry(master, bd = 5)
HUMAN_ENTRY.pack(side=RIGHT)
responselabel = Label(frame, textvariable=AI_RESPONSE, fg = 'purple', font = 'ComicSans', anchor ='s')
responselabel.pack()
</code></pre>
<p>Next method:</p>
<pre><code> def close():
quit()
</code></pre>
<p>probably you want to "clean" after object, then i recommend to read more about this, for example here: <a href="http://stackoverflow.com/questions/865115/how-do-i-correctly-clean-up-a-python-object">How do I correctly clean up a Python object?</a>
<br>
Also your another methods:</p>
<pre><code> def communicate():
sent.set(HUMAN_ENTRY.get())
bottalk(response)
AI_RESPONSE.set(response.get())
print (response.get())
print(AI_RESPONSE.get())
print(AI_RESPONSE)
root.update()
def bottalk(response):
if sent == 'hello':
response = 'hello recieved'
else:
response = 'hello not recieved'
return response
</code></pre>
<p>I hardly recommend you first at all read about basics of python programming rather then start using some advanced modules. I want to redirect you here: <a href="https://docs.python.org/3/tutorial/classes.html" rel="nofollow">https://docs.python.org/3/tutorial/classes.html</a></p>
| 0
|
2016-09-06T12:19:31Z
|
[
"python",
"tkinter"
] |
Filtering DataFrames in Pandas for multiple columns where a column name contains a pattern
| 39,348,317
|
<p>While filtering multiple columns I have seen examples where we could filter Rows using something like this <code>df[df['A'].str.contains("string") | df['B'].str.contains("string")]</code> .</p>
<p>I have multiple files where I want to fetch each file and get only those rows with <code>'gmail.com'</code> from the column names having <code>'email'</code> string in them. </p>
<p>So an example header can be like: 'firstname' 'lastname' 'companyname' 'address' 'emailid1' 'emailid2' 'emailid3' ...</p>
<p>The columns <code>emailid1..2..3</code> have emailids containing <code>gmail.com</code>. I would want to fetch rows where gmail can occur in any one of them.</p>
<pre><code>for file in files:
pdf = pd.read_csv('Reduced/'+file,delimiter = '\t')
emailids = [col for col in pdf.columns if 'email' in col]
# pdf['gmail' in pdf[emailids]]
</code></pre>
| 1
|
2016-09-06T11:47:54Z
| 39,348,412
|
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.any.html" rel="nofollow"><code>any</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>
<pre><code>pdf = pd.DataFrame({'A':[1,2,3],
'email1':['gmail.com','t','f'],
'email2':['u','gmail.com','t'],
'D':[1,3,5],
'E':[5,3,6],
'F':[7,4,3]})
print (pdf)
A D E F email1 email2
0 1 1 5 7 gmail.com u
1 2 3 3 4 t gmail.com
2 3 5 6 3 f t
#filter column names
emailids = [col for col in pdf.columns if 'email' in col]
print (emailids)
['email1', 'email2']
#apply string function for each filtered column
df = pd.concat([pdf[col].str.contains('gmail.com') for col in pdf[emailids]], axis=1)
print (df)
email1 email2
0 True False
1 False True
2 False False
#filter at least one True by any
print (pdf[df.any(1)])
A D E F email1 email2
0 1 1 5 7 gmail.com u
1 2 3 3 4 t gmail.com
</code></pre>
| 1
|
2016-09-06T11:53:18Z
|
[
"python",
"pandas",
"indexing",
"filter",
"multiple-columns"
] |
Filtering DataFrames in Pandas for multiple columns where a column name contains a pattern
| 39,348,317
|
<p>While filtering multiple columns I have seen examples where we could filter Rows using something like this <code>df[df['A'].str.contains("string") | df['B'].str.contains("string")]</code> .</p>
<p>I have multiple files where I want to fetch each file and get only those rows with <code>'gmail.com'</code> from the column names having <code>'email'</code> string in them. </p>
<p>So an example header can be like: 'firstname' 'lastname' 'companyname' 'address' 'emailid1' 'emailid2' 'emailid3' ...</p>
<p>The columns <code>emailid1..2..3</code> have emailids containing <code>gmail.com</code>. I would want to fetch rows where gmail can occur in any one of them.</p>
<pre><code>for file in files:
pdf = pd.read_csv('Reduced/'+file,delimiter = '\t')
emailids = [col for col in pdf.columns if 'email' in col]
# pdf['gmail' in pdf[emailids]]
</code></pre>
| 1
|
2016-09-06T11:47:54Z
| 39,348,462
|
<p>Given example input of:</p>
<pre><code>df = pd.DataFrame({'email': ['test@example.com', 'someone@gmail.com'], 'somethingelse': [1, 2], 'another_email': ['whatever@example.com', 'something@example.com']})
</code></pre>
<p>eg:</p>
<pre><code> another_email email somethingelse
0 whatever@example.com test@example.com 1
1 something@example.com someone@gmail.com 2
</code></pre>
<p>You can filter out the columns that contain email, look for <code>gmail.com</code> or whatever text you wish, then subset, eg:</p>
<pre><code>df[df.filter(like='email').applymap(lambda L: 'gmail.com' in L).any(axis=1)]
</code></pre>
<p>Which gives you:</p>
<pre><code> another_email email somethingelse
1 something@example.com someone@gmail.com 2
</code></pre>
| 1
|
2016-09-06T11:56:18Z
|
[
"python",
"pandas",
"indexing",
"filter",
"multiple-columns"
] |
Error while installing pygraphviz on OS X with Anaconda
| 39,348,416
|
<p>I am trying to install pygraphviz in OS X 10.9.5. I am using Python 2.7.12 with Anaconda 2.1.0. I already have graphviz installed. </p>
<p>Here is the error I get when running pip install pygraphviz </p>
<pre><code> #include "graphviz/cgraph.h"
^
compilation terminated.
error: command 'gcc' failed with exit status 1
----------------------------------------
Failed building wheel for pygraphviz
Running setup.py clean for pygraphviz
Failed to build pygraphviz
Installing collected packages: pygraphviz
Running setup.py install for pygraphviz ... error
Complete output from command /Users/safsafi/anaconda/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/vv/w5df7gw55bz_8bry85xf18rh0000gn/T/pip-build-QsLsqM/pygraphviz/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/vv/w5df7gw55bz_8bry85xf18rh0000gn/T/pip-_MkJKV-record/install-record.txt --single-version-externally-managed --compile:
running install
Trying pkg-config
Package libcgraph was not found in the pkg-config search path.
Perhaps you should add the directory containing `libcgraph.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libcgraph' found
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/private/var/folders/vv/w5df7gw55bz_8bry85xf18rh0000gn/T/pip-build-QsLsqM/pygraphviz/setup.py", line 87, in <module>
tests_require=['nose>=0.10.1', 'doctest-ignore-unicode>=0.1.0',],
File "/Users/safsafi/anaconda/lib/python2.7/distutils/core.py", line 151, in setup
dist.run_commands()
File "/Users/safsafi/anaconda/lib/python2.7/distutils/dist.py", line 953, in run_commands
self.run_command(cmd)
File "/Users/safsafi/anaconda/lib/python2.7/distutils/dist.py", line 972, in run_command
cmd_obj.run()
File "setup_commands.py", line 44, in modified_run
self.include_path, self.library_path = get_graphviz_dirs()
File "setup_extra.py", line 121, in get_graphviz_dirs
include_dirs, library_dirs = _pkg_config()
File "setup_extra.py", line 44, in _pkg_config
output = S.check_output(['pkg-config', '--libs-only-L', 'libcgraph'])
File "/Users/safsafi/anaconda/lib/python2.7/subprocess.py", line 574, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['pkg-config', '--libs-only-L', 'libcgraph']' returned non-zero exit status 1
----------------------------------------
Command "/Users/safsafi/anaconda/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/vv/w5df7gw55bz_8bry85xf18rh0000gn/T/pip-build-QsLsqM/pygraphviz/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/vv/w5df7gw55bz_8bry85xf18rh0000gn/T/pip-_MkJKV-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/vv/w5df7gw55bz_8bry85xf18rh0000gn/T/pip-build-QsLsqM/pygraphviz/
</code></pre>
<p>I have also tried running : </p>
<pre><code>conda install --channel https://conda.anaconda.org/garylschultz pygraphviz
</code></pre>
<p>Which does not give any error but import pygraphviz still don't work in python. </p>
<p>When I try import pygraphviz in python I get the following error: </p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/safsafi/anaconda/lib/python2.7/site-packages/pygraphviz/__init__.py", line 54, in <module>
from agraph import AGraph, Node, Edge, Attribute, ItemAttribute
File "/Users/safsafi/anaconda/lib/python2.7/site-packages/pygraphviz/agraph.py", line 20, in <module>
import graphviz as gv
File "/Users/safsafi/anaconda/lib/python2.7/site-packages/pygraphviz/graphviz.py", line 7, in <module>
import _graphviz
ImportError: dlopen(/Users/safsafi/anaconda/lib/python2.7/site-packages/pygraphviz/_graphviz.so, 2): Library not loaded: /opt/local/lib/libcgraph.6.dylib
Referenced from: /Users/safsafi/anaconda/lib/python2.7/site-packages/pygraphviz/_graphviz.so
Reason: image not found
</code></pre>
<p>Thanks in advance.</p>
| 1
|
2016-09-06T11:53:27Z
| 39,886,711
|
<p>On Mac OSX, I solve it with:</p>
<pre><code>pip install graphviz
pip install --install-option="--include-path=/opt/local/include" --install-option="--library-path=/opt/local/lib" pygraphviz
</code></pre>
<p>GitHub related <a href="https://github.com/pygraphviz/pygraphviz/issues/11" rel="nofollow">issue</a></p>
| 0
|
2016-10-06T02:46:24Z
|
[
"python",
"python-2.7",
"anaconda"
] |
Python - recursion not working
| 39,348,421
|
<p>I have a following code:</p>
<pre><code>d = {'init':
[{'solve':
[{'subsolve':
[{'vals': [{'Blade summary': 'asdf'},
{'Blade summary': 'fdsa'}]}]},
{'subsolve':
[{'vals': [{'Blade summary': 'ffff'}]}]}]},
{'solve':
[{'subsolve':
[{'vals': 'bbbb'}]}]}]}
def parseDics(lst, mainReg):
print('call')
for dic in lst:
for key, vals in dic.items():
if key == mainReg:
if mainReg == 'vals':
yield vals
parseDics(vals, 'vals')
else:
parseDics(vals, mainReg)
if __name__=='__main__':
pp.pprint(list(parseDics(d['init'], 'solve')))
</code></pre>
<p>The function itself is not complete, but that's not a problem for now. The problem is, it appears, that recursive calls don't work.</p>
<p>If I try to run it now, I'll get only this output:</p>
<pre><code>call
[]
</code></pre>
<p>So the function was called only once. When I try to step into the nested function call (I'm using PyCharm), then I'm simply not not able to and the function call is "over-stepped".</p>
<p>What am I doing wrong? Why isn't my function called recursively?</p>
| 0
|
2016-09-06T11:53:45Z
| 39,348,492
|
<p>You need to actually do something with the result of your recursive calls. Since you're using <code>yield</code> with the value, you probably need to use it there too.</p>
| 1
|
2016-09-06T11:57:47Z
|
[
"python",
"python-3.x",
"dictionary",
"recursion",
"pycharm"
] |
Python - recursion not working
| 39,348,421
|
<p>I have a following code:</p>
<pre><code>d = {'init':
[{'solve':
[{'subsolve':
[{'vals': [{'Blade summary': 'asdf'},
{'Blade summary': 'fdsa'}]}]},
{'subsolve':
[{'vals': [{'Blade summary': 'ffff'}]}]}]},
{'solve':
[{'subsolve':
[{'vals': 'bbbb'}]}]}]}
def parseDics(lst, mainReg):
print('call')
for dic in lst:
for key, vals in dic.items():
if key == mainReg:
if mainReg == 'vals':
yield vals
parseDics(vals, 'vals')
else:
parseDics(vals, mainReg)
if __name__=='__main__':
pp.pprint(list(parseDics(d['init'], 'solve')))
</code></pre>
<p>The function itself is not complete, but that's not a problem for now. The problem is, it appears, that recursive calls don't work.</p>
<p>If I try to run it now, I'll get only this output:</p>
<pre><code>call
[]
</code></pre>
<p>So the function was called only once. When I try to step into the nested function call (I'm using PyCharm), then I'm simply not not able to and the function call is "over-stepped".</p>
<p>What am I doing wrong? Why isn't my function called recursively?</p>
| 0
|
2016-09-06T11:53:45Z
| 39,348,695
|
<p>In Python 3.4 you can use <code>yield from parseDics(vals, 'vals')</code>, for Python 2:</p>
<pre><code>for val in parseDics(vals, 'vals'):
yield val
</code></pre>
| 1
|
2016-09-06T12:08:42Z
|
[
"python",
"python-3.x",
"dictionary",
"recursion",
"pycharm"
] |
Python - recursion not working
| 39,348,421
|
<p>I have a following code:</p>
<pre><code>d = {'init':
[{'solve':
[{'subsolve':
[{'vals': [{'Blade summary': 'asdf'},
{'Blade summary': 'fdsa'}]}]},
{'subsolve':
[{'vals': [{'Blade summary': 'ffff'}]}]}]},
{'solve':
[{'subsolve':
[{'vals': 'bbbb'}]}]}]}
def parseDics(lst, mainReg):
print('call')
for dic in lst:
for key, vals in dic.items():
if key == mainReg:
if mainReg == 'vals':
yield vals
parseDics(vals, 'vals')
else:
parseDics(vals, mainReg)
if __name__=='__main__':
pp.pprint(list(parseDics(d['init'], 'solve')))
</code></pre>
<p>The function itself is not complete, but that's not a problem for now. The problem is, it appears, that recursive calls don't work.</p>
<p>If I try to run it now, I'll get only this output:</p>
<pre><code>call
[]
</code></pre>
<p>So the function was called only once. When I try to step into the nested function call (I'm using PyCharm), then I'm simply not not able to and the function call is "over-stepped".</p>
<p>What am I doing wrong? Why isn't my function called recursively?</p>
| 0
|
2016-09-06T11:53:45Z
| 39,348,962
|
<p><code>parseDics</code> isn't a regular function, it's a generator. So you need to call it like a generator, rather than a regular function, otherwise it won't work. The first call works because when you call <code>list(parseDicts(...))</code>, the list constructor is calling <code>parseDicts</code> as a generator. But within <code>parseDicts</code>, you try to recursively call <code>parseDicts</code> as a function, which doesn't work.</p>
<p>Change the recursive calls to use <code>yield from</code> if you are using Python 3.3+:</p>
<pre><code>def parseDics(lst, mainReg):
print('call')
for dic in lst:
for key, vals in dic.items():
if key == mainReg:
if mainReg == 'vals':
yield vals
yield from parseDics(vals, 'vals')
else:
yield from parseDics(vals, mainReg)
</code></pre>
<p>For older versions of Python, you would need to iterate over those recursive calls and yield each value that generate:</p>
<pre><code>def parseDics(lst, mainReg):
print('call')
for dic in lst:
for key, vals in dic.items():
if key == mainReg:
if mainReg == 'vals':
yield vals
for val in parseDics(vals, 'vals'):
yield val
else:
for val in parseDics(vals, mainReg):
yield val
</code></pre>
<p>Calling a generator as a function merely creates the generator, it doesn't run it. E.g.:</p>
<pre><code>>>> def my_gen():
print("my_gen()")
for i in range(5):
print(i)
yield i
>>> my_gen()
<generator object my_gen at 0x00000000045B6B48>
>>> list(my_gen())
my_gen()
0
1
2
3
4
[0, 1, 2, 3, 4]
</code></pre>
| 1
|
2016-09-06T12:22:20Z
|
[
"python",
"python-3.x",
"dictionary",
"recursion",
"pycharm"
] |
Unsure how to cancel long-running asyncio task
| 39,348,476
|
<p>I'm developing a CLI that interacts with a web service. When run, it will try to establish communication with it, send requests, receive and process replies and then terminate. I'm using coroutines in various parts of my code and asyncio to drive them. What I'd like is to be able to perform all these steps and then have all coroutines cleanly terminate at the end (i.e. in a way that doesn't cause asyncio to complain). Unfortunately, I'm finding asyncio a lot more difficult to use and understand than asynchronicity in other languages like C#.</p>
<p>I define a class that handles all direct communication with the web service over websocket connections:</p>
<pre><code>class CommunicationService(object):
def __init__(self):
self._ws = None
self._listen_task = None
self._loop = asyncio.get_event_loop()
...
async def _listen_for_responses(self):
logging.debug('Listening for responses')
while True:
message = await self._ws.recv()
self.__received_response.on_next(message)
def establish_communication(self, hostname: str, port: int) -> None:
websocket_address = 'ws://{}:{}/'.format(hostname, port)
self._ws = self._loop.run_until_complete(websockets.connect(websocket_address))
self._listen_task = asyncio.ensure_future(self._listen_for_responses())
def send_request(self, request: str) -> None:
return asyncio.ensure_future(self._ws.send(request))
def stop(self):
if self._listen_task:
self._loop.call_soon_threadsafe(self._listen_task.cancel)
if self._ws and self._ws.open:
self._ws.close()
</code></pre>
<p>This class makes use of the <a href="https://github.com/aaugustin/websockets" rel="nofollow">websockets</a> and <a href="https://github.com/ReactiveX/RxPY" rel="nofollow">RxPY</a> libraries. When establishing communication, instances of this class will create an indefinitely-running task that will await responses from the web service and publish them on an RxPY subject.</p>
<p>I run <code>CommunicationService.establish_communication</code> in the main CLI method: </p>
<pre><code>def cli(context, hostname, port):
log_level = context.meta['click_log.core.logger']['level']
_initialize_logging(log_level)
# Create a new event loop for processing commands asynchronously on.
loop = asyncio.new_event_loop()
loop.set_debug(log_level == logging.DEBUG)
asyncio.set_event_loop(loop)
# Establish communication with TestCube Web Service.
context.comms = CommunicationService()
context.comms.establish_communication(hostname, port)
...
</code></pre>
<p>Depending on the supplied CLI arguments, this may invoke a subcommand callback, which I implement as a coroutine function.</p>
<p>I then register a function to handle the results of the invoked subcommands, which will either be <code>None</code> or a coroutine object:</p>
<pre><code>@cli.resultcallback()
@click.pass_context
def _handle_command_task(context, task: Coroutine, **_) -> None:
if task:
loop = asyncio.get_event_loop()
result = loop.run_until_complete(task)
context.comms.stop()
loop.close()
if result:
print(result, end='')
</code></pre>
<p>My program works, but I get the following output (when running the CLI at INFO log level):</p>
<pre class="lang-none prettyprint-override"><code>$ testcube relays.0.enabled false
2016-09-06 12:33:51,157 [INFO ] testcube.comms - Establishing connection to TestCube Web Service @ 127.0.0.1:36364
2016-09-06 12:33:51,219 [ERROR ] asyncio - Task was destroyed but it is pending!
task: <Task pending coro=<CommunicationService._listen_for_responses() running at c:\users\davidfallah\pycharmprojects\testcube\testcube\comms.py:34> wait_for=<Future pending cb=[Task._wakeup()]>>
2016-09-06 12:33:51,219 [ERROR ] asyncio - Task was destroyed but it is pending!
task: <Task pending coro=<WebSocketCommonProtocol.run() running at c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\site-packages\websockets\protocol.py:413> wait_for=<Future pending cb=[Task._wakeup()]> cb=[_wait.<locals>._on_completion() at c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\tasks.py:414]>
2016-09-06 12:33:51,219 [ERROR ] asyncio - Task was destroyed but it is pending!
task: <Task pending coro=<Queue.get() running at c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\queues.py:168> wait_for=<Future pending cb=[Task._wakeup()]> cb=[_wait.<locals>._on_completion() at c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\tasks.py:414]>
Exception ignored in: <generator object Queue.get at 0x03643600>
Traceback (most recent call last):
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\queues.py", line 170, in get
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\futures.py", line 227, in cancel
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\futures.py", line 242, in _schedule_callbacks
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\base_events.py", line 497, in call_soon
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\base_events.py", line 506, in _call_soon
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\base_events.py", line 334, in _check_closed
RuntimeError: Event loop is closed
</code></pre>
<p>If I change <code>CommunicationService.stop()</code> to directly cancel the response-listening task (as opposed to scheduling it)...</p>
<pre class="lang-none prettyprint-override"><code>self._listen_task.cancel()
#self._loop.call_soon_threadsafe(self._listen_task.cancel)
</code></pre>
<p>I get the following output instead:</p>
<pre class="lang-none prettyprint-override"><code>...
task: <Task pending coro=<CommunicationService._listen_for_responses() running at c:\users\davidfallah\pycharmprojects\testcube\testcube\comms.py:34> wait_for=<Future cancelled>>
...
</code></pre>
<p>In which <code>wait_for</code> is <code><Future cancelled></code> (as opposed to <code>wait_for=<Future pending cb=[Task._wakeup()]>></code>). I don't understand how I call <code>Task.cancel()</code> and it says <code>future cancelled</code> but the task is still pending. Do I need to do something special with the task e.g. wrap the code in <code>try...except asyncio.CancelledException...</code>?</p>
<p>If it's useful at all, this is the DEBUG-level output of the same command:</p>
<pre class="lang-none prettyprint-override"><code>$ testcube -v DEBUG relays.0.enabled false
2016-09-06 12:48:10,145 [DEBUG ] asyncio - Using selector: SelectSelector
2016-09-06 12:48:10,147 [DEBUG ] Rx - CurrentThreadScheduler.schedule(state=None)
2016-09-06 12:48:10,147 [INFO ] testcube.comms - Establishing connection to TestCube Web Service @ 127.0.0.1:36364
2016-09-06 12:48:10,153 [DEBUG ] asyncio - connect <socket.socket fd=608, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=6> to ('127.0.0.1', 36364)
2016-09-06 12:48:10,156 [DEBUG ] asyncio - poll took 0.000 ms: 1 events
2016-09-06 12:48:10,163 [DEBUG ] asyncio - <socket.socket fd=608, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=6, laddr=('127.0.0.1', 56647), raddr=('127.0.0.1', 36364)> connected to 127.0.0.1:36364: (<_SelectorSocketTransport fd=608 read=polling write=<idle, bufsize=0>>, <websockets.client.WebSocketClientProtocol object at 0x03623BF0>)
2016-09-06 12:48:10,198 [DEBUG ] asyncio - poll took 31.000 ms: 1 events
2016-09-06 12:48:10,202 [DEBUG ] root - Connected using websocket address: ws://127.0.0.1:36364/
2016-09-06 12:48:10,202 [DEBUG ] Rx - CurrentThreadScheduler.schedule(state=None)
2016-09-06 12:48:10,203 [DEBUG ] testcube.components.core - Using write handler
2016-09-06 12:48:10,203 [DEBUG ] root - Listening for responses
2016-09-06 12:48:10,205 [DEBUG ] testcube.comms - Sending request: {"op": "replace", "value": false, "path": "testcube.relays[0].enabled"}
2016-09-06 12:48:10,208 [DEBUG ] websockets.protocol - client >> Frame(fin=True, opcode=1, data=b'{"op": "replace", "value": false, "path": "testcube.relays[0].enabled"}')
2016-09-06 12:48:10,209 [DEBUG ] asyncio - Close <_WindowsSelectorEventLoop running=False closed=False debug=True>
2016-09-06 12:48:10,222 [ERROR ] asyncio - Task was destroyed but it is pending!
source_traceback: Object created at (most recent call last):
File "C:\Users\davidfallah\AppData\Local\Programs\Python\Python35-32\Scripts\testcube-script.py", line 9, in <module>
load_entry_point('testcube', 'console_scripts', 'testcube')()
File "c:\users\davidfallah\pycharmprojects\testcube\testcube\testcube.py", line 198, in main
cli(default_map=_get_default_settings())
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 716, in __call__
return self.main(*args, **kwargs)
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 696, in main
rv = self.invoke(ctx)
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 1057, in invoke
Command.invoke(self, ctx)
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 889, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 534, in invoke
return callback(*args, **kwargs)
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\site-packages\click\decorators.py", line 17, in new_func
return f(get_current_context(), *args, **kwargs)
File "c:\users\davidfallah\pycharmprojects\testcube\testcube\testcube.py", line 168, in cli
context.comms.establish_communication(hostname, port)
File "c:\users\davidfallah\pycharmprojects\testcube\testcube\comms.py", line 48, in establish_communication
self._listen_task = asyncio.ensure_future(self._listen_for_responses())
task: <Task pending coro=<CommunicationService._listen_for_responses() running at c:\users\davidfallah\pycharmprojects\testcube\testcube\comms.py:34> wait_for=<Future cancelled created at c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\base_events.py:252> created at c:\users\davidfallah\pycharmprojects\testcube\testcube\comms.py:48>
2016-09-06 12:48:10,223 [ERROR ] asyncio - Task was destroyed but it is pending!
source_traceback: Object created at (most recent call last):
File "C:\Users\davidfallah\AppData\Local\Programs\Python\Python35-32\Scripts\testcube-script.py", line 9, in <module>
load_entry_point('testcube', 'console_scripts', 'testcube')()
File "c:\users\davidfallah\pycharmprojects\testcube\testcube\testcube.py", line 198, in main
cli(default_map=_get_default_settings())
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 716, in __call__
return self.main(*args, **kwargs)
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 696, in main
rv = self.invoke(ctx)
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 1057, in invoke
Command.invoke(self, ctx)
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 889, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 534, in invoke
return callback(*args, **kwargs)
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\site-packages\click\decorators.py", line 17, in new_func
return f(get_current_context(), *args, **kwargs)
File "c:\users\davidfallah\pycharmprojects\testcube\testcube\testcube.py", line 168, in cli
context.comms.establish_communication(hostname, port)
File "c:\users\davidfallah\pycharmprojects\testcube\testcube\comms.py", line 47, in establish_communication
self._ws = self._loop.run_until_complete(websockets.connect(websocket_address))
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\base_events.py", line 375, in run_until_complete
self.run_forever()
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\base_events.py", line 345, in run_forever
self._run_once()
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\base_events.py", line 1304, in _run_once
handle._run()
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\events.py", line 125, in _run
self._callback(*self._args)
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\streams.py", line 238, in connection_made
self._stream_writer)
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\site-packages\websockets\protocol.py", line 633, in client_connected
self.worker_task = asyncio_ensure_future(self.run(), loop=self.loop)
task: <Task pending coro=<WebSocketCommonProtocol.run() running at c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\site-packages\websockets\protocol.py:413> wait_for=<Future pending cb=[Task._wakeup()] created at c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\base_events.py:252> cb=[_wait.<locals>._on_completion() at c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\tasks.py:414] created at c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\site-packages\websockets\protocol.py:633>
2016-09-06 12:48:10,223 [ERROR ] asyncio - Task was destroyed but it is pending!
source_traceback: Object created at (most recent call last):
File "C:\Users\davidfallah\AppData\Local\Programs\Python\Python35-32\Scripts\testcube-script.py", line 9, in <module>
load_entry_point('testcube', 'console_scripts', 'testcube')()
File "c:\users\davidfallah\pycharmprojects\testcube\testcube\testcube.py", line 198, in main
cli(default_map=_get_default_settings())
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 716, in __call__
return self.main(*args, **kwargs)
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 696, in main
rv = self.invoke(ctx)
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 1060, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 1025, in _process_result
**ctx.params)
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\site-packages\click\core.py", line 534, in invoke
return callback(*args, **kwargs)
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\site-packages\click\decorators.py", line 17, in new_func
return f(get_current_context(), *args, **kwargs)
File "c:\users\davidfallah\pycharmprojects\testcube\testcube\testcube.py", line 190, in _handle_command_task
result = loop.run_until_complete(task)
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\base_events.py", line 375, in run_until_complete
self.run_forever()
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\base_events.py", line 345, in run_forever
self._run_once()
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\base_events.py", line 1304, in _run_once
handle._run()
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\events.py", line 125, in _run
self._callback(*self._args)
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\tasks.py", line 239, in _step
result = coro.send(None)
File "c:\users\davidfallah\pycharmprojects\testcube\testcube\comms.py", line 34, in _listen_for_responses
message = await self._ws.recv()
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\site-packages\websockets\protocol.py", line 280, in recv
self.messages.get(), loop=self.loop)
task: <Task pending coro=<Queue.get() running at c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\queues.py:168> wait_for=<Future pending cb=[Task._wakeup()] created at c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\base_events.py:252> cb=[_wait.<locals>._on_completion() at c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\tasks.py:414] created at c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\site-packages\websockets\protocol.py:280>
Exception ignored in: <generator object Queue.get at 0x03641240>
Traceback (most recent call last):
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\queues.py", line 170, in get
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\futures.py", line 227, in cancel
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\futures.py", line 242, in _schedule_callbacks
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\base_events.py", line 497, in call_soon
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\base_events.py", line 506, in _call_soon
File "c:\users\davidfallah\appdata\local\programs\python\python35-32\lib\asyncio\base_events.py", line 334, in _check_closed
RuntimeError: Event loop is closed
</code></pre>
| 1
|
2016-09-06T11:56:59Z
| 39,352,458
|
<p>I figured it out - I need to define <code>CommunicationService.stop()</code> as the following:</p>
<pre><code>def stop(self):
if self._listen_task is None or self._ws is None:
return
self._listen_task.cancel()
self._loop.run_until_complete(asyncio.wait([self._listen_task, self._ws.close()]))
self._listen_task = None
self._ws = None
</code></pre>
<p>As documentation for anyone else that might end up struggling with related issues, the complete cleanup code is now:</p>
<pre><code>@cli.resultcallback()
@click.pass_context
def _handle_command_task(context, task: Coroutine, **_) -> None:
if task:
loop = asyncio.get_event_loop()
result = loop.run_until_complete(task)
context.comms.stop()
loop.close()
if result:
print(result, end='')
</code></pre>
| 0
|
2016-09-06T15:12:47Z
|
[
"python",
"python-3.x",
"python-asyncio"
] |
Gevent backdoor inspect runing code
| 39,348,488
|
<p>I am using <code>gevent</code> with its <code>Backdoor</code> feature.</p>
<p>This is a simplified version of my code :</p>
<pre><code>from gevent import backdoor, event
class App(object):
def __init__(self):
self.stop_event = event.Event()
self.servers = []
self.servers.append(backdoor.BackdoorServer((localhost, 6666))
# There is a tcp stream server using gevent configured too
def start(self):
for server in self.servers:
if not server.started:
server.start()
self.stop_event.wait()
for server in self.servers:
if server.started:
server.stop()
def run(*args, **kw):
app = App()
app.start()
</code></pre>
<p>The <code>run</code> method is called in a <code>console_scripts</code> created from the <code>entry_points</code> in my <code>setup.py</code></p>
<p>I want to use my backdoor to inspect the <code>app</code> variable local in my <code>run</code> function.</p>
<p>I connect to the backdoor, and run the command <code>inspect.stack()</code>. This is what I am getting :</p>
<pre><code>[
(<frame object at 0x7fa49ea0b3a0>, '<console>', 1, '<module>', None, None),
(<frame object at 0x7fa49ce727f0>, '/usr/lib/python2.7/code.py', 103, 'runcode', [' exec code in self.locals\n'], 0),
(<frame object at 0x7fa49ce70250>, '/usr/lib/python2.7/code.py', 87, 'runsource', [' self.runcode(code)\n'], 0),
(<frame object at 0x7fa49ced7d38>, '/usr/lib/python2.7/code.py', 265, 'push', [' more = self.runsource(source, self.filename)\n'], 0),
(<frame object at 0x3569a40>, '/usr/lib/python2.7/code.py', 243, 'interact', [' more = self.push(line)\n'], 0),
(<frame object at 0x7fa49ced39b0>, 'path_to_project/venv/local/lib/python2.7/site-packages/gevent-1.0.2-py2.7-linux-x86_64.egg/gevent/backdoor.py', 75, '_run', [' console.interact(banner=self.banner)\n'], 0),
(<frame object at 0x7fa49ced3b90>, 'path_to_project/venv/local/lib/python2.7/site-packages/gevent-1.0.2-py2.7-linux-x86_64.egg/gevent/greenlet.py', 327, 'run', [' result = self._run(*self.args, **self.kwargs)\n'], 0)
]
</code></pre>
<p>As you can see, it seems that gevent is rewriting the stack. The <code>run</code> function from my module which is starting the program is not in it. It stops at the run method of the greenlet executing the backdoor.</p>
<p>Is there any way to access the running <code>run</code> method which has started the program in order to inspect it and access its local <code>app</code> variable ?</p>
| 0
|
2016-09-06T11:57:29Z
| 39,350,901
|
<p>Ok, I found a solution. The <code>greenlet</code> object has a <code>parent</code> attribute to find which one has spawned the one you are currently looking at. Then the greenlet has an attribute <code>gr_frame</code> to store the stacktrace.</p>
<p>So in my case, once I am connected to the backdoor server, it would be something like that :</p>
<pre><code>>>> import greenlet, inspect
>>> greenlet.getcurrent()
<SocketConsole at 0x7fca7122d190>
>>> greenlet.getcurrent().parent
<Hub at 0x7fca71560050 epoll default pending=0 ref=4 fileno=3 resolver=<gevent.resolver_thread.Resolver at 0x7fca7126a510 pool=<ThreadPool at 0x7fca7127fe10 0/1/10>> threadpool=<ThreadPool at 0x7fca7127fe10 0/1/10>>
>>> greenlet.getcurrent().parent.parent
<greenlet.greenlet object at 0x7fca7d9be690>
>>> inspect.getouterframes(greenlet.getcurrent().parent.parent.gr_frame)
[
...
(<frame object at 0x174ac40>, 'path_to_project/endpoints/app.py', 238, 'run', [' app.start()\n'], 0),
...
]
>>> inspect.getouterframes(greenlet.getcurrent().parent.parent.gr_frame)[4][0]
<frame object at 0x174ac40>
>>> inspect.getargvalues(inspect.getouterframes(greenlet.getcurrent().parent.parent.gr_frame)[4][0]).locals
{'args': [], 'app': <endpoints.app.App object at 0x7fca71360190>, 'kw': {}}
>>> inspect.getargvalues(inspect.getouterframes(greenlet.getcurrent().parent.parent.gr_frame)[4][0]).locals['app']
<endpoints.app.App object at 0x7fca71360190>
</code></pre>
<p>I have noow access to the local object <code>app</code> inside the running function <code>run</code> to inspect the value of its other attributes and debug my live gevent application.</p>
| 0
|
2016-09-06T13:57:42Z
|
[
"python",
"python-2.7",
"gevent",
"inspect"
] |
Command "python setup.py egg_info" failed when installing a package
| 39,348,496
|
<p>I am trying to install a bunch of dependencies from the <code>requirements.txt</code> file of a cloned Django project. However, when it's trying to install one of them, <code>vobject-0.8.1c</code> the following error is displayed and none of the dependencies are installed:</p>
<blockquote>
<p>Command "python setup.py egg_info" failed with error code 1 in
c:\users\xxxxxx\appdata\local\temp\pip-build-n_0xlr\vobject\</p>
</blockquote>
<p>This is how I am trying to install these packages:</p>
<pre><code>pip install -r requirements.txt
</code></pre>
<p>I have spent hours trying to solve this problem. All the issues I see about it suggest installing or upgrading <code>setuptools</code> and <code>ez_setup</code>. I have done that and I still get the error, so the project keeps having a ton of missing dependencies.</p>
<p>I am on Windows.</p>
<p>What can I do? How can I install these dependencies?</p>
| 1
|
2016-09-06T11:57:52Z
| 39,350,379
|
<p>Install <code>0.8.2</code>. It's first pip-installable version. All files is the same as in <code>0.8.1c</code> version, except:</p>
<p><strong>base.py</strong></p>
<pre><code>286a287,288
> for k,v in self.params.items():
> self.params[k] = copy.copy(v)
630,631c632,633
< def __init__(self, message, lineNumber=None):
< self.message = message
---
> def __init__(self, msg, lineNumber=None):
> self.msg = msg
637c639
< (self.lineNumber, self.message)
---
> (self.lineNumber, self.msg)
639c641
< return repr(self.message)
---
> return repr(self.msg)
956c958,960
< for key, paramvals in obj.params.iteritems():
---
> keys = sorted(obj.params.iterkeys())
> for key in keys:
> paramvals = obj.params[key]
</code></pre>
<p>and <strong>icalendar.py</strong></p>
<pre><code>428a429,440
>
> # RFC2445 actually states that UNTIL must be a UTC value. Whilst the
> # changes above work OK, one problem case is if DTSTART is floating but
> # UNTIL is properly specified as UTC (or with a TZID). In that case dateutil
> # will fail datetime comparisons. There is no easy solution to this as
> # there is no obvious timezone (at this point) to do proper floating time
> # offset compisons. The best we can do is treat the UNTIL value as floating.
> # This could mean incorrect determination of the last instance. The better
> # solution here is to encourage clients to use COUNT rather than UNTIL
> # when DTSTART is floating.
> if dtstart.tzinfo is None:
> until = until.replace(tzinfo=None)
476c488
< if hasattr(self.contents, name):
---
> if name in self.contents:
</code></pre>
<p>There should be no problems with the change of version.</p>
| 0
|
2016-09-06T13:34:56Z
|
[
"python",
"django",
"pip"
] |
How to display Foreign Key's choices in django-admin?
| 39,348,521
|
<p>I have small problem related to django-admin panel.
I have 2 models:</p>
<pre><code>from django.db import models
class Subject(models.Model):
subject = models.CharField(max_length=30, choices=[('P', 'Personal'), ('W', 'Work')])
def __str__(self):
return self.subject
class BlogPost(models.Model):
id = models.AutoField(unique=True, primary_key=True)
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
text = models.TextField(null=False)
pic = models.ImageField(upload_to='static/img/', default='static/img/no-image.png')
date = models.DateTimeField()
def __str__(self):
return self.subject
</code></pre>
<p>But in admin panel whenever I try to create blog post, dropdown menu doesn't show any of subject's choices. Do I need to edit admin render function ?</p>
| 2
|
2016-09-06T11:58:40Z
| 39,350,224
|
<p>By the way you have done it you have to first add the subjects themselves so they can appear in your foreign key choices. you could have the same results by:</p>
<pre><code>class BlogPost(models.Model):
id = models.AutoField(unique=True, primary_key=True)
subject = models.CharField(max_length=30, choices=[('P', 'Personal'), ('W', 'Work')])
def __str__(self):
return self.subject
</code></pre>
<p>What do you want the ForeignKey for?</p>
| 2
|
2016-09-06T13:27:01Z
|
[
"python",
"django"
] |
Is any() evaluated lazily?
| 39,348,588
|
<p>I am writing a script in which i have to test numbers against a number of conditions. If <strong>any</strong> of the conditions are met i want to return <code>True</code> and i want to do that the fastest way possible.</p>
<p>My first idea was to use <code>any()</code> instead of nested <code>if</code> statements or multiple <code>or</code> linking my conditions. Since i would be satisfied if any of the conditions were <code>True</code> i could really benefit from <code>any()</code> being lazy and returning True as soon as it could.</p>
<p>Based on the fact that the following print happens instantly and not after 10 (= 0 + 1 + 2 + 3 + 4) seconds i assume it is. Is that the case or am i somehow mistaken?</p>
<pre><code>import time
def some(sec):
time.sleep(sec)
return True
print(any(some(x) for x in range(5)))
</code></pre>
| 3
|
2016-09-06T12:01:54Z
| 39,348,689
|
<p>Yes, <code>any()</code> and <code>all()</code> short-circuit, aborting as soon as the outcome is clear: See the <a href="https://docs.python.org/3/library/functions.html#all">docs</a>:</p>
<blockquote>
<p><strong>all(iterable)</strong></p>
<p>Return True if all elements of the iterable are true (or if the
iterable is empty). Equivalent to:</p>
<pre><code>def all(iterable):
for element in iterable:
if not element:
return False
return True
</code></pre>
<p><strong>any(iterable)</strong></p>
<p>Return True if any element of the iterable is true. If the iterable is
empty, return False. Equivalent to:</p>
<pre><code>def any(iterable):
for element in iterable:
if element:
return True
return False
</code></pre>
</blockquote>
| 9
|
2016-09-06T12:08:20Z
|
[
"python"
] |
Is any() evaluated lazily?
| 39,348,588
|
<p>I am writing a script in which i have to test numbers against a number of conditions. If <strong>any</strong> of the conditions are met i want to return <code>True</code> and i want to do that the fastest way possible.</p>
<p>My first idea was to use <code>any()</code> instead of nested <code>if</code> statements or multiple <code>or</code> linking my conditions. Since i would be satisfied if any of the conditions were <code>True</code> i could really benefit from <code>any()</code> being lazy and returning True as soon as it could.</p>
<p>Based on the fact that the following print happens instantly and not after 10 (= 0 + 1 + 2 + 3 + 4) seconds i assume it is. Is that the case or am i somehow mistaken?</p>
<pre><code>import time
def some(sec):
time.sleep(sec)
return True
print(any(some(x) for x in range(5)))
</code></pre>
| 3
|
2016-09-06T12:01:54Z
| 39,348,748
|
<p>While the <a href="https://docs.python.org/2.7/library/functions.html#all" rel="nofollow"><code>all()</code></a> and <a href="https://docs.python.org/2.7/library/functions.html#any" rel="nofollow"><code>any()</code></a> functions short-circuit on the first "true" element of an iterable, the iterable itself may be constructed in a non-lazy way. Consider this example:</p>
<pre><code>>> any(x == 100 for x in range(10**8))
True
</code></pre>
<p>This will take several seconds to execute in Python 2 as <code>range(10**8)</code> constructs a list of 10**8 elements. The same expression runs instantly in Python 3, where <code>range()</code> is lazy.</p>
| 4
|
2016-09-06T12:11:10Z
|
[
"python"
] |
Is any() evaluated lazily?
| 39,348,588
|
<p>I am writing a script in which i have to test numbers against a number of conditions. If <strong>any</strong> of the conditions are met i want to return <code>True</code> and i want to do that the fastest way possible.</p>
<p>My first idea was to use <code>any()</code> instead of nested <code>if</code> statements or multiple <code>or</code> linking my conditions. Since i would be satisfied if any of the conditions were <code>True</code> i could really benefit from <code>any()</code> being lazy and returning True as soon as it could.</p>
<p>Based on the fact that the following print happens instantly and not after 10 (= 0 + 1 + 2 + 3 + 4) seconds i assume it is. Is that the case or am i somehow mistaken?</p>
<pre><code>import time
def some(sec):
time.sleep(sec)
return True
print(any(some(x) for x in range(5)))
</code></pre>
| 3
|
2016-09-06T12:01:54Z
| 39,348,758
|
<p>Yes, it's lazy as demonstrated by the following:</p>
<pre><code>def some(x, result=True):
print(x)
return result
>>> print(any(some(x) for x in range(5)))
0
True
>>> print(any(some(x, False) for x in range(5)))
0
1
2
3
4
False
</code></pre>
<p>In the first run <code>any()</code> halted after testing the first item, i.e. it short circuited the evaluation.</p>
<p>In the second run <code>any()</code> continued testing until the sequence was exhausted.</p>
| 2
|
2016-09-06T12:11:31Z
|
[
"python"
] |
Is any() evaluated lazily?
| 39,348,588
|
<p>I am writing a script in which i have to test numbers against a number of conditions. If <strong>any</strong> of the conditions are met i want to return <code>True</code> and i want to do that the fastest way possible.</p>
<p>My first idea was to use <code>any()</code> instead of nested <code>if</code> statements or multiple <code>or</code> linking my conditions. Since i would be satisfied if any of the conditions were <code>True</code> i could really benefit from <code>any()</code> being lazy and returning True as soon as it could.</p>
<p>Based on the fact that the following print happens instantly and not after 10 (= 0 + 1 + 2 + 3 + 4) seconds i assume it is. Is that the case or am i somehow mistaken?</p>
<pre><code>import time
def some(sec):
time.sleep(sec)
return True
print(any(some(x) for x in range(5)))
</code></pre>
| 3
|
2016-09-06T12:01:54Z
| 39,348,770
|
<p>Yes, and here is an experiment that shows it even more definitively than your timing experiment:</p>
<pre><code>import random
def some(x):
print(x, end = ', ')
return random.random() < 0.25
for i in range(5):
print(any(some(x) for x in range(10)))
</code></pre>
<p>typical run:</p>
<pre><code>0, 1, 2, True
0, 1, True
0, True
0, 1, 2, 3, True
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, False
</code></pre>
| 2
|
2016-09-06T12:12:14Z
|
[
"python"
] |
Is any() evaluated lazily?
| 39,348,588
|
<p>I am writing a script in which i have to test numbers against a number of conditions. If <strong>any</strong> of the conditions are met i want to return <code>True</code> and i want to do that the fastest way possible.</p>
<p>My first idea was to use <code>any()</code> instead of nested <code>if</code> statements or multiple <code>or</code> linking my conditions. Since i would be satisfied if any of the conditions were <code>True</code> i could really benefit from <code>any()</code> being lazy and returning True as soon as it could.</p>
<p>Based on the fact that the following print happens instantly and not after 10 (= 0 + 1 + 2 + 3 + 4) seconds i assume it is. Is that the case or am i somehow mistaken?</p>
<pre><code>import time
def some(sec):
time.sleep(sec)
return True
print(any(some(x) for x in range(5)))
</code></pre>
| 3
|
2016-09-06T12:01:54Z
| 39,348,881
|
<p>As Tim correctly mentioned, <code>any</code> and <code>all</code> do short-circuit, but in your code, what makes it <em>lazy</em> is the use of <a href="http://stackoverflow.com/questions/47789/generator-expressions-vs-list-comprehension">generators</a>. For example, the following code would not be lazy:</p>
<pre><code>print(any([slow_operation(x) for x in big_list]))
</code></pre>
<p>The list would be fully constructed and calculated, and only then passed as an argument to <code>any</code>.</p>
<p>Generators, on the other hand, are iterables that calculate each item on demand. They can be <a href="https://www.python.org/dev/peps/pep-0289/" rel="nofollow">expressions</a>, <a href="https://www.python.org/dev/peps/pep-0255/" rel="nofollow">functions</a>, or sometimes manually implemented as lazy <a href="https://docs.python.org/3/tutorial/classes.html#iterators" rel="nofollow">iterators</a>.</p>
| 3
|
2016-09-06T12:18:07Z
|
[
"python"
] |
python testing strategy to develop and auto-grader
| 39,348,605
|
<p>I have a list of input files and an expected output file, I want to write an auto-grader that does the job of accepting a python program, running it on the input files, and comparing its output to the output file. The approach I have used is to use the <code>os</code> module of python to run the program using <code>os.system('python program.py > actual.out')</code> and then perform a diff between the output and expected.out again using os.system().</p>
<p>The problem which I am currently facing is reading the input from the file because the program which is given is reading from the console. So, how should I redirect the input from a file such that it is readable by sys.stdin in program.py.</p>
<pre><code>import os
def grade(program_py_file_handler,input_dir,output_dir):
#create temporary file for program.py using program_py_file_handler
#one by one read all files from input_dir
#run program.py using os.system generating a temp file
#do diff be temp file and expected file
</code></pre>
<p>Is there a better way to perform a diff without using the diff command?</p>
<p>To redirect output from program.py to a file I used <code>python program.py>tem.out</code>. What equivalent should I use to redirect an input file to progam.py such that wherever I have used sys.stdin in program.py it will instead read from the passed file? (Modifying program.py is not an option.)</p>
| 1
|
2016-09-06T12:02:49Z
| 39,348,840
|
<p>You can be doing everything using builtin modules in Python 3.3+, since you are effectively spinning up a <a href="https://docs.python.org/3/library/subprocess.html" rel="nofollow"><code>subprocess</code></a> and doing a <a href="https://docs.python.org/3/library/difflib.html" rel="nofollow"><code>diff</code></a> on the expected output. Simple minimum example:</p>
<p><em>check.py</em></p>
<pre><code>import sys
from subprocess import check_output
from difflib import ndiff
def split(s):
return s.splitlines(keepends=True)
def check(program_name, expected):
output = check_output([sys.executable, program_name]).decode('utf8')
diff = ndiff(split(output), split(expected))
print(''.join(diff), end="")
def main():
check('hello.py', 'Good Morning!\n')
if __name__ == '__main__':
main()
</code></pre>
<p><em>hello.py</em></p>
<pre><code>print('Good Evening!')
</code></pre>
<p>Example run</p>
<pre><code>$ python check.py
- Good Evening!
? ^^^
+ Good Morning!
? ^^^
</code></pre>
<p>Modify as you see fit, with other methods/functions in the libraries linked. If you need stdin for the subprocess you probably will need to create Popen object and call communicate, but please read documentations first for future reference.</p>
| 0
|
2016-09-06T12:16:08Z
|
[
"python",
"file",
"python-3.4",
"file-handling"
] |
pandas dataframe: len(df) is not equal to number of iterations in df.iterrows()
| 39,348,632
|
<p>I have a dataframe where I want to print each row to a different file. When the dataframe consists of e.g. only 50 rows, <code>len(df)</code> will print <code>50</code> and iterating over the rows of the dataframe like</p>
<pre><code>for index, row in df.iterrows():
print(index)
</code></pre>
<p>will print the index from <code>0</code> to <code>49</code>. </p>
<p>However, if my dataframe contains more than 50'000 rows, <code>len(df)</code>and the number of iterations when iterating over <code>df.iterrows()</code> differ significantly. For example, <code>len(df)</code> will say e.g. 50'554 and printing the index will go up to over 400'000. </p>
<p>How can this be? What am I missing here?</p>
| 0
|
2016-09-06T12:04:15Z
| 39,348,792
|
<p>First, as @EdChum noted in the comment, your question's title refers to <code>iterrows</code>, but the example you give refers to <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.iteritems.html" rel="nofollow"><code>iteritems</code></a>, which loops in the orthogonal direction to that relevant to <code>len</code>. I assume you meant <code>iterrows</code> (as in the title). </p>
<p>Note that a DataFrame's index need not be a running index, irrespective of the size of the DataFrame. For example:</p>
<pre><code>df = pd.DataFrame({'a': [1, 2, 3, 4]}, index=[2, 4, 5, 1000])
>>> for index, row in df.iterrows():
... print index
2
4
5
1000
</code></pre>
<p>Presumably, your long DataFrame was just created differently, then, or underwent some manipulation, affecting the index.</p>
<p>If you <em>really</em> must iterate with a running index, you can use Python's <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a>:</p>
<pre><code>>>> for index, row in enumerate(df.iterrows()):
... print index
0
1
2
3
</code></pre>
<p>(Note that, in this case, <code>row</code> is itself a tuple.)</p>
| 2
|
2016-09-06T12:13:12Z
|
[
"python",
"pandas",
"dataframe"
] |
Scons copy header files to build directory
| 39,348,788
|
<p>I'm trying to copy a number of headers files from my source directories to an 'includes' directory inside my build directory using scons. My target is a static library and I want to distribute it together with its relevant headers. The expected end result:</p>
<pre><code>build
|-- objects -> .o output files for constructing libmclib.a
|-- includes
| |-- foo.h
| `-- bar.h
`-- libmclib.a
</code></pre>
<p>My SConstruct:</p>
<pre class="lang-py prettyprint-override"><code>#!python
target = 'mock'
env = Environment(LINKCOM = "$LINK -o $TARGET $SOURCES $LINKFLAGS $CCFLAGS")
Export('env', 'target')
build_base = 'build'
SConscript('SConscript', variant_dir=build_base, duplicate=0)
# remove build directory
if GetOption('clean'):
import subprocess
subprocess.call(['rm', '-rf', build_base])
</code></pre>
<p>My SConscript:</p>
<pre class="lang-py prettyprint-override"><code>#!python
Import('env')
# ...
# other stuff to build 'mclib_target'
# ...
def copy_header_files(target, source, env):
Mkdir(target)
header_files = []
for d in env['CPPPATH']:
header_files += Glob(d + "/*.h")
for f in header_files:
Copy(target, f)
# copy all relevant header files
env.Command("includes", mclib_target, copy_header_files)
</code></pre>
<p>Scons does call 'copy_header_files' with arguments '["build/includes"], ["build/libmclib.a"]', but for some reason 'Mkdir' doesn't create the includes directory. Also 'Copy' seems to do nothing. If I however call Mkdir like this:</p>
<pre class="lang-py prettyprint-override"><code>env.Command("includes", mclib_target, [Mkdir('$TARGET')])
</code></pre>
<p>it seems to work well. How to fix/work around this? I'm also quite new to Scons so any alternative for doing this task are welcome. I'm using scons 2.5.0.</p>
| 1
|
2016-09-06T12:12:54Z
| 39,350,875
|
<p>You probably want to use "<code>Install()</code>" instead of "<code>Copy()</code>". Also the <code>Mkdir()</code> shouldn't be necessary, SCons creates all intermediate folders for its targets automatically.</p>
<p>Finally, allow me some comments about your general approach: I'd rather not mix "building" with "installing/preparing for packaging". The "<code>variant_dir</code>" option is there to help you with building several "variants" (release, optimized, debug, ARM-specific,...) from the same source files (let's say you have a folder named "src"). By passing the name of the current "build" directory into your "src" SConscript you're embedding variant-specific knowledge into your local build description, meaning that you'll have to touch it with every variant that you add.
Instead, you should move the "<code>Install/Package</code>" steps into the top-level SConstruct...where you have global knowledge about which variants get built. From there you can copy (= Install) the final files to a separate subfolder, e.g. <code>distribution</code>, and archive that one instead.</p>
<p>For a simple example of how to handle variants right in SCons, check out the repo <a href="https://bitbucket.org/dirkbaechle/scons_talks" rel="nofollow">https://bitbucket.org/dirkbaechle/scons_talks</a> and there the "<code>pyconde_2013/examples/exvar</code>" folder.</p>
| 2
|
2016-09-06T13:56:52Z
|
[
"python",
"scons"
] |
Scons copy header files to build directory
| 39,348,788
|
<p>I'm trying to copy a number of headers files from my source directories to an 'includes' directory inside my build directory using scons. My target is a static library and I want to distribute it together with its relevant headers. The expected end result:</p>
<pre><code>build
|-- objects -> .o output files for constructing libmclib.a
|-- includes
| |-- foo.h
| `-- bar.h
`-- libmclib.a
</code></pre>
<p>My SConstruct:</p>
<pre class="lang-py prettyprint-override"><code>#!python
target = 'mock'
env = Environment(LINKCOM = "$LINK -o $TARGET $SOURCES $LINKFLAGS $CCFLAGS")
Export('env', 'target')
build_base = 'build'
SConscript('SConscript', variant_dir=build_base, duplicate=0)
# remove build directory
if GetOption('clean'):
import subprocess
subprocess.call(['rm', '-rf', build_base])
</code></pre>
<p>My SConscript:</p>
<pre class="lang-py prettyprint-override"><code>#!python
Import('env')
# ...
# other stuff to build 'mclib_target'
# ...
def copy_header_files(target, source, env):
Mkdir(target)
header_files = []
for d in env['CPPPATH']:
header_files += Glob(d + "/*.h")
for f in header_files:
Copy(target, f)
# copy all relevant header files
env.Command("includes", mclib_target, copy_header_files)
</code></pre>
<p>Scons does call 'copy_header_files' with arguments '["build/includes"], ["build/libmclib.a"]', but for some reason 'Mkdir' doesn't create the includes directory. Also 'Copy' seems to do nothing. If I however call Mkdir like this:</p>
<pre class="lang-py prettyprint-override"><code>env.Command("includes", mclib_target, [Mkdir('$TARGET')])
</code></pre>
<p>it seems to work well. How to fix/work around this? I'm also quite new to Scons so any alternative for doing this task are welcome. I'm using scons 2.5.0.</p>
| 1
|
2016-09-06T12:12:54Z
| 39,355,253
|
<p>The <em>Mkdir</em> and <em>Copy</em> operations that you are using are Action factories for use in Command definitions, described in <a href="http://scons.org/doc/production/HTML/scons-user.html#chap-factories" rel="nofollow">Platform-Independent File System Manipulation</a>:</p>
<blockquote>
<p>SCons provides a number of platform-independent functions, called
factories, that perform common file system manipulations like copying,
moving or deleting files and directories, or making directories. <strong>These
functions are factories because they don't perform the action at the
time they're called, they each return an Action object that can be
executed at the appropriate time.</strong></p>
</blockquote>
<p>I have always had problems trying to use these functions within my own action functions. Perhaps I am missing something, but I don't think these functions can be used outside of the immediate list of operations in the Command builder.</p>
<p>Instead I use the platform-independent functions in python for creating directories and copying files, such as <a href="https://docs.python.org/2/library/os.html#os.makedirs" rel="nofollow"><code>os.makedirs</code></a> and <a href="https://docs.python.org/2/library/shutil.html#shutil.copy" rel="nofollow"><code>shutil.copy</code></a>.</p>
| 0
|
2016-09-06T18:06:23Z
|
[
"python",
"scons"
] |
Deactivate pyenv in current shell
| 39,348,806
|
<p>My .bashrc has this:</p>
<pre><code>enable-pyenv () {
# Load pyenv automatically by adding
# the following to your profile:
export PATH="$HOME/.pyenv/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"
}
enable-pyenv
</code></pre>
<p>Which enables pyenv. In some situations, I want to (tempararily) disable pyenv. How can I do this?</p>
| 0
|
2016-09-06T12:14:02Z
| 39,348,931
|
<p>Try <code>pyenv deactivate</code>, to manually deactivate the virtual env.</p>
<p>Doc here: <a href="https://github.com/yyuu/pyenv-virtualenv" rel="nofollow">https://github.com/yyuu/pyenv-virtualenv</a></p>
| 1
|
2016-09-06T12:20:55Z
|
[
"python",
"pyenv"
] |
Elasticsearch (Elasticsearch Curator) Python API. Get dictionary of ES indices and their sizes
| 39,348,851
|
<p>I can get all of ES indexes in list via such code:</p>
<pre><code>from elasticsearch import Elasticsearch
es = Elasticsearch()
indices=es.indices.get_aliases().keys()
sorted(indices)
</code></pre>
<p>But is it possible to get dictionary like <code>{'index1': '100gb', 'index2': '10gb', 'index3': '15gb'}</code>. So i mean dic with index name and size of them.</p>
| 1
|
2016-09-06T12:16:28Z
| 39,352,688
|
<p>My variant:</p>
<pre><code>import elasticsearch
client = elasticsearch.Elasticsearch()
all_indices = client.indices.stats(metric='store', human=True)['indices'].keys()
dic_indices = {}
for index in all_indices:
size = client.indices.stats(metric='store', human=True)['indices'][index]['total']['store']['size']
dic_indices[index] = size
print dic_indices
</code></pre>
<p>Result has next view:</p>
<pre><code>{u'haproxy-2016.09.02': u'1.6gb', u'haproxy-2016.09.03': u'827.3mb', u'marathon-2016.09.03': u'296.1mb', u'docker-2016-09-06': u'187.2mb', u'haproxy-2016.09.06': u'339.7mb', u'haproxy-2016.09.04': u'647.5mb', u'haproxy-2016.09.05': u'595.5mb'}
</code></pre>
| 2
|
2016-09-06T15:24:50Z
|
[
"python",
"api",
"dictionary",
"elasticsearch",
"elasticsearch-curator"
] |
Elasticsearch (Elasticsearch Curator) Python API. Get dictionary of ES indices and their sizes
| 39,348,851
|
<p>I can get all of ES indexes in list via such code:</p>
<pre><code>from elasticsearch import Elasticsearch
es = Elasticsearch()
indices=es.indices.get_aliases().keys()
sorted(indices)
</code></pre>
<p>But is it possible to get dictionary like <code>{'index1': '100gb', 'index2': '10gb', 'index3': '15gb'}</code>. So i mean dic with index name and size of them.</p>
| 1
|
2016-09-06T12:16:28Z
| 39,380,587
|
<p>Curator 4 pulls much of the index metadata at IndexList initialization. It's in bytes, rather than in human readable sizes, if that matters. </p>
<p>It is in <strong>IndexList.index_info[index_name]['size_in_bytes']</strong></p>
<p>Read more about the IndexList method at <a href="http://curator.readthedocs.io/en/latest/objectclasses.html#indexlist" rel="nofollow">http://curator.readthedocs.io/en/latest/objectclasses.html#indexlist</a></p>
<pre><code>import elasticsearch
import curator
client = elasticsearch.Elasticsearch(host='127.0.0.1')
il = curator.IndexList(client)
print('{0}'.format(il.indices))
[u'topbeat-2016.09.01', ...]
print('{0}'.format(il.index_info['topbeat-2016.09.01'])
{'number_of_replicas': u'1', 'size_in_bytes': 706503044, 'number_of_shards': u'5', 'docs': 1629986, 'age': {'creation_date': 1472688002}, 'state': u'open', 'segments': 0}
</code></pre>
| 2
|
2016-09-07T23:50:46Z
|
[
"python",
"api",
"dictionary",
"elasticsearch",
"elasticsearch-curator"
] |
python & pandas- Calculation bewteen rows based on certain values in columns from DataFrame
| 39,348,858
|
<p>I have a large DataFrame (called df_NoMissing) with thousands of rows, and I need to do calculation and analysis with them.</p>
<pre><code> NoDemande NoUsager Sens IdVehiculeUtilise Fait HeureArriveeSurSite HeureEffective Periods
0 42196000013 000001 + 287Véh 1 11/07/2015 08:02:07 11/07/2015 08:02:13 Matin
1 42196000013 000001 - 287Véh 1 11/07/2015 08:17:09 11/07/2015 08:17:13 Matin
2 42196000002 000314 + 263Véh 1 11/07/2015 09:37:43 11/07/2015 09:53:37 Matin
3 42196000016 002372 + 287Véh 1 11/07/2015 09:46:42 11/07/2015 10:01:39 Matin
4 42196000015 000466 + 287Véh 1 11/07/2015 09:46:42 11/07/2015 10:01:39 Matin
5 42196000002 000314 - 263Véh 1 11/07/2015 10:25:17 11/07/2015 10:38:11 Matin
6 42196000015 000466 - 287Véh 1 11/07/2015 10:48:51 11/07/2015 10:51:30 Matin
7 42196000016 002372 - 287Véh 1 11/07/2015 11:40:56 11/07/2015 11:41:01 Matin
8 42196000004 002641 + 263Véh 1 11/07/2015 13:39:29 11/07/2015 13:52:50 Soir
9 42196000004 002641 - 263Véh 1 11/07/2015 13:59:56 11/07/2015 14:07:41 Soir
</code></pre>
<p>What I want to do is to have two rows with the same value in the column <code>NoDemande</code>, <code>NoUsager</code>, <code>Periods</code> but different in column <code>Sens</code> do the subtraction between column <code>HeureArriveeSurSite</code> and <code>HeureEffective</code>. And because the result doesn't correspond to current DataFrame, so the result will be saved in a new DataFrame</p>
<hr>
<p>I tried to separate the DataFrame by identifying <code>Sens</code> so I could to the subtraction directly. But it doesn't work at all.</p>
<pre><code>df_new = pd.DataFrame(columns=['NoDemande', 'NoUsager', 'Periods', 'DureeTrajet']
df1 = df_NoMissing[(df_NoMissing['Sens'] == '+') & (df_NoMissing['Periods'] == 'Matin')]
df2 = df_NoMissing[(df_NoMissing['Sens'] == '-') & (df_NoMissing['Periods'] == 'Matin')]
df_new['DureeTrajet'] = df2['HeureArriveeSurSite'].values-df1['HeureEffective'].values
</code></pre>
<p>This one returned: <code>ValueError: operands could not be broadcast together with shapes (1478,) (1479,)</code></p>
<p>I also tried the loaded way by telling exactly what I want each time:</p>
<pre><code>df1.loc[df1['NoDemande'] == '42196000015','HeureEffective'] - df2.loc[df2['NoDemande'] == '42196000015','HeureArriveeSurSite']
</code></pre>
<p>But this one came back with:</p>
<pre><code>4 NaT
6 NaT
dtype: timedelta64[ns]
</code></pre>
<p>So what should I do to get what I want?</p>
<hr>
<p><strong>EDIT</strong></p>
<p>The output will look like:</p>
<pre><code> NoDemande NoUsager Periods DureeTrajet
0 42196000013 000001 Matin 00:14:54
1 42196000002 000314 Matin 00:31:40
2 42196000016 002372 Matin 00:39:23
3 42196000015 000466 Matin 00:47:12
4 42196000004 002641 Soir 00:07:06
</code></pre>
<p>Any help will be really appreciated~</p>
| 0
|
2016-09-06T12:16:44Z
| 39,349,987
|
<p>So my solution is:</p>
<ol>
<li><p>to join df1 and df2 (not append them, but join with outer join). For this you should rename all the columns in df2 except of NoDemande, NoUsager and Period. for example, in df1 it will be Sens, in df2 - Sens2. And after join try to subtract the dates as you want. </p></li>
<li><p>It can also be that you get some missings, if any of entries do not have a pair with another Sens value. hose who are not if paits you should just filter out, I think. Because you need just DureeTrajet for those users, who had several sessions, don't you? So, if a user had only one session, you don't need him in the df_new table?</p></li>
<li><p>At the end you shoud have only those entries, which have pairs. And for this you can subtract the dates.</p></li>
</ol>
<p><strong>EDIT:</strong></p>
<p>IF some entries have not just a pair, but two or more pairs, you should then define, which pair has more priority / makes more sense.</p>
| 1
|
2016-09-06T13:16:19Z
|
[
"python",
"pandas",
"dataframe"
] |
python & pandas- Calculation bewteen rows based on certain values in columns from DataFrame
| 39,348,858
|
<p>I have a large DataFrame (called df_NoMissing) with thousands of rows, and I need to do calculation and analysis with them.</p>
<pre><code> NoDemande NoUsager Sens IdVehiculeUtilise Fait HeureArriveeSurSite HeureEffective Periods
0 42196000013 000001 + 287Véh 1 11/07/2015 08:02:07 11/07/2015 08:02:13 Matin
1 42196000013 000001 - 287Véh 1 11/07/2015 08:17:09 11/07/2015 08:17:13 Matin
2 42196000002 000314 + 263Véh 1 11/07/2015 09:37:43 11/07/2015 09:53:37 Matin
3 42196000016 002372 + 287Véh 1 11/07/2015 09:46:42 11/07/2015 10:01:39 Matin
4 42196000015 000466 + 287Véh 1 11/07/2015 09:46:42 11/07/2015 10:01:39 Matin
5 42196000002 000314 - 263Véh 1 11/07/2015 10:25:17 11/07/2015 10:38:11 Matin
6 42196000015 000466 - 287Véh 1 11/07/2015 10:48:51 11/07/2015 10:51:30 Matin
7 42196000016 002372 - 287Véh 1 11/07/2015 11:40:56 11/07/2015 11:41:01 Matin
8 42196000004 002641 + 263Véh 1 11/07/2015 13:39:29 11/07/2015 13:52:50 Soir
9 42196000004 002641 - 263Véh 1 11/07/2015 13:59:56 11/07/2015 14:07:41 Soir
</code></pre>
<p>What I want to do is to have two rows with the same value in the column <code>NoDemande</code>, <code>NoUsager</code>, <code>Periods</code> but different in column <code>Sens</code> do the subtraction between column <code>HeureArriveeSurSite</code> and <code>HeureEffective</code>. And because the result doesn't correspond to current DataFrame, so the result will be saved in a new DataFrame</p>
<hr>
<p>I tried to separate the DataFrame by identifying <code>Sens</code> so I could to the subtraction directly. But it doesn't work at all.</p>
<pre><code>df_new = pd.DataFrame(columns=['NoDemande', 'NoUsager', 'Periods', 'DureeTrajet']
df1 = df_NoMissing[(df_NoMissing['Sens'] == '+') & (df_NoMissing['Periods'] == 'Matin')]
df2 = df_NoMissing[(df_NoMissing['Sens'] == '-') & (df_NoMissing['Periods'] == 'Matin')]
df_new['DureeTrajet'] = df2['HeureArriveeSurSite'].values-df1['HeureEffective'].values
</code></pre>
<p>This one returned: <code>ValueError: operands could not be broadcast together with shapes (1478,) (1479,)</code></p>
<p>I also tried the loaded way by telling exactly what I want each time:</p>
<pre><code>df1.loc[df1['NoDemande'] == '42196000015','HeureEffective'] - df2.loc[df2['NoDemande'] == '42196000015','HeureArriveeSurSite']
</code></pre>
<p>But this one came back with:</p>
<pre><code>4 NaT
6 NaT
dtype: timedelta64[ns]
</code></pre>
<p>So what should I do to get what I want?</p>
<hr>
<p><strong>EDIT</strong></p>
<p>The output will look like:</p>
<pre><code> NoDemande NoUsager Periods DureeTrajet
0 42196000013 000001 Matin 00:14:54
1 42196000002 000314 Matin 00:31:40
2 42196000016 002372 Matin 00:39:23
3 42196000015 000466 Matin 00:47:12
4 42196000004 002641 Soir 00:07:06
</code></pre>
<p>Any help will be really appreciated~</p>
| 0
|
2016-09-06T12:16:44Z
| 39,350,546
|
<p>Okay, starting with your DF as provided - let's create an index on the grouping columns and pivot to columns for the <code>Sens</code> action:</p>
<pre><code>temp = df.set_index(['NoDemande', 'NoUsager', 'Periods']).pivot(columns='Sens')
</code></pre>
<p>Then - we take the appropriate difference (as according to your code):</p>
<pre><code>duration = (temp['HeureArriveeSurSite', '-'] - temp['HeureEffective', '+']).to_frame(name='DureeTrajet').reset_index()
</code></pre>
<p>That then gives you:</p>
<pre><code> NoDemande NoUsager Periods DureeTrajet
0 42196000002 314 Matin 00:31:40
1 42196000004 2641 Soir 00:07:06
2 42196000013 1 Matin 00:14:56
3 42196000015 466 Matin 00:47:12
4 42196000016 2372 Matin 01:39:17
</code></pre>
| 0
|
2016-09-06T13:42:35Z
|
[
"python",
"pandas",
"dataframe"
] |
understanding Python asyncio profiler output
| 39,348,869
|
<p>I'm trying to understand the output of Python profiler while running Python asyncio based program:</p>
<p><a href="http://i.stack.imgur.com/LqYaw.png" rel="nofollow"><img src="http://i.stack.imgur.com/LqYaw.png" alt="Python3 asyncio profiler output"></a></p>
<p>I can see that my program is spending ~67% of time trying to acquire a thread lock. </p>
<ol>
<li><p>Is this normal in asyncio programs? My application is single-threaded, I am not deferring any work to worker threads and logging minimally to console.</p></li>
<li><p>My app spends ~21% in select call. Does this roughly mean that 20% of run-time is spent idle (waiting for an event or callback to happen)?</p></li>
</ol>
| 1
|
2016-09-06T12:17:13Z
| 39,353,903
|
<p>Looks like you are using debugger that collects data from all threads.
Waiting for condition variable acquiring means an idle waiting in thread pool for new tasks.</p>
<p>Time spent in <code>select</code> means again idle waiting, but in this case it's waiting for network activity.</p>
| 0
|
2016-09-06T16:36:23Z
|
[
"python",
"python-3.x",
"profiling",
"python-asyncio"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.